OSDN Git Service

Unify actions and commands
[pf3gnuchains/sourceware.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
4    1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
5    2008, 2009, 2010 Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "arch-utils.h"
24 #include <ctype.h>
25 #include "hashtab.h"
26 #include "symtab.h"
27 #include "frame.h"
28 #include "breakpoint.h"
29 #include "tracepoint.h"
30 #include "gdbtypes.h"
31 #include "expression.h"
32 #include "gdbcore.h"
33 #include "gdbcmd.h"
34 #include "value.h"
35 #include "command.h"
36 #include "inferior.h"
37 #include "gdbthread.h"
38 #include "target.h"
39 #include "language.h"
40 #include "gdb_string.h"
41 #include "demangle.h"
42 #include "annotate.h"
43 #include "symfile.h"
44 #include "objfiles.h"
45 #include "source.h"
46 #include "linespec.h"
47 #include "completer.h"
48 #include "gdb.h"
49 #include "ui-out.h"
50 #include "cli/cli-script.h"
51 #include "gdb_assert.h"
52 #include "block.h"
53 #include "solib.h"
54 #include "solist.h"
55 #include "observer.h"
56 #include "exceptions.h"
57 #include "memattr.h"
58 #include "ada-lang.h"
59 #include "top.h"
60 #include "wrapper.h"
61 #include "valprint.h"
62 #include "jit.h"
63 #include "xml-syscall.h"
64
65 /* readline include files */
66 #include "readline/readline.h"
67 #include "readline/history.h"
68
69 /* readline defines this.  */
70 #undef savestring
71
72 #include "mi/mi-common.h"
73
74 /* Arguments to pass as context to some catch command handlers.  */
75 #define CATCH_PERMANENT ((void *) (uintptr_t) 0)
76 #define CATCH_TEMPORARY ((void *) (uintptr_t) 1)
77
78 /* Prototypes for local functions. */
79
80 static void enable_delete_command (char *, int);
81
82 static void enable_delete_breakpoint (struct breakpoint *);
83
84 static void enable_once_command (char *, int);
85
86 static void enable_once_breakpoint (struct breakpoint *);
87
88 static void disable_command (char *, int);
89
90 static void enable_command (char *, int);
91
92 static void map_breakpoint_numbers (char *, void (*)(struct breakpoint *));
93
94 static void ignore_command (char *, int);
95
96 static int breakpoint_re_set_one (void *);
97
98 static void clear_command (char *, int);
99
100 static void catch_command (char *, int);
101
102 static void watch_command (char *, int);
103
104 static int can_use_hardware_watchpoint (struct value *);
105
106 static void break_command_1 (char *, int, int);
107
108 static void mention (struct breakpoint *);
109
110 /* This function is used in gdbtk sources and thus can not be made static.  */
111 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
112                                               struct symtab_and_line,
113                                               enum bptype);
114
115 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
116
117 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
118                                             CORE_ADDR bpaddr,
119                                             enum bptype bptype);
120
121 static void describe_other_breakpoints (struct gdbarch *,
122                                         struct program_space *, CORE_ADDR,
123                                         struct obj_section *, int);
124
125 static int breakpoint_address_match (struct address_space *aspace1,
126                                      CORE_ADDR addr1,
127                                      struct address_space *aspace2,
128                                      CORE_ADDR addr2);
129
130 static int watchpoint_locations_match (struct bp_location *loc1,
131                                        struct bp_location *loc2);
132
133 static void breakpoints_info (char *, int);
134
135 static void breakpoint_1 (int, int);
136
137 static bpstat bpstat_alloc (const struct bp_location *, bpstat);
138
139 static int breakpoint_cond_eval (void *);
140
141 static void cleanup_executing_breakpoints (void *);
142
143 static void commands_command (char *, int);
144
145 static void condition_command (char *, int);
146
147 static int get_number_trailer (char **, int);
148
149 void set_breakpoint_count (int);
150
151 typedef enum
152   {
153     mark_inserted,
154     mark_uninserted
155   }
156 insertion_state_t;
157
158 static int remove_breakpoint (struct bp_location *, insertion_state_t);
159 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
160
161 static enum print_stop_action print_it_typical (bpstat);
162
163 static enum print_stop_action print_bp_stop_message (bpstat bs);
164
165 static int watchpoint_check (void *);
166
167 static void maintenance_info_breakpoints (char *, int);
168
169 static int hw_breakpoint_used_count (void);
170
171 static int hw_watchpoint_used_count (enum bptype, int *);
172
173 static void hbreak_command (char *, int);
174
175 static void thbreak_command (char *, int);
176
177 static void watch_command_1 (char *, int, int);
178
179 static void rwatch_command (char *, int);
180
181 static void awatch_command (char *, int);
182
183 static void do_enable_breakpoint (struct breakpoint *, enum bpdisp);
184
185 static void stop_command (char *arg, int from_tty);
186
187 static void stopin_command (char *arg, int from_tty);
188
189 static void stopat_command (char *arg, int from_tty);
190
191 static char *ep_parse_optional_if_clause (char **arg);
192
193 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
194                                        char *arg, int tempflag, int from_tty);
195
196 static void tcatch_command (char *arg, int from_tty);
197
198 static void ep_skip_leading_whitespace (char **s);
199
200 static int single_step_breakpoint_inserted_here_p (struct address_space *,
201                                                    CORE_ADDR pc);
202
203 static void free_bp_location (struct bp_location *loc);
204
205 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
206
207 static void update_global_location_list (int);
208
209 static void update_global_location_list_nothrow (int);
210
211 static int is_hardware_watchpoint (struct breakpoint *bpt);
212
213 static int is_watchpoint (struct breakpoint *bpt);
214
215 static void insert_breakpoint_locations (void);
216
217 static int syscall_catchpoint_p (struct breakpoint *b);
218
219 static void tracepoints_info (char *, int);
220
221 static void delete_trace_command (char *, int);
222
223 static void enable_trace_command (char *, int);
224
225 static void disable_trace_command (char *, int);
226
227 static void trace_pass_command (char *, int);
228
229 static void skip_prologue_sal (struct symtab_and_line *sal);
230
231
232 /* Flag indicating that a command has proceeded the inferior past the
233    current breakpoint.  */
234
235 static int breakpoint_proceeded;
236
237 static const char *
238 bpdisp_text (enum bpdisp disp)
239 {
240   /* NOTE: the following values are a part of MI protocol and represent
241      values of 'disp' field returned when inferior stops at a breakpoint.  */
242   static char *bpdisps[] = {"del", "dstp", "dis", "keep"};
243   return bpdisps[(int) disp];
244 }
245
246 /* Prototypes for exported functions. */
247 /* If FALSE, gdb will not use hardware support for watchpoints, even
248    if such is available. */
249 static int can_use_hw_watchpoints;
250
251 static void
252 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
253                              struct cmd_list_element *c,
254                              const char *value)
255 {
256   fprintf_filtered (file, _("\
257 Debugger's willingness to use watchpoint hardware is %s.\n"),
258                     value);
259 }
260
261 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
262    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
263    for unrecognized breakpoint locations.  
264    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
265 static enum auto_boolean pending_break_support;
266 static void
267 show_pending_break_support (struct ui_file *file, int from_tty,
268                             struct cmd_list_element *c,
269                             const char *value)
270 {
271   fprintf_filtered (file, _("\
272 Debugger's behavior regarding pending breakpoints is %s.\n"),
273                     value);
274 }
275
276 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
277    set with "break" but falling in read-only memory. 
278    If 0, gdb will warn about such breakpoints, but won't automatically
279    use hardware breakpoints.  */
280 static int automatic_hardware_breakpoints;
281 static void
282 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
283                                      struct cmd_list_element *c,
284                                      const char *value)
285 {
286   fprintf_filtered (file, _("\
287 Automatic usage of hardware breakpoints is %s.\n"),
288                     value);
289 }
290
291 /* If on, gdb will keep breakpoints inserted even as inferior is
292    stopped, and immediately insert any new breakpoints.  If off, gdb
293    will insert breakpoints into inferior only when resuming it, and
294    will remove breakpoints upon stop.  If auto, GDB will behave as ON
295    if in non-stop mode, and as OFF if all-stop mode.*/
296
297 static const char always_inserted_auto[] = "auto";
298 static const char always_inserted_on[] = "on";
299 static const char always_inserted_off[] = "off";
300 static const char *always_inserted_enums[] = {
301   always_inserted_auto,
302   always_inserted_off,
303   always_inserted_on,
304   NULL
305 };
306 static const char *always_inserted_mode = always_inserted_auto;
307 static void
308 show_always_inserted_mode (struct ui_file *file, int from_tty,
309                      struct cmd_list_element *c, const char *value)
310 {
311   if (always_inserted_mode == always_inserted_auto)
312     fprintf_filtered (file, _("\
313 Always inserted breakpoint mode is %s (currently %s).\n"),
314                       value,
315                       breakpoints_always_inserted_mode () ? "on" : "off");
316   else
317     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"), value);
318 }
319
320 int
321 breakpoints_always_inserted_mode (void)
322 {
323   return (always_inserted_mode == always_inserted_on
324           || (always_inserted_mode == always_inserted_auto && non_stop));
325 }
326
327 void _initialize_breakpoint (void);
328
329 /* Are we executing breakpoint commands?  */
330 static int executing_breakpoint_commands;
331
332 /* Are overlay event breakpoints enabled? */
333 static int overlay_events_enabled;
334
335 /* Walk the following statement or block through all breakpoints.
336    ALL_BREAKPOINTS_SAFE does so even if the statment deletes the current
337    breakpoint.  */
338
339 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
340
341 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
342         for (B = breakpoint_chain;      \
343              B ? (TMP=B->next, 1): 0;   \
344              B = TMP)
345
346 /* Similar iterator for the low-level breakpoints.  SAFE variant is not
347    provided so update_global_location_list must not be called while executing
348    the block of ALL_BP_LOCATIONS.  */
349
350 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
351         for (BP_TMP = bp_location;                                      \
352              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
353              BP_TMP++)
354
355 /* Iterator for tracepoints only.  */
356
357 #define ALL_TRACEPOINTS(B)  \
358   for (B = breakpoint_chain; B; B = B->next)  \
359     if (tracepoint_type (B))
360
361 /* Chains of all breakpoints defined.  */
362
363 struct breakpoint *breakpoint_chain;
364
365 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
366
367 static struct bp_location **bp_location;
368
369 /* Number of elements of BP_LOCATION.  */
370
371 static unsigned bp_location_count;
372
373 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and ADDRESS
374    for the current elements of BP_LOCATION which get a valid result from
375    bp_location_has_shadow.  You can use it for roughly limiting the subrange of
376    BP_LOCATION to scan for shadow bytes for an address you need to read.  */
377
378 static CORE_ADDR bp_location_placed_address_before_address_max;
379
380 /* Maximum offset plus alignment between
381    bp_target_info.PLACED_ADDRESS + bp_target_info.SHADOW_LEN and ADDRESS for
382    the current elements of BP_LOCATION which get a valid result from
383    bp_location_has_shadow.  You can use it for roughly limiting the subrange of
384    BP_LOCATION to scan for shadow bytes for an address you need to read.  */
385
386 static CORE_ADDR bp_location_shadow_len_after_address_max;
387
388 /* The locations that no longer correspond to any breakpoint,
389    unlinked from bp_location array, but for which a hit
390    may still be reported by a target.  */
391 VEC(bp_location_p) *moribund_locations = NULL;
392
393 /* Number of last breakpoint made.  */
394
395 int breakpoint_count;
396
397 /* Number of last tracepoint made.  */
398
399 int tracepoint_count;
400
401 /* Return whether a breakpoint is an active enabled breakpoint.  */
402 static int
403 breakpoint_enabled (struct breakpoint *b)
404 {
405   return (b->enable_state == bp_enabled);
406 }
407
408 /* Set breakpoint count to NUM.  */
409
410 void
411 set_breakpoint_count (int num)
412 {
413   breakpoint_count = num;
414   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
415 }
416
417 /* Used in run_command to zero the hit count when a new run starts. */
418
419 void
420 clear_breakpoint_hit_counts (void)
421 {
422   struct breakpoint *b;
423
424   ALL_BREAKPOINTS (b)
425     b->hit_count = 0;
426 }
427
428 /* Encapsulate tests for different types of tracepoints.  */
429
430 static int
431 tracepoint_type (const struct breakpoint *b)
432 {
433   return (b->type == bp_tracepoint || b->type == bp_fast_tracepoint);
434 }
435   
436 /* Default address, symtab and line to put a breakpoint at
437    for "break" command with no arg.
438    if default_breakpoint_valid is zero, the other three are
439    not valid, and "break" with no arg is an error.
440
441    This set by print_stack_frame, which calls set_default_breakpoint.  */
442
443 int default_breakpoint_valid;
444 CORE_ADDR default_breakpoint_address;
445 struct symtab *default_breakpoint_symtab;
446 int default_breakpoint_line;
447 struct program_space *default_breakpoint_pspace;
448
449 \f
450 /* *PP is a string denoting a breakpoint.  Get the number of the breakpoint.
451    Advance *PP after the string and any trailing whitespace.
452
453    Currently the string can either be a number or "$" followed by the name
454    of a convenience variable.  Making it an expression wouldn't work well
455    for map_breakpoint_numbers (e.g. "4 + 5 + 6").
456
457    If the string is a NULL pointer, that denotes the last breakpoint.
458    
459    TRAILER is a character which can be found after the number; most
460    commonly this is `-'.  If you don't want a trailer, use \0.  */ 
461 static int
462 get_number_trailer (char **pp, int trailer)
463 {
464   int retval = 0;       /* default */
465   char *p = *pp;
466
467   if (p == NULL)
468     /* Empty line means refer to the last breakpoint.  */
469     return breakpoint_count;
470   else if (*p == '$')
471     {
472       /* Make a copy of the name, so we can null-terminate it
473          to pass to lookup_internalvar().  */
474       char *varname;
475       char *start = ++p;
476       LONGEST val;
477
478       while (isalnum (*p) || *p == '_')
479         p++;
480       varname = (char *) alloca (p - start + 1);
481       strncpy (varname, start, p - start);
482       varname[p - start] = '\0';
483       if (get_internalvar_integer (lookup_internalvar (varname), &val))
484         retval = (int) val;
485       else
486         {
487           printf_filtered (_("Convenience variable must have integer value.\n"));
488           retval = 0;
489         }
490     }
491   else
492     {
493       if (*p == '-')
494         ++p;
495       while (*p >= '0' && *p <= '9')
496         ++p;
497       if (p == *pp)
498         /* There is no number here.  (e.g. "cond a == b").  */
499         {
500           /* Skip non-numeric token */
501           while (*p && !isspace((int) *p))
502             ++p;
503           /* Return zero, which caller must interpret as error. */
504           retval = 0;
505         }
506       else
507         retval = atoi (*pp);
508     }
509   if (!(isspace (*p) || *p == '\0' || *p == trailer))
510     {
511       /* Trailing junk: return 0 and let caller print error msg. */
512       while (!(isspace (*p) || *p == '\0' || *p == trailer))
513         ++p;
514       retval = 0;
515     }
516   while (isspace (*p))
517     p++;
518   *pp = p;
519   return retval;
520 }
521
522
523 /* Like get_number_trailer, but don't allow a trailer.  */
524 int
525 get_number (char **pp)
526 {
527   return get_number_trailer (pp, '\0');
528 }
529
530 /* Parse a number or a range.
531  * A number will be of the form handled by get_number.
532  * A range will be of the form <number1> - <number2>, and 
533  * will represent all the integers between number1 and number2,
534  * inclusive.
535  *
536  * While processing a range, this fuction is called iteratively;
537  * At each call it will return the next value in the range.
538  *
539  * At the beginning of parsing a range, the char pointer PP will
540  * be advanced past <number1> and left pointing at the '-' token.
541  * Subsequent calls will not advance the pointer until the range
542  * is completed.  The call that completes the range will advance
543  * pointer PP past <number2>.
544  */
545
546 int 
547 get_number_or_range (char **pp)
548 {
549   static int last_retval, end_value;
550   static char *end_ptr;
551   static int in_range = 0;
552
553   if (**pp != '-')
554     {
555       /* Default case: pp is pointing either to a solo number, 
556          or to the first number of a range.  */
557       last_retval = get_number_trailer (pp, '-');
558       if (**pp == '-')
559         {
560           char **temp;
561
562           /* This is the start of a range (<number1> - <number2>).
563              Skip the '-', parse and remember the second number,
564              and also remember the end of the final token.  */
565
566           temp = &end_ptr; 
567           end_ptr = *pp + 1; 
568           while (isspace ((int) *end_ptr))
569             end_ptr++;  /* skip white space */
570           end_value = get_number (temp);
571           if (end_value < last_retval) 
572             {
573               error (_("inverted range"));
574             }
575           else if (end_value == last_retval)
576             {
577               /* degenerate range (number1 == number2).  Advance the
578                  token pointer so that the range will be treated as a
579                  single number.  */ 
580               *pp = end_ptr;
581             }
582           else
583             in_range = 1;
584         }
585     }
586   else if (! in_range)
587     error (_("negative value"));
588   else
589     {
590       /* pp points to the '-' that betokens a range.  All
591          number-parsing has already been done.  Return the next
592          integer value (one greater than the saved previous value).
593          Do not advance the token pointer 'pp' until the end of range
594          is reached.  */
595
596       if (++last_retval == end_value)
597         {
598           /* End of range reached; advance token pointer.  */
599           *pp = end_ptr;
600           in_range = 0;
601         }
602     }
603   return last_retval;
604 }
605
606 /* Return the breakpoint with the specified number, or NULL
607    if the number does not refer to an existing breakpoint.  */
608
609 struct breakpoint *
610 get_breakpoint (int num)
611 {
612   struct breakpoint *b;
613
614   ALL_BREAKPOINTS (b)
615     if (b->number == num)
616       return b;
617   
618   return NULL;
619 }
620
621 \f
622 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
623
624 static void
625 condition_command (char *arg, int from_tty)
626 {
627   struct breakpoint *b;
628   char *p;
629   int bnum;
630
631   if (arg == 0)
632     error_no_arg (_("breakpoint number"));
633
634   p = arg;
635   bnum = get_number (&p);
636   if (bnum == 0)
637     error (_("Bad breakpoint argument: '%s'"), arg);
638
639   ALL_BREAKPOINTS (b)
640     if (b->number == bnum)
641       {
642         struct bp_location *loc = b->loc;
643         for (; loc; loc = loc->next)
644           {
645             xfree (loc->cond);
646             loc->cond = NULL;
647           }
648         xfree (b->cond_string);
649         b->cond_string = NULL;
650         xfree (b->cond_exp);
651         b->cond_exp = NULL;
652
653         if (*p == 0)
654           {
655             if (from_tty)
656               printf_filtered (_("Breakpoint %d now unconditional.\n"), bnum);
657           }
658         else
659           {
660             arg = p;
661             /* I don't know if it matters whether this is the string the user
662                typed in or the decompiled expression.  */
663             b->cond_string = xstrdup (arg);
664             b->condition_not_parsed = 0;
665
666             if (is_watchpoint (b))
667               {
668                 innermost_block = NULL;
669                 arg = p;
670                 b->cond_exp = parse_exp_1 (&arg, 0, 0);
671                 if (*arg)
672                   error (_("Junk at end of expression"));
673                 b->cond_exp_valid_block = innermost_block;
674               }
675             else
676               {
677                 for (loc = b->loc; loc; loc = loc->next)
678                   {
679                     arg = p;
680                     loc->cond =
681                       parse_exp_1 (&arg, block_for_pc (loc->address), 0);
682                     if (*arg)
683                       error (_("Junk at end of expression"));
684                   }
685               }
686           }
687         breakpoints_changed ();
688         observer_notify_breakpoint_modified (b->number);
689         return;
690       }
691
692   error (_("No breakpoint number %d."), bnum);
693 }
694
695 /* Check that COMMAND do not contain commands that are suitable
696    only for tracepoints and not suitable for ordinary breakpoints.
697    Throw if any such commands is found.
698 */
699 static void
700 check_no_tracepoint_commands (struct command_line *commands)
701 {
702   struct command_line *c;
703   for (c = commands; c; c = c->next)
704     {
705       int i;
706
707       if (c->control_type == while_stepping_control)
708         error (_("The 'while-stepping' command can only be used for tracepoints"));
709
710       for (i = 0; i < c->body_count; ++i)
711         check_no_tracepoint_commands ((c->body_list)[i]);
712
713       /* Not that command parsing removes leading whitespace and comment
714          lines and also empty lines. So, we only need to check for
715          command directly.  */
716       if (strstr (c->line, "collect ") == c->line)
717         error (_("The 'collect' command can only be used for tracepoints"));
718
719       if (strstr (c->line, "eval ") == c->line)
720         error (_("The 'eval' command can only be used for tracepoints"));
721     }
722 }
723
724 int
725 breakpoint_is_tracepoint (const struct breakpoint *b)
726 {
727   switch (b->type)
728     {
729     case bp_tracepoint:
730     case bp_fast_tracepoint:
731       return 1;
732     default:
733       return 0;
734
735     }
736 }
737
738 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
739    validate that only allowed commands are included.
740 */
741
742 void
743 breakpoint_set_commands (struct breakpoint *b, struct command_line *commands)
744 {
745   if (breakpoint_is_tracepoint (b))
746     {
747       /* We need to verify that each top-level element of commands
748          is valid for tracepoints, that there's at most one while-stepping
749          element, and that while-stepping's body has valid tracing commands
750          excluding nested while-stepping.  */
751       struct command_line *c;
752       struct command_line *while_stepping = 0;
753       for (c = commands; c; c = c->next)
754         {
755           char *l = c->line;
756           if (c->control_type == while_stepping_control)
757             {
758               if (b->type == bp_fast_tracepoint)
759                 error (_("The 'while-stepping' command cannot be used for fast tracepoint"));
760
761               if (while_stepping)
762                 error (_("The 'while-stepping' command can be used only once"));
763               else
764                 while_stepping = c;
765             }
766         }
767       if (while_stepping)
768         {
769           struct command_line *c2;
770
771           gdb_assert (while_stepping->body_count == 1);
772           c2 = while_stepping->body_list[0];
773           for (; c2; c2 = c2->next)
774             {
775               char *l = c2->line;
776               if (c2->control_type == while_stepping_control)
777                 error (_("The 'while-stepping' command cannot be nested"));
778             }
779         }
780     }
781   else
782     {
783       check_no_tracepoint_commands (commands);
784     }
785
786   free_command_lines (&b->commands);
787   b->commands = commands;
788   breakpoints_changed ();
789   observer_notify_breakpoint_modified (b->number);
790 }
791
792 void check_tracepoint_command (char *line, void *closure)
793 {
794   struct breakpoint *b = closure;
795   validate_actionline (&line, b);
796 }
797
798 static void
799 commands_command (char *arg, int from_tty)
800 {
801   struct breakpoint *b;
802   char *p;
803   int bnum;
804   struct command_line *l;
805
806   /* If we allowed this, we would have problems with when to
807      free the storage, if we change the commands currently
808      being read from.  */
809
810   if (executing_breakpoint_commands)
811     error (_("Can't use the \"commands\" command among a breakpoint's commands."));
812
813   p = arg;
814   bnum = get_number (&p);
815
816   if (p && *p)
817     error (_("Unexpected extra arguments following breakpoint number."));
818
819   ALL_BREAKPOINTS (b)
820     if (b->number == bnum)
821       {
822         char *tmpbuf = xstrprintf ("Type commands for when breakpoint %d is hit, one per line.", 
823                                  bnum);
824         struct cleanup *cleanups = make_cleanup (xfree, tmpbuf);
825
826         if (breakpoint_is_tracepoint (b))
827           l = read_command_lines (tmpbuf, from_tty, 1,
828                                   check_tracepoint_command, b);
829         else
830           l = read_command_lines (tmpbuf, from_tty, 1, 0, 0);
831         do_cleanups (cleanups);
832         breakpoint_set_commands (b, l);
833         return;
834     }
835   error (_("No breakpoint number %d."), bnum);
836 }
837
838 /* Like commands_command, but instead of reading the commands from
839    input stream, takes them from an already parsed command structure.
840
841    This is used by cli-script.c to DTRT with breakpoint commands
842    that are part of if and while bodies.  */
843 enum command_control_type
844 commands_from_control_command (char *arg, struct command_line *cmd)
845 {
846   struct breakpoint *b;
847   char *p;
848   int bnum;
849
850   /* If we allowed this, we would have problems with when to
851      free the storage, if we change the commands currently
852      being read from.  */
853
854   if (executing_breakpoint_commands)
855     error (_("Can't use the \"commands\" command among a breakpoint's commands."));
856
857   /* An empty string for the breakpoint number means the last
858      breakpoint, but get_number expects a NULL pointer.  */
859   if (arg && !*arg)
860     p = NULL;
861   else
862     p = arg;
863   bnum = get_number (&p);
864
865   if (p && *p)
866     error (_("Unexpected extra arguments following breakpoint number."));
867
868   ALL_BREAKPOINTS (b)
869     if (b->number == bnum)
870       {
871         free_command_lines (&b->commands);
872         if (cmd->body_count != 1)
873           error (_("Invalid \"commands\" block structure."));
874         /* We need to copy the commands because if/while will free the
875            list after it finishes execution.  */
876         b->commands = copy_command_lines (cmd->body_list[0]);
877         breakpoints_changed ();
878         observer_notify_breakpoint_modified (b->number);
879         return simple_control;
880       }
881   error (_("No breakpoint number %d."), bnum);
882 }
883
884 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
885
886 static int
887 bp_location_has_shadow (struct bp_location *bl)
888 {
889   if (bl->loc_type != bp_loc_software_breakpoint)
890     return 0;
891   if (!bl->inserted)
892     return 0;
893   if (bl->target_info.shadow_len == 0)
894     /* bp isn't valid, or doesn't shadow memory.  */
895     return 0;
896   return 1;
897 }
898
899 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
900    by replacing any memory breakpoints with their shadowed contents.
901
902    The range of shadowed area by each bp_location is:
903      b->address - bp_location_placed_address_before_address_max
904      up to b->address + bp_location_shadow_len_after_address_max
905    The range we were requested to resolve shadows for is:
906      memaddr ... memaddr + len
907    Thus the safe cutoff boundaries for performance optimization are
908      memaddr + len <= b->address - bp_location_placed_address_before_address_max
909    and:
910      b->address + bp_location_shadow_len_after_address_max <= memaddr  */
911
912 void
913 breakpoint_restore_shadows (gdb_byte *buf, ULONGEST memaddr, LONGEST len)
914 {
915   /* Left boundary, right boundary and median element of our binary search.  */
916   unsigned bc_l, bc_r, bc;
917
918   /* Find BC_L which is a leftmost element which may affect BUF content.  It is
919      safe to report lower value but a failure to report higher one.  */
920
921   bc_l = 0;
922   bc_r = bp_location_count;
923   while (bc_l + 1 < bc_r)
924     {
925       struct bp_location *b;
926
927       bc = (bc_l + bc_r) / 2;
928       b = bp_location[bc];
929
930       /* Check first B->ADDRESS will not overflow due to the added constant.
931          Then advance the left boundary only if we are sure the BC element can
932          in no way affect the BUF content (MEMADDR to MEMADDR + LEN range).
933
934          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety offset so that
935          we cannot miss a breakpoint with its shadow range tail still reaching
936          MEMADDR.  */
937
938       if (b->address + bp_location_shadow_len_after_address_max >= b->address
939           && b->address + bp_location_shadow_len_after_address_max <= memaddr)
940         bc_l = bc;
941       else
942         bc_r = bc;
943     }
944
945   /* Now do full processing of the found relevant range of elements.  */
946
947   for (bc = bc_l; bc < bp_location_count; bc++)
948   {
949     struct bp_location *b = bp_location[bc];
950     CORE_ADDR bp_addr = 0;
951     int bp_size = 0;
952     int bptoffset = 0;
953
954     if (b->owner->type == bp_none)
955       warning (_("reading through apparently deleted breakpoint #%d?"),
956               b->owner->number);
957
958     /* Performance optimization: any futher element can no longer affect BUF
959        content.  */
960
961     if (b->address >= bp_location_placed_address_before_address_max
962         && memaddr + len <= b->address
963                             - bp_location_placed_address_before_address_max)
964       break;
965
966     if (!bp_location_has_shadow (b))
967       continue;
968     if (!breakpoint_address_match (b->target_info.placed_address_space, 0,
969                                    current_program_space->aspace, 0))
970       continue;
971
972     /* Addresses and length of the part of the breakpoint that
973        we need to copy.  */
974     bp_addr = b->target_info.placed_address;
975     bp_size = b->target_info.shadow_len;
976
977     if (bp_addr + bp_size <= memaddr)
978       /* The breakpoint is entirely before the chunk of memory we
979          are reading.  */
980       continue;
981
982     if (bp_addr >= memaddr + len)
983       /* The breakpoint is entirely after the chunk of memory we are
984          reading. */
985       continue;
986
987     /* Offset within shadow_contents.  */
988     if (bp_addr < memaddr)
989       {
990         /* Only copy the second part of the breakpoint.  */
991         bp_size -= memaddr - bp_addr;
992         bptoffset = memaddr - bp_addr;
993         bp_addr = memaddr;
994       }
995
996     if (bp_addr + bp_size > memaddr + len)
997       {
998         /* Only copy the first part of the breakpoint.  */
999         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1000       }
1001
1002     memcpy (buf + bp_addr - memaddr,
1003             b->target_info.shadow_contents + bptoffset, bp_size);
1004   }
1005 }
1006 \f
1007
1008 /* A wrapper function for inserting catchpoints.  */
1009 static void
1010 insert_catchpoint (struct ui_out *uo, void *args)
1011 {
1012   struct breakpoint *b = (struct breakpoint *) args;
1013   int val = -1;
1014
1015   gdb_assert (b->type == bp_catchpoint);
1016   gdb_assert (b->ops != NULL && b->ops->insert != NULL);
1017
1018   b->ops->insert (b);
1019 }
1020
1021 /* Return true if BPT is of any hardware watchpoint kind.  */
1022
1023 static int
1024 is_hardware_watchpoint (struct breakpoint *bpt)
1025 {
1026   return (bpt->type == bp_hardware_watchpoint
1027           || bpt->type == bp_read_watchpoint
1028           || bpt->type == bp_access_watchpoint);
1029 }
1030
1031 /* Return true if BPT is of any watchpoint kind, hardware or
1032    software.  */
1033
1034 static int
1035 is_watchpoint (struct breakpoint *bpt)
1036 {
1037   return (is_hardware_watchpoint (bpt)
1038           || bpt->type == bp_watchpoint);
1039 }
1040
1041 /* Find the current value of a watchpoint on EXP.  Return the value in
1042    *VALP and *RESULTP and the chain of intermediate and final values
1043    in *VAL_CHAIN.  RESULTP and VAL_CHAIN may be NULL if the caller does
1044    not need them.
1045
1046    If a memory error occurs while evaluating the expression, *RESULTP will
1047    be set to NULL.  *RESULTP may be a lazy value, if the result could
1048    not be read from memory.  It is used to determine whether a value
1049    is user-specified (we should watch the whole value) or intermediate
1050    (we should watch only the bit used to locate the final value).
1051
1052    If the final value, or any intermediate value, could not be read
1053    from memory, *VALP will be set to NULL.  *VAL_CHAIN will still be
1054    set to any referenced values.  *VALP will never be a lazy value.
1055    This is the value which we store in struct breakpoint.
1056
1057    If VAL_CHAIN is non-NULL, *VAL_CHAIN will be released from the
1058    value chain.  The caller must free the values individually.  If
1059    VAL_CHAIN is NULL, all generated values will be left on the value
1060    chain.  */
1061
1062 static void
1063 fetch_watchpoint_value (struct expression *exp, struct value **valp,
1064                         struct value **resultp, struct value **val_chain)
1065 {
1066   struct value *mark, *new_mark, *result;
1067   volatile struct gdb_exception ex;
1068
1069   *valp = NULL;
1070   if (resultp)
1071     *resultp = NULL;
1072   if (val_chain)
1073     *val_chain = NULL;
1074
1075   /* Evaluate the expression.  */
1076   mark = value_mark ();
1077   result = NULL;
1078
1079   TRY_CATCH (ex, RETURN_MASK_ALL)
1080     {
1081       result = evaluate_expression (exp);
1082     }
1083   if (ex.reason < 0)
1084     {
1085       /* Ignore memory errors, we want watchpoints pointing at
1086          inaccessible memory to still be created; otherwise, throw the
1087          error to some higher catcher.  */
1088       switch (ex.error)
1089         {
1090         case MEMORY_ERROR:
1091           break;
1092         default:
1093           throw_exception (ex);
1094           break;
1095         }
1096     }
1097
1098   new_mark = value_mark ();
1099   if (mark == new_mark)
1100     return;
1101   if (resultp)
1102     *resultp = result;
1103
1104   /* Make sure it's not lazy, so that after the target stops again we
1105      have a non-lazy previous value to compare with.  */
1106   if (result != NULL
1107       && (!value_lazy (result) || gdb_value_fetch_lazy (result)))
1108     *valp = result;
1109
1110   if (val_chain)
1111     {
1112       /* Return the chain of intermediate values.  We use this to
1113          decide which addresses to watch.  */
1114       *val_chain = new_mark;
1115       value_release_to_mark (mark);
1116     }
1117 }
1118
1119 /* Assuming that B is a watchpoint: returns true if the current thread
1120    and its running state are safe to evaluate or update watchpoint B.
1121    Watchpoints on local expressions need to be evaluated in the
1122    context of the thread that was current when the watchpoint was
1123    created, and, that thread needs to be stopped to be able to select
1124    the correct frame context.  Watchpoints on global expressions can
1125    be evaluated on any thread, and in any state.  It is presently left
1126    to the target allowing memory accesses when threads are
1127    running.  */
1128
1129 static int
1130 watchpoint_in_thread_scope (struct breakpoint *b)
1131 {
1132   return (ptid_equal (b->watchpoint_thread, null_ptid)
1133           || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1134               && !is_executing (inferior_ptid)));
1135 }
1136
1137 /* Assuming that B is a watchpoint:
1138    - Reparse watchpoint expression, if REPARSE is non-zero
1139    - Evaluate expression and store the result in B->val
1140    - Evaluate the condition if there is one, and store the result
1141      in b->loc->cond.
1142    - Update the list of values that must be watched in B->loc.
1143
1144    If the watchpoint disposition is disp_del_at_next_stop, then do nothing.
1145    If this is local watchpoint that is out of scope, delete it.
1146
1147    Even with `set breakpoint always-inserted on' the watchpoints are removed
1148    + inserted on each stop here.  Normal breakpoints must never be removed
1149    because they might be missed by a running thread when debugging in non-stop
1150    mode.  On the other hand, hardware watchpoints (is_hardware_watchpoint;
1151    processed here) are specific to each LWP since they are stored in each LWP's
1152    hardware debug registers.  Therefore, such LWP must be stopped first in
1153    order to be able to modify its hardware watchpoints.
1154
1155    Hardware watchpoints must be reset exactly once after being presented to the
1156    user.  It cannot be done sooner, because it would reset the data used to
1157    present the watchpoint hit to the user.  And it must not be done later
1158    because it could display the same single watchpoint hit during multiple GDB
1159    stops.  Note that the latter is relevant only to the hardware watchpoint
1160    types bp_read_watchpoint and bp_access_watchpoint.  False hit by
1161    bp_hardware_watchpoint is not user-visible - its hit is suppressed if the
1162    memory content has not changed.
1163
1164    The following constraints influence the location where we can reset hardware
1165    watchpoints:
1166
1167    * target_stopped_by_watchpoint and target_stopped_data_address are called
1168      several times when GDB stops.
1169
1170    [linux]
1171    * Multiple hardware watchpoints can be hit at the same time, causing GDB to
1172      stop.  GDB only presents one hardware watchpoint hit at a time as the
1173      reason for stopping, and all the other hits are presented later, one after
1174      the other, each time the user requests the execution to be resumed.
1175      Execution is not resumed for the threads still having pending hit event
1176      stored in LWP_INFO->STATUS.  While the watchpoint is already removed from
1177      the inferior on the first stop the thread hit event is kept being reported
1178      from its cached value by linux_nat_stopped_data_address until the real
1179      thread resume happens after the watchpoint gets presented and thus its
1180      LWP_INFO->STATUS gets reset.
1181
1182    Therefore the hardware watchpoint hit can get safely reset on the watchpoint
1183    removal from inferior.  */
1184
1185 static void
1186 update_watchpoint (struct breakpoint *b, int reparse)
1187 {
1188   int within_current_scope;
1189   struct frame_id saved_frame_id;
1190   struct bp_location *loc;
1191   int frame_saved;
1192   bpstat bs;
1193
1194   /* If this is a local watchpoint, we only want to check if the
1195      watchpoint frame is in scope if the current thread is the thread
1196      that was used to create the watchpoint.  */
1197   if (!watchpoint_in_thread_scope (b))
1198     return;
1199
1200   /* We don't free locations.  They are stored in bp_location array and
1201      update_global_locations will eventually delete them and remove
1202      breakpoints if needed.  */
1203   b->loc = NULL;
1204
1205   if (b->disposition == disp_del_at_next_stop)
1206     return;
1207  
1208   frame_saved = 0;
1209
1210   /* Determine if the watchpoint is within scope.  */
1211   if (b->exp_valid_block == NULL)
1212     within_current_scope = 1;
1213   else
1214     {
1215       struct frame_info *fi;
1216
1217       /* Save the current frame's ID so we can restore it after
1218          evaluating the watchpoint expression on its own frame.  */
1219       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1220          took a frame parameter, so that we didn't have to change the
1221          selected frame.  */
1222       frame_saved = 1;
1223       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1224
1225       fi = frame_find_by_id (b->watchpoint_frame);
1226       within_current_scope = (fi != NULL);
1227       if (within_current_scope)
1228         select_frame (fi);
1229     }
1230
1231   if (within_current_scope && reparse)
1232     {
1233       char *s;
1234       if (b->exp)
1235         {
1236           xfree (b->exp);
1237           b->exp = NULL;
1238         }
1239       s = b->exp_string;
1240       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1241       /* If the meaning of expression itself changed, the old value is
1242          no longer relevant.  We don't want to report a watchpoint hit
1243          to the user when the old value and the new value may actually
1244          be completely different objects.  */
1245       value_free (b->val);
1246       b->val = NULL;
1247       b->val_valid = 0;
1248
1249       /* Note that unlike with breakpoints, the watchpoint's condition
1250          expression is stored in the breakpoint object, not in the
1251          locations (re)created below.  */
1252       if (b->cond_string != NULL)
1253         {
1254           if (b->cond_exp != NULL)
1255             {
1256               xfree (b->cond_exp);
1257               b->cond_exp = NULL;
1258             }
1259
1260           s = b->cond_string;
1261           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1262         }
1263     }
1264
1265   /* If we failed to parse the expression, for example because
1266      it refers to a global variable in a not-yet-loaded shared library,
1267      don't try to insert watchpoint.  We don't automatically delete
1268      such watchpoint, though, since failure to parse expression
1269      is different from out-of-scope watchpoint.  */
1270   if ( !target_has_execution)
1271     {
1272       /* Without execution, memory can't change.  No use to try and
1273          set watchpoint locations.  The watchpoint will be reset when
1274          the target gains execution, through breakpoint_re_set.  */
1275     }
1276   else if (within_current_scope && b->exp)
1277     {
1278       struct value *val_chain, *v, *result, *next;
1279       struct program_space *frame_pspace;
1280
1281       fetch_watchpoint_value (b->exp, &v, &result, &val_chain);
1282
1283       /* Avoid setting b->val if it's already set.  The meaning of
1284          b->val is 'the last value' user saw, and we should update
1285          it only if we reported that last value to user.  As it
1286          happens, the code that reports it updates b->val directly.  */
1287       if (!b->val_valid)
1288         {
1289           b->val = v;
1290           b->val_valid = 1;
1291         }
1292
1293         /* Change the type of breakpoint between hardware assisted or an
1294            ordinary watchpoint depending on the hardware support and free
1295            hardware slots.  REPARSE is set when the inferior is started.  */
1296         if ((b->type == bp_watchpoint || b->type == bp_hardware_watchpoint)
1297             && reparse)
1298           {
1299             int i, mem_cnt, other_type_used;
1300
1301             /* We need to determine how many resources are already used
1302                for all other hardware watchpoints to see if we still have
1303                enough resources to also fit this watchpoint in as well.
1304                To avoid the hw_watchpoint_used_count call below from counting
1305                this watchpoint, make sure that it is marked as a software
1306                watchpoint.  */
1307             b->type = bp_watchpoint;
1308             i = hw_watchpoint_used_count (bp_hardware_watchpoint,
1309                                           &other_type_used);
1310             mem_cnt = can_use_hardware_watchpoint (val_chain);
1311
1312             if (!mem_cnt)
1313               b->type = bp_watchpoint;
1314             else
1315               {
1316                 int target_resources_ok = target_can_use_hardware_watchpoint
1317                   (bp_hardware_watchpoint, i + mem_cnt, other_type_used);
1318                 if (target_resources_ok <= 0)
1319                   b->type = bp_watchpoint;
1320                 else
1321                   b->type = bp_hardware_watchpoint;
1322               }
1323           }
1324
1325       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1326
1327       /* Look at each value on the value chain.  */
1328       for (v = val_chain; v; v = next)
1329         {
1330           /* If it's a memory location, and GDB actually needed
1331              its contents to evaluate the expression, then we
1332              must watch it.  If the first value returned is
1333              still lazy, that means an error occurred reading it;
1334              watch it anyway in case it becomes readable.  */
1335           if (VALUE_LVAL (v) == lval_memory
1336               && (v == val_chain || ! value_lazy (v)))
1337             {
1338               struct type *vtype = check_typedef (value_type (v));
1339
1340               /* We only watch structs and arrays if user asked
1341                  for it explicitly, never if they just happen to
1342                  appear in the middle of some value chain.  */
1343               if (v == result
1344                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1345                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1346                 {
1347                   CORE_ADDR addr;
1348                   int len, type;
1349                   struct bp_location *loc, **tmp;
1350
1351                   addr = value_address (v);
1352                   len = TYPE_LENGTH (value_type (v));
1353                   type = hw_write;
1354                   if (b->type == bp_read_watchpoint)
1355                     type = hw_read;
1356                   else if (b->type == bp_access_watchpoint)
1357                     type = hw_access;
1358                   
1359                   loc = allocate_bp_location (b);
1360                   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
1361                     ;
1362                   *tmp = loc;
1363                   loc->gdbarch = get_type_arch (value_type (v));
1364
1365                   loc->pspace = frame_pspace;
1366                   loc->address = addr;
1367                   loc->length = len;
1368                   loc->watchpoint_type = type;
1369                 }
1370             }
1371
1372           next = value_next (v);
1373           if (v != b->val)
1374             value_free (v);
1375         }
1376
1377       /* If a software watchpoint is not watching any memory, then the
1378          above left it without any location set up.  But,
1379          bpstat_stop_status requires a location to be able to report
1380          stops, so make sure there's at least a dummy one.  */
1381       if (b->type == bp_watchpoint && b->loc == NULL)
1382         {
1383           b->loc = allocate_bp_location (b);
1384           b->loc->pspace = frame_pspace;
1385           b->loc->address = -1;
1386           b->loc->length = -1;
1387           b->loc->watchpoint_type = -1;
1388         }
1389     }
1390   else if (!within_current_scope)
1391     {
1392       printf_filtered (_("\
1393 Watchpoint %d deleted because the program has left the block \n\
1394 in which its expression is valid.\n"),
1395                        b->number);
1396       if (b->related_breakpoint)
1397         {
1398           b->related_breakpoint->disposition = disp_del_at_next_stop;
1399           b->related_breakpoint->related_breakpoint = NULL;
1400           b->related_breakpoint= NULL;
1401         }
1402       b->disposition = disp_del_at_next_stop;
1403     }
1404
1405   /* Restore the selected frame.  */
1406   if (frame_saved)
1407     select_frame (frame_find_by_id (saved_frame_id));
1408 }
1409
1410
1411 /* Returns 1 iff breakpoint location should be
1412    inserted in the inferior.  */
1413 static int
1414 should_be_inserted (struct bp_location *bpt)
1415 {
1416   if (!breakpoint_enabled (bpt->owner))
1417     return 0;
1418
1419   if (bpt->owner->disposition == disp_del_at_next_stop)
1420     return 0;
1421
1422   if (!bpt->enabled || bpt->shlib_disabled || bpt->duplicate)
1423     return 0;
1424
1425   /* This is set for example, when we're attached to the parent of a
1426      vfork, and have detached from the child.  The child is running
1427      free, and we expect it to do an exec or exit, at which point the
1428      OS makes the parent schedulable again (and the target reports
1429      that the vfork is done).  Until the child is done with the shared
1430      memory region, do not insert breakpoints in the parent, otherwise
1431      the child could still trip on the parent's breakpoints.  Since
1432      the parent is blocked anyway, it won't miss any breakpoint.  */
1433   if (bpt->pspace->breakpoints_not_allowed)
1434     return 0;
1435
1436   /* Tracepoints are inserted by the target at a time of its choosing,
1437      not by us.  */
1438   if (tracepoint_type (bpt->owner))
1439     return 0;
1440
1441   return 1;
1442 }
1443
1444 /* Insert a low-level "breakpoint" of some type.  BPT is the breakpoint.
1445    Any error messages are printed to TMP_ERROR_STREAM; and DISABLED_BREAKS,
1446    and HW_BREAKPOINT_ERROR are used to report problems.
1447
1448    NOTE drow/2003-09-09: This routine could be broken down to an object-style
1449    method for each breakpoint or catchpoint type.  */
1450 static int
1451 insert_bp_location (struct bp_location *bpt,
1452                     struct ui_file *tmp_error_stream,
1453                     int *disabled_breaks,
1454                     int *hw_breakpoint_error)
1455 {
1456   int val = 0;
1457
1458   if (!should_be_inserted (bpt) || bpt->inserted)
1459     return 0;
1460
1461   /* Initialize the target-specific information.  */
1462   memset (&bpt->target_info, 0, sizeof (bpt->target_info));
1463   bpt->target_info.placed_address = bpt->address;
1464   bpt->target_info.placed_address_space = bpt->pspace->aspace;
1465
1466   if (bpt->loc_type == bp_loc_software_breakpoint
1467       || bpt->loc_type == bp_loc_hardware_breakpoint)
1468     {
1469       if (bpt->owner->type != bp_hardware_breakpoint)
1470         {
1471           /* If the explicitly specified breakpoint type
1472              is not hardware breakpoint, check the memory map to see
1473              if the breakpoint address is in read only memory or not.
1474              Two important cases are:
1475              - location type is not hardware breakpoint, memory
1476              is readonly.  We change the type of the location to
1477              hardware breakpoint.
1478              - location type is hardware breakpoint, memory is read-write.
1479              This means we've previously made the location hardware one, but
1480              then the memory map changed, so we undo.
1481              
1482              When breakpoints are removed, remove_breakpoints will
1483              use location types we've just set here, the only possible
1484              problem is that memory map has changed during running program,
1485              but it's not going to work anyway with current gdb.  */
1486           struct mem_region *mr 
1487             = lookup_mem_region (bpt->target_info.placed_address);
1488           
1489           if (mr)
1490             {
1491               if (automatic_hardware_breakpoints)
1492                 {
1493                   int changed = 0;
1494                   enum bp_loc_type new_type;
1495                   
1496                   if (mr->attrib.mode != MEM_RW)
1497                     new_type = bp_loc_hardware_breakpoint;
1498                   else 
1499                     new_type = bp_loc_software_breakpoint;
1500                   
1501                   if (new_type != bpt->loc_type)
1502                     {
1503                       static int said = 0;
1504                       bpt->loc_type = new_type;
1505                       if (!said)
1506                         {
1507                           fprintf_filtered (gdb_stdout, _("\
1508 Note: automatically using hardware breakpoints for read-only addresses.\n"));
1509                           said = 1;
1510                         }
1511                     }
1512                 }
1513               else if (bpt->loc_type == bp_loc_software_breakpoint
1514                        && mr->attrib.mode != MEM_RW)        
1515                 warning (_("cannot set software breakpoint at readonly address %s"),
1516                          paddress (bpt->gdbarch, bpt->address));
1517             }
1518         }
1519         
1520       /* First check to see if we have to handle an overlay.  */
1521       if (overlay_debugging == ovly_off
1522           || bpt->section == NULL
1523           || !(section_is_overlay (bpt->section)))
1524         {
1525           /* No overlay handling: just set the breakpoint.  */
1526
1527           if (bpt->loc_type == bp_loc_hardware_breakpoint)
1528             val = target_insert_hw_breakpoint (bpt->gdbarch,
1529                                                &bpt->target_info);
1530           else
1531             val = target_insert_breakpoint (bpt->gdbarch,
1532                                             &bpt->target_info);
1533         }
1534       else
1535         {
1536           /* This breakpoint is in an overlay section.  
1537              Shall we set a breakpoint at the LMA?  */
1538           if (!overlay_events_enabled)
1539             {
1540               /* Yes -- overlay event support is not active, 
1541                  so we must try to set a breakpoint at the LMA.
1542                  This will not work for a hardware breakpoint.  */
1543               if (bpt->loc_type == bp_loc_hardware_breakpoint)
1544                 warning (_("hardware breakpoint %d not supported in overlay!"),
1545                          bpt->owner->number);
1546               else
1547                 {
1548                   CORE_ADDR addr = overlay_unmapped_address (bpt->address,
1549                                                              bpt->section);
1550                   /* Set a software (trap) breakpoint at the LMA.  */
1551                   bpt->overlay_target_info = bpt->target_info;
1552                   bpt->overlay_target_info.placed_address = addr;
1553                   val = target_insert_breakpoint (bpt->gdbarch,
1554                                                   &bpt->overlay_target_info);
1555                   if (val != 0)
1556                     fprintf_unfiltered (tmp_error_stream,
1557                                         "Overlay breakpoint %d failed: in ROM?\n",
1558                                         bpt->owner->number);
1559                 }
1560             }
1561           /* Shall we set a breakpoint at the VMA? */
1562           if (section_is_mapped (bpt->section))
1563             {
1564               /* Yes.  This overlay section is mapped into memory.  */
1565               if (bpt->loc_type == bp_loc_hardware_breakpoint)
1566                 val = target_insert_hw_breakpoint (bpt->gdbarch,
1567                                                    &bpt->target_info);
1568               else
1569                 val = target_insert_breakpoint (bpt->gdbarch,
1570                                                 &bpt->target_info);
1571             }
1572           else
1573             {
1574               /* No.  This breakpoint will not be inserted.  
1575                  No error, but do not mark the bp as 'inserted'.  */
1576               return 0;
1577             }
1578         }
1579
1580       if (val)
1581         {
1582           /* Can't set the breakpoint.  */
1583           if (solib_name_from_address (bpt->pspace, bpt->address))
1584             {
1585               /* See also: disable_breakpoints_in_shlibs. */
1586               val = 0;
1587               bpt->shlib_disabled = 1;
1588               if (!*disabled_breaks)
1589                 {
1590                   fprintf_unfiltered (tmp_error_stream, 
1591                                       "Cannot insert breakpoint %d.\n", 
1592                                       bpt->owner->number);
1593                   fprintf_unfiltered (tmp_error_stream, 
1594                                       "Temporarily disabling shared library breakpoints:\n");
1595                 }
1596               *disabled_breaks = 1;
1597               fprintf_unfiltered (tmp_error_stream,
1598                                   "breakpoint #%d\n", bpt->owner->number);
1599             }
1600           else
1601             {
1602               if (bpt->loc_type == bp_loc_hardware_breakpoint)
1603                 {
1604                   *hw_breakpoint_error = 1;
1605                   fprintf_unfiltered (tmp_error_stream, 
1606                                       "Cannot insert hardware breakpoint %d.\n",
1607                                       bpt->owner->number);
1608                 }
1609               else
1610                 {
1611                   fprintf_unfiltered (tmp_error_stream, 
1612                                       "Cannot insert breakpoint %d.\n", 
1613                                       bpt->owner->number);
1614                   fprintf_filtered (tmp_error_stream, 
1615                                     "Error accessing memory address ");
1616                   fputs_filtered (paddress (bpt->gdbarch, bpt->address),
1617                                   tmp_error_stream);
1618                   fprintf_filtered (tmp_error_stream, ": %s.\n",
1619                                     safe_strerror (val));
1620                 }
1621
1622             }
1623         }
1624       else
1625         bpt->inserted = 1;
1626
1627       return val;
1628     }
1629
1630   else if (bpt->loc_type == bp_loc_hardware_watchpoint
1631            /* NOTE drow/2003-09-08: This state only exists for removing
1632               watchpoints.  It's not clear that it's necessary... */
1633            && bpt->owner->disposition != disp_del_at_next_stop)
1634     {
1635       val = target_insert_watchpoint (bpt->address,
1636                                       bpt->length,
1637                                       bpt->watchpoint_type);
1638
1639       /* If trying to set a read-watchpoint, and it turns out it's not
1640          supported, try emulating one with an access watchpoint.  */
1641       if (val == 1 && bpt->watchpoint_type == hw_read)
1642         {
1643           struct bp_location *loc, **loc_temp;
1644
1645           /* But don't try to insert it, if there's already another
1646              hw_access location that would be considered a duplicate
1647              of this one.  */
1648           ALL_BP_LOCATIONS (loc, loc_temp)
1649             if (loc != bpt
1650                 && loc->watchpoint_type == hw_access
1651                 && watchpoint_locations_match (bpt, loc))
1652               {
1653                 bpt->duplicate = 1;
1654                 bpt->inserted = 1;
1655                 bpt->target_info = loc->target_info;
1656                 bpt->watchpoint_type = hw_access;
1657                 val = 0;
1658                 break;
1659               }
1660
1661           if (val == 1)
1662             {
1663               val = target_insert_watchpoint (bpt->address,
1664                                               bpt->length,
1665                                               hw_access);
1666               if (val == 0)
1667                 bpt->watchpoint_type = hw_access;
1668             }
1669         }
1670
1671       bpt->inserted = (val == 0);
1672     }
1673
1674   else if (bpt->owner->type == bp_catchpoint)
1675     {
1676       struct gdb_exception e = catch_exception (uiout, insert_catchpoint,
1677                                                 bpt->owner, RETURN_MASK_ERROR);
1678       exception_fprintf (gdb_stderr, e, "warning: inserting catchpoint %d: ",
1679                          bpt->owner->number);
1680       if (e.reason < 0)
1681         bpt->owner->enable_state = bp_disabled;
1682       else
1683         bpt->inserted = 1;
1684
1685       /* We've already printed an error message if there was a problem
1686          inserting this catchpoint, and we've disabled the catchpoint,
1687          so just return success.  */
1688       return 0;
1689     }
1690
1691   return 0;
1692 }
1693
1694 /* This function is called when program space PSPACE is about to be
1695    deleted.  It takes care of updating breakpoints to not reference
1696    PSPACE anymore.  */
1697
1698 void
1699 breakpoint_program_space_exit (struct program_space *pspace)
1700 {
1701   struct breakpoint *b, *b_temp;
1702   struct bp_location *loc, **loc_temp;
1703
1704   /* Remove any breakpoint that was set through this program space.  */
1705   ALL_BREAKPOINTS_SAFE (b, b_temp)
1706     {
1707       if (b->pspace == pspace)
1708         delete_breakpoint (b);
1709     }
1710
1711   /* Breakpoints set through other program spaces could have locations
1712      bound to PSPACE as well.  Remove those.  */
1713   ALL_BP_LOCATIONS (loc, loc_temp)
1714     {
1715       struct bp_location *tmp;
1716
1717       if (loc->pspace == pspace)
1718         {
1719           if (loc->owner->loc == loc)
1720             loc->owner->loc = loc->next;
1721           else
1722             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
1723               if (tmp->next == loc)
1724                 {
1725                   tmp->next = loc->next;
1726                   break;
1727                 }
1728         }
1729     }
1730
1731   /* Now update the global location list to permanently delete the
1732      removed locations above.  */
1733   update_global_location_list (0);
1734 }
1735
1736 /* Make sure all breakpoints are inserted in inferior.
1737    Throws exception on any error.
1738    A breakpoint that is already inserted won't be inserted
1739    again, so calling this function twice is safe.  */
1740 void
1741 insert_breakpoints (void)
1742 {
1743   struct breakpoint *bpt;
1744
1745   ALL_BREAKPOINTS (bpt)
1746     if (is_hardware_watchpoint (bpt))
1747       update_watchpoint (bpt, 0 /* don't reparse. */);
1748
1749   update_global_location_list (1);
1750
1751   /* update_global_location_list does not insert breakpoints when
1752      always_inserted_mode is not enabled.  Explicitly insert them
1753      now.  */
1754   if (!breakpoints_always_inserted_mode ())
1755     insert_breakpoint_locations ();
1756 }
1757
1758 /* insert_breakpoints is used when starting or continuing the program.
1759    remove_breakpoints is used when the program stops.
1760    Both return zero if successful,
1761    or an `errno' value if could not write the inferior.  */
1762
1763 static void
1764 insert_breakpoint_locations (void)
1765 {
1766   struct breakpoint *bpt;
1767   struct bp_location *b, **bp_tmp;
1768   int error = 0;
1769   int val = 0;
1770   int disabled_breaks = 0;
1771   int hw_breakpoint_error = 0;
1772
1773   struct ui_file *tmp_error_stream = mem_fileopen ();
1774   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
1775   
1776   /* Explicitly mark the warning -- this will only be printed if
1777      there was an error.  */
1778   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
1779
1780   save_current_space_and_thread ();
1781
1782   ALL_BP_LOCATIONS (b, bp_tmp)
1783     {
1784       struct thread_info *tp;
1785       CORE_ADDR last_addr;
1786
1787       if (!should_be_inserted (b) || b->inserted)
1788         continue;
1789
1790       /* There is no point inserting thread-specific breakpoints if the
1791          thread no longer exists.  */
1792       if (b->owner->thread != -1
1793           && !valid_thread_id (b->owner->thread))
1794         continue;
1795
1796       switch_to_program_space_and_thread (b->pspace);
1797
1798       /* For targets that support global breakpoints, there's no need
1799          to select an inferior to insert breakpoint to.  In fact, even
1800          if we aren't attached to any process yet, we should still
1801          insert breakpoints.  */
1802       if (!gdbarch_has_global_breakpoints (target_gdbarch)
1803           && ptid_equal (inferior_ptid, null_ptid))
1804         continue;
1805
1806       val = insert_bp_location (b, tmp_error_stream,
1807                                     &disabled_breaks,
1808                                     &hw_breakpoint_error);
1809       if (val)
1810         error = val;
1811     }
1812
1813   /* If we failed to insert all locations of a watchpoint,
1814      remove them, as half-inserted watchpoint is of limited use.  */
1815   ALL_BREAKPOINTS (bpt)  
1816     {
1817       int some_failed = 0;
1818       struct bp_location *loc;
1819
1820       if (!is_hardware_watchpoint (bpt))
1821         continue;
1822
1823       if (!breakpoint_enabled (bpt))
1824         continue;
1825
1826       if (bpt->disposition == disp_del_at_next_stop)
1827         continue;
1828       
1829       for (loc = bpt->loc; loc; loc = loc->next)
1830         if (!loc->inserted && should_be_inserted (loc))
1831           {
1832             some_failed = 1;
1833             break;
1834           }
1835       if (some_failed)
1836         {
1837           for (loc = bpt->loc; loc; loc = loc->next)
1838             if (loc->inserted)
1839               remove_breakpoint (loc, mark_uninserted);
1840
1841           hw_breakpoint_error = 1;
1842           fprintf_unfiltered (tmp_error_stream,
1843                               "Could not insert hardware watchpoint %d.\n", 
1844                               bpt->number);
1845           error = -1;
1846         }
1847     }
1848
1849   if (error)
1850     {
1851       /* If a hardware breakpoint or watchpoint was inserted, add a
1852          message about possibly exhausted resources.  */
1853       if (hw_breakpoint_error)
1854         {
1855           fprintf_unfiltered (tmp_error_stream, 
1856                               "Could not insert hardware breakpoints:\n\
1857 You may have requested too many hardware breakpoints/watchpoints.\n");
1858         }
1859       target_terminal_ours_for_output ();
1860       error_stream (tmp_error_stream);
1861     }
1862
1863   do_cleanups (cleanups);
1864 }
1865
1866 int
1867 remove_breakpoints (void)
1868 {
1869   struct bp_location *b, **bp_tmp;
1870   int val = 0;
1871
1872   ALL_BP_LOCATIONS (b, bp_tmp)
1873   {
1874     if (b->inserted)
1875       val |= remove_breakpoint (b, mark_uninserted);
1876   }
1877   return val;
1878 }
1879
1880 /* Remove breakpoints of process PID.  */
1881
1882 int
1883 remove_breakpoints_pid (int pid)
1884 {
1885   struct bp_location *b, **b_tmp;
1886   int val;
1887   struct inferior *inf = find_inferior_pid (pid);
1888
1889   ALL_BP_LOCATIONS (b, b_tmp)
1890   {
1891     if (b->pspace != inf->pspace)
1892       continue;
1893
1894     if (b->inserted)
1895       {
1896         val = remove_breakpoint (b, mark_uninserted);
1897         if (val != 0)
1898           return val;
1899       }
1900   }
1901   return 0;
1902 }
1903
1904 int
1905 remove_hw_watchpoints (void)
1906 {
1907   struct bp_location *b, **bp_tmp;
1908   int val = 0;
1909
1910   ALL_BP_LOCATIONS (b, bp_tmp)
1911   {
1912     if (b->inserted && b->loc_type == bp_loc_hardware_watchpoint)
1913       val |= remove_breakpoint (b, mark_uninserted);
1914   }
1915   return val;
1916 }
1917
1918 int
1919 reattach_breakpoints (int pid)
1920 {
1921   struct cleanup *old_chain;
1922   struct bp_location *b, **bp_tmp;
1923   int val;
1924   struct ui_file *tmp_error_stream = mem_fileopen ();
1925   int dummy1 = 0, dummy2 = 0;
1926   struct inferior *inf;
1927   struct thread_info *tp;
1928
1929   tp = any_live_thread_of_process (pid);
1930   if (tp == NULL)
1931     return 1;
1932
1933   inf = find_inferior_pid (pid);
1934   old_chain = save_inferior_ptid ();
1935
1936   inferior_ptid = tp->ptid;
1937
1938   make_cleanup_ui_file_delete (tmp_error_stream);
1939
1940   ALL_BP_LOCATIONS (b, bp_tmp)
1941   {
1942     if (b->pspace != inf->pspace)
1943       continue;
1944
1945     if (b->inserted)
1946       {
1947         b->inserted = 0;
1948         val = insert_bp_location (b, tmp_error_stream,
1949                                   &dummy1, &dummy2);
1950         if (val != 0)
1951           {
1952             do_cleanups (old_chain);
1953             return val;
1954           }
1955       }
1956   }
1957   do_cleanups (old_chain);
1958   return 0;
1959 }
1960
1961 static int internal_breakpoint_number = -1;
1962
1963 static struct breakpoint *
1964 create_internal_breakpoint (struct gdbarch *gdbarch,
1965                             CORE_ADDR address, enum bptype type)
1966 {
1967   struct symtab_and_line sal;
1968   struct breakpoint *b;
1969
1970   init_sal (&sal);              /* initialize to zeroes */
1971
1972   sal.pc = address;
1973   sal.section = find_pc_overlay (sal.pc);
1974   sal.pspace = current_program_space;
1975
1976   b = set_raw_breakpoint (gdbarch, sal, type);
1977   b->number = internal_breakpoint_number--;
1978   b->disposition = disp_donttouch;
1979
1980   return b;
1981 }
1982
1983 static void
1984 create_overlay_event_breakpoint (char *func_name)
1985 {
1986   struct objfile *objfile;
1987
1988   ALL_OBJFILES (objfile)
1989     {
1990       struct breakpoint *b;
1991       struct minimal_symbol *m;
1992
1993       m = lookup_minimal_symbol_text (func_name, objfile);
1994       if (m == NULL)
1995         continue;
1996
1997       b = create_internal_breakpoint (get_objfile_arch (objfile),
1998                                       SYMBOL_VALUE_ADDRESS (m),
1999                                       bp_overlay_event);
2000       b->addr_string = xstrdup (func_name);
2001
2002       if (overlay_debugging == ovly_auto)
2003         {
2004           b->enable_state = bp_enabled;
2005           overlay_events_enabled = 1;
2006         }
2007       else
2008        {
2009          b->enable_state = bp_disabled;
2010          overlay_events_enabled = 0;
2011        }
2012     }
2013   update_global_location_list (1);
2014 }
2015
2016 static void
2017 create_longjmp_master_breakpoint (char *func_name)
2018 {
2019   struct program_space *pspace;
2020   struct objfile *objfile;
2021   struct cleanup *old_chain;
2022
2023   old_chain = save_current_program_space ();
2024
2025   ALL_PSPACES (pspace)
2026   ALL_OBJFILES (objfile)
2027     {
2028       struct breakpoint *b;
2029       struct minimal_symbol *m;
2030
2031       if (!gdbarch_get_longjmp_target_p (get_objfile_arch (objfile)))
2032         continue;
2033
2034       set_current_program_space (pspace);
2035
2036       m = lookup_minimal_symbol_text (func_name, objfile);
2037       if (m == NULL)
2038         continue;
2039
2040       b = create_internal_breakpoint (get_objfile_arch (objfile),
2041                                       SYMBOL_VALUE_ADDRESS (m),
2042                                       bp_longjmp_master);
2043       b->addr_string = xstrdup (func_name);
2044       b->enable_state = bp_disabled;
2045     }
2046   update_global_location_list (1);
2047
2048   do_cleanups (old_chain);
2049 }
2050
2051 void
2052 update_breakpoints_after_exec (void)
2053 {
2054   struct breakpoint *b;
2055   struct breakpoint *temp;
2056   struct bp_location *bploc, **bplocp_tmp;
2057
2058   /* We're about to delete breakpoints from GDB's lists.  If the
2059      INSERTED flag is true, GDB will try to lift the breakpoints by
2060      writing the breakpoints' "shadow contents" back into memory.  The
2061      "shadow contents" are NOT valid after an exec, so GDB should not
2062      do that.  Instead, the target is responsible from marking
2063      breakpoints out as soon as it detects an exec.  We don't do that
2064      here instead, because there may be other attempts to delete
2065      breakpoints after detecting an exec and before reaching here.  */
2066   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
2067     if (bploc->pspace == current_program_space)
2068       gdb_assert (!bploc->inserted);
2069
2070   ALL_BREAKPOINTS_SAFE (b, temp)
2071   {
2072     if (b->pspace != current_program_space)
2073       continue;
2074
2075     /* Solib breakpoints must be explicitly reset after an exec(). */
2076     if (b->type == bp_shlib_event)
2077       {
2078         delete_breakpoint (b);
2079         continue;
2080       }
2081
2082     /* JIT breakpoints must be explicitly reset after an exec(). */
2083     if (b->type == bp_jit_event)
2084       {
2085         delete_breakpoint (b);
2086         continue;
2087       }
2088
2089     /* Thread event breakpoints must be set anew after an exec(),
2090        as must overlay event and longjmp master breakpoints.  */
2091     if (b->type == bp_thread_event || b->type == bp_overlay_event
2092         || b->type == bp_longjmp_master)
2093       {
2094         delete_breakpoint (b);
2095         continue;
2096       }
2097
2098     /* Step-resume breakpoints are meaningless after an exec(). */
2099     if (b->type == bp_step_resume)
2100       {
2101         delete_breakpoint (b);
2102         continue;
2103       }
2104
2105     /* Longjmp and longjmp-resume breakpoints are also meaningless
2106        after an exec.  */
2107     if (b->type == bp_longjmp || b->type == bp_longjmp_resume)
2108       {
2109         delete_breakpoint (b);
2110         continue;
2111       }
2112
2113     if (b->type == bp_catchpoint)
2114       {
2115         /* For now, none of the bp_catchpoint breakpoints need to
2116            do anything at this point.  In the future, if some of
2117            the catchpoints need to something, we will need to add
2118            a new method, and call this method from here.  */
2119         continue;
2120       }
2121
2122     /* bp_finish is a special case.  The only way we ought to be able
2123        to see one of these when an exec() has happened, is if the user
2124        caught a vfork, and then said "finish".  Ordinarily a finish just
2125        carries them to the call-site of the current callee, by setting
2126        a temporary bp there and resuming.  But in this case, the finish
2127        will carry them entirely through the vfork & exec.
2128
2129        We don't want to allow a bp_finish to remain inserted now.  But
2130        we can't safely delete it, 'cause finish_command has a handle to
2131        the bp on a bpstat, and will later want to delete it.  There's a
2132        chance (and I've seen it happen) that if we delete the bp_finish
2133        here, that its storage will get reused by the time finish_command
2134        gets 'round to deleting the "use to be a bp_finish" breakpoint.
2135        We really must allow finish_command to delete a bp_finish.
2136
2137        In the absense of a general solution for the "how do we know
2138        it's safe to delete something others may have handles to?"
2139        problem, what we'll do here is just uninsert the bp_finish, and
2140        let finish_command delete it.
2141
2142        (We know the bp_finish is "doomed" in the sense that it's
2143        momentary, and will be deleted as soon as finish_command sees
2144        the inferior stopped.  So it doesn't matter that the bp's
2145        address is probably bogus in the new a.out, unlike e.g., the
2146        solib breakpoints.)  */
2147
2148     if (b->type == bp_finish)
2149       {
2150         continue;
2151       }
2152
2153     /* Without a symbolic address, we have little hope of the
2154        pre-exec() address meaning the same thing in the post-exec()
2155        a.out. */
2156     if (b->addr_string == NULL)
2157       {
2158         delete_breakpoint (b);
2159         continue;
2160       }
2161   }
2162   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
2163   create_overlay_event_breakpoint ("_ovly_debug_event");
2164   create_longjmp_master_breakpoint ("longjmp");
2165   create_longjmp_master_breakpoint ("_longjmp");
2166   create_longjmp_master_breakpoint ("siglongjmp");
2167   create_longjmp_master_breakpoint ("_siglongjmp");
2168 }
2169
2170 int
2171 detach_breakpoints (int pid)
2172 {
2173   struct bp_location *b, **bp_tmp;
2174   int val = 0;
2175   struct cleanup *old_chain = save_inferior_ptid ();
2176   struct inferior *inf = current_inferior ();
2177
2178   if (pid == PIDGET (inferior_ptid))
2179     error (_("Cannot detach breakpoints of inferior_ptid"));
2180
2181   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
2182   inferior_ptid = pid_to_ptid (pid);
2183   ALL_BP_LOCATIONS (b, bp_tmp)
2184   {
2185     if (b->pspace != inf->pspace)
2186       continue;
2187
2188     if (b->inserted)
2189       val |= remove_breakpoint_1 (b, mark_inserted);
2190   }
2191   do_cleanups (old_chain);
2192   return val;
2193 }
2194
2195 /* Remove the breakpoint location B from the current address space.
2196    Note that this is used to detach breakpoints from a child fork.
2197    When we get here, the child isn't in the inferior list, and neither
2198    do we have objects to represent its address space --- we should
2199    *not* look at b->pspace->aspace here.  */
2200
2201 static int
2202 remove_breakpoint_1 (struct bp_location *b, insertion_state_t is)
2203 {
2204   int val;
2205   struct cleanup *old_chain;
2206
2207   if (b->owner->enable_state == bp_permanent)
2208     /* Permanent breakpoints cannot be inserted or removed.  */
2209     return 0;
2210
2211   /* The type of none suggests that owner is actually deleted.
2212      This should not ever happen.  */
2213   gdb_assert (b->owner->type != bp_none);
2214
2215   if (b->loc_type == bp_loc_software_breakpoint
2216       || b->loc_type == bp_loc_hardware_breakpoint)
2217     {
2218       /* "Normal" instruction breakpoint: either the standard
2219          trap-instruction bp (bp_breakpoint), or a
2220          bp_hardware_breakpoint.  */
2221
2222       /* First check to see if we have to handle an overlay.  */
2223       if (overlay_debugging == ovly_off
2224           || b->section == NULL
2225           || !(section_is_overlay (b->section)))
2226         {
2227           /* No overlay handling: just remove the breakpoint.  */
2228
2229           if (b->loc_type == bp_loc_hardware_breakpoint)
2230             val = target_remove_hw_breakpoint (b->gdbarch, &b->target_info);
2231           else
2232             val = target_remove_breakpoint (b->gdbarch, &b->target_info);
2233         }
2234       else
2235         {
2236           /* This breakpoint is in an overlay section.  
2237              Did we set a breakpoint at the LMA?  */
2238           if (!overlay_events_enabled)
2239               {
2240                 /* Yes -- overlay event support is not active, so we
2241                    should have set a breakpoint at the LMA.  Remove it.  
2242                 */
2243                 /* Ignore any failures: if the LMA is in ROM, we will
2244                    have already warned when we failed to insert it.  */
2245                 if (b->loc_type == bp_loc_hardware_breakpoint)
2246                   target_remove_hw_breakpoint (b->gdbarch,
2247                                                &b->overlay_target_info);
2248                 else
2249                   target_remove_breakpoint (b->gdbarch,
2250                                             &b->overlay_target_info);
2251               }
2252           /* Did we set a breakpoint at the VMA? 
2253              If so, we will have marked the breakpoint 'inserted'.  */
2254           if (b->inserted)
2255             {
2256               /* Yes -- remove it.  Previously we did not bother to
2257                  remove the breakpoint if the section had been
2258                  unmapped, but let's not rely on that being safe.  We
2259                  don't know what the overlay manager might do.  */
2260               if (b->loc_type == bp_loc_hardware_breakpoint)
2261                 val = target_remove_hw_breakpoint (b->gdbarch,
2262                                                    &b->target_info);
2263
2264               /* However, we should remove *software* breakpoints only
2265                  if the section is still mapped, or else we overwrite
2266                  wrong code with the saved shadow contents.  */
2267               else if (section_is_mapped (b->section))
2268                 val = target_remove_breakpoint (b->gdbarch,
2269                                                 &b->target_info);
2270               else
2271                 val = 0;
2272             }
2273           else
2274             {
2275               /* No -- not inserted, so no need to remove.  No error.  */
2276               val = 0;
2277             }
2278         }
2279
2280       /* In some cases, we might not be able to remove a breakpoint
2281          in a shared library that has already been removed, but we
2282          have not yet processed the shlib unload event.  */
2283       if (val && solib_name_from_address (b->pspace, b->address))
2284         val = 0;
2285
2286       if (val)
2287         return val;
2288       b->inserted = (is == mark_inserted);
2289     }
2290   else if (b->loc_type == bp_loc_hardware_watchpoint)
2291     {
2292       struct value *v;
2293       struct value *n;
2294
2295       b->inserted = (is == mark_inserted);
2296       val = target_remove_watchpoint (b->address, b->length, 
2297                                       b->watchpoint_type);
2298
2299       /* Failure to remove any of the hardware watchpoints comes here.  */
2300       if ((is == mark_uninserted) && (b->inserted))
2301         warning (_("Could not remove hardware watchpoint %d."),
2302                  b->owner->number);
2303     }
2304   else if (b->owner->type == bp_catchpoint
2305            && breakpoint_enabled (b->owner)
2306            && !b->duplicate)
2307     {
2308       gdb_assert (b->owner->ops != NULL && b->owner->ops->remove != NULL);
2309
2310       val = b->owner->ops->remove (b->owner);
2311       if (val)
2312         return val;
2313       b->inserted = (is == mark_inserted);
2314     }
2315
2316   return 0;
2317 }
2318
2319 static int
2320 remove_breakpoint (struct bp_location *b, insertion_state_t is)
2321 {
2322   int ret;
2323   struct cleanup *old_chain;
2324
2325   if (b->owner->enable_state == bp_permanent)
2326     /* Permanent breakpoints cannot be inserted or removed.  */
2327     return 0;
2328
2329   /* The type of none suggests that owner is actually deleted.
2330      This should not ever happen.  */
2331   gdb_assert (b->owner->type != bp_none);
2332
2333   old_chain = save_current_space_and_thread ();
2334
2335   switch_to_program_space_and_thread (b->pspace);
2336
2337   ret = remove_breakpoint_1 (b, is);
2338
2339   do_cleanups (old_chain);
2340   return ret;
2341 }
2342
2343 /* Clear the "inserted" flag in all breakpoints.  */
2344
2345 void
2346 mark_breakpoints_out (void)
2347 {
2348   struct bp_location *bpt, **bptp_tmp;
2349
2350   ALL_BP_LOCATIONS (bpt, bptp_tmp)
2351     if (bpt->pspace == current_program_space)
2352       bpt->inserted = 0;
2353 }
2354
2355 /* Clear the "inserted" flag in all breakpoints and delete any
2356    breakpoints which should go away between runs of the program.
2357
2358    Plus other such housekeeping that has to be done for breakpoints
2359    between runs.
2360
2361    Note: this function gets called at the end of a run (by
2362    generic_mourn_inferior) and when a run begins (by
2363    init_wait_for_inferior). */
2364
2365
2366
2367 void
2368 breakpoint_init_inferior (enum inf_context context)
2369 {
2370   struct breakpoint *b, *temp;
2371   struct bp_location *bpt, **bptp_tmp;
2372   int ix;
2373   struct program_space *pspace = current_program_space;
2374
2375   /* If breakpoint locations are shared across processes, then there's
2376      nothing to do.  */
2377   if (gdbarch_has_global_breakpoints (target_gdbarch))
2378     return;
2379
2380   ALL_BP_LOCATIONS (bpt, bptp_tmp)
2381   {
2382     if (bpt->pspace == pspace
2383         && bpt->owner->enable_state != bp_permanent)
2384       bpt->inserted = 0;
2385   }
2386
2387   ALL_BREAKPOINTS_SAFE (b, temp)
2388   {
2389     if (b->loc && b->loc->pspace != pspace)
2390       continue;
2391
2392     switch (b->type)
2393       {
2394       case bp_call_dummy:
2395
2396         /* If the call dummy breakpoint is at the entry point it will
2397            cause problems when the inferior is rerun, so we better get
2398            rid of it.  */
2399
2400       case bp_watchpoint_scope:
2401
2402         /* Also get rid of scope breakpoints.  */
2403
2404       case bp_shlib_event:
2405
2406         /* Also remove solib event breakpoints.  Their addresses may
2407            have changed since the last time we ran the program.
2408            Actually we may now be debugging against different target;
2409            and so the solib backend that installed this breakpoint may
2410            not be used in by the target.  E.g.,
2411
2412            (gdb) file prog-linux
2413            (gdb) run               # native linux target
2414            ...
2415            (gdb) kill
2416            (gdb) file prog-win.exe
2417            (gdb) tar rem :9999     # remote Windows gdbserver.
2418         */
2419
2420         delete_breakpoint (b);
2421         break;
2422
2423       case bp_watchpoint:
2424       case bp_hardware_watchpoint:
2425       case bp_read_watchpoint:
2426       case bp_access_watchpoint:
2427
2428         /* Likewise for watchpoints on local expressions.  */
2429         if (b->exp_valid_block != NULL)
2430           delete_breakpoint (b);
2431         else if (context == inf_starting) 
2432           {
2433             /* Reset val field to force reread of starting value
2434                in insert_breakpoints.  */
2435             if (b->val)
2436               value_free (b->val);
2437             b->val = NULL;
2438             b->val_valid = 0;
2439           }
2440         break;
2441       default:
2442         break;
2443       }
2444   }
2445
2446   /* Get rid of the moribund locations.  */
2447   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bpt); ++ix)
2448     free_bp_location (bpt);
2449   VEC_free (bp_location_p, moribund_locations);
2450 }
2451
2452 /* These functions concern about actual breakpoints inserted in the
2453    target --- to e.g. check if we need to do decr_pc adjustment or if
2454    we need to hop over the bkpt --- so we check for address space
2455    match, not program space.  */
2456
2457 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
2458    exists at PC.  It returns ordinary_breakpoint_here if it's an
2459    ordinary breakpoint, or permanent_breakpoint_here if it's a
2460    permanent breakpoint.
2461    - When continuing from a location with an ordinary breakpoint, we
2462      actually single step once before calling insert_breakpoints.
2463    - When continuing from a localion with a permanent breakpoint, we
2464      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
2465      the target, to advance the PC past the breakpoint.  */
2466
2467 enum breakpoint_here
2468 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
2469 {
2470   struct bp_location *bpt, **bptp_tmp;
2471   int any_breakpoint_here = 0;
2472
2473   ALL_BP_LOCATIONS (bpt, bptp_tmp)
2474     {
2475       if (bpt->loc_type != bp_loc_software_breakpoint
2476           && bpt->loc_type != bp_loc_hardware_breakpoint)
2477         continue;
2478
2479       if ((breakpoint_enabled (bpt->owner)
2480            || bpt->owner->enable_state == bp_permanent)
2481           && breakpoint_address_match (bpt->pspace->aspace, bpt->address,
2482                                        aspace, pc))
2483         {
2484           if (overlay_debugging 
2485               && section_is_overlay (bpt->section) 
2486               && !section_is_mapped (bpt->section))
2487             continue;           /* unmapped overlay -- can't be a match */
2488           else if (bpt->owner->enable_state == bp_permanent)
2489             return permanent_breakpoint_here;
2490           else
2491             any_breakpoint_here = 1;
2492         }
2493     }
2494
2495   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
2496 }
2497
2498 /* Return true if there's a moribund breakpoint at PC.  */
2499
2500 int
2501 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
2502 {
2503   struct bp_location *loc;
2504   int ix;
2505
2506   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
2507     if (breakpoint_address_match (loc->pspace->aspace, loc->address,
2508                                   aspace,  pc))
2509       return 1;
2510
2511   return 0;
2512 }
2513
2514 /* Returns non-zero if there's a breakpoint inserted at PC, which is
2515    inserted using regular breakpoint_chain / bp_location array mechanism.
2516    This does not check for single-step breakpoints, which are
2517    inserted and removed using direct target manipulation.  */
2518
2519 int
2520 regular_breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
2521 {
2522   struct bp_location *bpt, **bptp_tmp;
2523
2524   ALL_BP_LOCATIONS (bpt, bptp_tmp)
2525     {
2526       if (bpt->loc_type != bp_loc_software_breakpoint
2527           && bpt->loc_type != bp_loc_hardware_breakpoint)
2528         continue;
2529
2530       if (bpt->inserted
2531           && breakpoint_address_match (bpt->pspace->aspace, bpt->address,
2532                                        aspace, pc))
2533         {
2534           if (overlay_debugging 
2535               && section_is_overlay (bpt->section) 
2536               && !section_is_mapped (bpt->section))
2537             continue;           /* unmapped overlay -- can't be a match */
2538           else
2539             return 1;
2540         }
2541     }
2542   return 0;
2543 }
2544
2545 /* Returns non-zero iff there's either regular breakpoint
2546    or a single step breakpoint inserted at PC.  */
2547
2548 int
2549 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
2550 {
2551   if (regular_breakpoint_inserted_here_p (aspace, pc))
2552     return 1;
2553
2554   if (single_step_breakpoint_inserted_here_p (aspace, pc))
2555     return 1;
2556
2557   return 0;
2558 }
2559
2560 /* This function returns non-zero iff there is a software breakpoint
2561    inserted at PC.  */
2562
2563 int
2564 software_breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
2565 {
2566   struct bp_location *bpt, **bptp_tmp;
2567   int any_breakpoint_here = 0;
2568
2569   ALL_BP_LOCATIONS (bpt, bptp_tmp)
2570     {
2571       if (bpt->loc_type != bp_loc_software_breakpoint)
2572         continue;
2573
2574       if (bpt->inserted
2575           && breakpoint_address_match (bpt->pspace->aspace, bpt->address,
2576                                        aspace, pc))
2577         {
2578           if (overlay_debugging 
2579               && section_is_overlay (bpt->section) 
2580               && !section_is_mapped (bpt->section))
2581             continue;           /* unmapped overlay -- can't be a match */
2582           else
2583             return 1;
2584         }
2585     }
2586
2587   /* Also check for software single-step breakpoints.  */
2588   if (single_step_breakpoint_inserted_here_p (aspace, pc))
2589     return 1;
2590
2591   return 0;
2592 }
2593
2594 int
2595 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
2596                                        CORE_ADDR addr, ULONGEST len)
2597 {
2598   struct breakpoint *bpt;
2599
2600   ALL_BREAKPOINTS (bpt)
2601     {
2602       struct bp_location *loc;
2603
2604       if (bpt->type != bp_hardware_watchpoint
2605           && bpt->type != bp_access_watchpoint)
2606         continue;
2607
2608       if (!breakpoint_enabled (bpt))
2609         continue;
2610
2611       for (loc = bpt->loc; loc; loc = loc->next)
2612         if (loc->pspace->aspace == aspace && loc->inserted)
2613           {
2614             CORE_ADDR l, h;
2615
2616             /* Check for intersection.  */
2617             l = max (loc->address, addr);
2618             h = min (loc->address + loc->length, addr + len);
2619             if (l < h)
2620               return 1;
2621           }
2622     }
2623   return 0;
2624 }
2625
2626 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
2627    PC is valid for process/thread PTID.  */
2628
2629 int
2630 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
2631                          ptid_t ptid)
2632 {
2633   struct bp_location *bpt, **bptp_tmp;
2634   /* The thread and task IDs associated to PTID, computed lazily.  */
2635   int thread = -1;
2636   int task = 0;
2637   
2638   ALL_BP_LOCATIONS (bpt, bptp_tmp)
2639     {
2640       if (bpt->loc_type != bp_loc_software_breakpoint
2641           && bpt->loc_type != bp_loc_hardware_breakpoint)
2642         continue;
2643
2644       if (!breakpoint_enabled (bpt->owner)
2645           && bpt->owner->enable_state != bp_permanent)
2646         continue;
2647
2648       if (!breakpoint_address_match (bpt->pspace->aspace, bpt->address,
2649                                      aspace, pc))
2650         continue;
2651
2652       if (bpt->owner->thread != -1)
2653         {
2654           /* This is a thread-specific breakpoint.  Check that ptid
2655              matches that thread.  If thread hasn't been computed yet,
2656              it is now time to do so.  */
2657           if (thread == -1)
2658             thread = pid_to_thread_id (ptid);
2659           if (bpt->owner->thread != thread)
2660             continue;
2661         }
2662
2663       if (bpt->owner->task != 0)
2664         {
2665           /* This is a task-specific breakpoint.  Check that ptid
2666              matches that task.  If task hasn't been computed yet,
2667              it is now time to do so.  */
2668           if (task == 0)
2669             task = ada_get_task_number (ptid);
2670           if (bpt->owner->task != task)
2671             continue;
2672         }
2673
2674       if (overlay_debugging 
2675           && section_is_overlay (bpt->section) 
2676           && !section_is_mapped (bpt->section))
2677         continue;           /* unmapped overlay -- can't be a match */
2678
2679       return 1;
2680     }
2681
2682   return 0;
2683 }
2684 \f
2685
2686 /* bpstat stuff.  External routines' interfaces are documented
2687    in breakpoint.h.  */
2688
2689 int
2690 ep_is_catchpoint (struct breakpoint *ep)
2691 {
2692   return (ep->type == bp_catchpoint);
2693 }
2694
2695 void 
2696 bpstat_free (bpstat bs)
2697 {
2698   if (bs->old_val != NULL)
2699     value_free (bs->old_val);
2700   free_command_lines (&bs->commands);
2701   xfree (bs);
2702 }
2703
2704 /* Clear a bpstat so that it says we are not at any breakpoint.
2705    Also free any storage that is part of a bpstat.  */
2706
2707 void
2708 bpstat_clear (bpstat *bsp)
2709 {
2710   bpstat p;
2711   bpstat q;
2712
2713   if (bsp == 0)
2714     return;
2715   p = *bsp;
2716   while (p != NULL)
2717     {
2718       q = p->next;
2719       bpstat_free (p);
2720       p = q;
2721     }
2722   *bsp = NULL;
2723 }
2724
2725 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
2726    is part of the bpstat is copied as well.  */
2727
2728 bpstat
2729 bpstat_copy (bpstat bs)
2730 {
2731   bpstat p = NULL;
2732   bpstat tmp;
2733   bpstat retval = NULL;
2734
2735   if (bs == NULL)
2736     return bs;
2737
2738   for (; bs != NULL; bs = bs->next)
2739     {
2740       tmp = (bpstat) xmalloc (sizeof (*tmp));
2741       memcpy (tmp, bs, sizeof (*tmp));
2742       if (bs->commands != NULL)
2743         tmp->commands = copy_command_lines (bs->commands);
2744       if (bs->old_val != NULL)
2745         {
2746           tmp->old_val = value_copy (bs->old_val);
2747           release_value (tmp->old_val);
2748         }
2749
2750       if (p == NULL)
2751         /* This is the first thing in the chain.  */
2752         retval = tmp;
2753       else
2754         p->next = tmp;
2755       p = tmp;
2756     }
2757   p->next = NULL;
2758   return retval;
2759 }
2760
2761 /* Find the bpstat associated with this breakpoint */
2762
2763 bpstat
2764 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
2765 {
2766   if (bsp == NULL)
2767     return NULL;
2768
2769   for (; bsp != NULL; bsp = bsp->next)
2770     {
2771       if (bsp->breakpoint_at && bsp->breakpoint_at->owner == breakpoint)
2772         return bsp;
2773     }
2774   return NULL;
2775 }
2776
2777 /* Find a step_resume breakpoint associated with this bpstat.
2778    (If there are multiple step_resume bp's on the list, this function
2779    will arbitrarily pick one.)
2780
2781    It is an error to use this function if BPSTAT doesn't contain a
2782    step_resume breakpoint.
2783
2784    See wait_for_inferior's use of this function.  */
2785 struct breakpoint *
2786 bpstat_find_step_resume_breakpoint (bpstat bsp)
2787 {
2788   int current_thread;
2789
2790   gdb_assert (bsp != NULL);
2791
2792   current_thread = pid_to_thread_id (inferior_ptid);
2793
2794   for (; bsp != NULL; bsp = bsp->next)
2795     {
2796       if ((bsp->breakpoint_at != NULL)
2797           && (bsp->breakpoint_at->owner->type == bp_step_resume)
2798           && (bsp->breakpoint_at->owner->thread == current_thread
2799               || bsp->breakpoint_at->owner->thread == -1))
2800         return bsp->breakpoint_at->owner;
2801     }
2802
2803   internal_error (__FILE__, __LINE__, _("No step_resume breakpoint found."));
2804 }
2805
2806
2807 /* Put in *NUM the breakpoint number of the first breakpoint we are stopped
2808    at.  *BSP upon return is a bpstat which points to the remaining
2809    breakpoints stopped at (but which is not guaranteed to be good for
2810    anything but further calls to bpstat_num).
2811    Return 0 if passed a bpstat which does not indicate any breakpoints.
2812    Return -1 if stopped at a breakpoint that has been deleted since
2813    we set it.
2814    Return 1 otherwise.  */
2815
2816 int
2817 bpstat_num (bpstat *bsp, int *num)
2818 {
2819   struct breakpoint *b;
2820
2821   if ((*bsp) == NULL)
2822     return 0;                   /* No more breakpoint values */
2823
2824   /* We assume we'll never have several bpstats that
2825      correspond to a single breakpoint -- otherwise, 
2826      this function might return the same number more
2827      than once and this will look ugly.  */
2828   b = (*bsp)->breakpoint_at ? (*bsp)->breakpoint_at->owner : NULL;
2829   *bsp = (*bsp)->next;
2830   if (b == NULL)
2831     return -1;                  /* breakpoint that's been deleted since */
2832
2833   *num = b->number;             /* We have its number */
2834   return 1;
2835 }
2836
2837 /* Modify BS so that the actions will not be performed.  */
2838
2839 void
2840 bpstat_clear_actions (bpstat bs)
2841 {
2842   for (; bs != NULL; bs = bs->next)
2843     {
2844       free_command_lines (&bs->commands);
2845       if (bs->old_val != NULL)
2846         {
2847           value_free (bs->old_val);
2848           bs->old_val = NULL;
2849         }
2850     }
2851 }
2852
2853 /* Called when a command is about to proceed the inferior.  */
2854
2855 static void
2856 breakpoint_about_to_proceed (void)
2857 {
2858   if (!ptid_equal (inferior_ptid, null_ptid))
2859     {
2860       struct thread_info *tp = inferior_thread ();
2861
2862       /* Allow inferior function calls in breakpoint commands to not
2863          interrupt the command list.  When the call finishes
2864          successfully, the inferior will be standing at the same
2865          breakpoint as if nothing happened.  */
2866       if (tp->in_infcall)
2867         return;
2868     }
2869
2870   breakpoint_proceeded = 1;
2871 }
2872
2873 /* Stub for cleaning up our state if we error-out of a breakpoint command */
2874 static void
2875 cleanup_executing_breakpoints (void *ignore)
2876 {
2877   executing_breakpoint_commands = 0;
2878 }
2879
2880 /* Execute all the commands associated with all the breakpoints at this
2881    location.  Any of these commands could cause the process to proceed
2882    beyond this point, etc.  We look out for such changes by checking
2883    the global "breakpoint_proceeded" after each command.
2884
2885    Returns true if a breakpoint command resumed the inferior.  In that
2886    case, it is the caller's responsibility to recall it again with the
2887    bpstat of the current thread.  */
2888
2889 static int
2890 bpstat_do_actions_1 (bpstat *bsp)
2891 {
2892   bpstat bs;
2893   struct cleanup *old_chain;
2894   int again = 0;
2895
2896   /* Avoid endless recursion if a `source' command is contained
2897      in bs->commands.  */
2898   if (executing_breakpoint_commands)
2899     return 0;
2900
2901   executing_breakpoint_commands = 1;
2902   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
2903
2904   /* This pointer will iterate over the list of bpstat's. */
2905   bs = *bsp;
2906
2907   breakpoint_proceeded = 0;
2908   for (; bs != NULL; bs = bs->next)
2909     {
2910       struct command_line *cmd;
2911       struct cleanup *this_cmd_tree_chain;
2912
2913       /* Take ownership of the BSP's command tree, if it has one.
2914
2915          The command tree could legitimately contain commands like
2916          'step' and 'next', which call clear_proceed_status, which
2917          frees stop_bpstat's command tree.  To make sure this doesn't
2918          free the tree we're executing out from under us, we need to
2919          take ownership of the tree ourselves.  Since a given bpstat's
2920          commands are only executed once, we don't need to copy it; we
2921          can clear the pointer in the bpstat, and make sure we free
2922          the tree when we're done.  */
2923       cmd = bs->commands;
2924       bs->commands = 0;
2925       this_cmd_tree_chain = make_cleanup_free_command_lines (&cmd);
2926
2927       while (cmd != NULL)
2928         {
2929           execute_control_command (cmd);
2930
2931           if (breakpoint_proceeded)
2932             break;
2933           else
2934             cmd = cmd->next;
2935         }
2936
2937       /* We can free this command tree now.  */
2938       do_cleanups (this_cmd_tree_chain);
2939
2940       if (breakpoint_proceeded)
2941         {
2942           if (target_can_async_p ())
2943             /* If we are in async mode, then the target might be still
2944                running, not stopped at any breakpoint, so nothing for
2945                us to do here -- just return to the event loop.  */
2946             ;
2947           else
2948             /* In sync mode, when execute_control_command returns
2949                we're already standing on the next breakpoint.
2950                Breakpoint commands for that stop were not run, since
2951                execute_command does not run breakpoint commands --
2952                only command_line_handler does, but that one is not
2953                involved in execution of breakpoint commands.  So, we
2954                can now execute breakpoint commands.  It should be
2955                noted that making execute_command do bpstat actions is
2956                not an option -- in this case we'll have recursive
2957                invocation of bpstat for each breakpoint with a
2958                command, and can easily blow up GDB stack.  Instead, we
2959                return true, which will trigger the caller to recall us
2960                with the new stop_bpstat.  */
2961             again = 1;
2962           break;
2963         }
2964     }
2965   do_cleanups (old_chain);
2966   return again;
2967 }
2968
2969 void
2970 bpstat_do_actions (void)
2971 {
2972   /* Do any commands attached to breakpoint we are stopped at.  */
2973   while (!ptid_equal (inferior_ptid, null_ptid)
2974          && target_has_execution
2975          && !is_exited (inferior_ptid)
2976          && !is_executing (inferior_ptid))
2977     /* Since in sync mode, bpstat_do_actions may resume the inferior,
2978        and only return when it is stopped at the next breakpoint, we
2979        keep doing breakpoint actions until it returns false to
2980        indicate the inferior was not resumed.  */
2981     if (!bpstat_do_actions_1 (&inferior_thread ()->stop_bpstat))
2982       break;
2983 }
2984
2985 /* Print out the (old or new) value associated with a watchpoint.  */
2986
2987 static void
2988 watchpoint_value_print (struct value *val, struct ui_file *stream)
2989 {
2990   if (val == NULL)
2991     fprintf_unfiltered (stream, _("<unreadable>"));
2992   else
2993     {
2994       struct value_print_options opts;
2995       get_user_print_options (&opts);
2996       value_print (val, stream, &opts);
2997     }
2998 }
2999
3000 /* This is the normal print function for a bpstat.  In the future,
3001    much of this logic could (should?) be moved to bpstat_stop_status,
3002    by having it set different print_it values.
3003
3004    Current scheme: When we stop, bpstat_print() is called.  It loops
3005    through the bpstat list of things causing this stop, calling the
3006    print_bp_stop_message function on each one. The behavior of the
3007    print_bp_stop_message function depends on the print_it field of
3008    bpstat. If such field so indicates, call this function here.
3009
3010    Return values from this routine (ultimately used by bpstat_print()
3011    and normal_stop() to decide what to do): 
3012    PRINT_NOTHING: Means we already printed all we needed to print,
3013    don't print anything else.
3014    PRINT_SRC_ONLY: Means we printed something, and we do *not* desire
3015    that something to be followed by a location.
3016    PRINT_SCR_AND_LOC: Means we printed something, and we *do* desire
3017    that something to be followed by a location.
3018    PRINT_UNKNOWN: Means we printed nothing or we need to do some more
3019    analysis.  */
3020
3021 static enum print_stop_action
3022 print_it_typical (bpstat bs)
3023 {
3024   struct cleanup *old_chain;
3025   struct breakpoint *b;
3026   const struct bp_location *bl;
3027   struct ui_stream *stb;
3028   int bp_temp = 0;
3029   enum print_stop_action result;
3030
3031   /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
3032      which has since been deleted.  */
3033   if (bs->breakpoint_at == NULL)
3034     return PRINT_UNKNOWN;
3035   bl = bs->breakpoint_at;
3036   b = bl->owner;
3037
3038   stb = ui_out_stream_new (uiout);
3039   old_chain = make_cleanup_ui_out_stream_delete (stb);
3040
3041   switch (b->type)
3042     {
3043     case bp_breakpoint:
3044     case bp_hardware_breakpoint:
3045       bp_temp = bs->breakpoint_at->owner->disposition == disp_del;
3046       if (bl->address != bl->requested_address)
3047         breakpoint_adjustment_warning (bl->requested_address,
3048                                        bl->address,
3049                                        b->number, 1);
3050       annotate_breakpoint (b->number);
3051       if (bp_temp) 
3052         ui_out_text (uiout, "\nTemporary breakpoint ");
3053       else
3054         ui_out_text (uiout, "\nBreakpoint ");
3055       if (ui_out_is_mi_like_p (uiout))
3056         {
3057           ui_out_field_string (uiout, "reason", 
3058                           async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
3059           ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
3060         }
3061       ui_out_field_int (uiout, "bkptno", b->number);
3062       ui_out_text (uiout, ", ");
3063       result = PRINT_SRC_AND_LOC;
3064       break;
3065
3066     case bp_shlib_event:
3067       /* Did we stop because the user set the stop_on_solib_events
3068          variable?  (If so, we report this as a generic, "Stopped due
3069          to shlib event" message.) */
3070       printf_filtered (_("Stopped due to shared library event\n"));
3071       result = PRINT_NOTHING;
3072       break;
3073
3074     case bp_thread_event:
3075       /* Not sure how we will get here. 
3076          GDB should not stop for these breakpoints.  */
3077       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
3078       result = PRINT_NOTHING;
3079       break;
3080
3081     case bp_overlay_event:
3082       /* By analogy with the thread event, GDB should not stop for these. */
3083       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
3084       result = PRINT_NOTHING;
3085       break;
3086
3087     case bp_longjmp_master:
3088       /* These should never be enabled.  */
3089       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
3090       result = PRINT_NOTHING;
3091       break;
3092
3093     case bp_watchpoint:
3094     case bp_hardware_watchpoint:
3095       annotate_watchpoint (b->number);
3096       if (ui_out_is_mi_like_p (uiout))
3097         ui_out_field_string
3098           (uiout, "reason",
3099            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
3100       mention (b);
3101       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
3102       ui_out_text (uiout, "\nOld value = ");
3103       watchpoint_value_print (bs->old_val, stb->stream);
3104       ui_out_field_stream (uiout, "old", stb);
3105       ui_out_text (uiout, "\nNew value = ");
3106       watchpoint_value_print (b->val, stb->stream);
3107       ui_out_field_stream (uiout, "new", stb);
3108       ui_out_text (uiout, "\n");
3109       /* More than one watchpoint may have been triggered.  */
3110       result = PRINT_UNKNOWN;
3111       break;
3112
3113     case bp_read_watchpoint:
3114       if (ui_out_is_mi_like_p (uiout))
3115         ui_out_field_string
3116           (uiout, "reason",
3117            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
3118       mention (b);
3119       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
3120       ui_out_text (uiout, "\nValue = ");
3121       watchpoint_value_print (b->val, stb->stream);
3122       ui_out_field_stream (uiout, "value", stb);
3123       ui_out_text (uiout, "\n");
3124       result = PRINT_UNKNOWN;
3125       break;
3126
3127     case bp_access_watchpoint:
3128       if (bs->old_val != NULL)
3129         {
3130           annotate_watchpoint (b->number);
3131           if (ui_out_is_mi_like_p (uiout))
3132             ui_out_field_string
3133               (uiout, "reason",
3134                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
3135           mention (b);
3136           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
3137           ui_out_text (uiout, "\nOld value = ");
3138           watchpoint_value_print (bs->old_val, stb->stream);
3139           ui_out_field_stream (uiout, "old", stb);
3140           ui_out_text (uiout, "\nNew value = ");
3141         }
3142       else 
3143         {
3144           mention (b);
3145           if (ui_out_is_mi_like_p (uiout))
3146             ui_out_field_string
3147               (uiout, "reason",
3148                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
3149           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
3150           ui_out_text (uiout, "\nValue = ");
3151         }
3152       watchpoint_value_print (b->val, stb->stream);
3153       ui_out_field_stream (uiout, "new", stb);
3154       ui_out_text (uiout, "\n");
3155       result = PRINT_UNKNOWN;
3156       break;
3157
3158     /* Fall through, we don't deal with these types of breakpoints
3159        here. */
3160
3161     case bp_finish:
3162       if (ui_out_is_mi_like_p (uiout))
3163         ui_out_field_string
3164           (uiout, "reason",
3165            async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
3166       result = PRINT_UNKNOWN;
3167       break;
3168
3169     case bp_until:
3170       if (ui_out_is_mi_like_p (uiout))
3171         ui_out_field_string
3172           (uiout, "reason",
3173            async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
3174       result = PRINT_UNKNOWN;
3175       break;
3176
3177     case bp_none:
3178     case bp_longjmp:
3179     case bp_longjmp_resume:
3180     case bp_step_resume:
3181     case bp_watchpoint_scope:
3182     case bp_call_dummy:
3183     case bp_tracepoint:
3184     case bp_fast_tracepoint:
3185     case bp_jit_event:
3186     default:
3187       result = PRINT_UNKNOWN;
3188       break;
3189     }
3190
3191   do_cleanups (old_chain);
3192   return result;
3193 }
3194
3195 /* Generic routine for printing messages indicating why we
3196    stopped. The behavior of this function depends on the value
3197    'print_it' in the bpstat structure.  Under some circumstances we
3198    may decide not to print anything here and delegate the task to
3199    normal_stop(). */
3200
3201 static enum print_stop_action
3202 print_bp_stop_message (bpstat bs)
3203 {
3204   switch (bs->print_it)
3205     {
3206     case print_it_noop:
3207       /* Nothing should be printed for this bpstat entry. */
3208       return PRINT_UNKNOWN;
3209       break;
3210
3211     case print_it_done:
3212       /* We still want to print the frame, but we already printed the
3213          relevant messages. */
3214       return PRINT_SRC_AND_LOC;
3215       break;
3216
3217     case print_it_normal:
3218       {
3219         const struct bp_location *bl = bs->breakpoint_at;
3220         struct breakpoint *b = bl ? bl->owner : NULL;
3221         
3222         /* Normal case.  Call the breakpoint's print_it method, or
3223            print_it_typical.  */
3224         /* FIXME: how breakpoint can ever be NULL here?  */
3225         if (b != NULL && b->ops != NULL && b->ops->print_it != NULL)
3226           return b->ops->print_it (b);
3227         else
3228           return print_it_typical (bs);
3229       }
3230         break;
3231
3232     default:
3233       internal_error (__FILE__, __LINE__,
3234                       _("print_bp_stop_message: unrecognized enum value"));
3235       break;
3236     }
3237 }
3238
3239 /* Print a message indicating what happened.  This is called from
3240    normal_stop().  The input to this routine is the head of the bpstat
3241    list - a list of the eventpoints that caused this stop.  This
3242    routine calls the generic print routine for printing a message
3243    about reasons for stopping.  This will print (for example) the
3244    "Breakpoint n," part of the output.  The return value of this
3245    routine is one of:
3246
3247    PRINT_UNKNOWN: Means we printed nothing
3248    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
3249    code to print the location. An example is 
3250    "Breakpoint 1, " which should be followed by
3251    the location.
3252    PRINT_SRC_ONLY: Means we printed something, but there is no need
3253    to also print the location part of the message.
3254    An example is the catch/throw messages, which
3255    don't require a location appended to the end.  
3256    PRINT_NOTHING: We have done some printing and we don't need any 
3257    further info to be printed.*/
3258
3259 enum print_stop_action
3260 bpstat_print (bpstat bs)
3261 {
3262   int val;
3263
3264   /* Maybe another breakpoint in the chain caused us to stop.
3265      (Currently all watchpoints go on the bpstat whether hit or not.
3266      That probably could (should) be changed, provided care is taken
3267      with respect to bpstat_explains_signal).  */
3268   for (; bs; bs = bs->next)
3269     {
3270       val = print_bp_stop_message (bs);
3271       if (val == PRINT_SRC_ONLY 
3272           || val == PRINT_SRC_AND_LOC 
3273           || val == PRINT_NOTHING)
3274         return val;
3275     }
3276
3277   /* We reached the end of the chain, or we got a null BS to start
3278      with and nothing was printed. */
3279   return PRINT_UNKNOWN;
3280 }
3281
3282 /* Evaluate the expression EXP and return 1 if value is zero.
3283    This is used inside a catch_errors to evaluate the breakpoint condition. 
3284    The argument is a "struct expression *" that has been cast to char * to 
3285    make it pass through catch_errors.  */
3286
3287 static int
3288 breakpoint_cond_eval (void *exp)
3289 {
3290   struct value *mark = value_mark ();
3291   int i = !value_true (evaluate_expression ((struct expression *) exp));
3292   value_free_to_mark (mark);
3293   return i;
3294 }
3295
3296 /* Allocate a new bpstat and chain it to the current one.  */
3297
3298 static bpstat
3299 bpstat_alloc (const struct bp_location *bl, bpstat cbs /* Current "bs" value */ )
3300 {
3301   bpstat bs;
3302
3303   bs = (bpstat) xmalloc (sizeof (*bs));
3304   cbs->next = bs;
3305   bs->breakpoint_at = bl;
3306   /* If the condition is false, etc., don't do the commands.  */
3307   bs->commands = NULL;
3308   bs->old_val = NULL;
3309   bs->print_it = print_it_normal;
3310   return bs;
3311 }
3312 \f
3313 /* The target has stopped with waitstatus WS.  Check if any hardware
3314    watchpoints have triggered, according to the target.  */
3315
3316 int
3317 watchpoints_triggered (struct target_waitstatus *ws)
3318 {
3319   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
3320   CORE_ADDR addr;
3321   struct breakpoint *b;
3322
3323   if (!stopped_by_watchpoint)
3324     {
3325       /* We were not stopped by a watchpoint.  Mark all watchpoints
3326          as not triggered.  */
3327       ALL_BREAKPOINTS (b)
3328         if (b->type == bp_hardware_watchpoint
3329             || b->type == bp_read_watchpoint
3330             || b->type == bp_access_watchpoint)
3331           b->watchpoint_triggered = watch_triggered_no;
3332
3333       return 0;
3334     }
3335
3336   if (!target_stopped_data_address (&current_target, &addr))
3337     {
3338       /* We were stopped by a watchpoint, but we don't know where.
3339          Mark all watchpoints as unknown.  */
3340       ALL_BREAKPOINTS (b)
3341         if (b->type == bp_hardware_watchpoint
3342             || b->type == bp_read_watchpoint
3343             || b->type == bp_access_watchpoint)
3344           b->watchpoint_triggered = watch_triggered_unknown;
3345
3346       return stopped_by_watchpoint;
3347     }
3348
3349   /* The target could report the data address.  Mark watchpoints
3350      affected by this data address as triggered, and all others as not
3351      triggered.  */
3352
3353   ALL_BREAKPOINTS (b)
3354     if (b->type == bp_hardware_watchpoint
3355         || b->type == bp_read_watchpoint
3356         || b->type == bp_access_watchpoint)
3357       {
3358         struct bp_location *loc;
3359         struct value *v;
3360
3361         b->watchpoint_triggered = watch_triggered_no;
3362         for (loc = b->loc; loc; loc = loc->next)
3363           /* Exact match not required.  Within range is
3364              sufficient.  */
3365           if (target_watchpoint_addr_within_range (&current_target,
3366                                                    addr, loc->address,
3367                                                    loc->length))
3368             {
3369               b->watchpoint_triggered = watch_triggered_yes;
3370               break;
3371             }
3372       }
3373
3374   return 1;
3375 }
3376
3377 /* Possible return values for watchpoint_check (this can't be an enum
3378    because of check_errors).  */
3379 /* The watchpoint has been deleted.  */
3380 #define WP_DELETED 1
3381 /* The value has changed.  */
3382 #define WP_VALUE_CHANGED 2
3383 /* The value has not changed.  */
3384 #define WP_VALUE_NOT_CHANGED 3
3385 /* Ignore this watchpoint, no matter if the value changed or not.  */
3386 #define WP_IGNORE 4
3387
3388 #define BP_TEMPFLAG 1
3389 #define BP_HARDWAREFLAG 2
3390
3391 /* Evaluate watchpoint condition expression and check if its value changed.
3392
3393    P should be a pointer to struct bpstat, but is defined as a void *
3394    in order for this function to be usable with catch_errors.  */
3395
3396 static int
3397 watchpoint_check (void *p)
3398 {
3399   bpstat bs = (bpstat) p;
3400   struct breakpoint *b;
3401   struct frame_info *fr;
3402   int within_current_scope;
3403
3404   b = bs->breakpoint_at->owner;
3405
3406   /* If this is a local watchpoint, we only want to check if the
3407      watchpoint frame is in scope if the current thread is the thread
3408      that was used to create the watchpoint.  */
3409   if (!watchpoint_in_thread_scope (b))
3410     return WP_IGNORE;
3411
3412   if (b->exp_valid_block == NULL)
3413     within_current_scope = 1;
3414   else
3415     {
3416       struct frame_info *frame = get_current_frame ();
3417       struct gdbarch *frame_arch = get_frame_arch (frame);
3418       CORE_ADDR frame_pc = get_frame_pc (frame);
3419
3420       /* in_function_epilogue_p() returns a non-zero value if we're still
3421          in the function but the stack frame has already been invalidated.
3422          Since we can't rely on the values of local variables after the
3423          stack has been destroyed, we are treating the watchpoint in that
3424          state as `not changed' without further checking.  Don't mark
3425          watchpoints as changed if the current frame is in an epilogue -
3426          even if they are in some other frame, our view of the stack
3427          is likely to be wrong and frame_find_by_id could error out.  */
3428       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
3429         return WP_IGNORE;
3430
3431       fr = frame_find_by_id (b->watchpoint_frame);
3432       within_current_scope = (fr != NULL);
3433
3434       /* If we've gotten confused in the unwinder, we might have
3435          returned a frame that can't describe this variable.  */
3436       if (within_current_scope)
3437         {
3438           struct symbol *function;
3439
3440           function = get_frame_function (fr);
3441           if (function == NULL
3442               || !contained_in (b->exp_valid_block,
3443                                 SYMBOL_BLOCK_VALUE (function)))
3444             within_current_scope = 0;
3445         }
3446
3447       if (within_current_scope)
3448         /* If we end up stopping, the current frame will get selected
3449            in normal_stop.  So this call to select_frame won't affect
3450            the user.  */
3451         select_frame (fr);
3452     }
3453
3454   if (within_current_scope)
3455     {
3456       /* We use value_{,free_to_}mark because it could be a
3457          *long* time before we return to the command level and
3458          call free_all_values.  We can't call free_all_values because
3459          we might be in the middle of evaluating a function call.  */
3460
3461       struct value *mark = value_mark ();
3462       struct value *new_val;
3463
3464       fetch_watchpoint_value (b->exp, &new_val, NULL, NULL);
3465
3466       /* We use value_equal_contents instead of value_equal because the latter
3467          coerces an array to a pointer, thus comparing just the address of the
3468          array instead of its contents.  This is not what we want.  */
3469       if ((b->val != NULL) != (new_val != NULL)
3470           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
3471         {
3472           if (new_val != NULL)
3473             {
3474               release_value (new_val);
3475               value_free_to_mark (mark);
3476             }
3477           bs->old_val = b->val;
3478           b->val = new_val;
3479           b->val_valid = 1;
3480           return WP_VALUE_CHANGED;
3481         }
3482       else
3483         {
3484           /* Nothing changed.  */
3485           value_free_to_mark (mark);
3486           return WP_VALUE_NOT_CHANGED;
3487         }
3488     }
3489   else
3490     {
3491       /* This seems like the only logical thing to do because
3492          if we temporarily ignored the watchpoint, then when
3493          we reenter the block in which it is valid it contains
3494          garbage (in the case of a function, it may have two
3495          garbage values, one before and one after the prologue).
3496          So we can't even detect the first assignment to it and
3497          watch after that (since the garbage may or may not equal
3498          the first value assigned).  */
3499       /* We print all the stop information in print_it_typical(), but
3500          in this case, by the time we call print_it_typical() this bp
3501          will be deleted already. So we have no choice but print the
3502          information here. */
3503       if (ui_out_is_mi_like_p (uiout))
3504         ui_out_field_string
3505           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
3506       ui_out_text (uiout, "\nWatchpoint ");
3507       ui_out_field_int (uiout, "wpnum", b->number);
3508       ui_out_text (uiout, " deleted because the program has left the block in\n\
3509 which its expression is valid.\n");     
3510
3511       if (b->related_breakpoint)
3512         {
3513           b->related_breakpoint->disposition = disp_del_at_next_stop;
3514           b->related_breakpoint->related_breakpoint = NULL;
3515           b->related_breakpoint = NULL;
3516         }
3517       b->disposition = disp_del_at_next_stop;
3518
3519       return WP_DELETED;
3520     }
3521 }
3522
3523 /* Return true if it looks like target has stopped due to hitting
3524    breakpoint location BL.  This function does not check if we
3525    should stop, only if BL explains the stop.   */
3526 static int
3527 bpstat_check_location (const struct bp_location *bl,
3528                        struct address_space *aspace, CORE_ADDR bp_addr)
3529 {
3530   struct breakpoint *b = bl->owner;
3531
3532   /* By definition, the inferior does not report stops at
3533      tracepoints.  */
3534   if (tracepoint_type (b))
3535     return 0;
3536
3537   if (b->type != bp_watchpoint
3538       && b->type != bp_hardware_watchpoint
3539       && b->type != bp_read_watchpoint
3540       && b->type != bp_access_watchpoint
3541       && b->type != bp_hardware_breakpoint
3542       && b->type != bp_catchpoint)      /* a non-watchpoint bp */
3543     {
3544       if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
3545                                      aspace, bp_addr))
3546         return 0;
3547       if (overlay_debugging             /* unmapped overlay section */
3548           && section_is_overlay (bl->section) 
3549           && !section_is_mapped (bl->section))
3550         return 0;
3551     }
3552   
3553   /* Continuable hardware watchpoints are treated as non-existent if the
3554      reason we stopped wasn't a hardware watchpoint (we didn't stop on
3555      some data address).  Otherwise gdb won't stop on a break instruction
3556      in the code (not from a breakpoint) when a hardware watchpoint has
3557      been defined.  Also skip watchpoints which we know did not trigger
3558      (did not match the data address).  */
3559   
3560   if ((b->type == bp_hardware_watchpoint
3561        || b->type == bp_read_watchpoint
3562        || b->type == bp_access_watchpoint)
3563       && b->watchpoint_triggered == watch_triggered_no)
3564     return 0;
3565   
3566   if (b->type == bp_hardware_breakpoint)
3567     {
3568       if (bl->address != bp_addr)
3569         return 0;
3570       if (overlay_debugging             /* unmapped overlay section */
3571           && section_is_overlay (bl->section) 
3572           && !section_is_mapped (bl->section))
3573         return 0;
3574     }
3575
3576   if (b->type == bp_catchpoint)
3577     {
3578       gdb_assert (b->ops != NULL && b->ops->breakpoint_hit != NULL);
3579       if (!b->ops->breakpoint_hit (b))
3580         return 0;
3581     }
3582      
3583   return 1;
3584 }
3585
3586 /* If BS refers to a watchpoint, determine if the watched values
3587    has actually changed, and we should stop.  If not, set BS->stop
3588    to 0.  */
3589 static void
3590 bpstat_check_watchpoint (bpstat bs)
3591 {
3592   const struct bp_location *bl = bs->breakpoint_at;
3593   struct breakpoint *b = bl->owner;
3594
3595   if (b->type == bp_watchpoint
3596       || b->type == bp_read_watchpoint
3597       || b->type == bp_access_watchpoint
3598       || b->type == bp_hardware_watchpoint)
3599     {
3600       CORE_ADDR addr;
3601       struct value *v;
3602       int must_check_value = 0;
3603       
3604       if (b->type == bp_watchpoint)
3605         /* For a software watchpoint, we must always check the
3606            watched value.  */
3607         must_check_value = 1;
3608       else if (b->watchpoint_triggered == watch_triggered_yes)
3609         /* We have a hardware watchpoint (read, write, or access)
3610            and the target earlier reported an address watched by
3611            this watchpoint.  */
3612         must_check_value = 1;
3613       else if (b->watchpoint_triggered == watch_triggered_unknown
3614                && b->type == bp_hardware_watchpoint)
3615         /* We were stopped by a hardware watchpoint, but the target could
3616            not report the data address.  We must check the watchpoint's
3617            value.  Access and read watchpoints are out of luck; without
3618            a data address, we can't figure it out.  */
3619         must_check_value = 1;
3620       
3621       if (must_check_value)
3622         {
3623           char *message = xstrprintf ("Error evaluating expression for watchpoint %d\n",
3624                                       b->number);
3625           struct cleanup *cleanups = make_cleanup (xfree, message);
3626           int e = catch_errors (watchpoint_check, bs, message,
3627                                 RETURN_MASK_ALL);
3628           do_cleanups (cleanups);
3629           switch (e)
3630             {
3631             case WP_DELETED:
3632               /* We've already printed what needs to be printed.  */
3633               bs->print_it = print_it_done;
3634               /* Stop.  */
3635               break;
3636             case WP_IGNORE:
3637               bs->print_it = print_it_noop;
3638               bs->stop = 0;
3639               break;
3640             case WP_VALUE_CHANGED:
3641               if (b->type == bp_read_watchpoint)
3642                 {
3643                   /* There are two cases to consider here:
3644
3645                      1. we're watching the triggered memory for reads.
3646                      In that case, trust the target, and always report
3647                      the watchpoint hit to the user.  Even though
3648                      reads don't cause value changes, the value may
3649                      have changed since the last time it was read, and
3650                      since we're not trapping writes, we will not see
3651                      those, and as such we should ignore our notion of
3652                      old value.
3653
3654                      2. we're watching the triggered memory for both
3655                      reads and writes.  There are two ways this may
3656                      happen:
3657
3658                      2.1. this is a target that can't break on data
3659                      reads only, but can break on accesses (reads or
3660                      writes), such as e.g., x86.  We detect this case
3661                      at the time we try to insert read watchpoints.
3662
3663                      2.2. otherwise, the target supports read
3664                      watchpoints, but, the user set an access or write
3665                      watchpoint watching the same memory as this read
3666                      watchpoint.
3667
3668                      If we're watching memory writes as well as reads,
3669                      ignore watchpoint hits when we find that the
3670                      value hasn't changed, as reads don't cause
3671                      changes.  This still gives false positives when
3672                      the program writes the same value to memory as
3673                      what there was already in memory (we will confuse
3674                      it for a read), but it's much better than
3675                      nothing.  */
3676
3677                   int other_write_watchpoint = 0;
3678
3679                   if (bl->watchpoint_type == hw_read)
3680                     {
3681                       struct breakpoint *other_b;
3682
3683                       ALL_BREAKPOINTS (other_b)
3684                         if ((other_b->type == bp_hardware_watchpoint
3685                              || other_b->type == bp_access_watchpoint)
3686                             && (other_b->watchpoint_triggered
3687                                 == watch_triggered_yes))
3688                           {
3689                             other_write_watchpoint = 1;
3690                             break;
3691                           }
3692                     }
3693
3694                   if (other_write_watchpoint
3695                       || bl->watchpoint_type == hw_access)
3696                     {
3697                       /* We're watching the same memory for writes,
3698                          and the value changed since the last time we
3699                          updated it, so this trap must be for a write.
3700                          Ignore it.  */
3701                       bs->print_it = print_it_noop;
3702                       bs->stop = 0;
3703                     }
3704                 }
3705               break;
3706             case WP_VALUE_NOT_CHANGED:
3707               if (b->type == bp_hardware_watchpoint
3708                   || b->type == bp_watchpoint)
3709                 {
3710                   /* Don't stop: write watchpoints shouldn't fire if
3711                      the value hasn't changed.  */
3712                   bs->print_it = print_it_noop;
3713                   bs->stop = 0;
3714                 }
3715               /* Stop.  */
3716               break;
3717             default:
3718               /* Can't happen.  */
3719             case 0:
3720               /* Error from catch_errors.  */
3721               printf_filtered (_("Watchpoint %d deleted.\n"), b->number);
3722               if (b->related_breakpoint)
3723                 b->related_breakpoint->disposition = disp_del_at_next_stop;
3724               b->disposition = disp_del_at_next_stop;
3725               /* We've already printed what needs to be printed.  */
3726               bs->print_it = print_it_done;
3727               break;
3728             }
3729         }
3730       else      /* must_check_value == 0 */
3731         {
3732           /* This is a case where some watchpoint(s) triggered, but
3733              not at the address of this watchpoint, or else no
3734              watchpoint triggered after all.  So don't print
3735              anything for this watchpoint.  */
3736           bs->print_it = print_it_noop;
3737           bs->stop = 0;
3738         }
3739     }
3740 }
3741
3742
3743 /* Check conditions (condition proper, frame, thread and ignore count)
3744    of breakpoint referred to by BS.  If we should not stop for this
3745    breakpoint, set BS->stop to 0.  */
3746 static void
3747 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
3748 {
3749   int thread_id = pid_to_thread_id (ptid);
3750   const struct bp_location *bl = bs->breakpoint_at;
3751   struct breakpoint *b = bl->owner;
3752
3753   if (frame_id_p (b->frame_id)
3754       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
3755     bs->stop = 0;
3756   else if (bs->stop)
3757     {
3758       int value_is_zero = 0;
3759       struct expression *cond;
3760
3761       /* If this is a scope breakpoint, mark the associated
3762          watchpoint as triggered so that we will handle the
3763          out-of-scope event.  We'll get to the watchpoint next
3764          iteration.  */
3765       if (b->type == bp_watchpoint_scope)
3766         b->related_breakpoint->watchpoint_triggered = watch_triggered_yes;
3767
3768       if (is_watchpoint (b))
3769         cond = b->cond_exp;
3770       else
3771         cond = bl->cond;
3772
3773       if (cond && bl->owner->disposition != disp_del_at_next_stop)
3774         {
3775           int within_current_scope = 1;
3776
3777           /* We use value_mark and value_free_to_mark because it could
3778              be a long time before we return to the command level and
3779              call free_all_values.  We can't call free_all_values
3780              because we might be in the middle of evaluating a
3781              function call.  */
3782           struct value *mark = value_mark ();
3783
3784           /* Need to select the frame, with all that implies so that
3785              the conditions will have the right context.  Because we
3786              use the frame, we will not see an inlined function's
3787              variables when we arrive at a breakpoint at the start
3788              of the inlined function; the current frame will be the
3789              call site.  */
3790           if (!is_watchpoint (b) || b->cond_exp_valid_block == NULL)
3791             select_frame (get_current_frame ());
3792           else
3793             {
3794               struct frame_info *frame;
3795
3796               /* For local watchpoint expressions, which particular
3797                  instance of a local is being watched matters, so we
3798                  keep track of the frame to evaluate the expression
3799                  in.  To evaluate the condition however, it doesn't
3800                  really matter which instantiation of the function
3801                  where the condition makes sense triggers the
3802                  watchpoint.  This allows an expression like "watch
3803                  global if q > 10" set in `func', catch writes to
3804                  global on all threads that call `func', or catch
3805                  writes on all recursive calls of `func' by a single
3806                  thread.  We simply always evaluate the condition in
3807                  the innermost frame that's executing where it makes
3808                  sense to evaluate the condition.  It seems
3809                  intuitive.  */
3810               frame = block_innermost_frame (b->cond_exp_valid_block);
3811               if (frame != NULL)
3812                 select_frame (frame);
3813               else
3814                 within_current_scope = 0;
3815             }
3816           if (within_current_scope)
3817             value_is_zero
3818               = catch_errors (breakpoint_cond_eval, cond,
3819                               "Error in testing breakpoint condition:\n",
3820                               RETURN_MASK_ALL);
3821           else
3822             {
3823               warning (_("Watchpoint condition cannot be tested "
3824                          "in the current scope"));
3825               /* If we failed to set the right context for this
3826                  watchpoint, unconditionally report it.  */
3827               value_is_zero = 0;
3828             }
3829           /* FIXME-someday, should give breakpoint # */
3830           value_free_to_mark (mark);
3831         }
3832
3833       if (cond && value_is_zero)
3834         {
3835           bs->stop = 0;
3836         }
3837       else if (b->thread != -1 && b->thread != thread_id)
3838         {
3839           bs->stop = 0;
3840         }
3841       else if (b->ignore_count > 0)
3842         {
3843           b->ignore_count--;
3844           annotate_ignore_count_change ();
3845           bs->stop = 0;
3846           /* Increase the hit count even though we don't
3847              stop.  */
3848           ++(b->hit_count);
3849         }       
3850     }
3851 }
3852
3853
3854 /* Get a bpstat associated with having just stopped at address
3855    BP_ADDR in thread PTID.
3856
3857    Determine whether we stopped at a breakpoint, etc, or whether we
3858    don't understand this stop.  Result is a chain of bpstat's such that:
3859
3860    if we don't understand the stop, the result is a null pointer.
3861
3862    if we understand why we stopped, the result is not null.
3863
3864    Each element of the chain refers to a particular breakpoint or
3865    watchpoint at which we have stopped.  (We may have stopped for
3866    several reasons concurrently.)
3867
3868    Each element of the chain has valid next, breakpoint_at,
3869    commands, FIXME??? fields.  */
3870
3871 bpstat
3872 bpstat_stop_status (struct address_space *aspace,
3873                     CORE_ADDR bp_addr, ptid_t ptid)
3874 {
3875   struct breakpoint *b = NULL;
3876   struct bp_location *bl, **blp_tmp;
3877   struct bp_location *loc;
3878   /* Root of the chain of bpstat's */
3879   struct bpstats root_bs[1];
3880   /* Pointer to the last thing in the chain currently.  */
3881   bpstat bs = root_bs;
3882   int ix;
3883   int need_remove_insert;
3884
3885   /* ALL_BP_LOCATIONS iteration would break across
3886      update_global_location_list possibly executed by
3887      bpstat_check_breakpoint_conditions's inferior call.  */
3888
3889   ALL_BREAKPOINTS (b)
3890     {
3891       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
3892         continue;
3893
3894       for (bl = b->loc; bl != NULL; bl = bl->next)
3895         {
3896           /* For hardware watchpoints, we look only at the first location.
3897              The watchpoint_check function will work on entire expression,
3898              not the individual locations.  For read watchopints, the
3899              watchpoints_triggered function have checked all locations
3900              already.  */
3901           if (b->type == bp_hardware_watchpoint && bl != b->loc)
3902             break;
3903
3904           if (bl->shlib_disabled)
3905             continue;
3906
3907           if (!bpstat_check_location (bl, aspace, bp_addr))
3908             continue;
3909
3910           /* Come here if it's a watchpoint, or if the break address matches */
3911
3912           bs = bpstat_alloc (bl, bs);   /* Alloc a bpstat to explain stop */
3913
3914           /* Assume we stop.  Should we find watchpoint that is not actually
3915              triggered, or if condition of breakpoint is false, we'll reset
3916              'stop' to 0.  */
3917           bs->stop = 1;
3918           bs->print = 1;
3919
3920           bpstat_check_watchpoint (bs);
3921           if (!bs->stop)
3922             continue;
3923
3924           if (b->type == bp_thread_event || b->type == bp_overlay_event
3925               || b->type == bp_longjmp_master)
3926             /* We do not stop for these.  */
3927             bs->stop = 0;
3928           else
3929             bpstat_check_breakpoint_conditions (bs, ptid);
3930         
3931           if (bs->stop)
3932             {
3933               ++(b->hit_count);
3934
3935               /* We will stop here */
3936               if (b->disposition == disp_disable)
3937                 {
3938                   if (b->enable_state != bp_permanent)
3939                     b->enable_state = bp_disabled;
3940                   update_global_location_list (0);
3941                 }
3942               if (b->silent)
3943                 bs->print = 0;
3944               bs->commands = b->commands;
3945               if (bs->commands
3946                   && (strcmp ("silent", bs->commands->line) == 0
3947                       || (xdb_commands && strcmp ("Q",
3948                                                   bs->commands->line) == 0)))
3949                 {
3950                   bs->commands = bs->commands->next;
3951                   bs->print = 0;
3952                 }
3953               bs->commands = copy_command_lines (bs->commands);
3954             }
3955
3956           /* Print nothing for this entry if we dont stop or dont print.  */
3957           if (bs->stop == 0 || bs->print == 0)
3958             bs->print_it = print_it_noop;
3959         }
3960     }
3961
3962   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3963     {
3964       if (breakpoint_address_match (loc->pspace->aspace, loc->address,
3965                                     aspace, bp_addr))
3966         {
3967           bs = bpstat_alloc (loc, bs);
3968           /* For hits of moribund locations, we should just proceed.  */
3969           bs->stop = 0;
3970           bs->print = 0;
3971           bs->print_it = print_it_noop;
3972         }
3973     }
3974
3975   bs->next = NULL;              /* Terminate the chain */
3976
3977   /* If we aren't stopping, the value of some hardware watchpoint may
3978      not have changed, but the intermediate memory locations we are
3979      watching may have.  Don't bother if we're stopping; this will get
3980      done later.  */
3981   for (bs = root_bs->next; bs != NULL; bs = bs->next)
3982     if (bs->stop)
3983       break;
3984
3985   need_remove_insert = 0;
3986   if (bs == NULL)
3987     for (bs = root_bs->next; bs != NULL; bs = bs->next)
3988       if (!bs->stop
3989           && bs->breakpoint_at->owner
3990           && is_hardware_watchpoint (bs->breakpoint_at->owner))
3991         {
3992           update_watchpoint (bs->breakpoint_at->owner, 0 /* don't reparse. */);
3993           /* Updating watchpoints invalidates bs->breakpoint_at.
3994              Prevent further code from trying to use it.  */
3995           bs->breakpoint_at = NULL;
3996           need_remove_insert = 1;
3997         }
3998
3999   if (need_remove_insert)
4000     update_global_location_list (1);
4001
4002   return root_bs->next;
4003 }
4004 \f
4005 /* Tell what to do about this bpstat.  */
4006 struct bpstat_what
4007 bpstat_what (bpstat bs)
4008 {
4009   /* Classify each bpstat as one of the following.  */
4010   enum class
4011     {
4012       /* This bpstat element has no effect on the main_action.  */
4013       no_effect = 0,
4014
4015       /* There was a watchpoint, stop but don't print.  */
4016       wp_silent,
4017
4018       /* There was a watchpoint, stop and print.  */
4019       wp_noisy,
4020
4021       /* There was a breakpoint but we're not stopping.  */
4022       bp_nostop,
4023
4024       /* There was a breakpoint, stop but don't print.  */
4025       bp_silent,
4026
4027       /* There was a breakpoint, stop and print.  */
4028       bp_noisy,
4029
4030       /* We hit the longjmp breakpoint.  */
4031       long_jump,
4032
4033       /* We hit the longjmp_resume breakpoint.  */
4034       long_resume,
4035
4036       /* We hit the step_resume breakpoint.  */
4037       step_resume,
4038
4039       /* We hit the shared library event breakpoint.  */
4040       shlib_event,
4041
4042       /* We hit the jit event breakpoint.  */
4043       jit_event,
4044
4045       /* This is just used to count how many enums there are.  */
4046       class_last
4047     };
4048
4049   /* Here is the table which drives this routine.  So that we can
4050      format it pretty, we define some abbreviations for the
4051      enum bpstat_what codes.  */
4052 #define kc BPSTAT_WHAT_KEEP_CHECKING
4053 #define ss BPSTAT_WHAT_STOP_SILENT
4054 #define sn BPSTAT_WHAT_STOP_NOISY
4055 #define sgl BPSTAT_WHAT_SINGLE
4056 #define slr BPSTAT_WHAT_SET_LONGJMP_RESUME
4057 #define clr BPSTAT_WHAT_CLEAR_LONGJMP_RESUME
4058 #define sr BPSTAT_WHAT_STEP_RESUME
4059 #define shl BPSTAT_WHAT_CHECK_SHLIBS
4060 #define jit BPSTAT_WHAT_CHECK_JIT
4061
4062 /* "Can't happen."  Might want to print an error message.
4063    abort() is not out of the question, but chances are GDB is just
4064    a bit confused, not unusable.  */
4065 #define err BPSTAT_WHAT_STOP_NOISY
4066
4067   /* Given an old action and a class, come up with a new action.  */
4068   /* One interesting property of this table is that wp_silent is the same
4069      as bp_silent and wp_noisy is the same as bp_noisy.  That is because
4070      after stopping, the check for whether to step over a breakpoint
4071      (BPSTAT_WHAT_SINGLE type stuff) is handled in proceed() without
4072      reference to how we stopped.  We retain separate wp_silent and
4073      bp_silent codes in case we want to change that someday. 
4074
4075      Another possibly interesting property of this table is that
4076      there's a partial ordering, priority-like, of the actions.  Once
4077      you've decided that some action is appropriate, you'll never go
4078      back and decide something of a lower priority is better.  The
4079      ordering is:
4080
4081      kc   < jit clr sgl shl slr sn sr ss
4082      sgl  < jit shl slr sn sr ss
4083      slr  < jit err shl sn sr ss
4084      clr  < jit err shl sn sr ss
4085      ss   < jit shl sn sr
4086      sn   < jit shl sr
4087      jit  < shl sr
4088      shl  < sr
4089      sr   <
4090
4091      What I think this means is that we don't need a damned table
4092      here.  If you just put the rows and columns in the right order,
4093      it'd look awfully regular.  We could simply walk the bpstat list
4094      and choose the highest priority action we find, with a little
4095      logic to handle the 'err' cases.  */
4096
4097   /* step_resume entries: a step resume breakpoint overrides another
4098      breakpoint of signal handling (see comment in wait_for_inferior
4099      at where we set the step_resume breakpoint).  */
4100
4101   static const enum bpstat_what_main_action
4102     table[(int) class_last][(int) BPSTAT_WHAT_LAST] =
4103   {
4104   /*                              old action */
4105   /*               kc   ss   sn   sgl  slr  clr  sr  shl  jit */
4106 /* no_effect */   {kc,  ss,  sn,  sgl, slr, clr, sr, shl, jit},
4107 /* wp_silent */   {ss,  ss,  sn,  ss,  ss,  ss,  sr, shl, jit},
4108 /* wp_noisy */    {sn,  sn,  sn,  sn,  sn,  sn,  sr, shl, jit},
4109 /* bp_nostop */   {sgl, ss,  sn,  sgl, slr, slr, sr, shl, jit},
4110 /* bp_silent */   {ss,  ss,  sn,  ss,  ss,  ss,  sr, shl, jit},
4111 /* bp_noisy */    {sn,  sn,  sn,  sn,  sn,  sn,  sr, shl, jit},
4112 /* long_jump */   {slr, ss,  sn,  slr, slr, err, sr, shl, jit},
4113 /* long_resume */ {clr, ss,  sn,  err, err, err, sr, shl, jit},
4114 /* step_resume */ {sr,  sr,  sr,  sr,  sr,  sr,  sr, sr,  sr },
4115 /* shlib */       {shl, shl, shl, shl, shl, shl, sr, shl, shl},
4116 /* jit_event */   {jit, jit, jit, jit, jit, jit, sr, jit, jit}
4117   };
4118
4119 #undef kc
4120 #undef ss
4121 #undef sn
4122 #undef sgl
4123 #undef slr
4124 #undef clr
4125 #undef err
4126 #undef sr
4127 #undef ts
4128 #undef shl
4129 #undef jit
4130   enum bpstat_what_main_action current_action = BPSTAT_WHAT_KEEP_CHECKING;
4131   struct bpstat_what retval;
4132
4133   retval.call_dummy = 0;
4134   for (; bs != NULL; bs = bs->next)
4135     {
4136       enum class bs_class = no_effect;
4137       if (bs->breakpoint_at == NULL)
4138         /* I suspect this can happen if it was a momentary breakpoint
4139            which has since been deleted.  */
4140         continue;
4141       if (bs->breakpoint_at->owner == NULL)
4142         bs_class = bp_nostop;
4143       else
4144       switch (bs->breakpoint_at->owner->type)
4145         {
4146         case bp_none:
4147           continue;
4148
4149         case bp_breakpoint:
4150         case bp_hardware_breakpoint:
4151         case bp_until:
4152         case bp_finish:
4153           if (bs->stop)
4154             {
4155               if (bs->print)
4156                 bs_class = bp_noisy;
4157               else
4158                 bs_class = bp_silent;
4159             }
4160           else
4161             bs_class = bp_nostop;
4162           break;
4163         case bp_watchpoint:
4164         case bp_hardware_watchpoint:
4165         case bp_read_watchpoint:
4166         case bp_access_watchpoint:
4167           if (bs->stop)
4168             {
4169               if (bs->print)
4170                 bs_class = wp_noisy;
4171               else
4172                 bs_class = wp_silent;
4173             }
4174           else
4175             /* There was a watchpoint, but we're not stopping. 
4176                This requires no further action.  */
4177             bs_class = no_effect;
4178           break;
4179         case bp_longjmp:
4180           bs_class = long_jump;
4181           break;
4182         case bp_longjmp_resume:
4183           bs_class = long_resume;
4184           break;
4185         case bp_step_resume:
4186           if (bs->stop)
4187             {
4188               bs_class = step_resume;
4189             }
4190           else
4191             /* It is for the wrong frame.  */
4192             bs_class = bp_nostop;
4193           break;
4194         case bp_watchpoint_scope:
4195           bs_class = bp_nostop;
4196           break;
4197         case bp_shlib_event:
4198           bs_class = shlib_event;
4199           break;
4200         case bp_jit_event:
4201           bs_class = jit_event;
4202           break;
4203         case bp_thread_event:
4204         case bp_overlay_event:
4205         case bp_longjmp_master:
4206           bs_class = bp_nostop;
4207           break;
4208         case bp_catchpoint:
4209           if (bs->stop)
4210             {
4211               if (bs->print)
4212                 bs_class = bp_noisy;
4213               else
4214                 bs_class = bp_silent;
4215             }
4216           else
4217             /* There was a catchpoint, but we're not stopping.  
4218                This requires no further action.  */
4219             bs_class = no_effect;
4220           break;
4221         case bp_call_dummy:
4222           /* Make sure the action is stop (silent or noisy),
4223              so infrun.c pops the dummy frame.  */
4224           bs_class = bp_silent;
4225           retval.call_dummy = 1;
4226           break;
4227         case bp_tracepoint:
4228         case bp_fast_tracepoint:
4229           /* Tracepoint hits should not be reported back to GDB, and
4230              if one got through somehow, it should have been filtered
4231              out already.  */
4232           internal_error (__FILE__, __LINE__,
4233                           _("bpstat_what: tracepoint encountered"));
4234           break;
4235         }
4236       current_action = table[(int) bs_class][(int) current_action];
4237     }
4238   retval.main_action = current_action;
4239   return retval;
4240 }
4241
4242 /* Nonzero if we should step constantly (e.g. watchpoints on machines
4243    without hardware support).  This isn't related to a specific bpstat,
4244    just to things like whether watchpoints are set.  */
4245
4246 int
4247 bpstat_should_step (void)
4248 {
4249   struct breakpoint *b;
4250   ALL_BREAKPOINTS (b)
4251     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
4252       return 1;
4253   return 0;
4254 }
4255
4256 int
4257 bpstat_causes_stop (bpstat bs)
4258 {
4259   for (; bs != NULL; bs = bs->next)
4260     if (bs->stop)
4261       return 1;
4262
4263   return 0;
4264 }
4265
4266 \f
4267
4268 /* Print the LOC location out of the list of B->LOC locations.  */
4269
4270 static void print_breakpoint_location (struct breakpoint *b,
4271                                        struct bp_location *loc,
4272                                        char *wrap_indent,
4273                                        struct ui_stream *stb)
4274 {
4275   struct cleanup *old_chain = save_current_program_space ();
4276
4277   if (loc != NULL && loc->shlib_disabled)
4278     loc = NULL;
4279
4280   if (loc != NULL)
4281     set_current_program_space (loc->pspace);
4282
4283   if (b->source_file && loc)
4284     {
4285       struct symbol *sym 
4286         = find_pc_sect_function (loc->address, loc->section);
4287       if (sym)
4288         {
4289           ui_out_text (uiout, "in ");
4290           ui_out_field_string (uiout, "func",
4291                                SYMBOL_PRINT_NAME (sym));
4292           ui_out_wrap_hint (uiout, wrap_indent);
4293           ui_out_text (uiout, " at ");
4294         }
4295       ui_out_field_string (uiout, "file", b->source_file);
4296       ui_out_text (uiout, ":");
4297       
4298       if (ui_out_is_mi_like_p (uiout))
4299         {
4300           struct symtab_and_line sal = find_pc_line (loc->address, 0);
4301           char *fullname = symtab_to_fullname (sal.symtab);
4302           
4303           if (fullname)
4304             ui_out_field_string (uiout, "fullname", fullname);
4305         }
4306       
4307       ui_out_field_int (uiout, "line", b->line_number);
4308     }
4309   else if (loc)
4310     {
4311       print_address_symbolic (loc->gdbarch, loc->address, stb->stream,
4312                               demangle, "");
4313       ui_out_field_stream (uiout, "at", stb);
4314     }
4315   else
4316     ui_out_field_string (uiout, "pending", b->addr_string);
4317
4318   do_cleanups (old_chain);
4319 }
4320
4321 /* Print B to gdb_stdout. */
4322 static void
4323 print_one_breakpoint_location (struct breakpoint *b,
4324                                struct bp_location *loc,
4325                                int loc_number,
4326                                struct bp_location **last_loc,
4327                                int print_address_bits,
4328                                int allflag)
4329 {
4330   struct command_line *l;
4331   struct symbol *sym;
4332   struct ep_type_description
4333     {
4334       enum bptype type;
4335       char *description;
4336     };
4337   static struct ep_type_description bptypes[] =
4338   {
4339     {bp_none, "?deleted?"},
4340     {bp_breakpoint, "breakpoint"},
4341     {bp_hardware_breakpoint, "hw breakpoint"},
4342     {bp_until, "until"},
4343     {bp_finish, "finish"},
4344     {bp_watchpoint, "watchpoint"},
4345     {bp_hardware_watchpoint, "hw watchpoint"},
4346     {bp_read_watchpoint, "read watchpoint"},
4347     {bp_access_watchpoint, "acc watchpoint"},
4348     {bp_longjmp, "longjmp"},
4349     {bp_longjmp_resume, "longjmp resume"},
4350     {bp_step_resume, "step resume"},
4351     {bp_watchpoint_scope, "watchpoint scope"},
4352     {bp_call_dummy, "call dummy"},
4353     {bp_shlib_event, "shlib events"},
4354     {bp_thread_event, "thread events"},
4355     {bp_overlay_event, "overlay events"},
4356     {bp_longjmp_master, "longjmp master"},
4357     {bp_catchpoint, "catchpoint"},
4358     {bp_tracepoint, "tracepoint"},
4359     {bp_fast_tracepoint, "fast tracepoint"},
4360     {bp_jit_event, "jit events"},
4361   };
4362   
4363   static char bpenables[] = "nynny";
4364   char wrap_indent[80];
4365   struct ui_stream *stb = ui_out_stream_new (uiout);
4366   struct cleanup *old_chain = make_cleanup_ui_out_stream_delete (stb);
4367   struct cleanup *bkpt_chain;
4368
4369   int header_of_multiple = 0;
4370   int part_of_multiple = (loc != NULL);
4371   struct value_print_options opts;
4372
4373   get_user_print_options (&opts);
4374
4375   gdb_assert (!loc || loc_number != 0);
4376   /* See comment in print_one_breakpoint concerning
4377      treatment of breakpoints with single disabled
4378      location.  */
4379   if (loc == NULL 
4380       && (b->loc != NULL 
4381           && (b->loc->next != NULL || !b->loc->enabled)))
4382     header_of_multiple = 1;
4383   if (loc == NULL)
4384     loc = b->loc;
4385
4386   annotate_record ();
4387   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
4388
4389   /* 1 */
4390   annotate_field (0);
4391   if (part_of_multiple)
4392     {
4393       char *formatted;
4394       formatted = xstrprintf ("%d.%d", b->number, loc_number);
4395       ui_out_field_string (uiout, "number", formatted);
4396       xfree (formatted);
4397     }
4398   else
4399     {
4400       ui_out_field_int (uiout, "number", b->number);
4401     }
4402
4403   /* 2 */
4404   annotate_field (1);
4405   if (part_of_multiple)
4406     ui_out_field_skip (uiout, "type");
4407   else 
4408     {
4409       if (((int) b->type >= (sizeof (bptypes) / sizeof (bptypes[0])))
4410           || ((int) b->type != bptypes[(int) b->type].type))
4411         internal_error (__FILE__, __LINE__,
4412                         _("bptypes table does not describe type #%d."),
4413                         (int) b->type);
4414       ui_out_field_string (uiout, "type", bptypes[(int) b->type].description);
4415     }
4416
4417   /* 3 */
4418   annotate_field (2);
4419   if (part_of_multiple)
4420     ui_out_field_skip (uiout, "disp");
4421   else
4422     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
4423
4424
4425   /* 4 */
4426   annotate_field (3);
4427   if (part_of_multiple)
4428     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
4429   else
4430       ui_out_field_fmt (uiout, "enabled", "%c", 
4431                         bpenables[(int) b->enable_state]);
4432   ui_out_spaces (uiout, 2);
4433
4434   
4435   /* 5 and 6 */
4436   strcpy (wrap_indent, "                           ");
4437   if (opts.addressprint)
4438     {
4439       if (print_address_bits <= 32)
4440         strcat (wrap_indent, "           ");
4441       else
4442         strcat (wrap_indent, "                   ");
4443     }
4444
4445   if (b->ops != NULL && b->ops->print_one != NULL)
4446     {
4447       /* Although the print_one can possibly print
4448          all locations,  calling it here is not likely
4449          to get any nice result.  So, make sure there's
4450          just one location.  */
4451       gdb_assert (b->loc == NULL || b->loc->next == NULL);
4452       b->ops->print_one (b, last_loc);
4453     }
4454   else
4455     switch (b->type)
4456       {
4457       case bp_none:
4458         internal_error (__FILE__, __LINE__,
4459                         _("print_one_breakpoint: bp_none encountered\n"));
4460         break;
4461
4462       case bp_watchpoint:
4463       case bp_hardware_watchpoint:
4464       case bp_read_watchpoint:
4465       case bp_access_watchpoint:
4466         /* Field 4, the address, is omitted (which makes the columns
4467            not line up too nicely with the headers, but the effect
4468            is relatively readable).  */
4469         if (opts.addressprint)
4470           ui_out_field_skip (uiout, "addr");
4471         annotate_field (5);
4472         ui_out_field_string (uiout, "what", b->exp_string);
4473         break;
4474
4475       case bp_breakpoint:
4476       case bp_hardware_breakpoint:
4477       case bp_until:
4478       case bp_finish:
4479       case bp_longjmp:
4480       case bp_longjmp_resume:
4481       case bp_step_resume:
4482       case bp_watchpoint_scope:
4483       case bp_call_dummy:
4484       case bp_shlib_event:
4485       case bp_thread_event:
4486       case bp_overlay_event:
4487       case bp_longjmp_master:
4488       case bp_tracepoint:
4489       case bp_fast_tracepoint:
4490       case bp_jit_event:
4491         if (opts.addressprint)
4492           {
4493             annotate_field (4);
4494             if (header_of_multiple)
4495               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
4496             else if (b->loc == NULL || loc->shlib_disabled)
4497               ui_out_field_string (uiout, "addr", "<PENDING>");
4498             else
4499               ui_out_field_core_addr (uiout, "addr",
4500                                       loc->gdbarch, loc->address);
4501           }
4502         annotate_field (5);
4503         if (!header_of_multiple)
4504           print_breakpoint_location (b, loc, wrap_indent, stb);
4505         if (b->loc)
4506           *last_loc = b->loc;
4507         break;
4508       }
4509
4510
4511   /* For backward compatibility, don't display inferiors unless there
4512      are several.  */
4513   if (loc != NULL
4514       && !header_of_multiple
4515       && (allflag
4516           || (!gdbarch_has_global_breakpoints (target_gdbarch)
4517               && (number_of_program_spaces () > 1
4518                   || number_of_inferiors () > 1)
4519               && loc->owner->type != bp_catchpoint)))
4520     {
4521       struct inferior *inf;
4522       int first = 1;
4523
4524       for (inf = inferior_list; inf != NULL; inf = inf->next)
4525         {
4526           if (inf->pspace == loc->pspace)
4527             {
4528               if (first)
4529                 {
4530                   first = 0;
4531                   ui_out_text (uiout, " inf ");
4532                 }
4533               else
4534                 ui_out_text (uiout, ", ");
4535               ui_out_text (uiout, plongest (inf->num));
4536             }
4537         }
4538     }
4539
4540   if (!part_of_multiple)
4541     {
4542       if (b->thread != -1)
4543         {
4544           /* FIXME: This seems to be redundant and lost here; see the
4545              "stop only in" line a little further down. */
4546           ui_out_text (uiout, " thread ");
4547           ui_out_field_int (uiout, "thread", b->thread);
4548         }
4549       else if (b->task != 0)
4550         {
4551           ui_out_text (uiout, " task ");
4552           ui_out_field_int (uiout, "task", b->task);
4553         }
4554     }
4555   
4556   ui_out_text (uiout, "\n");
4557   
4558   if (part_of_multiple && frame_id_p (b->frame_id))
4559     {
4560       annotate_field (6);
4561       ui_out_text (uiout, "\tstop only in stack frame at ");
4562       /* FIXME: cagney/2002-12-01: Shouldn't be poeking around inside
4563          the frame ID.  */
4564       ui_out_field_core_addr (uiout, "frame",
4565                               b->gdbarch, b->frame_id.stack_addr);
4566       ui_out_text (uiout, "\n");
4567     }
4568   
4569   if (!part_of_multiple && b->cond_string && !ada_exception_catchpoint_p (b))
4570     {
4571       /* We do not print the condition for Ada exception catchpoints
4572          because the condition is an internal implementation detail
4573          that we do not want to expose to the user.  */
4574       annotate_field (7);
4575       if (tracepoint_type (b))
4576         ui_out_text (uiout, "\ttrace only if ");
4577       else
4578         ui_out_text (uiout, "\tstop only if ");
4579       ui_out_field_string (uiout, "cond", b->cond_string);
4580       ui_out_text (uiout, "\n");
4581     }
4582
4583   if (!part_of_multiple && b->thread != -1)
4584     {
4585       /* FIXME should make an annotation for this */
4586       ui_out_text (uiout, "\tstop only in thread ");
4587       ui_out_field_int (uiout, "thread", b->thread);
4588       ui_out_text (uiout, "\n");
4589     }
4590   
4591   if (!part_of_multiple && b->hit_count)
4592     {
4593       /* FIXME should make an annotation for this */
4594       if (ep_is_catchpoint (b))
4595         ui_out_text (uiout, "\tcatchpoint");
4596       else
4597         ui_out_text (uiout, "\tbreakpoint");
4598       ui_out_text (uiout, " already hit ");
4599       ui_out_field_int (uiout, "times", b->hit_count);
4600       if (b->hit_count == 1)
4601         ui_out_text (uiout, " time\n");
4602       else
4603         ui_out_text (uiout, " times\n");
4604     }
4605   
4606   /* Output the count also if it is zero, but only if this is
4607      mi. FIXME: Should have a better test for this. */
4608   if (ui_out_is_mi_like_p (uiout))
4609     if (!part_of_multiple && b->hit_count == 0)
4610       ui_out_field_int (uiout, "times", b->hit_count);
4611
4612   if (!part_of_multiple && b->ignore_count)
4613     {
4614       annotate_field (8);
4615       ui_out_text (uiout, "\tignore next ");
4616       ui_out_field_int (uiout, "ignore", b->ignore_count);
4617       ui_out_text (uiout, " hits\n");
4618     }
4619
4620   l = b->commands;
4621   if (!part_of_multiple && l)
4622     {
4623       struct cleanup *script_chain;
4624
4625       annotate_field (9);
4626       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
4627       print_command_lines (uiout, l, 4);
4628       do_cleanups (script_chain);
4629     }
4630
4631   if (!part_of_multiple && b->pass_count)
4632     {
4633       annotate_field (10);
4634       ui_out_text (uiout, "\tpass count ");
4635       ui_out_field_int (uiout, "pass", b->pass_count);
4636       ui_out_text (uiout, " \n");
4637     }
4638
4639   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
4640     {
4641       if (b->addr_string)
4642         ui_out_field_string (uiout, "original-location", b->addr_string);
4643       else if (b->exp_string)
4644         ui_out_field_string (uiout, "original-location", b->exp_string);
4645     }
4646         
4647   do_cleanups (bkpt_chain);
4648   do_cleanups (old_chain);
4649 }
4650
4651 static void
4652 print_one_breakpoint (struct breakpoint *b,
4653                       struct bp_location **last_loc, int print_address_bits,
4654                       int allflag)
4655 {
4656   print_one_breakpoint_location (b, NULL, 0, last_loc,
4657                                  print_address_bits, allflag);
4658
4659   /* If this breakpoint has custom print function,
4660      it's already printed.  Otherwise, print individual
4661      locations, if any.  */
4662   if (b->ops == NULL || b->ops->print_one == NULL)
4663     {
4664       /* If breakpoint has a single location that is
4665          disabled, we print it as if it had
4666          several locations, since otherwise it's hard to
4667          represent "breakpoint enabled, location disabled"
4668          situation.  
4669          Note that while hardware watchpoints have
4670          several locations internally, that's no a property
4671          exposed to user.  */
4672       if (b->loc 
4673           && !is_hardware_watchpoint (b)
4674           && (b->loc->next || !b->loc->enabled)
4675           && !ui_out_is_mi_like_p (uiout)) 
4676         {
4677           struct bp_location *loc;
4678           int n = 1;
4679           for (loc = b->loc; loc; loc = loc->next, ++n)
4680             print_one_breakpoint_location (b, loc, n, last_loc,
4681                                            print_address_bits, allflag);
4682         }
4683     }
4684 }
4685
4686 static int
4687 breakpoint_address_bits (struct breakpoint *b)
4688 {
4689   int print_address_bits = 0;
4690   struct bp_location *loc;
4691
4692   for (loc = b->loc; loc; loc = loc->next)
4693     {
4694       int addr_bit;
4695
4696       /* Software watchpoints that aren't watching memory don't have
4697          an address to print.  */
4698       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
4699         continue;
4700
4701       addr_bit = gdbarch_addr_bit (loc->gdbarch);
4702       if (addr_bit > print_address_bits)
4703         print_address_bits = addr_bit;
4704     }
4705
4706   return print_address_bits;
4707 }
4708
4709 struct captured_breakpoint_query_args
4710   {
4711     int bnum;
4712   };
4713
4714 static int
4715 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
4716 {
4717   struct captured_breakpoint_query_args *args = data;
4718   struct breakpoint *b;
4719   struct bp_location *dummy_loc = NULL;
4720   ALL_BREAKPOINTS (b)
4721     {
4722       if (args->bnum == b->number)
4723         {
4724           int print_address_bits = breakpoint_address_bits (b);
4725           print_one_breakpoint (b, &dummy_loc, print_address_bits, 0);
4726           return GDB_RC_OK;
4727         }
4728     }
4729   return GDB_RC_NONE;
4730 }
4731
4732 enum gdb_rc
4733 gdb_breakpoint_query (struct ui_out *uiout, int bnum, char **error_message)
4734 {
4735   struct captured_breakpoint_query_args args;
4736   args.bnum = bnum;
4737   /* For the moment we don't trust print_one_breakpoint() to not throw
4738      an error. */
4739   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
4740                                  error_message, RETURN_MASK_ALL) < 0)
4741     return GDB_RC_FAIL;
4742   else
4743     return GDB_RC_OK;
4744 }
4745
4746 /* Return non-zero if B is user settable (breakpoints, watchpoints,
4747    catchpoints, et.al.). */
4748
4749 static int
4750 user_settable_breakpoint (const struct breakpoint *b)
4751 {
4752   return (b->type == bp_breakpoint
4753           || b->type == bp_catchpoint
4754           || b->type == bp_hardware_breakpoint
4755           || tracepoint_type (b)
4756           || b->type == bp_watchpoint
4757           || b->type == bp_read_watchpoint
4758           || b->type == bp_access_watchpoint
4759           || b->type == bp_hardware_watchpoint);
4760 }
4761         
4762 /* Print information on user settable breakpoint (watchpoint, etc)
4763    number BNUM.  If BNUM is -1 print all user settable breakpoints.
4764    If ALLFLAG is non-zero, include non- user settable breakpoints. */
4765
4766 static void
4767 breakpoint_1 (int bnum, int allflag)
4768 {
4769   struct breakpoint *b;
4770   struct bp_location *last_loc = NULL;
4771   int nr_printable_breakpoints;
4772   struct cleanup *bkpttbl_chain;
4773   struct value_print_options opts;
4774   int print_address_bits = 0;
4775   
4776   get_user_print_options (&opts);
4777
4778   /* Compute the number of rows in the table, as well as the
4779      size required for address fields.  */
4780   nr_printable_breakpoints = 0;
4781   ALL_BREAKPOINTS (b)
4782     if (bnum == -1
4783         || bnum == b->number)
4784       {
4785         if (allflag || user_settable_breakpoint (b))
4786           {
4787             int addr_bit = breakpoint_address_bits (b);
4788             if (addr_bit > print_address_bits)
4789               print_address_bits = addr_bit;
4790
4791             nr_printable_breakpoints++;
4792           }
4793       }
4794
4795   if (opts.addressprint)
4796     bkpttbl_chain 
4797       = make_cleanup_ui_out_table_begin_end (uiout, 6, nr_printable_breakpoints,
4798                                              "BreakpointTable");
4799   else
4800     bkpttbl_chain 
4801       = make_cleanup_ui_out_table_begin_end (uiout, 5, nr_printable_breakpoints,
4802                                              "BreakpointTable");
4803
4804   if (nr_printable_breakpoints > 0)
4805     annotate_breakpoints_headers ();
4806   if (nr_printable_breakpoints > 0)
4807     annotate_field (0);
4808   ui_out_table_header (uiout, 7, ui_left, "number", "Num");             /* 1 */
4809   if (nr_printable_breakpoints > 0)
4810     annotate_field (1);
4811   ui_out_table_header (uiout, 14, ui_left, "type", "Type");             /* 2 */
4812   if (nr_printable_breakpoints > 0)
4813     annotate_field (2);
4814   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");              /* 3 */
4815   if (nr_printable_breakpoints > 0)
4816     annotate_field (3);
4817   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
4818   if (opts.addressprint)
4819         {
4820           if (nr_printable_breakpoints > 0)
4821             annotate_field (4);
4822           if (print_address_bits <= 32)
4823             ui_out_table_header (uiout, 10, ui_left, "addr", "Address");/* 5 */
4824           else
4825             ui_out_table_header (uiout, 18, ui_left, "addr", "Address");/* 5 */
4826         }
4827   if (nr_printable_breakpoints > 0)
4828     annotate_field (5);
4829   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
4830   ui_out_table_body (uiout);
4831   if (nr_printable_breakpoints > 0)
4832     annotate_breakpoints_table ();
4833
4834   ALL_BREAKPOINTS (b)
4835   {
4836     QUIT;
4837     if (bnum == -1
4838         || bnum == b->number)
4839       {
4840         /* We only print out user settable breakpoints unless the
4841            allflag is set. */
4842         if (allflag || user_settable_breakpoint (b))
4843           print_one_breakpoint (b, &last_loc, print_address_bits, allflag);
4844       }
4845   }
4846   
4847   do_cleanups (bkpttbl_chain);
4848
4849   if (nr_printable_breakpoints == 0)
4850     {
4851       if (bnum == -1)
4852         ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
4853       else
4854         ui_out_message (uiout, 0, "No breakpoint or watchpoint number %d.\n",
4855                         bnum);
4856     }
4857   else
4858     {
4859       if (last_loc && !server_command)
4860         set_next_address (last_loc->gdbarch, last_loc->address);
4861     }
4862
4863   /* FIXME? Should this be moved up so that it is only called when
4864      there have been breakpoints? */
4865   annotate_breakpoints_table_end ();
4866 }
4867
4868 static void
4869 breakpoints_info (char *bnum_exp, int from_tty)
4870 {
4871   int bnum = -1;
4872
4873   if (bnum_exp)
4874     bnum = parse_and_eval_long (bnum_exp);
4875
4876   breakpoint_1 (bnum, 0);
4877 }
4878
4879 static void
4880 maintenance_info_breakpoints (char *bnum_exp, int from_tty)
4881 {
4882   int bnum = -1;
4883
4884   if (bnum_exp)
4885     bnum = parse_and_eval_long (bnum_exp);
4886
4887   breakpoint_1 (bnum, 1);
4888 }
4889
4890 static int
4891 breakpoint_has_pc (struct breakpoint *b,
4892                    struct program_space *pspace,
4893                    CORE_ADDR pc, struct obj_section *section)
4894 {
4895   struct bp_location *bl = b->loc;
4896   for (; bl; bl = bl->next)
4897     {
4898       if (bl->pspace == pspace
4899           && bl->address == pc
4900           && (!overlay_debugging || bl->section == section))
4901         return 1;         
4902     }
4903   return 0;
4904 }
4905
4906 /* Print a message describing any breakpoints set at PC.  This
4907    concerns with logical breakpoints, so we match program spaces, not
4908    address spaces.  */
4909
4910 static void
4911 describe_other_breakpoints (struct gdbarch *gdbarch,
4912                             struct program_space *pspace, CORE_ADDR pc,
4913                             struct obj_section *section, int thread)
4914 {
4915   int others = 0;
4916   struct breakpoint *b;
4917
4918   ALL_BREAKPOINTS (b)
4919     others += breakpoint_has_pc (b, pspace, pc, section);
4920   if (others > 0)
4921     {
4922       if (others == 1)
4923         printf_filtered (_("Note: breakpoint "));
4924       else /* if (others == ???) */
4925         printf_filtered (_("Note: breakpoints "));
4926       ALL_BREAKPOINTS (b)
4927         if (breakpoint_has_pc (b, pspace, pc, section))
4928           {
4929             others--;
4930             printf_filtered ("%d", b->number);
4931             if (b->thread == -1 && thread != -1)
4932               printf_filtered (" (all threads)");
4933             else if (b->thread != -1)
4934               printf_filtered (" (thread %d)", b->thread);
4935             printf_filtered ("%s%s ",
4936                              ((b->enable_state == bp_disabled
4937                                || b->enable_state == bp_call_disabled
4938                                || b->enable_state == bp_startup_disabled)
4939                               ? " (disabled)"
4940                               : b->enable_state == bp_permanent 
4941                               ? " (permanent)"
4942                               : ""),
4943                              (others > 1) ? "," 
4944                              : ((others == 1) ? " and" : ""));
4945           }
4946       printf_filtered (_("also set at pc "));
4947       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
4948       printf_filtered (".\n");
4949     }
4950 }
4951 \f
4952 /* Set the default place to put a breakpoint
4953    for the `break' command with no arguments.  */
4954
4955 void
4956 set_default_breakpoint (int valid, struct program_space *pspace,
4957                         CORE_ADDR addr, struct symtab *symtab,
4958                         int line)
4959 {
4960   default_breakpoint_valid = valid;
4961   default_breakpoint_pspace = pspace;
4962   default_breakpoint_address = addr;
4963   default_breakpoint_symtab = symtab;
4964   default_breakpoint_line = line;
4965 }
4966
4967 /* Return true iff it is meaningful to use the address member of
4968    BPT.  For some breakpoint types, the address member is irrelevant
4969    and it makes no sense to attempt to compare it to other addresses
4970    (or use it for any other purpose either).
4971
4972    More specifically, each of the following breakpoint types will always
4973    have a zero valued address and we don't want to mark breakpoints of any of
4974    these types to be a duplicate of an actual breakpoint at address zero:
4975
4976       bp_watchpoint
4977       bp_catchpoint
4978
4979 */
4980
4981 static int
4982 breakpoint_address_is_meaningful (struct breakpoint *bpt)
4983 {
4984   enum bptype type = bpt->type;
4985
4986   return (type != bp_watchpoint && type != bp_catchpoint);
4987 }
4988
4989 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
4990    true if LOC1 and LOC2 represent the same watchpoint location.  */
4991
4992 static int
4993 watchpoint_locations_match (struct bp_location *loc1, struct bp_location *loc2)
4994 {
4995   /* Note that this checks the owner's type, not the location's.  In
4996      case the target does not support read watchpoints, but does
4997      support access watchpoints, we'll have bp_read_watchpoint
4998      watchpoints with hw_access locations.  Those should be considered
4999      duplicates of hw_read locations.  The hw_read locations will
5000      become hw_access locations later.  */
5001   return (loc1->owner->type == loc2->owner->type
5002           && loc1->pspace->aspace == loc2->pspace->aspace
5003           && loc1->address == loc2->address
5004           && loc1->length == loc2->length);
5005 }
5006
5007 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
5008    same breakpoint location.  In most targets, this can only be true
5009    if ASPACE1 matches ASPACE2.  On targets that have global
5010    breakpoints, the address space doesn't really matter.  */
5011
5012 static int
5013 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
5014                           struct address_space *aspace2, CORE_ADDR addr2)
5015 {
5016   return ((gdbarch_has_global_breakpoints (target_gdbarch)
5017            || aspace1 == aspace2)
5018           && addr1 == addr2);
5019 }
5020
5021 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
5022    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
5023    represent the same location.  */
5024
5025 static int
5026 breakpoint_locations_match (struct bp_location *loc1, struct bp_location *loc2)
5027 {
5028   int hw_point1 = is_hardware_watchpoint (loc1->owner);
5029   int hw_point2 = is_hardware_watchpoint (loc2->owner);
5030
5031   if (hw_point1 != hw_point2)
5032     return 0;
5033   else if (hw_point1)
5034     return watchpoint_locations_match (loc1, loc2);
5035   else
5036     return breakpoint_address_match (loc1->pspace->aspace, loc1->address,
5037                                      loc2->pspace->aspace, loc2->address);
5038 }
5039
5040 static void
5041 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
5042                                int bnum, int have_bnum)
5043 {
5044   char astr1[40];
5045   char astr2[40];
5046
5047   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
5048   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
5049   if (have_bnum)
5050     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
5051              bnum, astr1, astr2);
5052   else
5053     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
5054 }
5055
5056 /* Adjust a breakpoint's address to account for architectural constraints
5057    on breakpoint placement.  Return the adjusted address.  Note: Very
5058    few targets require this kind of adjustment.  For most targets,
5059    this function is simply the identity function.  */
5060
5061 static CORE_ADDR
5062 adjust_breakpoint_address (struct gdbarch *gdbarch,
5063                            CORE_ADDR bpaddr, enum bptype bptype)
5064 {
5065   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
5066     {
5067       /* Very few targets need any kind of breakpoint adjustment.  */
5068       return bpaddr;
5069     }
5070   else if (bptype == bp_watchpoint
5071            || bptype == bp_hardware_watchpoint
5072            || bptype == bp_read_watchpoint
5073            || bptype == bp_access_watchpoint
5074            || bptype == bp_catchpoint)
5075     {
5076       /* Watchpoints and the various bp_catch_* eventpoints should not
5077          have their addresses modified.  */
5078       return bpaddr;
5079     }
5080   else
5081     {
5082       CORE_ADDR adjusted_bpaddr;
5083
5084       /* Some targets have architectural constraints on the placement
5085          of breakpoint instructions.  Obtain the adjusted address.  */
5086       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
5087
5088       /* An adjusted breakpoint address can significantly alter
5089          a user's expectations.  Print a warning if an adjustment
5090          is required.  */
5091       if (adjusted_bpaddr != bpaddr)
5092         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
5093
5094       return adjusted_bpaddr;
5095     }
5096 }
5097
5098 /* Allocate a struct bp_location.  */
5099
5100 static struct bp_location *
5101 allocate_bp_location (struct breakpoint *bpt)
5102 {
5103   struct bp_location *loc, *loc_p;
5104
5105   loc = xmalloc (sizeof (struct bp_location));
5106   memset (loc, 0, sizeof (*loc));
5107
5108   loc->owner = bpt;
5109   loc->cond = NULL;
5110   loc->shlib_disabled = 0;
5111   loc->enabled = 1;
5112
5113   switch (bpt->type)
5114     {
5115     case bp_breakpoint:
5116     case bp_until:
5117     case bp_finish:
5118     case bp_longjmp:
5119     case bp_longjmp_resume:
5120     case bp_step_resume:
5121     case bp_watchpoint_scope:
5122     case bp_call_dummy:
5123     case bp_shlib_event:
5124     case bp_thread_event:
5125     case bp_overlay_event:
5126     case bp_jit_event:
5127     case bp_longjmp_master:
5128       loc->loc_type = bp_loc_software_breakpoint;
5129       break;
5130     case bp_hardware_breakpoint:
5131       loc->loc_type = bp_loc_hardware_breakpoint;
5132       break;
5133     case bp_hardware_watchpoint:
5134     case bp_read_watchpoint:
5135     case bp_access_watchpoint:
5136       loc->loc_type = bp_loc_hardware_watchpoint;
5137       break;
5138     case bp_watchpoint:
5139     case bp_catchpoint:
5140     case bp_tracepoint:
5141     case bp_fast_tracepoint:
5142       loc->loc_type = bp_loc_other;
5143       break;
5144     default:
5145       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
5146     }
5147
5148   return loc;
5149 }
5150
5151 static void free_bp_location (struct bp_location *loc)
5152 {
5153   if (loc->cond)
5154     xfree (loc->cond);
5155
5156   if (loc->function_name)
5157     xfree (loc->function_name);
5158   
5159   xfree (loc);
5160 }
5161
5162 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
5163    that has type BPTYPE and has no locations as yet.  */
5164 /* This function is used in gdbtk sources and thus can not be made static.  */
5165
5166 static struct breakpoint *
5167 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
5168                                      enum bptype bptype)
5169 {
5170   struct breakpoint *b, *b1;
5171
5172   b = (struct breakpoint *) xmalloc (sizeof (struct breakpoint));
5173   memset (b, 0, sizeof (*b));
5174
5175   b->type = bptype;
5176   b->gdbarch = gdbarch;
5177   b->language = current_language->la_language;
5178   b->input_radix = input_radix;
5179   b->thread = -1;
5180   b->enable_state = bp_enabled;
5181   b->next = 0;
5182   b->silent = 0;
5183   b->ignore_count = 0;
5184   b->commands = NULL;
5185   b->frame_id = null_frame_id;
5186   b->forked_inferior_pid = null_ptid;
5187   b->exec_pathname = NULL;
5188   b->syscalls_to_be_caught = NULL;
5189   b->ops = NULL;
5190   b->condition_not_parsed = 0;
5191
5192   /* Add this breakpoint to the end of the chain
5193      so that a list of breakpoints will come out in order
5194      of increasing numbers.  */
5195
5196   b1 = breakpoint_chain;
5197   if (b1 == 0)
5198     breakpoint_chain = b;
5199   else
5200     {
5201       while (b1->next)
5202         b1 = b1->next;
5203       b1->next = b;
5204     }
5205   return b;
5206 }
5207
5208 /* Initialize loc->function_name.  */
5209 static void
5210 set_breakpoint_location_function (struct bp_location *loc)
5211 {
5212   if (loc->owner->type == bp_breakpoint
5213       || loc->owner->type == bp_hardware_breakpoint
5214       || tracepoint_type (loc->owner))
5215     {
5216       find_pc_partial_function (loc->address, &(loc->function_name), 
5217                                 NULL, NULL);
5218       if (loc->function_name)
5219         loc->function_name = xstrdup (loc->function_name);
5220     }
5221 }
5222
5223 /* Attempt to determine architecture of location identified by SAL.  */
5224 static struct gdbarch *
5225 get_sal_arch (struct symtab_and_line sal)
5226 {
5227   if (sal.section)
5228     return get_objfile_arch (sal.section->objfile);
5229   if (sal.symtab)
5230     return get_objfile_arch (sal.symtab->objfile);
5231
5232   return NULL;
5233 }
5234
5235 /* set_raw_breakpoint is a low level routine for allocating and
5236    partially initializing a breakpoint of type BPTYPE.  The newly
5237    created breakpoint's address, section, source file name, and line
5238    number are provided by SAL.  The newly created and partially
5239    initialized breakpoint is added to the breakpoint chain and
5240    is also returned as the value of this function.
5241
5242    It is expected that the caller will complete the initialization of
5243    the newly created breakpoint struct as well as output any status
5244    information regarding the creation of a new breakpoint.  In
5245    particular, set_raw_breakpoint does NOT set the breakpoint
5246    number!  Care should be taken to not allow an error to occur
5247    prior to completing the initialization of the breakpoint.  If this
5248    should happen, a bogus breakpoint will be left on the chain.  */
5249
5250 struct breakpoint *
5251 set_raw_breakpoint (struct gdbarch *gdbarch,
5252                     struct symtab_and_line sal, enum bptype bptype)
5253 {
5254   struct breakpoint *b = set_raw_breakpoint_without_location (gdbarch, bptype);
5255   CORE_ADDR adjusted_address;
5256   struct gdbarch *loc_gdbarch;
5257
5258   loc_gdbarch = get_sal_arch (sal);
5259   if (!loc_gdbarch)
5260     loc_gdbarch = b->gdbarch;
5261
5262   if (bptype != bp_catchpoint)
5263     gdb_assert (sal.pspace != NULL);
5264
5265   /* Adjust the breakpoint's address prior to allocating a location.
5266      Once we call allocate_bp_location(), that mostly uninitialized
5267      location will be placed on the location chain.  Adjustment of the
5268      breakpoint may cause target_read_memory() to be called and we do
5269      not want its scan of the location chain to find a breakpoint and
5270      location that's only been partially initialized.  */
5271   adjusted_address = adjust_breakpoint_address (loc_gdbarch, sal.pc, b->type);
5272
5273   b->loc = allocate_bp_location (b);
5274   b->loc->gdbarch = loc_gdbarch;
5275   b->loc->requested_address = sal.pc;
5276   b->loc->address = adjusted_address;
5277   b->loc->pspace = sal.pspace;
5278
5279   /* Store the program space that was used to set the breakpoint, for
5280      breakpoint resetting.  */
5281   b->pspace = sal.pspace;
5282
5283   if (sal.symtab == NULL)
5284     b->source_file = NULL;
5285   else
5286     b->source_file = xstrdup (sal.symtab->filename);
5287   b->loc->section = sal.section;
5288   b->line_number = sal.line;
5289
5290   set_breakpoint_location_function (b->loc);
5291
5292   breakpoints_changed ();
5293
5294   return b;
5295 }
5296
5297
5298 /* Note that the breakpoint object B describes a permanent breakpoint
5299    instruction, hard-wired into the inferior's code.  */
5300 void
5301 make_breakpoint_permanent (struct breakpoint *b)
5302 {
5303   struct bp_location *bl;
5304   b->enable_state = bp_permanent;
5305
5306   /* By definition, permanent breakpoints are already present in the code. 
5307      Mark all locations as inserted.  For now, make_breakpoint_permanent
5308      is called in just one place, so it's hard to say if it's reasonable
5309      to have permanent breakpoint with multiple locations or not,
5310      but it's easy to implmement.  */
5311   for (bl = b->loc; bl; bl = bl->next)
5312     bl->inserted = 1;
5313 }
5314
5315 /* Call this routine when stepping and nexting to enable a breakpoint
5316    if we do a longjmp() in THREAD.  When we hit that breakpoint, call
5317    set_longjmp_resume_breakpoint() to figure out where we are going. */
5318
5319 void
5320 set_longjmp_breakpoint (int thread)
5321 {
5322   struct breakpoint *b, *temp;
5323
5324   /* To avoid having to rescan all objfile symbols at every step,
5325      we maintain a list of continually-inserted but always disabled
5326      longjmp "master" breakpoints.  Here, we simply create momentary
5327      clones of those and enable them for the requested thread.  */
5328   ALL_BREAKPOINTS_SAFE (b, temp)
5329     if (b->pspace == current_program_space
5330         && b->type == bp_longjmp_master)
5331       {
5332         struct breakpoint *clone = clone_momentary_breakpoint (b);
5333         clone->type = bp_longjmp;
5334         clone->thread = thread;
5335       }
5336 }
5337
5338 /* Delete all longjmp breakpoints from THREAD.  */
5339 void
5340 delete_longjmp_breakpoint (int thread)
5341 {
5342   struct breakpoint *b, *temp;
5343
5344   ALL_BREAKPOINTS_SAFE (b, temp)
5345     if (b->type == bp_longjmp)
5346       {
5347         if (b->thread == thread)
5348           delete_breakpoint (b);
5349       }
5350 }
5351
5352 void
5353 enable_overlay_breakpoints (void)
5354 {
5355   struct breakpoint *b;
5356
5357   ALL_BREAKPOINTS (b)
5358     if (b->type == bp_overlay_event)
5359     {
5360       b->enable_state = bp_enabled;
5361       update_global_location_list (1);
5362       overlay_events_enabled = 1;
5363     }
5364 }
5365
5366 void
5367 disable_overlay_breakpoints (void)
5368 {
5369   struct breakpoint *b;
5370
5371   ALL_BREAKPOINTS (b)
5372     if (b->type == bp_overlay_event)
5373     {
5374       b->enable_state = bp_disabled;
5375       update_global_location_list (0);
5376       overlay_events_enabled = 0;
5377     }
5378 }
5379
5380 struct breakpoint *
5381 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
5382 {
5383   struct breakpoint *b;
5384
5385   b = create_internal_breakpoint (gdbarch, address, bp_thread_event);
5386   
5387   b->enable_state = bp_enabled;
5388   /* addr_string has to be used or breakpoint_re_set will delete me.  */
5389   b->addr_string
5390     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
5391
5392   update_global_location_list_nothrow (1);
5393
5394   return b;
5395 }
5396
5397 void
5398 remove_thread_event_breakpoints (void)
5399 {
5400   struct breakpoint *b, *temp;
5401
5402   ALL_BREAKPOINTS_SAFE (b, temp)
5403     if (b->type == bp_thread_event
5404         && b->loc->pspace == current_program_space)
5405       delete_breakpoint (b);
5406 }
5407
5408 struct captured_parse_breakpoint_args
5409   {
5410     char **arg_p;
5411     struct symtabs_and_lines *sals_p;
5412     char ***addr_string_p;
5413     int *not_found_ptr;
5414   };
5415
5416 struct lang_and_radix
5417   {
5418     enum language lang;
5419     int radix;
5420   };
5421
5422 /* Create a breakpoint for JIT code registration and unregistration.  */
5423
5424 struct breakpoint *
5425 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
5426 {
5427   struct breakpoint *b;
5428
5429   b = create_internal_breakpoint (gdbarch, address, bp_jit_event);
5430   update_global_location_list_nothrow (1);
5431   return b;
5432 }
5433
5434 void
5435 remove_solib_event_breakpoints (void)
5436 {
5437   struct breakpoint *b, *temp;
5438
5439   ALL_BREAKPOINTS_SAFE (b, temp)
5440     if (b->type == bp_shlib_event
5441         && b->loc->pspace == current_program_space)
5442       delete_breakpoint (b);
5443 }
5444
5445 struct breakpoint *
5446 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
5447 {
5448   struct breakpoint *b;
5449
5450   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event);
5451   update_global_location_list_nothrow (1);
5452   return b;
5453 }
5454
5455 /* Disable any breakpoints that are on code in shared libraries.  Only
5456    apply to enabled breakpoints, disabled ones can just stay disabled.  */
5457
5458 void
5459 disable_breakpoints_in_shlibs (void)
5460 {
5461   struct bp_location *loc, **locp_tmp;
5462
5463   ALL_BP_LOCATIONS (loc, locp_tmp)
5464   {
5465     struct breakpoint *b = loc->owner;
5466     /* We apply the check to all breakpoints, including disabled
5467        for those with loc->duplicate set.  This is so that when breakpoint
5468        becomes enabled, or the duplicate is removed, gdb will try to insert
5469        all breakpoints.  If we don't set shlib_disabled here, we'll try
5470        to insert those breakpoints and fail.  */
5471     if (((b->type == bp_breakpoint)
5472          || (b->type == bp_jit_event)
5473          || (b->type == bp_hardware_breakpoint)
5474          || (tracepoint_type (b)))
5475         && loc->pspace == current_program_space
5476         && !loc->shlib_disabled
5477 #ifdef PC_SOLIB
5478         && PC_SOLIB (loc->address)
5479 #else
5480         && solib_name_from_address (loc->pspace, loc->address)
5481 #endif
5482         )
5483       {
5484         loc->shlib_disabled = 1;
5485       }
5486   }
5487 }
5488
5489 /* Disable any breakpoints that are in in an unloaded shared library.  Only
5490    apply to enabled breakpoints, disabled ones can just stay disabled.  */
5491
5492 static void
5493 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
5494 {
5495   struct bp_location *loc, **locp_tmp;
5496   int disabled_shlib_breaks = 0;
5497
5498   /* SunOS a.out shared libraries are always mapped, so do not
5499      disable breakpoints; they will only be reported as unloaded
5500      through clear_solib when GDB discards its shared library
5501      list.  See clear_solib for more information.  */
5502   if (exec_bfd != NULL
5503       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
5504     return;
5505
5506   ALL_BP_LOCATIONS (loc, locp_tmp)
5507   {
5508     struct breakpoint *b = loc->owner;
5509     if ((loc->loc_type == bp_loc_hardware_breakpoint
5510          || loc->loc_type == bp_loc_software_breakpoint)
5511         && solib->pspace == loc->pspace
5512         && !loc->shlib_disabled
5513         && (b->type == bp_breakpoint
5514             || b->type == bp_jit_event
5515             || b->type == bp_hardware_breakpoint)
5516         && solib_contains_address_p (solib, loc->address))
5517       {
5518         loc->shlib_disabled = 1;
5519         /* At this point, we cannot rely on remove_breakpoint
5520            succeeding so we must mark the breakpoint as not inserted
5521            to prevent future errors occurring in remove_breakpoints.  */
5522         loc->inserted = 0;
5523         if (!disabled_shlib_breaks)
5524           {
5525             target_terminal_ours_for_output ();
5526             warning (_("Temporarily disabling breakpoints for unloaded shared library \"%s\""),
5527                      solib->so_name);
5528           }
5529         disabled_shlib_breaks = 1;
5530       }
5531   }
5532 }
5533
5534 /* FORK & VFORK catchpoints.  */
5535
5536 /* Implement the "insert" breakpoint_ops method for fork catchpoints.  */
5537
5538 static void
5539 insert_catch_fork (struct breakpoint *b)
5540 {
5541   target_insert_fork_catchpoint (PIDGET (inferior_ptid));
5542 }
5543
5544 /* Implement the "remove" breakpoint_ops method for fork catchpoints.  */
5545
5546 static int
5547 remove_catch_fork (struct breakpoint *b)
5548 {
5549   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
5550 }
5551
5552 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
5553    catchpoints.  */
5554
5555 static int
5556 breakpoint_hit_catch_fork (struct breakpoint *b)
5557 {
5558   return inferior_has_forked (inferior_ptid, &b->forked_inferior_pid);
5559 }
5560
5561 /* Implement the "print_it" breakpoint_ops method for fork catchpoints.  */
5562
5563 static enum print_stop_action
5564 print_it_catch_fork (struct breakpoint *b)
5565 {
5566   annotate_catchpoint (b->number);
5567   printf_filtered (_("\nCatchpoint %d (forked process %d), "),
5568                    b->number, ptid_get_pid (b->forked_inferior_pid));
5569   return PRINT_SRC_AND_LOC;
5570 }
5571
5572 /* Implement the "print_one" breakpoint_ops method for fork catchpoints.  */
5573
5574 static void
5575 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
5576 {
5577   struct value_print_options opts;
5578
5579   get_user_print_options (&opts);
5580
5581   /* Field 4, the address, is omitted (which makes the columns
5582      not line up too nicely with the headers, but the effect
5583      is relatively readable).  */
5584   if (opts.addressprint)
5585     ui_out_field_skip (uiout, "addr");
5586   annotate_field (5);
5587   ui_out_text (uiout, "fork");
5588   if (!ptid_equal (b->forked_inferior_pid, null_ptid))
5589     {
5590       ui_out_text (uiout, ", process ");
5591       ui_out_field_int (uiout, "what",
5592                         ptid_get_pid (b->forked_inferior_pid));
5593       ui_out_spaces (uiout, 1);
5594     }
5595 }
5596
5597 /* Implement the "print_mention" breakpoint_ops method for fork
5598    catchpoints.  */
5599
5600 static void
5601 print_mention_catch_fork (struct breakpoint *b)
5602 {
5603   printf_filtered (_("Catchpoint %d (fork)"), b->number);
5604 }
5605
5606 /* The breakpoint_ops structure to be used in fork catchpoints.  */
5607
5608 static struct breakpoint_ops catch_fork_breakpoint_ops =
5609 {
5610   insert_catch_fork,
5611   remove_catch_fork,
5612   breakpoint_hit_catch_fork,
5613   print_it_catch_fork,
5614   print_one_catch_fork,
5615   print_mention_catch_fork
5616 };
5617
5618 /* Implement the "insert" breakpoint_ops method for vfork catchpoints.  */
5619
5620 static void
5621 insert_catch_vfork (struct breakpoint *b)
5622 {
5623   target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
5624 }
5625
5626 /* Implement the "remove" breakpoint_ops method for vfork catchpoints.  */
5627
5628 static int
5629 remove_catch_vfork (struct breakpoint *b)
5630 {
5631   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
5632 }
5633
5634 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
5635    catchpoints.  */
5636
5637 static int
5638 breakpoint_hit_catch_vfork (struct breakpoint *b)
5639 {
5640   return inferior_has_vforked (inferior_ptid, &b->forked_inferior_pid);
5641 }
5642
5643 /* Implement the "print_it" breakpoint_ops method for vfork catchpoints.  */
5644
5645 static enum print_stop_action
5646 print_it_catch_vfork (struct breakpoint *b)
5647 {
5648   annotate_catchpoint (b->number);
5649   printf_filtered (_("\nCatchpoint %d (vforked process %d), "),
5650                    b->number, ptid_get_pid (b->forked_inferior_pid));
5651   return PRINT_SRC_AND_LOC;
5652 }
5653
5654 /* Implement the "print_one" breakpoint_ops method for vfork catchpoints.  */
5655
5656 static void
5657 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
5658 {
5659   struct value_print_options opts;
5660
5661   get_user_print_options (&opts);
5662   /* Field 4, the address, is omitted (which makes the columns
5663      not line up too nicely with the headers, but the effect
5664      is relatively readable).  */
5665   if (opts.addressprint)
5666     ui_out_field_skip (uiout, "addr");
5667   annotate_field (5);
5668   ui_out_text (uiout, "vfork");
5669   if (!ptid_equal (b->forked_inferior_pid, null_ptid))
5670     {
5671       ui_out_text (uiout, ", process ");
5672       ui_out_field_int (uiout, "what",
5673                         ptid_get_pid (b->forked_inferior_pid));
5674       ui_out_spaces (uiout, 1);
5675     }
5676 }
5677
5678 /* Implement the "print_mention" breakpoint_ops method for vfork
5679    catchpoints.  */
5680
5681 static void
5682 print_mention_catch_vfork (struct breakpoint *b)
5683 {
5684   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
5685 }
5686
5687 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
5688
5689 static struct breakpoint_ops catch_vfork_breakpoint_ops =
5690 {
5691   insert_catch_vfork,
5692   remove_catch_vfork,
5693   breakpoint_hit_catch_vfork,
5694   print_it_catch_vfork,
5695   print_one_catch_vfork,
5696   print_mention_catch_vfork
5697 };
5698
5699 /* Implement the "insert" breakpoint_ops method for syscall
5700    catchpoints.  */
5701
5702 static void
5703 insert_catch_syscall (struct breakpoint *b)
5704 {
5705   struct inferior *inf = current_inferior ();
5706
5707   ++inf->total_syscalls_count;
5708   if (!b->syscalls_to_be_caught)
5709     ++inf->any_syscall_count;
5710   else
5711     {
5712       int i, iter;
5713       for (i = 0;
5714            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
5715            i++)
5716         {
5717           int elem;
5718           if (iter >= VEC_length (int, inf->syscalls_counts))
5719             {
5720               int old_size = VEC_length (int, inf->syscalls_counts);
5721               uintptr_t vec_addr_offset = old_size * ((uintptr_t) sizeof (int));
5722               uintptr_t vec_addr;
5723               VEC_safe_grow (int, inf->syscalls_counts, iter + 1);
5724               vec_addr = (uintptr_t) VEC_address (int, inf->syscalls_counts) +
5725                 vec_addr_offset;
5726               memset ((void *) vec_addr, 0,
5727                       (iter + 1 - old_size) * sizeof (int));
5728             }
5729           elem = VEC_index (int, inf->syscalls_counts, iter);
5730           VEC_replace (int, inf->syscalls_counts, iter, ++elem);
5731         }
5732     }
5733
5734   target_set_syscall_catchpoint (PIDGET (inferior_ptid),
5735                                  inf->total_syscalls_count != 0,
5736                                  inf->any_syscall_count,
5737                                  VEC_length (int, inf->syscalls_counts),
5738                                  VEC_address (int, inf->syscalls_counts));
5739 }
5740
5741 /* Implement the "remove" breakpoint_ops method for syscall
5742    catchpoints.  */
5743
5744 static int
5745 remove_catch_syscall (struct breakpoint *b)
5746 {
5747   struct inferior *inf = current_inferior ();
5748
5749   --inf->total_syscalls_count;
5750   if (!b->syscalls_to_be_caught)
5751     --inf->any_syscall_count;
5752   else
5753     {
5754       int i, iter;
5755       for (i = 0;
5756            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
5757            i++)
5758         {
5759           int elem;
5760           if (iter >= VEC_length (int, inf->syscalls_counts))
5761             /* Shouldn't happen.  */
5762             continue;
5763           elem = VEC_index (int, inf->syscalls_counts, iter);
5764           VEC_replace (int, inf->syscalls_counts, iter, --elem);
5765         }
5766     }
5767
5768   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
5769                                         inf->total_syscalls_count != 0,
5770                                         inf->any_syscall_count,
5771                                         VEC_length (int, inf->syscalls_counts),
5772                                         VEC_address (int, inf->syscalls_counts));
5773 }
5774
5775 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
5776    catchpoints.  */
5777
5778 static int
5779 breakpoint_hit_catch_syscall (struct breakpoint *b)
5780 {
5781   /* We must check if we are catching specific syscalls in this breakpoint.
5782      If we are, then we must guarantee that the called syscall is the same
5783      syscall we are catching.  */
5784   int syscall_number = 0;
5785
5786   if (!inferior_has_called_syscall (inferior_ptid, &syscall_number))
5787     return 0;
5788
5789   /* Now, checking if the syscall is the same.  */
5790   if (b->syscalls_to_be_caught)
5791     {
5792       int i, iter;
5793       for (i = 0;
5794            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
5795            i++)
5796         if (syscall_number == iter)
5797           break;
5798       /* Not the same.  */
5799       if (!iter)
5800         return 0;
5801     }
5802
5803   return 1;
5804 }
5805
5806 /* Implement the "print_it" breakpoint_ops method for syscall
5807    catchpoints.  */
5808
5809 static enum print_stop_action
5810 print_it_catch_syscall (struct breakpoint *b)
5811 {
5812   /* These are needed because we want to know in which state a
5813      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
5814      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
5815      must print "called syscall" or "returned from syscall".  */
5816   ptid_t ptid;
5817   struct target_waitstatus last;
5818   struct syscall s;
5819   struct cleanup *old_chain;
5820   char *syscall_id;
5821
5822   get_last_target_status (&ptid, &last);
5823
5824   get_syscall_by_number (last.value.syscall_number, &s);
5825
5826   annotate_catchpoint (b->number);
5827
5828   if (s.name == NULL)
5829     syscall_id = xstrprintf ("%d", last.value.syscall_number);
5830   else
5831     syscall_id = xstrprintf ("'%s'", s.name);
5832
5833   old_chain = make_cleanup (xfree, syscall_id);
5834
5835   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
5836     printf_filtered (_("\nCatchpoint %d (call to syscall %s), "),
5837                      b->number, syscall_id);
5838   else if (last.kind == TARGET_WAITKIND_SYSCALL_RETURN)
5839     printf_filtered (_("\nCatchpoint %d (returned from syscall %s), "),
5840                      b->number, syscall_id);
5841
5842   do_cleanups (old_chain);
5843
5844   return PRINT_SRC_AND_LOC;
5845 }
5846
5847 /* Implement the "print_one" breakpoint_ops method for syscall
5848    catchpoints.  */
5849
5850 static void
5851 print_one_catch_syscall (struct breakpoint *b,
5852                          struct bp_location **last_loc)
5853 {
5854   struct value_print_options opts;
5855
5856   get_user_print_options (&opts);
5857   /* Field 4, the address, is omitted (which makes the columns
5858      not line up too nicely with the headers, but the effect
5859      is relatively readable).  */
5860   if (opts.addressprint)
5861     ui_out_field_skip (uiout, "addr");
5862   annotate_field (5);
5863
5864   if (b->syscalls_to_be_caught
5865       && VEC_length (int, b->syscalls_to_be_caught) > 1)
5866     ui_out_text (uiout, "syscalls \"");
5867   else
5868     ui_out_text (uiout, "syscall \"");
5869
5870   if (b->syscalls_to_be_caught)
5871     {
5872       int i, iter;
5873       char *text = xstrprintf ("%s", "");
5874       for (i = 0;
5875            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
5876            i++)
5877         {
5878           char *x = text;
5879           struct syscall s;
5880           get_syscall_by_number (iter, &s);
5881
5882           if (s.name != NULL)
5883             text = xstrprintf ("%s%s, ", text, s.name);
5884           else
5885             text = xstrprintf ("%s%d, ", text, iter);
5886
5887           /* We have to xfree the last 'text' (now stored at 'x')
5888              because xstrprintf dinamically allocates new space for it
5889              on every call.  */
5890           xfree (x);
5891         }
5892       /* Remove the last comma.  */
5893       text[strlen (text) - 2] = '\0';
5894       ui_out_field_string (uiout, "what", text);
5895     }
5896   else
5897     ui_out_field_string (uiout, "what", "<any syscall>");
5898   ui_out_text (uiout, "\" ");
5899 }
5900
5901 /* Implement the "print_mention" breakpoint_ops method for syscall
5902    catchpoints.  */
5903
5904 static void
5905 print_mention_catch_syscall (struct breakpoint *b)
5906 {
5907   if (b->syscalls_to_be_caught)
5908     {
5909       int i, iter;
5910
5911       if (VEC_length (int, b->syscalls_to_be_caught) > 1)
5912         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
5913       else
5914         printf_filtered (_("Catchpoint %d (syscall"), b->number);
5915
5916       for (i = 0;
5917            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
5918            i++)
5919         {
5920           struct syscall s;
5921           get_syscall_by_number (iter, &s);
5922
5923           if (s.name)
5924             printf_filtered (" '%s' [%d]", s.name, s.number);
5925           else
5926             printf_filtered (" %d", s.number);
5927         }
5928       printf_filtered (")");
5929     }
5930   else
5931     printf_filtered (_("Catchpoint %d (any syscall)"),
5932                      b->number);
5933 }
5934
5935 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
5936
5937 static struct breakpoint_ops catch_syscall_breakpoint_ops =
5938 {
5939   insert_catch_syscall,
5940   remove_catch_syscall,
5941   breakpoint_hit_catch_syscall,
5942   print_it_catch_syscall,
5943   print_one_catch_syscall,
5944   print_mention_catch_syscall
5945 };
5946
5947 /* Returns non-zero if 'b' is a syscall catchpoint.  */
5948
5949 static int
5950 syscall_catchpoint_p (struct breakpoint *b)
5951 {
5952   return (b->ops == &catch_syscall_breakpoint_ops);
5953 }
5954
5955 /* Create a new breakpoint of the bp_catchpoint kind and return it,
5956    but does NOT mention it nor update the global location list.
5957    This is useful if you need to fill more fields in the
5958    struct breakpoint before calling mention.
5959  
5960    If TEMPFLAG is non-zero, then make the breakpoint temporary.
5961    If COND_STRING is not NULL, then store it in the breakpoint.
5962    OPS, if not NULL, is the breakpoint_ops structure associated
5963    to the catchpoint.  */
5964
5965 static struct breakpoint *
5966 create_catchpoint_without_mention (struct gdbarch *gdbarch, int tempflag,
5967                                    char *cond_string,
5968                                    struct breakpoint_ops *ops)
5969 {
5970   struct symtab_and_line sal;
5971   struct breakpoint *b;
5972
5973   init_sal (&sal);
5974   sal.pspace = current_program_space;
5975
5976   b = set_raw_breakpoint (gdbarch, sal, bp_catchpoint);
5977   set_breakpoint_count (breakpoint_count + 1);
5978   b->number = breakpoint_count;
5979
5980   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
5981   b->thread = -1;
5982   b->addr_string = NULL;
5983   b->enable_state = bp_enabled;
5984   b->disposition = tempflag ? disp_del : disp_donttouch;
5985   b->ops = ops;
5986
5987   return b;
5988 }
5989
5990 /* Create a new breakpoint of the bp_catchpoint kind and return it.
5991  
5992    If TEMPFLAG is non-zero, then make the breakpoint temporary.
5993    If COND_STRING is not NULL, then store it in the breakpoint.
5994    OPS, if not NULL, is the breakpoint_ops structure associated
5995    to the catchpoint.  */
5996
5997 static struct breakpoint *
5998 create_catchpoint (struct gdbarch *gdbarch, int tempflag,
5999                    char *cond_string, struct breakpoint_ops *ops)
6000 {
6001   struct breakpoint *b =
6002     create_catchpoint_without_mention (gdbarch, tempflag, cond_string, ops);
6003
6004   mention (b);
6005   update_global_location_list (1);
6006
6007   return b;
6008 }
6009
6010 static void
6011 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
6012                                     int tempflag, char *cond_string,
6013                                     struct breakpoint_ops *ops)
6014 {
6015   struct breakpoint *b
6016     = create_catchpoint (gdbarch, tempflag, cond_string, ops);
6017
6018   /* FIXME: We should put this information in a breakpoint private data
6019      area.  */
6020   b->forked_inferior_pid = null_ptid;
6021 }
6022
6023 /* Exec catchpoints.  */
6024
6025 static void
6026 insert_catch_exec (struct breakpoint *b)
6027 {
6028   target_insert_exec_catchpoint (PIDGET (inferior_ptid));
6029 }
6030
6031 static int
6032 remove_catch_exec (struct breakpoint *b)
6033 {
6034   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
6035 }
6036
6037 static int
6038 breakpoint_hit_catch_exec (struct breakpoint *b)
6039 {
6040   return inferior_has_execd (inferior_ptid, &b->exec_pathname);
6041 }
6042
6043 static enum print_stop_action
6044 print_it_catch_exec (struct breakpoint *b)
6045 {
6046   annotate_catchpoint (b->number);
6047   printf_filtered (_("\nCatchpoint %d (exec'd %s), "), b->number,
6048                    b->exec_pathname);
6049   return PRINT_SRC_AND_LOC;
6050 }
6051
6052 static void
6053 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
6054 {
6055   struct value_print_options opts;
6056
6057   get_user_print_options (&opts);
6058
6059   /* Field 4, the address, is omitted (which makes the columns
6060      not line up too nicely with the headers, but the effect
6061      is relatively readable).  */
6062   if (opts.addressprint)
6063     ui_out_field_skip (uiout, "addr");
6064   annotate_field (5);
6065   ui_out_text (uiout, "exec");
6066   if (b->exec_pathname != NULL)
6067     {
6068       ui_out_text (uiout, ", program \"");
6069       ui_out_field_string (uiout, "what", b->exec_pathname);
6070       ui_out_text (uiout, "\" ");
6071     }
6072 }
6073
6074 static void
6075 print_mention_catch_exec (struct breakpoint *b)
6076 {
6077   printf_filtered (_("Catchpoint %d (exec)"), b->number);
6078 }
6079
6080 static struct breakpoint_ops catch_exec_breakpoint_ops =
6081 {
6082   insert_catch_exec,
6083   remove_catch_exec,
6084   breakpoint_hit_catch_exec,
6085   print_it_catch_exec,
6086   print_one_catch_exec,
6087   print_mention_catch_exec
6088 };
6089
6090 static void
6091 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
6092                                  struct breakpoint_ops *ops)
6093 {
6094   struct gdbarch *gdbarch = get_current_arch ();
6095   struct breakpoint *b =
6096     create_catchpoint_without_mention (gdbarch, tempflag, NULL, ops);
6097
6098   b->syscalls_to_be_caught = filter;
6099
6100   /* Now, we have to mention the breakpoint and update the global
6101      location list.  */
6102   mention (b);
6103   update_global_location_list (1);
6104 }
6105
6106 static int
6107 hw_breakpoint_used_count (void)
6108 {
6109   struct breakpoint *b;
6110   int i = 0;
6111
6112   ALL_BREAKPOINTS (b)
6113   {
6114     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
6115       i++;
6116   }
6117
6118   return i;
6119 }
6120
6121 static int
6122 hw_watchpoint_used_count (enum bptype type, int *other_type_used)
6123 {
6124   struct breakpoint *b;
6125   int i = 0;
6126
6127   *other_type_used = 0;
6128   ALL_BREAKPOINTS (b)
6129   {
6130     if (breakpoint_enabled (b))
6131       {
6132         if (b->type == type)
6133           i++;
6134         else if ((b->type == bp_hardware_watchpoint
6135                   || b->type == bp_read_watchpoint
6136                   || b->type == bp_access_watchpoint))
6137           *other_type_used = 1;
6138       }
6139   }
6140   return i;
6141 }
6142
6143 void
6144 disable_watchpoints_before_interactive_call_start (void)
6145 {
6146   struct breakpoint *b;
6147
6148   ALL_BREAKPOINTS (b)
6149   {
6150     if (((b->type == bp_watchpoint)
6151          || (b->type == bp_hardware_watchpoint)
6152          || (b->type == bp_read_watchpoint)
6153          || (b->type == bp_access_watchpoint))
6154         && breakpoint_enabled (b))
6155       {
6156         b->enable_state = bp_call_disabled;
6157         update_global_location_list (0);
6158       }
6159   }
6160 }
6161
6162 void
6163 enable_watchpoints_after_interactive_call_stop (void)
6164 {
6165   struct breakpoint *b;
6166
6167   ALL_BREAKPOINTS (b)
6168   {
6169     if (((b->type == bp_watchpoint)
6170          || (b->type == bp_hardware_watchpoint)
6171          || (b->type == bp_read_watchpoint)
6172          || (b->type == bp_access_watchpoint))
6173         && (b->enable_state == bp_call_disabled))
6174       {
6175         b->enable_state = bp_enabled;
6176         update_global_location_list (1);
6177       }
6178   }
6179 }
6180
6181 void
6182 disable_breakpoints_before_startup (void)
6183 {
6184   struct breakpoint *b;
6185   int found = 0;
6186
6187   ALL_BREAKPOINTS (b)
6188     {
6189       if (b->pspace != current_program_space)
6190         continue;
6191
6192       if ((b->type == bp_breakpoint
6193            || b->type == bp_hardware_breakpoint)
6194           && breakpoint_enabled (b))
6195         {
6196           b->enable_state = bp_startup_disabled;
6197           found = 1;
6198         }
6199     }
6200
6201   if (found)
6202     update_global_location_list (0);
6203
6204   current_program_space->executing_startup = 1;
6205 }
6206
6207 void
6208 enable_breakpoints_after_startup (void)
6209 {
6210   struct breakpoint *b;
6211   int found = 0;
6212
6213   current_program_space->executing_startup = 0;
6214
6215   ALL_BREAKPOINTS (b)
6216     {
6217       if (b->pspace != current_program_space)
6218         continue;
6219
6220       if ((b->type == bp_breakpoint
6221            || b->type == bp_hardware_breakpoint)
6222           && b->enable_state == bp_startup_disabled)
6223         {
6224           b->enable_state = bp_enabled;
6225           found = 1;
6226         }
6227     }
6228
6229   if (found)
6230     breakpoint_re_set ();
6231 }
6232
6233
6234 /* Set a breakpoint that will evaporate an end of command
6235    at address specified by SAL.
6236    Restrict it to frame FRAME if FRAME is nonzero.  */
6237
6238 struct breakpoint *
6239 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
6240                           struct frame_id frame_id, enum bptype type)
6241 {
6242   struct breakpoint *b;
6243
6244   /* If FRAME_ID is valid, it should be a real frame, not an inlined
6245      one.  */
6246   gdb_assert (!frame_id_inlined_p (frame_id));
6247
6248   b = set_raw_breakpoint (gdbarch, sal, type);
6249   b->enable_state = bp_enabled;
6250   b->disposition = disp_donttouch;
6251   b->frame_id = frame_id;
6252
6253   /* If we're debugging a multi-threaded program, then we
6254      want momentary breakpoints to be active in only a 
6255      single thread of control.  */
6256   if (in_thread_list (inferior_ptid))
6257     b->thread = pid_to_thread_id (inferior_ptid);
6258
6259   update_global_location_list_nothrow (1);
6260
6261   return b;
6262 }
6263
6264 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
6265    ORIG is NULL.  */
6266
6267 struct breakpoint *
6268 clone_momentary_breakpoint (struct breakpoint *orig)
6269 {
6270   struct breakpoint *copy;
6271
6272   /* If there's nothing to clone, then return nothing.  */
6273   if (orig == NULL)
6274     return NULL;
6275
6276   copy = set_raw_breakpoint_without_location (orig->gdbarch, orig->type);
6277   copy->loc = allocate_bp_location (copy);
6278   set_breakpoint_location_function (copy->loc);
6279
6280   copy->loc->gdbarch = orig->loc->gdbarch;
6281   copy->loc->requested_address = orig->loc->requested_address;
6282   copy->loc->address = orig->loc->address;
6283   copy->loc->section = orig->loc->section;
6284   copy->loc->pspace = orig->loc->pspace;
6285
6286   if (orig->source_file == NULL)
6287     copy->source_file = NULL;
6288   else
6289     copy->source_file = xstrdup (orig->source_file);
6290
6291   copy->line_number = orig->line_number;
6292   copy->frame_id = orig->frame_id;
6293   copy->thread = orig->thread;
6294   copy->pspace = orig->pspace;
6295
6296   copy->enable_state = bp_enabled;
6297   copy->disposition = disp_donttouch;
6298   copy->number = internal_breakpoint_number--;
6299
6300   update_global_location_list_nothrow (0);
6301   return copy;
6302 }
6303
6304 struct breakpoint *
6305 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
6306                                 enum bptype type)
6307 {
6308   struct symtab_and_line sal;
6309
6310   sal = find_pc_line (pc, 0);
6311   sal.pc = pc;
6312   sal.section = find_pc_overlay (pc);
6313   sal.explicit_pc = 1;
6314
6315   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
6316 }
6317 \f
6318
6319 /* Tell the user we have just set a breakpoint B.  */
6320
6321 static void
6322 mention (struct breakpoint *b)
6323 {
6324   int say_where = 0;
6325   struct cleanup *ui_out_chain;
6326   struct value_print_options opts;
6327
6328   get_user_print_options (&opts);
6329
6330   /* FIXME: This is misplaced; mention() is called by things (like
6331      hitting a watchpoint) other than breakpoint creation.  It should
6332      be possible to clean this up and at the same time replace the
6333      random calls to breakpoint_changed with this hook.  */
6334   observer_notify_breakpoint_created (b->number);
6335
6336   if (b->ops != NULL && b->ops->print_mention != NULL)
6337     b->ops->print_mention (b);
6338   else
6339     switch (b->type)
6340       {
6341       case bp_none:
6342         printf_filtered (_("(apparently deleted?) Eventpoint %d: "), b->number);
6343         break;
6344       case bp_watchpoint:
6345         ui_out_text (uiout, "Watchpoint ");
6346         ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
6347         ui_out_field_int (uiout, "number", b->number);
6348         ui_out_text (uiout, ": ");
6349         ui_out_field_string (uiout, "exp", b->exp_string);
6350         do_cleanups (ui_out_chain);
6351         break;
6352       case bp_hardware_watchpoint:
6353         ui_out_text (uiout, "Hardware watchpoint ");
6354         ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
6355         ui_out_field_int (uiout, "number", b->number);
6356         ui_out_text (uiout, ": ");
6357         ui_out_field_string (uiout, "exp", b->exp_string);
6358         do_cleanups (ui_out_chain);
6359         break;
6360       case bp_read_watchpoint:
6361         ui_out_text (uiout, "Hardware read watchpoint ");
6362         ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
6363         ui_out_field_int (uiout, "number", b->number);
6364         ui_out_text (uiout, ": ");
6365         ui_out_field_string (uiout, "exp", b->exp_string);
6366         do_cleanups (ui_out_chain);
6367         break;
6368       case bp_access_watchpoint:
6369         ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
6370         ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
6371         ui_out_field_int (uiout, "number", b->number);
6372         ui_out_text (uiout, ": ");
6373         ui_out_field_string (uiout, "exp", b->exp_string);
6374         do_cleanups (ui_out_chain);
6375         break;
6376       case bp_breakpoint:
6377         if (ui_out_is_mi_like_p (uiout))
6378           {
6379             say_where = 0;
6380             break;
6381           }
6382         if (b->disposition == disp_del)
6383           printf_filtered (_("Temporary breakpoint"));
6384         else
6385           printf_filtered (_("Breakpoint"));
6386         printf_filtered (_(" %d"), b->number);
6387         say_where = 1;
6388         break;
6389       case bp_hardware_breakpoint:
6390         if (ui_out_is_mi_like_p (uiout))
6391           {
6392             say_where = 0;
6393             break;
6394           }
6395         printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
6396         say_where = 1;
6397         break;
6398       case bp_tracepoint:
6399         if (ui_out_is_mi_like_p (uiout))
6400           {
6401             say_where = 0;
6402             break;
6403           }
6404         printf_filtered (_("Tracepoint"));
6405         printf_filtered (_(" %d"), b->number);
6406         say_where = 1;
6407         break;
6408       case bp_fast_tracepoint:
6409         if (ui_out_is_mi_like_p (uiout))
6410           {
6411             say_where = 0;
6412             break;
6413           }
6414         printf_filtered (_("Fast tracepoint"));
6415         printf_filtered (_(" %d"), b->number);
6416         say_where = 1;
6417         break;
6418
6419       case bp_until:
6420       case bp_finish:
6421       case bp_longjmp:
6422       case bp_longjmp_resume:
6423       case bp_step_resume:
6424       case bp_call_dummy:
6425       case bp_watchpoint_scope:
6426       case bp_shlib_event:
6427       case bp_thread_event:
6428       case bp_overlay_event:
6429       case bp_jit_event:
6430       case bp_longjmp_master:
6431         break;
6432       }
6433
6434   if (say_where)
6435     {
6436       /* i18n: cagney/2005-02-11: Below needs to be merged into a
6437          single string.  */
6438       if (b->loc == NULL)
6439         {
6440           printf_filtered (_(" (%s) pending."), b->addr_string);
6441         }
6442       else
6443         {
6444           if (opts.addressprint || b->source_file == NULL)
6445             {
6446               printf_filtered (" at ");
6447               fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
6448                               gdb_stdout);
6449             }
6450           if (b->source_file)
6451             printf_filtered (": file %s, line %d.",
6452                              b->source_file, b->line_number);
6453           
6454           if (b->loc->next)
6455             {
6456               struct bp_location *loc = b->loc;
6457               int n = 0;
6458               for (; loc; loc = loc->next)
6459                 ++n;
6460               printf_filtered (" (%d locations)", n);           
6461             }
6462
6463         }
6464     }
6465   if (ui_out_is_mi_like_p (uiout))
6466     return;
6467   printf_filtered ("\n");
6468 }
6469 \f
6470
6471 static struct bp_location *
6472 add_location_to_breakpoint (struct breakpoint *b,
6473                             const struct symtab_and_line *sal)
6474 {
6475   struct bp_location *loc, **tmp;
6476
6477   loc = allocate_bp_location (b);
6478   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
6479     ;
6480   *tmp = loc;
6481   loc->gdbarch = get_sal_arch (*sal);
6482   if (!loc->gdbarch)
6483     loc->gdbarch = b->gdbarch;
6484   loc->requested_address = sal->pc;
6485   loc->address = adjust_breakpoint_address (loc->gdbarch,
6486                                             loc->requested_address, b->type);
6487   loc->pspace = sal->pspace;
6488   gdb_assert (loc->pspace != NULL);
6489   loc->section = sal->section;
6490
6491   set_breakpoint_location_function (loc);
6492   return loc;
6493 }
6494 \f
6495
6496 /* Return 1 if LOC is pointing to a permanent breakpoint, 
6497    return 0 otherwise.  */
6498
6499 static int
6500 bp_loc_is_permanent (struct bp_location *loc)
6501 {
6502   int len;
6503   CORE_ADDR addr;
6504   const gdb_byte *brk;
6505   gdb_byte *target_mem;
6506   struct cleanup *cleanup;
6507   int retval = 0;
6508
6509   gdb_assert (loc != NULL);
6510
6511   addr = loc->address;
6512   brk = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
6513
6514   /* Software breakpoints unsupported?  */
6515   if (brk == NULL)
6516     return 0;
6517
6518   target_mem = alloca (len);
6519
6520   /* Enable the automatic memory restoration from breakpoints while
6521      we read the memory.  Otherwise we could say about our temporary
6522      breakpoints they are permanent.  */
6523   cleanup = save_current_space_and_thread ();
6524
6525   switch_to_program_space_and_thread (loc->pspace);
6526   make_show_memory_breakpoints_cleanup (0);
6527
6528   if (target_read_memory (loc->address, target_mem, len) == 0
6529       && memcmp (target_mem, brk, len) == 0)
6530     retval = 1;
6531
6532   do_cleanups (cleanup);
6533
6534   return retval;
6535 }
6536
6537
6538
6539 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
6540    as textual description of the location, and COND_STRING
6541    as condition expression.  */
6542
6543 static void
6544 create_breakpoint_sal (struct gdbarch *gdbarch,
6545                        struct symtabs_and_lines sals, char *addr_string,
6546                        char *cond_string,
6547                        enum bptype type, enum bpdisp disposition,
6548                        int thread, int task, int ignore_count,
6549                        struct breakpoint_ops *ops, int from_tty, int enabled)
6550 {
6551   struct breakpoint *b = NULL;
6552   int i;
6553
6554   if (type == bp_hardware_breakpoint)
6555     {
6556       int i = hw_breakpoint_used_count ();
6557       int target_resources_ok = 
6558         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
6559                                             i + 1, 0);
6560       if (target_resources_ok == 0)
6561         error (_("No hardware breakpoint support in the target."));
6562       else if (target_resources_ok < 0)
6563         error (_("Hardware breakpoints used exceeds limit."));
6564     }
6565
6566   gdb_assert (sals.nelts > 0);
6567
6568   for (i = 0; i < sals.nelts; ++i)
6569     {
6570       struct symtab_and_line sal = sals.sals[i];
6571       struct bp_location *loc;
6572
6573       if (from_tty)
6574         {
6575           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
6576           if (!loc_gdbarch)
6577             loc_gdbarch = gdbarch;
6578
6579           describe_other_breakpoints (loc_gdbarch,
6580                                       sal.pspace, sal.pc, sal.section, thread);
6581         }
6582
6583       if (i == 0)
6584         {
6585           b = set_raw_breakpoint (gdbarch, sal, type);
6586           set_breakpoint_count (breakpoint_count + 1);
6587           b->number = breakpoint_count;
6588           b->thread = thread;
6589           b->task = task;
6590   
6591           b->cond_string = cond_string;
6592           b->ignore_count = ignore_count;
6593           b->enable_state = enabled ? bp_enabled : bp_disabled;
6594           b->disposition = disposition;
6595
6596           b->pspace = sals.sals[0].pspace;
6597
6598           if (enabled && b->pspace->executing_startup
6599               && (b->type == bp_breakpoint
6600                   || b->type == bp_hardware_breakpoint))
6601             b->enable_state = bp_startup_disabled;
6602
6603           loc = b->loc;
6604         }
6605       else
6606         {
6607           loc = add_location_to_breakpoint (b, &sal);
6608         }
6609
6610       if (bp_loc_is_permanent (loc))
6611         make_breakpoint_permanent (b);
6612
6613       if (b->cond_string)
6614         {
6615           char *arg = b->cond_string;
6616           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
6617           if (*arg)
6618               error (_("Garbage %s follows condition"), arg);
6619         }
6620     }   
6621
6622   if (addr_string)
6623     b->addr_string = addr_string;
6624   else
6625     /* addr_string has to be used or breakpoint_re_set will delete
6626        me.  */
6627     b->addr_string
6628       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6629
6630   b->ops = ops;
6631   mention (b);
6632 }
6633
6634 /* Remove element at INDEX_TO_REMOVE from SAL, shifting other
6635    elements to fill the void space.  */
6636 static void
6637 remove_sal (struct symtabs_and_lines *sal, int index_to_remove)
6638 {
6639   int i = index_to_remove+1;
6640   int last_index = sal->nelts-1;
6641
6642   for (;i <= last_index; ++i)
6643     sal->sals[i-1] = sal->sals[i];
6644
6645   --(sal->nelts);
6646 }
6647
6648 /* If appropriate, obtains all sals that correspond to the same file
6649    and line as SAL, in all program spaces.  Users debugging with IDEs,
6650    will want to set a breakpoint at foo.c:line, and not really care
6651    about program spaces.  This is done only if SAL does not have
6652    explicit PC and has line and file information.  If we got just a
6653    single expanded sal, return the original.
6654
6655    Otherwise, if SAL.explicit_line is not set, filter out all sals for
6656    which the name of enclosing function is different from SAL.  This
6657    makes sure that if we have breakpoint originally set in template
6658    instantiation, say foo<int>(), we won't expand SAL to locations at
6659    the same line in all existing instantiations of 'foo'.  */
6660
6661 static struct symtabs_and_lines
6662 expand_line_sal_maybe (struct symtab_and_line sal)
6663 {
6664   struct symtabs_and_lines expanded;
6665   CORE_ADDR original_pc = sal.pc;
6666   char *original_function = NULL;
6667   int found;
6668   int i;
6669   struct cleanup *old_chain;
6670
6671   /* If we have explicit pc, don't expand.
6672      If we have no line number, we can't expand.  */
6673   if (sal.explicit_pc || sal.line == 0 || sal.symtab == NULL)
6674     {
6675       expanded.nelts = 1;
6676       expanded.sals = xmalloc (sizeof (struct symtab_and_line));
6677       expanded.sals[0] = sal;
6678       return expanded;
6679     }
6680
6681   sal.pc = 0;
6682
6683   old_chain = save_current_space_and_thread ();
6684
6685   switch_to_program_space_and_thread (sal.pspace);
6686
6687   find_pc_partial_function (original_pc, &original_function, NULL, NULL);
6688
6689   /* Note that expand_line_sal visits *all* program spaces.  */
6690   expanded = expand_line_sal (sal);
6691
6692   if (expanded.nelts == 1)
6693     {
6694       /* We had one sal, we got one sal.  Return that sal, adjusting it
6695          past the function prologue if necessary.  */
6696       xfree (expanded.sals);
6697       expanded.nelts = 1;
6698       expanded.sals = xmalloc (sizeof (struct symtab_and_line));
6699       sal.pc = original_pc;
6700       expanded.sals[0] = sal;
6701       skip_prologue_sal (&expanded.sals[0]);
6702       do_cleanups (old_chain);
6703       return expanded;      
6704     }
6705
6706   if (!sal.explicit_line)
6707     {
6708       CORE_ADDR func_addr, func_end;
6709       for (i = 0; i < expanded.nelts; ++i)
6710         {
6711           CORE_ADDR pc = expanded.sals[i].pc;
6712           char *this_function;
6713
6714           /* We need to switch threads as well since we're about to
6715              read memory.  */
6716           switch_to_program_space_and_thread (expanded.sals[i].pspace);
6717
6718           if (find_pc_partial_function (pc, &this_function, 
6719                                         &func_addr, &func_end))
6720             {
6721               if (this_function
6722                   && strcmp (this_function, original_function) != 0)
6723                 {
6724                   remove_sal (&expanded, i);
6725                   --i;
6726                 }
6727               else if (func_addr == pc)     
6728                 {            
6729                   /* We're at beginning of a function, and should
6730                      skip prologue.  */
6731                   struct symbol *sym = find_pc_function (pc);
6732                   if (sym)
6733                     expanded.sals[i] = find_function_start_sal (sym, 1);
6734                   else
6735                     {
6736                       /* Since find_pc_partial_function returned true,
6737                          we should really always find the section here.  */
6738                       struct obj_section *section = find_pc_section (pc);
6739                       if (section)
6740                         {
6741                           struct gdbarch *gdbarch
6742                             = get_objfile_arch (section->objfile);
6743                           expanded.sals[i].pc
6744                             = gdbarch_skip_prologue (gdbarch, pc);
6745                         }
6746                     }
6747                 }
6748             }
6749         }
6750     }
6751   else
6752     {
6753       for (i = 0; i < expanded.nelts; ++i)
6754         {
6755           /* If this SAL corresponds to a breakpoint inserted using a
6756              line number, then skip the function prologue if necessary.  */
6757           skip_prologue_sal (&expanded.sals[i]);
6758         }
6759     }
6760
6761   do_cleanups (old_chain);
6762
6763   if (expanded.nelts <= 1)
6764     {
6765       /* This is un ugly workaround. If we get zero
6766        expanded sals then something is really wrong.
6767       Fix that by returnign the original sal. */
6768       xfree (expanded.sals);
6769       expanded.nelts = 1;
6770       expanded.sals = xmalloc (sizeof (struct symtab_and_line));
6771       sal.pc = original_pc;
6772       expanded.sals[0] = sal;
6773       return expanded;      
6774     }
6775
6776   if (original_pc)
6777     {
6778       found = 0;
6779       for (i = 0; i < expanded.nelts; ++i)
6780         if (expanded.sals[i].pc == original_pc)
6781           {
6782             found = 1;
6783             break;
6784           }
6785       gdb_assert (found);
6786     }
6787
6788   return expanded;
6789 }
6790
6791 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
6792    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
6793    value.  COND_STRING, if not NULL, specified the condition to be
6794    used for all breakpoints.  Essentially the only case where
6795    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
6796    function.  In that case, it's still not possible to specify
6797    separate conditions for different overloaded functions, so
6798    we take just a single condition string.
6799    
6800    NOTE: If the function succeeds, the caller is expected to cleanup
6801    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
6802    array contents).  If the function fails (error() is called), the
6803    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
6804    COND and SALS arrays and each of those arrays contents. */
6805
6806 static void
6807 create_breakpoints_sal (struct gdbarch *gdbarch,
6808                         struct symtabs_and_lines sals, char **addr_string,
6809                         char *cond_string,
6810                         enum bptype type, enum bpdisp disposition,
6811                         int thread, int task, int ignore_count,
6812                         struct breakpoint_ops *ops, int from_tty,
6813                         int enabled)
6814 {
6815   int i;
6816   for (i = 0; i < sals.nelts; ++i)
6817     {
6818       struct symtabs_and_lines expanded = 
6819         expand_line_sal_maybe (sals.sals[i]);
6820
6821       create_breakpoint_sal (gdbarch, expanded, addr_string[i],
6822                              cond_string, type, disposition,
6823                              thread, task, ignore_count, ops, from_tty, enabled);
6824     }
6825 }
6826
6827 /* Parse ARG which is assumed to be a SAL specification possibly
6828    followed by conditionals.  On return, SALS contains an array of SAL
6829    addresses found. ADDR_STRING contains a vector of (canonical)
6830    address strings. ARG points to the end of the SAL. */
6831
6832 static void
6833 parse_breakpoint_sals (char **address,
6834                        struct symtabs_and_lines *sals,
6835                        char ***addr_string,
6836                        int *not_found_ptr)
6837 {
6838   char *addr_start = *address;
6839   *addr_string = NULL;
6840   /* If no arg given, or if first arg is 'if ', use the default
6841      breakpoint. */
6842   if ((*address) == NULL
6843       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
6844     {
6845       if (default_breakpoint_valid)
6846         {
6847           struct symtab_and_line sal;
6848           init_sal (&sal);              /* initialize to zeroes */
6849           sals->sals = (struct symtab_and_line *)
6850             xmalloc (sizeof (struct symtab_and_line));
6851           sal.pc = default_breakpoint_address;
6852           sal.line = default_breakpoint_line;
6853           sal.symtab = default_breakpoint_symtab;
6854           sal.pspace = default_breakpoint_pspace;
6855           sal.section = find_pc_overlay (sal.pc);
6856
6857           /* "break" without arguments is equivalent to "break *PC" where PC is
6858              the default_breakpoint_address.  So make sure to set
6859              sal.explicit_pc to prevent GDB from trying to expand the list of
6860              sals to include all other instances with the same symtab and line.
6861            */
6862           sal.explicit_pc = 1;
6863
6864           sals->sals[0] = sal;
6865           sals->nelts = 1;
6866         }
6867       else
6868         error (_("No default breakpoint address now."));
6869     }
6870   else
6871     {
6872       /* Force almost all breakpoints to be in terms of the
6873          current_source_symtab (which is decode_line_1's default).  This
6874          should produce the results we want almost all of the time while
6875          leaving default_breakpoint_* alone.  
6876          ObjC: However, don't match an Objective-C method name which
6877          may have a '+' or '-' succeeded by a '[' */
6878          
6879       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
6880                         
6881       if (default_breakpoint_valid
6882           && (!cursal.symtab
6883               || ((strchr ("+-", (*address)[0]) != NULL)
6884                   && ((*address)[1] != '['))))
6885         *sals = decode_line_1 (address, 1, default_breakpoint_symtab,
6886                                default_breakpoint_line, addr_string, 
6887                                not_found_ptr);
6888       else
6889         *sals = decode_line_1 (address, 1, (struct symtab *) NULL, 0,
6890                                addr_string, not_found_ptr);
6891     }
6892   /* For any SAL that didn't have a canonical string, fill one in. */
6893   if (sals->nelts > 0 && *addr_string == NULL)
6894     *addr_string = xcalloc (sals->nelts, sizeof (char **));
6895   if (addr_start != (*address))
6896     {
6897       int i;
6898       for (i = 0; i < sals->nelts; i++)
6899         {
6900           /* Add the string if not present. */
6901           if ((*addr_string)[i] == NULL)
6902             (*addr_string)[i] = savestring (addr_start, (*address) - addr_start);
6903         }
6904     }
6905 }
6906
6907
6908 /* Convert each SAL into a real PC.  Verify that the PC can be
6909    inserted as a breakpoint.  If it can't throw an error. */
6910
6911 static void
6912 breakpoint_sals_to_pc (struct symtabs_and_lines *sals,
6913                        char *address)
6914 {    
6915   int i;
6916   for (i = 0; i < sals->nelts; i++)
6917     resolve_sal_pc (&sals->sals[i]);
6918 }
6919
6920 /* Fast tracepoints may have restrictions on valid locations.  For
6921    instance, a fast tracepoint using a jump instead of a trap will
6922    likely have to overwrite more bytes than a trap would, and so can
6923    only be placed where the instruction is longer than the jump, or a
6924    multi-instruction sequence does not have a jump into the middle of
6925    it, etc.  */
6926
6927 static void
6928 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
6929                             struct symtabs_and_lines *sals)
6930 {
6931   int i, rslt;
6932   struct symtab_and_line *sal;
6933   char *msg;
6934   struct cleanup *old_chain;
6935
6936   for (i = 0; i < sals->nelts; i++)
6937     {
6938       sal = &sals->sals[i];
6939
6940       rslt = gdbarch_fast_tracepoint_valid_at (gdbarch, sal->pc,
6941                                                NULL, &msg);
6942       old_chain = make_cleanup (xfree, msg);
6943
6944       if (!rslt)
6945         error (_("May not have a fast tracepoint at 0x%s%s"),
6946                paddress (gdbarch, sal->pc), (msg ? msg : ""));
6947
6948       do_cleanups (old_chain);
6949     }
6950 }
6951
6952 static void
6953 do_captured_parse_breakpoint (struct ui_out *ui, void *data)
6954 {
6955   struct captured_parse_breakpoint_args *args = data;
6956   
6957   parse_breakpoint_sals (args->arg_p, args->sals_p, args->addr_string_p, 
6958                          args->not_found_ptr);
6959 }
6960
6961 /* Given TOK, a string specification of condition and thread, as
6962    accepted by the 'break' command, extract the condition
6963    string and thread number and set *COND_STRING and *THREAD.
6964    PC identifies the context at which the condition should be parsed.  
6965    If no condition is found, *COND_STRING is set to NULL.
6966    If no thread is found, *THREAD is set to -1.  */
6967 static void 
6968 find_condition_and_thread (char *tok, CORE_ADDR pc, 
6969                            char **cond_string, int *thread, int *task)
6970 {
6971   *cond_string = NULL;
6972   *thread = -1;
6973   while (tok && *tok)
6974     {
6975       char *end_tok;
6976       int toklen;
6977       char *cond_start = NULL;
6978       char *cond_end = NULL;
6979       while (*tok == ' ' || *tok == '\t')
6980         tok++;
6981       
6982       end_tok = tok;
6983       
6984       while (*end_tok != ' ' && *end_tok != '\t' && *end_tok != '\000')
6985         end_tok++;
6986       
6987       toklen = end_tok - tok;
6988       
6989       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
6990         {
6991           struct expression *expr;
6992
6993           tok = cond_start = end_tok + 1;
6994           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
6995           xfree (expr);
6996           cond_end = tok;
6997           *cond_string = savestring (cond_start, 
6998                                      cond_end - cond_start);
6999         }
7000       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
7001         {
7002           char *tmptok;
7003           
7004           tok = end_tok + 1;
7005           tmptok = tok;
7006           *thread = strtol (tok, &tok, 0);
7007           if (tok == tmptok)
7008             error (_("Junk after thread keyword."));
7009           if (!valid_thread_id (*thread))
7010             error (_("Unknown thread %d."), *thread);
7011         }
7012       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
7013         {
7014           char *tmptok;
7015
7016           tok = end_tok + 1;
7017           tmptok = tok;
7018           *task = strtol (tok, &tok, 0);
7019           if (tok == tmptok)
7020             error (_("Junk after task keyword."));
7021           if (!valid_task_id (*task))
7022             error (_("Unknown task %d."), *task);
7023         }
7024       else
7025         error (_("Junk at end of arguments."));
7026     }
7027 }
7028
7029 /* Set a breakpoint.  This function is shared between CLI and MI
7030    functions for setting a breakpoint.  This function has two major
7031    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
7032    parameter.  If non-zero, the function will parse arg, extracting
7033    breakpoint location, address and thread. Otherwise, ARG is just the
7034    location of breakpoint, with condition and thread specified by the
7035    COND_STRING and THREAD parameters.  Returns true if any breakpoint
7036    was created; false otherwise.  */
7037
7038 int
7039 create_breakpoint (struct gdbarch *gdbarch,
7040                    char *arg, char *cond_string, int thread,
7041                    int parse_condition_and_thread,
7042                    int tempflag, int hardwareflag, int traceflag,
7043                    int ignore_count,
7044                    enum auto_boolean pending_break_support,
7045                    struct breakpoint_ops *ops,
7046                    int from_tty,
7047                    int enabled)
7048 {
7049   struct gdb_exception e;
7050   struct symtabs_and_lines sals;
7051   struct symtab_and_line pending_sal;
7052   char *copy_arg;
7053   char *err_msg;
7054   char *addr_start = arg;
7055   char **addr_string;
7056   struct cleanup *old_chain;
7057   struct cleanup *bkpt_chain = NULL;
7058   struct captured_parse_breakpoint_args parse_args;
7059   int i;
7060   int pending = 0;
7061   int not_found = 0;
7062   enum bptype type_wanted;
7063   int task = 0;
7064
7065   sals.sals = NULL;
7066   sals.nelts = 0;
7067   addr_string = NULL;
7068
7069   parse_args.arg_p = &arg;
7070   parse_args.sals_p = &sals;
7071   parse_args.addr_string_p = &addr_string;
7072   parse_args.not_found_ptr = &not_found;
7073
7074   e = catch_exception (uiout, do_captured_parse_breakpoint, 
7075                        &parse_args, RETURN_MASK_ALL);
7076
7077   /* If caller is interested in rc value from parse, set value.  */
7078   switch (e.reason)
7079     {
7080     case RETURN_QUIT:
7081       throw_exception (e);
7082     case RETURN_ERROR:
7083       switch (e.error)
7084         {
7085         case NOT_FOUND_ERROR:
7086
7087           /* If pending breakpoint support is turned off, throw
7088              error.  */
7089
7090           if (pending_break_support == AUTO_BOOLEAN_FALSE)
7091             throw_exception (e);
7092
7093           exception_print (gdb_stderr, e);
7094
7095           /* If pending breakpoint support is auto query and the user
7096              selects no, then simply return the error code.  */
7097           if (pending_break_support == AUTO_BOOLEAN_AUTO
7098               && !nquery ("Make breakpoint pending on future shared library load? "))
7099             return 0;
7100
7101           /* At this point, either the user was queried about setting
7102              a pending breakpoint and selected yes, or pending
7103              breakpoint behavior is on and thus a pending breakpoint
7104              is defaulted on behalf of the user.  */
7105           copy_arg = xstrdup (addr_start);
7106           addr_string = &copy_arg;
7107           sals.nelts = 1;
7108           sals.sals = &pending_sal;
7109           pending_sal.pc = 0;
7110           pending = 1;
7111           break;
7112         default:
7113           throw_exception (e);
7114         }
7115     default:
7116       if (!sals.nelts)
7117         return 0;
7118     }
7119
7120   /* Create a chain of things that always need to be cleaned up. */
7121   old_chain = make_cleanup (null_cleanup, 0);
7122
7123   if (!pending)
7124     {
7125       /* Make sure that all storage allocated to SALS gets freed.  */
7126       make_cleanup (xfree, sals.sals);
7127       
7128       /* Cleanup the addr_string array but not its contents. */
7129       make_cleanup (xfree, addr_string);
7130     }
7131
7132   /* ----------------------------- SNIP -----------------------------
7133      Anything added to the cleanup chain beyond this point is assumed
7134      to be part of a breakpoint.  If the breakpoint create succeeds
7135      then the memory is not reclaimed.  */
7136   bkpt_chain = make_cleanup (null_cleanup, 0);
7137
7138   /* Mark the contents of the addr_string for cleanup.  These go on
7139      the bkpt_chain and only occur if the breakpoint create fails.  */
7140   for (i = 0; i < sals.nelts; i++)
7141     {
7142       if (addr_string[i] != NULL)
7143         make_cleanup (xfree, addr_string[i]);
7144     }
7145
7146   /* Resolve all line numbers to PC's and verify that the addresses
7147      are ok for the target.  */
7148   if (!pending)
7149     breakpoint_sals_to_pc (&sals, addr_start);
7150
7151   type_wanted = (traceflag
7152                  ? (hardwareflag ? bp_fast_tracepoint : bp_tracepoint)
7153                  : (hardwareflag ? bp_hardware_breakpoint : bp_breakpoint));
7154
7155   /* Fast tracepoints may have additional restrictions on location.  */
7156   if (type_wanted == bp_fast_tracepoint)
7157     check_fast_tracepoint_sals (gdbarch, &sals);
7158
7159   /* Verify that condition can be parsed, before setting any
7160      breakpoints.  Allocate a separate condition expression for each
7161      breakpoint. */
7162   if (!pending)
7163     {
7164       if (parse_condition_and_thread)
7165         {
7166             /* Here we only parse 'arg' to separate condition
7167                from thread number, so parsing in context of first
7168                sal is OK.  When setting the breakpoint we'll 
7169                re-parse it in context of each sal.  */
7170             cond_string = NULL;
7171             thread = -1;
7172             find_condition_and_thread (arg, sals.sals[0].pc, &cond_string,
7173                                        &thread, &task);
7174             if (cond_string)
7175                 make_cleanup (xfree, cond_string);
7176         }
7177       else
7178         {
7179             /* Create a private copy of condition string.  */
7180             if (cond_string)
7181             {
7182                 cond_string = xstrdup (cond_string);
7183                 make_cleanup (xfree, cond_string);
7184             }
7185         }
7186       create_breakpoints_sal (gdbarch, sals, addr_string, cond_string,
7187                               type_wanted, tempflag ? disp_del : disp_donttouch,
7188                               thread, task, ignore_count, ops, from_tty,
7189                               enabled);
7190     }
7191   else
7192     {
7193       struct symtab_and_line sal = {0};
7194       struct breakpoint *b;
7195
7196       make_cleanup (xfree, copy_arg);
7197
7198       b = set_raw_breakpoint_without_location (gdbarch, type_wanted);
7199       set_breakpoint_count (breakpoint_count + 1);
7200       b->number = breakpoint_count;
7201       b->thread = -1;
7202       b->addr_string = addr_string[0];
7203       b->cond_string = NULL;
7204       b->ignore_count = ignore_count;
7205       b->disposition = tempflag ? disp_del : disp_donttouch;
7206       b->condition_not_parsed = 1;
7207       b->ops = ops;
7208       b->enable_state = enabled ? bp_enabled : bp_disabled;
7209       b->pspace = current_program_space;
7210
7211       if (enabled && b->pspace->executing_startup
7212           && (b->type == bp_breakpoint
7213               || b->type == bp_hardware_breakpoint))
7214         b->enable_state = bp_startup_disabled;
7215
7216       mention (b);
7217     }
7218   
7219   if (sals.nelts > 1)
7220     warning (_("Multiple breakpoints were set.\n"
7221                "Use the \"delete\" command to delete unwanted breakpoints."));
7222   /* That's it.  Discard the cleanups for data inserted into the
7223      breakpoint.  */
7224   discard_cleanups (bkpt_chain);
7225   /* But cleanup everything else.  */
7226   do_cleanups (old_chain);
7227
7228   /* error call may happen here - have BKPT_CHAIN already discarded.  */
7229   update_global_location_list (1);
7230
7231   return 1;
7232 }
7233
7234 /* Set a breakpoint. 
7235    ARG is a string describing breakpoint address,
7236    condition, and thread.
7237    FLAG specifies if a breakpoint is hardware on,
7238    and if breakpoint is temporary, using BP_HARDWARE_FLAG
7239    and BP_TEMPFLAG.  */
7240    
7241 static void
7242 break_command_1 (char *arg, int flag, int from_tty)
7243 {
7244   int hardwareflag = flag & BP_HARDWAREFLAG;
7245   int tempflag = flag & BP_TEMPFLAG;
7246
7247   create_breakpoint (get_current_arch (),
7248                      arg,
7249                      NULL, 0, 1 /* parse arg */,
7250                      tempflag, hardwareflag, 0 /* traceflag */,
7251                      0 /* Ignore count */,
7252                      pending_break_support,
7253                      NULL /* breakpoint_ops */,
7254                      from_tty,
7255                      1 /* enabled */);
7256 }
7257
7258
7259
7260 /* Adjust SAL to the first instruction past the function prologue.
7261    The end of the prologue is determined using the line table from
7262    the debugging information.  explicit_pc and explicit_line are
7263    not modified.
7264
7265    If SAL is already past the prologue, then do nothing.  */
7266
7267 static void
7268 skip_prologue_sal (struct symtab_and_line *sal)
7269 {
7270   struct symbol *sym;
7271   struct symtab_and_line start_sal;
7272   struct cleanup *old_chain;
7273
7274   old_chain = save_current_space_and_thread ();
7275
7276   sym = find_pc_function (sal->pc);
7277   if (sym != NULL)
7278     {
7279       start_sal = find_function_start_sal (sym, 1);
7280       if (sal->pc < start_sal.pc)
7281         {
7282           start_sal.explicit_line = sal->explicit_line;
7283           start_sal.explicit_pc = sal->explicit_pc;
7284           *sal = start_sal;
7285         }
7286     }
7287
7288   do_cleanups (old_chain);
7289 }
7290
7291 /* Helper function for break_command_1 and disassemble_command.  */
7292
7293 void
7294 resolve_sal_pc (struct symtab_and_line *sal)
7295 {
7296   CORE_ADDR pc;
7297
7298   if (sal->pc == 0 && sal->symtab != NULL)
7299     {
7300       if (!find_line_pc (sal->symtab, sal->line, &pc))
7301         error (_("No line %d in file \"%s\"."),
7302                sal->line, sal->symtab->filename);
7303       sal->pc = pc;
7304
7305       /* If this SAL corresponds to a breakpoint inserted using
7306          a line number, then skip the function prologue if necessary.  */
7307       if (sal->explicit_line)
7308         {
7309           /* Preserve the original line number.  */
7310           int saved_line = sal->line;
7311           skip_prologue_sal (sal);
7312           sal->line = saved_line;
7313         }
7314     }
7315
7316   if (sal->section == 0 && sal->symtab != NULL)
7317     {
7318       struct blockvector *bv;
7319       struct block *b;
7320       struct symbol *sym;
7321
7322       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
7323       if (bv != NULL)
7324         {
7325           sym = block_linkage_function (b);
7326           if (sym != NULL)
7327             {
7328               fixup_symbol_section (sym, sal->symtab->objfile);
7329               sal->section = SYMBOL_OBJ_SECTION (sym);
7330             }
7331           else
7332             {
7333               /* It really is worthwhile to have the section, so we'll just
7334                  have to look harder. This case can be executed if we have 
7335                  line numbers but no functions (as can happen in assembly 
7336                  source).  */
7337
7338               struct minimal_symbol *msym;
7339               struct cleanup *old_chain = save_current_space_and_thread ();
7340
7341               switch_to_program_space_and_thread (sal->pspace);
7342
7343               msym = lookup_minimal_symbol_by_pc (sal->pc);
7344               if (msym)
7345                 sal->section = SYMBOL_OBJ_SECTION (msym);
7346
7347               do_cleanups (old_chain);
7348             }
7349         }
7350     }
7351 }
7352
7353 void
7354 break_command (char *arg, int from_tty)
7355 {
7356   break_command_1 (arg, 0, from_tty);
7357 }
7358
7359 void
7360 tbreak_command (char *arg, int from_tty)
7361 {
7362   break_command_1 (arg, BP_TEMPFLAG, from_tty);
7363 }
7364
7365 static void
7366 hbreak_command (char *arg, int from_tty)
7367 {
7368   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
7369 }
7370
7371 static void
7372 thbreak_command (char *arg, int from_tty)
7373 {
7374   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
7375 }
7376
7377 static void
7378 stop_command (char *arg, int from_tty)
7379 {
7380   printf_filtered (_("Specify the type of breakpoint to set.\n\
7381 Usage: stop in <function | address>\n\
7382        stop at <line>\n"));
7383 }
7384
7385 static void
7386 stopin_command (char *arg, int from_tty)
7387 {
7388   int badInput = 0;
7389
7390   if (arg == (char *) NULL)
7391     badInput = 1;
7392   else if (*arg != '*')
7393     {
7394       char *argptr = arg;
7395       int hasColon = 0;
7396
7397       /* look for a ':'.  If this is a line number specification, then
7398          say it is bad, otherwise, it should be an address or
7399          function/method name */
7400       while (*argptr && !hasColon)
7401         {
7402           hasColon = (*argptr == ':');
7403           argptr++;
7404         }
7405
7406       if (hasColon)
7407         badInput = (*argptr != ':');    /* Not a class::method */
7408       else
7409         badInput = isdigit (*arg);      /* a simple line number */
7410     }
7411
7412   if (badInput)
7413     printf_filtered (_("Usage: stop in <function | address>\n"));
7414   else
7415     break_command_1 (arg, 0, from_tty);
7416 }
7417
7418 static void
7419 stopat_command (char *arg, int from_tty)
7420 {
7421   int badInput = 0;
7422
7423   if (arg == (char *) NULL || *arg == '*')      /* no line number */
7424     badInput = 1;
7425   else
7426     {
7427       char *argptr = arg;
7428       int hasColon = 0;
7429
7430       /* look for a ':'.  If there is a '::' then get out, otherwise
7431          it is probably a line number. */
7432       while (*argptr && !hasColon)
7433         {
7434           hasColon = (*argptr == ':');
7435           argptr++;
7436         }
7437
7438       if (hasColon)
7439         badInput = (*argptr == ':');    /* we have class::method */
7440       else
7441         badInput = !isdigit (*arg);     /* not a line number */
7442     }
7443
7444   if (badInput)
7445     printf_filtered (_("Usage: stop at <line>\n"));
7446   else
7447     break_command_1 (arg, 0, from_tty);
7448 }
7449
7450 /* accessflag:  hw_write:  watch write, 
7451                 hw_read:   watch read, 
7452                 hw_access: watch access (read or write) */
7453 static void
7454 watch_command_1 (char *arg, int accessflag, int from_tty)
7455 {
7456   struct gdbarch *gdbarch = get_current_arch ();
7457   struct breakpoint *b, *scope_breakpoint = NULL;
7458   struct expression *exp;
7459   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
7460   struct value *val, *mark;
7461   struct frame_info *frame;
7462   char *exp_start = NULL;
7463   char *exp_end = NULL;
7464   char *tok, *id_tok_start, *end_tok;
7465   int toklen;
7466   char *cond_start = NULL;
7467   char *cond_end = NULL;
7468   int i, other_type_used, target_resources_ok = 0;
7469   enum bptype bp_type;
7470   int mem_cnt = 0;
7471   int thread = -1;
7472
7473   /* Make sure that we actually have parameters to parse.  */
7474   if (arg != NULL && arg[0] != '\0')
7475     {
7476       toklen = strlen (arg); /* Size of argument list.  */
7477
7478       /* Points tok to the end of the argument list.  */
7479       tok = arg + toklen - 1;
7480
7481       /* Go backwards in the parameters list. Skip the last parameter.
7482          If we're expecting a 'thread <thread_num>' parameter, this should
7483          be the thread identifier.  */
7484       while (tok > arg && (*tok == ' ' || *tok == '\t'))
7485         tok--;
7486       while (tok > arg && (*tok != ' ' && *tok != '\t'))
7487         tok--;
7488
7489       /* Points end_tok to the beginning of the last token.  */
7490       id_tok_start = tok + 1;
7491
7492       /* Go backwards in the parameters list. Skip one more parameter.
7493          If we're expecting a 'thread <thread_num>' parameter, we should
7494          reach a "thread" token.  */
7495       while (tok > arg && (*tok == ' ' || *tok == '\t'))
7496         tok--;
7497
7498       end_tok = tok;
7499
7500       while (tok > arg && (*tok != ' ' && *tok != '\t'))
7501         tok--;
7502
7503       /* Move the pointer forward to skip the whitespace and
7504          calculate the length of the token.  */
7505       tok++;
7506       toklen = end_tok - tok;
7507
7508       if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
7509         {
7510           /* At this point we've found a "thread" token, which means
7511              the user is trying to set a watchpoint that triggers
7512              only in a specific thread.  */
7513           char *endp;
7514
7515           /* Extract the thread ID from the next token.  */
7516           thread = strtol (id_tok_start, &endp, 0);
7517
7518           /* Check if the user provided a valid numeric value for the
7519              thread ID.  */
7520           if (*endp != ' ' && *endp != '\t' && *endp != '\0')
7521             error (_("Invalid thread ID specification %s."), id_tok_start);
7522
7523           /* Check if the thread actually exists.  */
7524           if (!valid_thread_id (thread))
7525             error (_("Unknown thread %d."), thread);
7526
7527           /* Truncate the string and get rid of the thread <thread_num>
7528              parameter before the parameter list is parsed by the
7529              evaluate_expression() function.  */
7530           *tok = '\0';
7531         }
7532     }
7533
7534   /* Parse the rest of the arguments.  */
7535   innermost_block = NULL;
7536   exp_start = arg;
7537   exp = parse_exp_1 (&arg, 0, 0);
7538   exp_end = arg;
7539   /* Remove trailing whitespace from the expression before saving it.
7540      This makes the eventual display of the expression string a bit
7541      prettier.  */
7542   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
7543     --exp_end;
7544
7545   exp_valid_block = innermost_block;
7546   mark = value_mark ();
7547   fetch_watchpoint_value (exp, &val, NULL, NULL);
7548   if (val != NULL)
7549     release_value (val);
7550
7551   tok = arg;
7552   while (*tok == ' ' || *tok == '\t')
7553     tok++;
7554   end_tok = tok;
7555
7556   while (*end_tok != ' ' && *end_tok != '\t' && *end_tok != '\000')
7557     end_tok++;
7558
7559   toklen = end_tok - tok;
7560   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
7561     {
7562       struct expression *cond;
7563
7564       innermost_block = NULL;
7565       tok = cond_start = end_tok + 1;
7566       cond = parse_exp_1 (&tok, 0, 0);
7567
7568       /* The watchpoint expression may not be local, but the condition
7569          may still be.  E.g.: `watch global if local > 0'.  */
7570       cond_exp_valid_block = innermost_block;
7571
7572       xfree (cond);
7573       cond_end = tok;
7574     }
7575   if (*tok)
7576     error (_("Junk at end of command."));
7577
7578   if (accessflag == hw_read)
7579     bp_type = bp_read_watchpoint;
7580   else if (accessflag == hw_access)
7581     bp_type = bp_access_watchpoint;
7582   else
7583     bp_type = bp_hardware_watchpoint;
7584
7585   mem_cnt = can_use_hardware_watchpoint (val);
7586   if (mem_cnt == 0 && bp_type != bp_hardware_watchpoint)
7587     error (_("Expression cannot be implemented with read/access watchpoint."));
7588   if (mem_cnt != 0)
7589     {
7590       i = hw_watchpoint_used_count (bp_type, &other_type_used);
7591       target_resources_ok = 
7592         target_can_use_hardware_watchpoint (bp_type, i + mem_cnt, 
7593                                             other_type_used);
7594       if (target_resources_ok == 0 && bp_type != bp_hardware_watchpoint)
7595         error (_("Target does not support this type of hardware watchpoint."));
7596
7597       if (target_resources_ok < 0 && bp_type != bp_hardware_watchpoint)
7598         error (_("Target can only support one kind of HW watchpoint at a time."));
7599     }
7600
7601   /* Change the type of breakpoint to an ordinary watchpoint if a hardware
7602      watchpoint could not be set.  */
7603   if (!mem_cnt || target_resources_ok <= 0)
7604     bp_type = bp_watchpoint;
7605
7606   frame = block_innermost_frame (exp_valid_block);
7607
7608   /* If the expression is "local", then set up a "watchpoint scope"
7609      breakpoint at the point where we've left the scope of the watchpoint
7610      expression.  Create the scope breakpoint before the watchpoint, so
7611      that we will encounter it first in bpstat_stop_status.  */
7612   if (exp_valid_block && frame)
7613     {
7614       if (frame_id_p (frame_unwind_caller_id (frame)))
7615         {
7616           scope_breakpoint
7617             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
7618                                           frame_unwind_caller_pc (frame),
7619                                           bp_watchpoint_scope);
7620
7621           scope_breakpoint->enable_state = bp_enabled;
7622
7623           /* Automatically delete the breakpoint when it hits.  */
7624           scope_breakpoint->disposition = disp_del;
7625
7626           /* Only break in the proper frame (help with recursion).  */
7627           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
7628
7629           /* Set the address at which we will stop.  */
7630           scope_breakpoint->loc->gdbarch
7631             = frame_unwind_caller_arch (frame);
7632           scope_breakpoint->loc->requested_address
7633             = frame_unwind_caller_pc (frame);
7634           scope_breakpoint->loc->address
7635             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
7636                                          scope_breakpoint->loc->requested_address,
7637                                          scope_breakpoint->type);
7638         }
7639     }
7640
7641   /* Now set up the breakpoint.  */
7642   b = set_raw_breakpoint_without_location (NULL, bp_type);
7643   set_breakpoint_count (breakpoint_count + 1);
7644   b->number = breakpoint_count;
7645   b->thread = thread;
7646   b->disposition = disp_donttouch;
7647   b->exp = exp;
7648   b->exp_valid_block = exp_valid_block;
7649   b->cond_exp_valid_block = cond_exp_valid_block;
7650   b->exp_string = savestring (exp_start, exp_end - exp_start);
7651   b->val = val;
7652   b->val_valid = 1;
7653   if (cond_start)
7654     b->cond_string = savestring (cond_start, cond_end - cond_start);
7655   else
7656     b->cond_string = 0;
7657
7658   if (frame)
7659     {
7660       b->watchpoint_frame = get_frame_id (frame);
7661       b->watchpoint_thread = inferior_ptid;
7662     }
7663   else
7664     {
7665       b->watchpoint_frame = null_frame_id;
7666       b->watchpoint_thread = null_ptid;
7667     }
7668
7669   if (scope_breakpoint != NULL)
7670     {
7671       /* The scope breakpoint is related to the watchpoint.  We will
7672          need to act on them together.  */
7673       b->related_breakpoint = scope_breakpoint;
7674       scope_breakpoint->related_breakpoint = b;
7675     }
7676
7677   value_free_to_mark (mark);
7678
7679   /* Finally update the new watchpoint.  This creates the locations
7680      that should be inserted.  */
7681   update_watchpoint (b, 1);
7682
7683   mention (b);
7684   update_global_location_list (1);
7685 }
7686
7687 /* Return count of locations need to be watched and can be handled
7688    in hardware.  If the watchpoint can not be handled
7689    in hardware return zero.  */
7690
7691 static int
7692 can_use_hardware_watchpoint (struct value *v)
7693 {
7694   int found_memory_cnt = 0;
7695   struct value *head = v;
7696
7697   /* Did the user specifically forbid us to use hardware watchpoints? */
7698   if (!can_use_hw_watchpoints)
7699     return 0;
7700
7701   /* Make sure that the value of the expression depends only upon
7702      memory contents, and values computed from them within GDB.  If we
7703      find any register references or function calls, we can't use a
7704      hardware watchpoint.
7705
7706      The idea here is that evaluating an expression generates a series
7707      of values, one holding the value of every subexpression.  (The
7708      expression a*b+c has five subexpressions: a, b, a*b, c, and
7709      a*b+c.)  GDB's values hold almost enough information to establish
7710      the criteria given above --- they identify memory lvalues,
7711      register lvalues, computed values, etcetera.  So we can evaluate
7712      the expression, and then scan the chain of values that leaves
7713      behind to decide whether we can detect any possible change to the
7714      expression's final value using only hardware watchpoints.
7715
7716      However, I don't think that the values returned by inferior
7717      function calls are special in any way.  So this function may not
7718      notice that an expression involving an inferior function call
7719      can't be watched with hardware watchpoints.  FIXME.  */
7720   for (; v; v = value_next (v))
7721     {
7722       if (VALUE_LVAL (v) == lval_memory)
7723         {
7724           if (value_lazy (v))
7725             /* A lazy memory lvalue is one that GDB never needed to fetch;
7726                we either just used its address (e.g., `a' in `a.b') or
7727                we never needed it at all (e.g., `a' in `a,b').  */
7728             ;
7729           else
7730             {
7731               /* Ahh, memory we actually used!  Check if we can cover
7732                  it with hardware watchpoints.  */
7733               struct type *vtype = check_typedef (value_type (v));
7734
7735               /* We only watch structs and arrays if user asked for it
7736                  explicitly, never if they just happen to appear in a
7737                  middle of some value chain.  */
7738               if (v == head
7739                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
7740                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
7741                 {
7742                   CORE_ADDR vaddr = value_address (v);
7743                   int       len   = TYPE_LENGTH (value_type (v));
7744
7745                   if (!target_region_ok_for_hw_watchpoint (vaddr, len))
7746                     return 0;
7747                   else
7748                     found_memory_cnt++;
7749                 }
7750             }
7751         }
7752       else if (VALUE_LVAL (v) != not_lval
7753                && deprecated_value_modifiable (v) == 0)
7754         return 0;       /* ??? What does this represent? */
7755       else if (VALUE_LVAL (v) == lval_register)
7756         return 0;       /* cannot watch a register with a HW watchpoint */
7757     }
7758
7759   /* The expression itself looks suitable for using a hardware
7760      watchpoint, but give the target machine a chance to reject it.  */
7761   return found_memory_cnt;
7762 }
7763
7764 void
7765 watch_command_wrapper (char *arg, int from_tty)
7766 {
7767   watch_command (arg, from_tty);
7768 }
7769
7770 static void
7771 watch_command (char *arg, int from_tty)
7772 {
7773   watch_command_1 (arg, hw_write, from_tty);
7774 }
7775
7776 void
7777 rwatch_command_wrapper (char *arg, int from_tty)
7778 {
7779   rwatch_command (arg, from_tty);
7780 }
7781
7782 static void
7783 rwatch_command (char *arg, int from_tty)
7784 {
7785   watch_command_1 (arg, hw_read, from_tty);
7786 }
7787
7788 void
7789 awatch_command_wrapper (char *arg, int from_tty)
7790 {
7791   awatch_command (arg, from_tty);
7792 }
7793
7794 static void
7795 awatch_command (char *arg, int from_tty)
7796 {
7797   watch_command_1 (arg, hw_access, from_tty);
7798 }
7799 \f
7800
7801 /* Helper routines for the until_command routine in infcmd.c.  Here
7802    because it uses the mechanisms of breakpoints.  */
7803
7804 struct until_break_command_continuation_args
7805 {
7806   struct breakpoint *breakpoint;
7807   struct breakpoint *breakpoint2;
7808 };
7809
7810 /* This function is called by fetch_inferior_event via the
7811    cmd_continuation pointer, to complete the until command. It takes
7812    care of cleaning up the temporary breakpoints set up by the until
7813    command. */
7814 static void
7815 until_break_command_continuation (void *arg)
7816 {
7817   struct until_break_command_continuation_args *a = arg;
7818
7819   delete_breakpoint (a->breakpoint);
7820   if (a->breakpoint2)
7821     delete_breakpoint (a->breakpoint2);
7822 }
7823
7824 void
7825 until_break_command (char *arg, int from_tty, int anywhere)
7826 {
7827   struct symtabs_and_lines sals;
7828   struct symtab_and_line sal;
7829   struct frame_info *frame = get_selected_frame (NULL);
7830   struct breakpoint *breakpoint;
7831   struct breakpoint *breakpoint2 = NULL;
7832   struct cleanup *old_chain;
7833
7834   clear_proceed_status ();
7835
7836   /* Set a breakpoint where the user wants it and at return from
7837      this function */
7838
7839   if (default_breakpoint_valid)
7840     sals = decode_line_1 (&arg, 1, default_breakpoint_symtab,
7841                           default_breakpoint_line, (char ***) NULL, NULL);
7842   else
7843     sals = decode_line_1 (&arg, 1, (struct symtab *) NULL, 
7844                           0, (char ***) NULL, NULL);
7845
7846   if (sals.nelts != 1)
7847     error (_("Couldn't get information on specified line."));
7848
7849   sal = sals.sals[0];
7850   xfree (sals.sals);    /* malloc'd, so freed */
7851
7852   if (*arg)
7853     error (_("Junk at end of arguments."));
7854
7855   resolve_sal_pc (&sal);
7856
7857   if (anywhere)
7858     /* If the user told us to continue until a specified location,
7859        we don't specify a frame at which we need to stop.  */
7860     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
7861                                            null_frame_id, bp_until);
7862   else
7863     /* Otherwise, specify the selected frame, because we want to stop only
7864        at the very same frame.  */
7865     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
7866                                            get_stack_frame_id (frame),
7867                                            bp_until);
7868
7869   old_chain = make_cleanup_delete_breakpoint (breakpoint);
7870
7871   /* Keep within the current frame, or in frames called by the current
7872      one.  */
7873
7874   if (frame_id_p (frame_unwind_caller_id (frame)))
7875     {
7876       sal = find_pc_line (frame_unwind_caller_pc (frame), 0);
7877       sal.pc = frame_unwind_caller_pc (frame);
7878       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
7879                                               sal,
7880                                               frame_unwind_caller_id (frame),
7881                                               bp_until);
7882       make_cleanup_delete_breakpoint (breakpoint2);
7883     }
7884
7885   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
7886
7887   /* If we are running asynchronously, and proceed call above has actually
7888      managed to start the target, arrange for breakpoints to be
7889      deleted when the target stops.  Otherwise, we're already stopped and
7890      delete breakpoints via cleanup chain.  */
7891
7892   if (target_can_async_p () && is_running (inferior_ptid))
7893     {
7894       struct until_break_command_continuation_args *args;
7895       args = xmalloc (sizeof (*args));
7896
7897       args->breakpoint = breakpoint;
7898       args->breakpoint2 = breakpoint2;
7899
7900       discard_cleanups (old_chain);
7901       add_continuation (inferior_thread (),
7902                         until_break_command_continuation, args,
7903                         xfree);
7904     }
7905   else
7906     do_cleanups (old_chain);
7907 }
7908
7909 static void
7910 ep_skip_leading_whitespace (char **s)
7911 {
7912   if ((s == NULL) || (*s == NULL))
7913     return;
7914   while (isspace (**s))
7915     *s += 1;
7916 }
7917
7918 /* This function attempts to parse an optional "if <cond>" clause
7919    from the arg string.  If one is not found, it returns NULL.
7920
7921    Else, it returns a pointer to the condition string.  (It does not
7922    attempt to evaluate the string against a particular block.)  And,
7923    it updates arg to point to the first character following the parsed
7924    if clause in the arg string. */
7925
7926 static char *
7927 ep_parse_optional_if_clause (char **arg)
7928 {
7929   char *cond_string;
7930
7931   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
7932     return NULL;
7933
7934   /* Skip the "if" keyword. */
7935   (*arg) += 2;
7936
7937   /* Skip any extra leading whitespace, and record the start of the
7938      condition string. */
7939   ep_skip_leading_whitespace (arg);
7940   cond_string = *arg;
7941
7942   /* Assume that the condition occupies the remainder of the arg string. */
7943   (*arg) += strlen (cond_string);
7944
7945   return cond_string;
7946 }
7947
7948 /* Commands to deal with catching events, such as signals, exceptions,
7949    process start/exit, etc.  */
7950
7951 typedef enum
7952 {
7953   catch_fork_temporary, catch_vfork_temporary,
7954   catch_fork_permanent, catch_vfork_permanent
7955 }
7956 catch_fork_kind;
7957
7958 static void
7959 catch_fork_command_1 (char *arg, int from_tty, struct cmd_list_element *command)
7960 {
7961   struct gdbarch *gdbarch = get_current_arch ();
7962   char *cond_string = NULL;
7963   catch_fork_kind fork_kind;
7964   int tempflag;
7965
7966   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
7967   tempflag = (fork_kind == catch_fork_temporary
7968               || fork_kind == catch_vfork_temporary);
7969
7970   if (!arg)
7971     arg = "";
7972   ep_skip_leading_whitespace (&arg);
7973
7974   /* The allowed syntax is:
7975      catch [v]fork
7976      catch [v]fork if <cond>
7977
7978      First, check if there's an if clause. */
7979   cond_string = ep_parse_optional_if_clause (&arg);
7980
7981   if ((*arg != '\0') && !isspace (*arg))
7982     error (_("Junk at end of arguments."));
7983
7984   /* If this target supports it, create a fork or vfork catchpoint
7985      and enable reporting of such events. */
7986   switch (fork_kind)
7987     {
7988     case catch_fork_temporary:
7989     case catch_fork_permanent:
7990       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
7991                                           &catch_fork_breakpoint_ops);
7992       break;
7993     case catch_vfork_temporary:
7994     case catch_vfork_permanent:
7995       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
7996                                           &catch_vfork_breakpoint_ops);
7997       break;
7998     default:
7999       error (_("unsupported or unknown fork kind; cannot catch it"));
8000       break;
8001     }
8002 }
8003
8004 static void
8005 catch_exec_command_1 (char *arg, int from_tty, struct cmd_list_element *command)
8006 {
8007   struct gdbarch *gdbarch = get_current_arch ();
8008   int tempflag;
8009   char *cond_string = NULL;
8010
8011   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8012
8013   if (!arg)
8014     arg = "";
8015   ep_skip_leading_whitespace (&arg);
8016
8017   /* The allowed syntax is:
8018      catch exec
8019      catch exec if <cond>
8020
8021      First, check if there's an if clause. */
8022   cond_string = ep_parse_optional_if_clause (&arg);
8023
8024   if ((*arg != '\0') && !isspace (*arg))
8025     error (_("Junk at end of arguments."));
8026
8027   /* If this target supports it, create an exec catchpoint
8028      and enable reporting of such events. */
8029   create_catchpoint (gdbarch, tempflag, cond_string,
8030                      &catch_exec_breakpoint_ops);
8031 }
8032
8033 static enum print_stop_action
8034 print_exception_catchpoint (struct breakpoint *b)
8035 {
8036   int bp_temp, bp_throw;
8037
8038   annotate_catchpoint (b->number);
8039
8040   bp_throw = strstr (b->addr_string, "throw") != NULL;
8041   if (b->loc->address != b->loc->requested_address)
8042     breakpoint_adjustment_warning (b->loc->requested_address,
8043                                    b->loc->address,
8044                                    b->number, 1);
8045   bp_temp = b->disposition == disp_del;
8046   ui_out_text (uiout, 
8047                bp_temp ? "Temporary catchpoint "
8048                        : "Catchpoint ");
8049   if (!ui_out_is_mi_like_p (uiout))
8050     ui_out_field_int (uiout, "bkptno", b->number);
8051   ui_out_text (uiout,
8052                bp_throw ? " (exception thrown), "
8053                         : " (exception caught), ");
8054   if (ui_out_is_mi_like_p (uiout))
8055     {
8056       ui_out_field_string (uiout, "reason", 
8057                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
8058       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8059       ui_out_field_int (uiout, "bkptno", b->number);
8060     }
8061   return PRINT_SRC_AND_LOC;
8062 }
8063
8064 static void
8065 print_one_exception_catchpoint (struct breakpoint *b, struct bp_location **last_loc)
8066 {
8067   struct value_print_options opts;
8068   get_user_print_options (&opts);
8069   if (opts.addressprint)
8070     {
8071       annotate_field (4);
8072       if (b->loc == NULL || b->loc->shlib_disabled)
8073         ui_out_field_string (uiout, "addr", "<PENDING>");
8074       else
8075         ui_out_field_core_addr (uiout, "addr",
8076                                 b->loc->gdbarch, b->loc->address);
8077     }
8078   annotate_field (5);
8079   if (b->loc)
8080     *last_loc = b->loc;
8081   if (strstr (b->addr_string, "throw") != NULL)
8082     ui_out_field_string (uiout, "what", "exception throw");
8083   else
8084     ui_out_field_string (uiout, "what", "exception catch");
8085 }
8086
8087 static void
8088 print_mention_exception_catchpoint (struct breakpoint *b)
8089 {
8090   int bp_temp;
8091   int bp_throw;
8092
8093   bp_temp = b->disposition == disp_del;
8094   bp_throw = strstr (b->addr_string, "throw") != NULL;
8095   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
8096                               : _("Catchpoint "));
8097   ui_out_field_int (uiout, "bkptno", b->number);
8098   ui_out_text (uiout, bp_throw ? _(" (throw)")
8099                                : _(" (catch)"));
8100 }
8101
8102 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops = {
8103   NULL, /* insert */
8104   NULL, /* remove */
8105   NULL, /* breakpoint_hit */
8106   print_exception_catchpoint,
8107   print_one_exception_catchpoint,
8108   print_mention_exception_catchpoint
8109 };
8110
8111 static int
8112 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
8113                           enum exception_event_kind ex_event, int from_tty)
8114 {
8115   char *trigger_func_name;
8116  
8117   if (ex_event == EX_EVENT_CATCH)
8118     trigger_func_name = "__cxa_begin_catch";
8119   else
8120     trigger_func_name = "__cxa_throw";
8121
8122   create_breakpoint (get_current_arch (),
8123                      trigger_func_name, cond_string, -1,
8124                      0 /* condition and thread are valid.  */,
8125                      tempflag, 0, 0,
8126                      0,
8127                      AUTO_BOOLEAN_TRUE /* pending */,
8128                      &gnu_v3_exception_catchpoint_ops, from_tty,
8129                      1 /* enabled */);
8130
8131   return 1;
8132 }
8133
8134 /* Deal with "catch catch" and "catch throw" commands */
8135
8136 static void
8137 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
8138                            int tempflag, int from_tty)
8139 {
8140   char *cond_string = NULL;
8141   struct symtab_and_line *sal = NULL;
8142
8143   if (!arg)
8144     arg = "";
8145   ep_skip_leading_whitespace (&arg);
8146
8147   cond_string = ep_parse_optional_if_clause (&arg);
8148
8149   if ((*arg != '\0') && !isspace (*arg))
8150     error (_("Junk at end of arguments."));
8151
8152   if (ex_event != EX_EVENT_THROW
8153       && ex_event != EX_EVENT_CATCH)
8154     error (_("Unsupported or unknown exception event; cannot catch it"));
8155
8156   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
8157     return;
8158
8159   warning (_("Unsupported with this platform/compiler combination."));
8160 }
8161
8162 /* Implementation of "catch catch" command.  */
8163
8164 static void
8165 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
8166 {
8167   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8168   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
8169 }
8170
8171 /* Implementation of "catch throw" command.  */
8172
8173 static void
8174 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
8175 {
8176   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8177   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
8178 }
8179
8180 /* Create a breakpoint struct for Ada exception catchpoints.  */
8181
8182 static void
8183 create_ada_exception_breakpoint (struct gdbarch *gdbarch,
8184                                  struct symtab_and_line sal,
8185                                  char *addr_string,
8186                                  char *exp_string,
8187                                  char *cond_string,
8188                                  struct expression *cond,
8189                                  struct breakpoint_ops *ops,
8190                                  int tempflag,
8191                                  int from_tty)
8192 {
8193   struct breakpoint *b;
8194
8195   if (from_tty)
8196     {
8197       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8198       if (!loc_gdbarch)
8199         loc_gdbarch = gdbarch;
8200
8201       describe_other_breakpoints (loc_gdbarch,
8202                                   sal.pspace, sal.pc, sal.section, -1);
8203       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
8204          version for exception catchpoints, because two catchpoints
8205          used for different exception names will use the same address.
8206          In this case, a "breakpoint ... also set at..." warning is
8207          unproductive.  Besides. the warning phrasing is also a bit
8208          inapropriate, we should use the word catchpoint, and tell
8209          the user what type of catchpoint it is.  The above is good
8210          enough for now, though.  */
8211     }
8212
8213   b = set_raw_breakpoint (gdbarch, sal, bp_breakpoint);
8214   set_breakpoint_count (breakpoint_count + 1);
8215
8216   b->enable_state = bp_enabled;
8217   b->disposition = tempflag ? disp_del : disp_donttouch;
8218   b->number = breakpoint_count;
8219   b->ignore_count = 0;
8220   b->loc->cond = cond;
8221   b->addr_string = addr_string;
8222   b->language = language_ada;
8223   b->cond_string = cond_string;
8224   b->exp_string = exp_string;
8225   b->thread = -1;
8226   b->ops = ops;
8227
8228   mention (b);
8229   update_global_location_list (1);
8230 }
8231
8232 /* Implement the "catch exception" command.  */
8233
8234 static void
8235 catch_ada_exception_command (char *arg, int from_tty,
8236                              struct cmd_list_element *command)
8237 {
8238   struct gdbarch *gdbarch = get_current_arch ();
8239   int tempflag;
8240   struct symtab_and_line sal;
8241   enum bptype type;
8242   char *addr_string = NULL;
8243   char *exp_string = NULL;
8244   char *cond_string = NULL;
8245   struct expression *cond = NULL;
8246   struct breakpoint_ops *ops = NULL;
8247
8248   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8249
8250   if (!arg)
8251     arg = "";
8252   sal = ada_decode_exception_location (arg, &addr_string, &exp_string,
8253                                        &cond_string, &cond, &ops);
8254   create_ada_exception_breakpoint (gdbarch, sal, addr_string, exp_string,
8255                                    cond_string, cond, ops, tempflag,
8256                                    from_tty);
8257 }
8258
8259 /* Cleanup function for a syscall filter list.  */
8260 static void
8261 clean_up_filters (void *arg)
8262 {
8263   VEC(int) *iter = *(VEC(int) **) arg;
8264   VEC_free (int, iter);
8265 }
8266
8267 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
8268    filter list, or NULL if no filtering is required.  */
8269 static VEC(int) *
8270 catch_syscall_split_args (char *arg)
8271 {
8272   VEC(int) *result = NULL;
8273   struct cleanup *cleanup = make_cleanup (clean_up_filters, &result);
8274
8275   while (*arg != '\0')
8276     {
8277       int i, syscall_number;
8278       char *endptr;
8279       char cur_name[128];
8280       struct syscall s;
8281
8282       /* Skip whitespace.  */
8283       while (isspace (*arg))
8284         arg++;
8285
8286       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
8287         cur_name[i] = arg[i];
8288       cur_name[i] = '\0';
8289       arg += i;
8290
8291       /* Check if the user provided a syscall name or a number.  */
8292       syscall_number = (int) strtol (cur_name, &endptr, 0);
8293       if (*endptr == '\0')
8294         get_syscall_by_number (syscall_number, &s);
8295       else
8296         {
8297           /* We have a name.  Let's check if it's valid and convert it
8298              to a number.  */
8299           get_syscall_by_name (cur_name, &s);
8300
8301           if (s.number == UNKNOWN_SYSCALL)
8302             /* Here we have to issue an error instead of a warning, because
8303                GDB cannot do anything useful if there's no syscall number to
8304                be caught.  */
8305             error (_("Unknown syscall name '%s'."), cur_name);
8306         }
8307
8308       /* Ok, it's valid.  */
8309       VEC_safe_push (int, result, s.number);
8310     }
8311
8312   discard_cleanups (cleanup);
8313   return result;
8314 }
8315
8316 /* Implement the "catch syscall" command.  */
8317
8318 static void
8319 catch_syscall_command_1 (char *arg, int from_tty, struct cmd_list_element *command)
8320 {
8321   int tempflag;
8322   VEC(int) *filter;
8323   struct syscall s;
8324   struct gdbarch *gdbarch = get_current_arch ();
8325
8326   /* Checking if the feature if supported.  */
8327   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
8328     error (_("The feature 'catch syscall' is not supported on \
8329 this architeture yet."));
8330
8331   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8332
8333   ep_skip_leading_whitespace (&arg);
8334
8335   /* We need to do this first "dummy" translation in order
8336      to get the syscall XML file loaded or, most important,
8337      to display a warning to the user if there's no XML file
8338      for his/her architecture.  */
8339   get_syscall_by_number (0, &s);
8340
8341   /* The allowed syntax is:
8342      catch syscall
8343      catch syscall <name | number> [<name | number> ... <name | number>]
8344
8345      Let's check if there's a syscall name.  */
8346
8347   if (arg != NULL)
8348     filter = catch_syscall_split_args (arg);
8349   else
8350     filter = NULL;
8351
8352   create_syscall_event_catchpoint (tempflag, filter,
8353                                    &catch_syscall_breakpoint_ops);
8354 }
8355
8356 /* Implement the "catch assert" command.  */
8357
8358 static void
8359 catch_assert_command (char *arg, int from_tty, struct cmd_list_element *command)
8360 {
8361   struct gdbarch *gdbarch = get_current_arch ();
8362   int tempflag;
8363   struct symtab_and_line sal;
8364   char *addr_string = NULL;
8365   struct breakpoint_ops *ops = NULL;
8366
8367   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8368
8369   if (!arg)
8370     arg = "";
8371   sal = ada_decode_assert_location (arg, &addr_string, &ops);
8372   create_ada_exception_breakpoint (gdbarch, sal, addr_string, NULL, NULL, NULL,
8373                                    ops, tempflag, from_tty);
8374 }
8375
8376 static void
8377 catch_command (char *arg, int from_tty)
8378 {
8379   error (_("Catch requires an event name."));
8380 }
8381 \f
8382
8383 static void
8384 tcatch_command (char *arg, int from_tty)
8385 {
8386   error (_("Catch requires an event name."));
8387 }
8388
8389 /* Delete breakpoints by address or line.  */
8390
8391 static void
8392 clear_command (char *arg, int from_tty)
8393 {
8394   struct breakpoint *b;
8395   VEC(breakpoint_p) *found = 0;
8396   int ix;
8397   int default_match;
8398   struct symtabs_and_lines sals;
8399   struct symtab_and_line sal;
8400   int i;
8401
8402   if (arg)
8403     {
8404       sals = decode_line_spec (arg, 1);
8405       default_match = 0;
8406     }
8407   else
8408     {
8409       sals.sals = (struct symtab_and_line *)
8410         xmalloc (sizeof (struct symtab_and_line));
8411       make_cleanup (xfree, sals.sals);
8412       init_sal (&sal);          /* initialize to zeroes */
8413       sal.line = default_breakpoint_line;
8414       sal.symtab = default_breakpoint_symtab;
8415       sal.pc = default_breakpoint_address;
8416       sal.pspace = default_breakpoint_pspace;
8417       if (sal.symtab == 0)
8418         error (_("No source file specified."));
8419
8420       sals.sals[0] = sal;
8421       sals.nelts = 1;
8422
8423       default_match = 1;
8424     }
8425
8426   /* We don't call resolve_sal_pc here. That's not
8427      as bad as it seems, because all existing breakpoints
8428      typically have both file/line and pc set.  So, if
8429      clear is given file/line, we can match this to existing
8430      breakpoint without obtaining pc at all.
8431
8432      We only support clearing given the address explicitly 
8433      present in breakpoint table.  Say, we've set breakpoint 
8434      at file:line. There were several PC values for that file:line,
8435      due to optimization, all in one block.
8436      We've picked one PC value. If "clear" is issued with another
8437      PC corresponding to the same file:line, the breakpoint won't
8438      be cleared.  We probably can still clear the breakpoint, but 
8439      since the other PC value is never presented to user, user
8440      can only find it by guessing, and it does not seem important
8441      to support that.  */
8442
8443   /* For each line spec given, delete bps which correspond
8444      to it.  Do it in two passes, solely to preserve the current
8445      behavior that from_tty is forced true if we delete more than
8446      one breakpoint.  */
8447
8448   found = NULL;
8449   for (i = 0; i < sals.nelts; i++)
8450     {
8451       /* If exact pc given, clear bpts at that pc.
8452          If line given (pc == 0), clear all bpts on specified line.
8453          If defaulting, clear all bpts on default line
8454          or at default pc.
8455
8456          defaulting    sal.pc != 0    tests to do
8457
8458          0              1             pc
8459          1              1             pc _and_ line
8460          0              0             line
8461          1              0             <can't happen> */
8462
8463       sal = sals.sals[i];
8464
8465       /* Find all matching breakpoints and add them to
8466          'found'.  */
8467       ALL_BREAKPOINTS (b)
8468         {
8469           int match = 0;
8470           /* Are we going to delete b? */
8471           if (b->type != bp_none
8472               && b->type != bp_watchpoint
8473               && b->type != bp_hardware_watchpoint
8474               && b->type != bp_read_watchpoint
8475               && b->type != bp_access_watchpoint)
8476             {
8477               struct bp_location *loc = b->loc;
8478               for (; loc; loc = loc->next)
8479                 {
8480                   int pc_match = sal.pc
8481                     && (loc->pspace == sal.pspace)
8482                     && (loc->address == sal.pc)
8483                     && (!section_is_overlay (loc->section)
8484                         || loc->section == sal.section);
8485                   int line_match = ((default_match || (0 == sal.pc))
8486                                     && b->source_file != NULL
8487                                     && sal.symtab != NULL
8488                                     && sal.pspace == loc->pspace
8489                                     && strcmp (b->source_file, sal.symtab->filename) == 0
8490                                     && b->line_number == sal.line);
8491                   if (pc_match || line_match)
8492                     {
8493                       match = 1;
8494                       break;
8495                     }
8496                 }
8497             }
8498
8499           if (match)
8500             VEC_safe_push(breakpoint_p, found, b);
8501         }
8502     }
8503   /* Now go thru the 'found' chain and delete them.  */
8504   if (VEC_empty(breakpoint_p, found))
8505     {
8506       if (arg)
8507         error (_("No breakpoint at %s."), arg);
8508       else
8509         error (_("No breakpoint at this line."));
8510     }
8511
8512   if (VEC_length(breakpoint_p, found) > 1)
8513     from_tty = 1;               /* Always report if deleted more than one */
8514   if (from_tty)
8515     {
8516       if (VEC_length(breakpoint_p, found) == 1)
8517         printf_unfiltered (_("Deleted breakpoint "));
8518       else
8519         printf_unfiltered (_("Deleted breakpoints "));
8520     }
8521   breakpoints_changed ();
8522
8523   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
8524     {
8525       if (from_tty)
8526         printf_unfiltered ("%d ", b->number);
8527       delete_breakpoint (b);
8528     }
8529   if (from_tty)
8530     putchar_unfiltered ('\n');
8531 }
8532 \f
8533 /* Delete breakpoint in BS if they are `delete' breakpoints and
8534    all breakpoints that are marked for deletion, whether hit or not.
8535    This is called after any breakpoint is hit, or after errors.  */
8536
8537 void
8538 breakpoint_auto_delete (bpstat bs)
8539 {
8540   struct breakpoint *b, *temp;
8541
8542   for (; bs; bs = bs->next)
8543     if (bs->breakpoint_at 
8544         && bs->breakpoint_at->owner
8545         && bs->breakpoint_at->owner->disposition == disp_del
8546         && bs->stop)
8547       delete_breakpoint (bs->breakpoint_at->owner);
8548
8549   ALL_BREAKPOINTS_SAFE (b, temp)
8550   {
8551     if (b->disposition == disp_del_at_next_stop)
8552       delete_breakpoint (b);
8553   }
8554 }
8555
8556 /* A comparison function for bp_location AP and BP being interfaced to qsort.
8557    Sort elements primarily by their ADDRESS (no matter what does
8558    breakpoint_address_is_meaningful say for its OWNER), secondarily by ordering
8559    first bp_permanent OWNERed elements and terciarily just ensuring the array
8560    is sorted stable way despite qsort being an instable algorithm.  */
8561
8562 static int
8563 bp_location_compare (const void *ap, const void *bp)
8564 {
8565   struct bp_location *a = *(void **) ap;
8566   struct bp_location *b = *(void **) bp;
8567   int a_perm = a->owner->enable_state == bp_permanent;
8568   int b_perm = b->owner->enable_state == bp_permanent;
8569
8570   if (a->address != b->address)
8571     return (a->address > b->address) - (a->address < b->address);
8572
8573   /* Sort permanent breakpoints first.  */
8574   if (a_perm != b_perm)
8575     return (a_perm < b_perm) - (a_perm > b_perm);
8576
8577   /* Make the user-visible order stable across GDB runs.  Locations of the same
8578      breakpoint can be sorted in arbitrary order.  */
8579
8580   if (a->owner->number != b->owner->number)
8581     return (a->owner->number > b->owner->number)
8582            - (a->owner->number < b->owner->number);
8583
8584   return (a > b) - (a < b);
8585 }
8586
8587 /* Set bp_location_placed_address_before_address_max and
8588    bp_location_shadow_len_after_address_max according to the current content of
8589    the bp_location array.  */
8590
8591 static void
8592 bp_location_target_extensions_update (void)
8593 {
8594   struct bp_location *bl, **blp_tmp;
8595
8596   bp_location_placed_address_before_address_max = 0;
8597   bp_location_shadow_len_after_address_max = 0;
8598
8599   ALL_BP_LOCATIONS (bl, blp_tmp)
8600     {
8601       CORE_ADDR start, end, addr;
8602
8603       if (!bp_location_has_shadow (bl))
8604         continue;
8605
8606       start = bl->target_info.placed_address;
8607       end = start + bl->target_info.shadow_len;
8608
8609       gdb_assert (bl->address >= start);
8610       addr = bl->address - start;
8611       if (addr > bp_location_placed_address_before_address_max)
8612         bp_location_placed_address_before_address_max = addr;
8613
8614       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
8615
8616       gdb_assert (bl->address < end);
8617       addr = end - bl->address;
8618       if (addr > bp_location_shadow_len_after_address_max)
8619         bp_location_shadow_len_after_address_max = addr;
8620     }
8621 }
8622
8623 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
8624    into the inferior, only remove already-inserted locations that no
8625    longer should be inserted.  Functions that delete a breakpoint or
8626    breakpoints should pass false, so that deleting a breakpoint
8627    doesn't have the side effect of inserting the locations of other
8628    breakpoints that are marked not-inserted, but should_be_inserted
8629    returns true on them.
8630
8631    This behaviour is useful is situations close to tear-down -- e.g.,
8632    after an exec, while the target still has execution, but breakpoint
8633    shadows of the previous executable image should *NOT* be restored
8634    to the new image; or before detaching, where the target still has
8635    execution and wants to delete breakpoints from GDB's lists, and all
8636    breakpoints had already been removed from the inferior.  */
8637
8638 static void
8639 update_global_location_list (int should_insert)
8640 {
8641   struct breakpoint *b;
8642   struct bp_location **locp, *loc;
8643   struct cleanup *cleanups;
8644
8645   /* Used in the duplicates detection below.  When iterating over all
8646      bp_locations, points to the first bp_location of a given address.
8647      Breakpoints and watchpoints of different types are never
8648      duplicates of each other.  Keep one pointer for each type of
8649      breakpoint/watchpoint, so we only need to loop over all locations
8650      once.  */
8651   struct bp_location *bp_loc_first;  /* breakpoint */
8652   struct bp_location *wp_loc_first;  /* hardware watchpoint */
8653   struct bp_location *awp_loc_first; /* access watchpoint */
8654   struct bp_location *rwp_loc_first; /* read watchpoint */
8655
8656   /* Saved former bp_location array which we compare against the newly built
8657      bp_location from the current state of ALL_BREAKPOINTS.  */
8658   struct bp_location **old_location, **old_locp;
8659   unsigned old_location_count;
8660
8661   old_location = bp_location;
8662   old_location_count = bp_location_count;
8663   bp_location = NULL;
8664   bp_location_count = 0;
8665   cleanups = make_cleanup (xfree, old_location);
8666
8667   ALL_BREAKPOINTS (b)
8668     for (loc = b->loc; loc; loc = loc->next)
8669       bp_location_count++;
8670
8671   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
8672   locp = bp_location;
8673   ALL_BREAKPOINTS (b)
8674     for (loc = b->loc; loc; loc = loc->next)
8675       *locp++ = loc;
8676   qsort (bp_location, bp_location_count, sizeof (*bp_location),
8677          bp_location_compare);
8678
8679   bp_location_target_extensions_update ();
8680
8681   /* Identify bp_location instances that are no longer present in the new
8682      list, and therefore should be freed.  Note that it's not necessary that
8683      those locations should be removed from inferior -- if there's another
8684      location at the same address (previously marked as duplicate),
8685      we don't need to remove/insert the location.
8686      
8687      LOCP is kept in sync with OLD_LOCP, each pointing to the current and
8688      former bp_location array state respectively.  */
8689
8690   locp = bp_location;
8691   for (old_locp = old_location; old_locp < old_location + old_location_count;
8692        old_locp++)
8693     {
8694       struct bp_location *old_loc = *old_locp;
8695       struct bp_location **loc2p;
8696
8697       /* Tells if 'old_loc' is found amoung the new locations.  If not, we
8698          have to free it.  */
8699       int found_object = 0;
8700       /* Tells if the location should remain inserted in the target.  */
8701       int keep_in_target = 0;
8702       int removed = 0;
8703
8704       /* Skip LOCP entries which will definitely never be needed.  Stop either
8705          at or being the one matching OLD_LOC.  */
8706       while (locp < bp_location + bp_location_count
8707              && (*locp)->address < old_loc->address)
8708         locp++;
8709
8710       for (loc2p = locp;
8711            (loc2p < bp_location + bp_location_count
8712             && (*loc2p)->address == old_loc->address);
8713            loc2p++)
8714         {
8715           if (*loc2p == old_loc)
8716             {
8717               found_object = 1;
8718               break;
8719             }
8720         }
8721
8722       /* If this location is no longer present, and inserted, look if there's
8723          maybe a new location at the same address.  If so, mark that one 
8724          inserted, and don't remove this one.  This is needed so that we 
8725          don't have a time window where a breakpoint at certain location is not
8726          inserted.  */
8727
8728       if (old_loc->inserted)
8729         {
8730           /* If the location is inserted now, we might have to remove it.  */
8731
8732           if (found_object && should_be_inserted (old_loc))
8733             {
8734               /* The location is still present in the location list, and still
8735                  should be inserted.  Don't do anything.  */
8736               keep_in_target = 1;
8737             }
8738           else
8739             {
8740               /* The location is either no longer present, or got disabled.
8741                  See if there's another location at the same address, in which 
8742                  case we don't need to remove this one from the target.  */
8743
8744               if (breakpoint_address_is_meaningful (old_loc->owner))
8745                 {
8746                   for (loc2p = locp;
8747                        (loc2p < bp_location + bp_location_count
8748                         && (*loc2p)->address == old_loc->address);
8749                        loc2p++)
8750                     {
8751                       struct bp_location *loc2 = *loc2p;
8752
8753                       if (breakpoint_locations_match (loc2, old_loc))
8754                         {
8755                           /* For the sake of should_be_inserted.
8756                              Duplicates check below will fix up this later.  */
8757                           loc2->duplicate = 0;
8758
8759                           /* Read watchpoint locations are switched to
8760                              access watchpoints, if the former are not
8761                              supported, but the latter are.  */
8762                           if (is_hardware_watchpoint (old_loc->owner))
8763                             {
8764                               gdb_assert (is_hardware_watchpoint (loc2->owner));
8765                               loc2->watchpoint_type = old_loc->watchpoint_type;
8766                             }
8767
8768                           if (loc2 != old_loc && should_be_inserted (loc2))
8769                             {
8770                               loc2->inserted = 1;
8771                               loc2->target_info = old_loc->target_info;
8772                               keep_in_target = 1;
8773                               break;
8774                             }
8775                         }
8776                     }
8777                 }
8778             }
8779
8780           if (!keep_in_target)
8781             {
8782               if (remove_breakpoint (old_loc, mark_uninserted))
8783                 {
8784                   /* This is just about all we can do.  We could keep this
8785                      location on the global list, and try to remove it next
8786                      time, but there's no particular reason why we will
8787                      succeed next time.  
8788                      
8789                      Note that at this point, old_loc->owner is still valid,
8790                      as delete_breakpoint frees the breakpoint only
8791                      after calling us.  */
8792                   printf_filtered (_("warning: Error removing breakpoint %d\n"), 
8793                                    old_loc->owner->number);
8794                 }
8795               removed = 1;
8796             }
8797         }
8798
8799       if (!found_object)
8800         {
8801           if (removed && non_stop
8802               && breakpoint_address_is_meaningful (old_loc->owner)
8803               && !is_hardware_watchpoint (old_loc->owner))
8804             {
8805               /* This location was removed from the target.  In
8806                  non-stop mode, a race condition is possible where
8807                  we've removed a breakpoint, but stop events for that
8808                  breakpoint are already queued and will arrive later.
8809                  We apply an heuristic to be able to distinguish such
8810                  SIGTRAPs from other random SIGTRAPs: we keep this
8811                  breakpoint location for a bit, and will retire it
8812                  after we see some number of events.  The theory here
8813                  is that reporting of events should, "on the average",
8814                  be fair, so after a while we'll see events from all
8815                  threads that have anything of interest, and no longer
8816                  need to keep this breakpoint location around.  We
8817                  don't hold locations forever so to reduce chances of
8818                  mistaking a non-breakpoint SIGTRAP for a breakpoint
8819                  SIGTRAP.
8820
8821                  The heuristic failing can be disastrous on
8822                  decr_pc_after_break targets.
8823
8824                  On decr_pc_after_break targets, like e.g., x86-linux,
8825                  if we fail to recognize a late breakpoint SIGTRAP,
8826                  because events_till_retirement has reached 0 too
8827                  soon, we'll fail to do the PC adjustment, and report
8828                  a random SIGTRAP to the user.  When the user resumes
8829                  the inferior, it will most likely immediately crash
8830                  with SIGILL/SIGBUS/SEGSEGV, or worse, get silently
8831                  corrupted, because of being resumed e.g., in the
8832                  middle of a multi-byte instruction, or skipped a
8833                  one-byte instruction.  This was actually seen happen
8834                  on native x86-linux, and should be less rare on
8835                  targets that do not support new thread events, like
8836                  remote, due to the heuristic depending on
8837                  thread_count.
8838
8839                  Mistaking a random SIGTRAP for a breakpoint trap
8840                  causes similar symptoms (PC adjustment applied when
8841                  it shouldn't), but then again, playing with SIGTRAPs
8842                  behind the debugger's back is asking for trouble.
8843
8844                  Since hardware watchpoint traps are always
8845                  distinguishable from other traps, so we don't need to
8846                  apply keep hardware watchpoint moribund locations
8847                  around.  We simply always ignore hardware watchpoint
8848                  traps we can no longer explain.  */
8849
8850               old_loc->events_till_retirement = 3 * (thread_count () + 1);
8851               old_loc->owner = NULL;
8852
8853               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
8854             }
8855           else
8856             free_bp_location (old_loc);
8857         }
8858     }
8859
8860   /* Rescan breakpoints at the same address and section, marking the
8861      first one as "first" and any others as "duplicates".  This is so
8862      that the bpt instruction is only inserted once.  If we have a
8863      permanent breakpoint at the same place as BPT, make that one the
8864      official one, and the rest as duplicates.  Permanent breakpoints
8865      are sorted first for the same address.
8866
8867      Do the same for hardware watchpoints, but also considering the
8868      watchpoint's type (regular/access/read) and length.  */
8869
8870   bp_loc_first = NULL;
8871   wp_loc_first = NULL;
8872   awp_loc_first = NULL;
8873   rwp_loc_first = NULL;
8874   ALL_BP_LOCATIONS (loc, locp)
8875     {
8876       struct breakpoint *b = loc->owner;
8877       struct bp_location **loc_first_p;
8878
8879       if (b->enable_state == bp_disabled
8880           || b->enable_state == bp_call_disabled
8881           || b->enable_state == bp_startup_disabled
8882           || !loc->enabled
8883           || loc->shlib_disabled
8884           || !breakpoint_address_is_meaningful (b)
8885           || tracepoint_type (b))
8886         continue;
8887
8888       /* Permanent breakpoint should always be inserted.  */
8889       if (b->enable_state == bp_permanent && ! loc->inserted)
8890         internal_error (__FILE__, __LINE__,
8891                         _("allegedly permanent breakpoint is not "
8892                         "actually inserted"));
8893
8894       if (b->type == bp_hardware_watchpoint)
8895         loc_first_p = &wp_loc_first;
8896       else if (b->type == bp_read_watchpoint)
8897         loc_first_p = &rwp_loc_first;
8898       else if (b->type == bp_access_watchpoint)
8899         loc_first_p = &awp_loc_first;
8900       else
8901         loc_first_p = &bp_loc_first;
8902
8903       if (*loc_first_p == NULL
8904           || (overlay_debugging && loc->section != (*loc_first_p)->section)
8905           || !breakpoint_locations_match (loc, *loc_first_p))
8906         {
8907           *loc_first_p = loc;
8908           loc->duplicate = 0;
8909           continue;
8910         }
8911
8912       loc->duplicate = 1;
8913
8914       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
8915           && b->enable_state != bp_permanent)
8916         internal_error (__FILE__, __LINE__,
8917                         _("another breakpoint was inserted on top of "
8918                         "a permanent breakpoint"));
8919     }
8920
8921   if (breakpoints_always_inserted_mode () && should_insert
8922       && (have_live_inferiors ()
8923           || (gdbarch_has_global_breakpoints (target_gdbarch))))
8924     insert_breakpoint_locations ();
8925
8926   do_cleanups (cleanups);
8927 }
8928
8929 void
8930 breakpoint_retire_moribund (void)
8931 {
8932   struct bp_location *loc;
8933   int ix;
8934
8935   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
8936     if (--(loc->events_till_retirement) == 0)
8937       {
8938         free_bp_location (loc);
8939         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
8940         --ix;
8941       }
8942 }
8943
8944 static void
8945 update_global_location_list_nothrow (int inserting)
8946 {
8947   struct gdb_exception e;
8948   TRY_CATCH (e, RETURN_MASK_ERROR)
8949     update_global_location_list (inserting);
8950 }
8951
8952 /* Clear BPT from a BPS.  */
8953 static void
8954 bpstat_remove_breakpoint (bpstat bps, struct breakpoint *bpt)
8955 {
8956   bpstat bs;
8957   for (bs = bps; bs; bs = bs->next)
8958     if (bs->breakpoint_at && bs->breakpoint_at->owner == bpt)
8959       {
8960         bs->breakpoint_at = NULL;
8961         bs->old_val = NULL;
8962         /* bs->commands will be freed later.  */
8963       }
8964 }
8965
8966 /* Callback for iterate_over_threads.  */
8967 static int
8968 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
8969 {
8970   struct breakpoint *bpt = data;
8971   bpstat_remove_breakpoint (th->stop_bpstat, bpt);
8972   return 0;
8973 }
8974
8975 /* Delete a breakpoint and clean up all traces of it in the data
8976    structures. */
8977
8978 void
8979 delete_breakpoint (struct breakpoint *bpt)
8980 {
8981   struct breakpoint *b;
8982   struct bp_location *loc, *next;
8983
8984   gdb_assert (bpt != NULL);
8985
8986   /* Has this bp already been deleted?  This can happen because multiple
8987      lists can hold pointers to bp's.  bpstat lists are especial culprits.
8988
8989      One example of this happening is a watchpoint's scope bp.  When the
8990      scope bp triggers, we notice that the watchpoint is out of scope, and
8991      delete it.  We also delete its scope bp.  But the scope bp is marked
8992      "auto-deleting", and is already on a bpstat.  That bpstat is then
8993      checked for auto-deleting bp's, which are deleted.
8994
8995      A real solution to this problem might involve reference counts in bp's,
8996      and/or giving them pointers back to their referencing bpstat's, and
8997      teaching delete_breakpoint to only free a bp's storage when no more
8998      references were extent.  A cheaper bandaid was chosen.  */
8999   if (bpt->type == bp_none)
9000     return;
9001
9002   /* At least avoid this stale reference until the reference counting of
9003      breakpoints gets resolved.  */
9004   if (bpt->related_breakpoint != NULL)
9005     {
9006       gdb_assert (bpt->related_breakpoint->related_breakpoint == bpt);
9007       bpt->related_breakpoint->disposition = disp_del_at_next_stop;
9008       bpt->related_breakpoint->related_breakpoint = NULL;
9009       bpt->related_breakpoint = NULL;
9010     }
9011
9012   observer_notify_breakpoint_deleted (bpt->number);
9013
9014   if (breakpoint_chain == bpt)
9015     breakpoint_chain = bpt->next;
9016
9017   ALL_BREAKPOINTS (b)
9018     if (b->next == bpt)
9019     {
9020       b->next = bpt->next;
9021       break;
9022     }
9023
9024   free_command_lines (&bpt->commands);
9025   xfree (bpt->cond_string);
9026   xfree (bpt->cond_exp);
9027   xfree (bpt->addr_string);
9028   xfree (bpt->exp);
9029   xfree (bpt->exp_string);
9030   value_free (bpt->val);
9031   xfree (bpt->source_file);
9032   xfree (bpt->exec_pathname);
9033   clean_up_filters (&bpt->syscalls_to_be_caught);
9034
9035   /* Be sure no bpstat's are pointing at it after it's been freed.  */
9036   /* FIXME, how can we find all bpstat's?
9037      We just check stop_bpstat for now.  Note that we cannot just
9038      remove bpstats pointing at bpt from the stop_bpstat list
9039      entirely, as breakpoint commands are associated with the bpstat;
9040      if we remove it here, then the later call to
9041          bpstat_do_actions (&stop_bpstat);
9042      in event-top.c won't do anything, and temporary breakpoints
9043      with commands won't work.  */
9044
9045   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
9046
9047   /* Now that breakpoint is removed from breakpoint
9048      list, update the global location list.  This
9049      will remove locations that used to belong to
9050      this breakpoint.  Do this before freeing
9051      the breakpoint itself, since remove_breakpoint
9052      looks at location's owner.  It might be better
9053      design to have location completely self-contained,
9054      but it's not the case now.  */
9055   update_global_location_list (0);
9056
9057
9058   /* On the chance that someone will soon try again to delete this same
9059      bp, we mark it as deleted before freeing its storage. */
9060   bpt->type = bp_none;
9061
9062   xfree (bpt);
9063 }
9064
9065 static void
9066 do_delete_breakpoint_cleanup (void *b)
9067 {
9068   delete_breakpoint (b);
9069 }
9070
9071 struct cleanup *
9072 make_cleanup_delete_breakpoint (struct breakpoint *b)
9073 {
9074   return make_cleanup (do_delete_breakpoint_cleanup, b);
9075 }
9076
9077 void
9078 delete_command (char *arg, int from_tty)
9079 {
9080   struct breakpoint *b, *temp;
9081
9082   dont_repeat ();
9083
9084   if (arg == 0)
9085     {
9086       int breaks_to_delete = 0;
9087
9088       /* Delete all breakpoints if no argument.
9089          Do not delete internal or call-dummy breakpoints, these
9090          have to be deleted with an explicit breakpoint number argument.  */
9091       ALL_BREAKPOINTS (b)
9092       {
9093         if (b->type != bp_call_dummy
9094             && b->type != bp_shlib_event
9095             && b->type != bp_jit_event
9096             && b->type != bp_thread_event
9097             && b->type != bp_overlay_event
9098             && b->type != bp_longjmp_master
9099             && b->number >= 0)
9100           {
9101             breaks_to_delete = 1;
9102             break;
9103           }
9104       }
9105
9106       /* Ask user only if there are some breakpoints to delete.  */
9107       if (!from_tty
9108           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
9109         {
9110           ALL_BREAKPOINTS_SAFE (b, temp)
9111           {
9112             if (b->type != bp_call_dummy
9113                 && b->type != bp_shlib_event
9114                 && b->type != bp_thread_event
9115                 && b->type != bp_jit_event
9116                 && b->type != bp_overlay_event
9117                 && b->type != bp_longjmp_master
9118                 && b->number >= 0)
9119               delete_breakpoint (b);
9120           }
9121         }
9122     }
9123   else
9124     map_breakpoint_numbers (arg, delete_breakpoint);
9125 }
9126
9127 static int
9128 all_locations_are_pending (struct bp_location *loc)
9129 {
9130   for (; loc; loc = loc->next)
9131     if (!loc->shlib_disabled)
9132       return 0;
9133   return 1;
9134 }
9135
9136 /* Subroutine of update_breakpoint_locations to simplify it.
9137    Return non-zero if multiple fns in list LOC have the same name.
9138    Null names are ignored.  */
9139
9140 static int
9141 ambiguous_names_p (struct bp_location *loc)
9142 {
9143   struct bp_location *l;
9144   htab_t htab = htab_create_alloc (13, htab_hash_string,
9145                                    (int (*) (const void *, const void *)) streq,
9146                                    NULL, xcalloc, xfree);
9147
9148   for (l = loc; l != NULL; l = l->next)
9149     {
9150       const char **slot;
9151       const char *name = l->function_name;
9152
9153       /* Allow for some names to be NULL, ignore them.  */
9154       if (name == NULL)
9155         continue;
9156
9157       slot = (const char **) htab_find_slot (htab, (const void *) name,
9158                                              INSERT);
9159       /* NOTE: We can assume slot != NULL here because xcalloc never returns
9160          NULL.  */
9161       if (*slot != NULL)
9162         {
9163           htab_delete (htab);
9164           return 1;
9165         }
9166       *slot = name;
9167     }
9168
9169   htab_delete (htab);
9170   return 0;
9171 }
9172
9173 static void
9174 update_breakpoint_locations (struct breakpoint *b,
9175                              struct symtabs_and_lines sals)
9176 {
9177   int i;
9178   char *s;
9179   struct bp_location *existing_locations = b->loc;
9180
9181   /* If there's no new locations, and all existing locations
9182      are pending, don't do anything.  This optimizes
9183      the common case where all locations are in the same
9184      shared library, that was unloaded. We'd like to
9185      retain the location, so that when the library
9186      is loaded again, we don't loose the enabled/disabled
9187      status of the individual locations.  */
9188   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
9189     return;
9190
9191   b->loc = NULL;
9192
9193   for (i = 0; i < sals.nelts; ++i)
9194     {
9195       struct bp_location *new_loc = 
9196         add_location_to_breakpoint (b, &(sals.sals[i]));
9197
9198       /* Reparse conditions, they might contain references to the
9199          old symtab.  */
9200       if (b->cond_string != NULL)
9201         {
9202           struct gdb_exception e;
9203
9204           s = b->cond_string;
9205           TRY_CATCH (e, RETURN_MASK_ERROR)
9206             {
9207               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
9208                                            0);
9209             }
9210           if (e.reason < 0)
9211             {
9212               warning (_("failed to reevaluate condition for breakpoint %d: %s"), 
9213                        b->number, e.message);
9214               new_loc->enabled = 0;
9215             }
9216         }
9217
9218       if (b->source_file != NULL)
9219         xfree (b->source_file);
9220       if (sals.sals[i].symtab == NULL)
9221         b->source_file = NULL;
9222       else
9223         b->source_file = xstrdup (sals.sals[i].symtab->filename);
9224
9225       if (b->line_number == 0)
9226         b->line_number = sals.sals[i].line;
9227     }
9228
9229   /* Update locations of permanent breakpoints.  */
9230   if (b->enable_state == bp_permanent)
9231     make_breakpoint_permanent (b);
9232
9233   /* If possible, carry over 'disable' status from existing breakpoints.  */
9234   {
9235     struct bp_location *e = existing_locations;
9236     /* If there are multiple breakpoints with the same function name,
9237        e.g. for inline functions, comparing function names won't work.
9238        Instead compare pc addresses; this is just a heuristic as things
9239        may have moved, but in practice it gives the correct answer
9240        often enough until a better solution is found.  */
9241     int have_ambiguous_names = ambiguous_names_p (b->loc);
9242
9243     for (; e; e = e->next)
9244       {
9245         if (!e->enabled && e->function_name)
9246           {
9247             struct bp_location *l = b->loc;
9248             if (have_ambiguous_names)
9249               {
9250                 for (; l; l = l->next)
9251                   if (breakpoint_address_match (e->pspace->aspace, e->address,
9252                                                 l->pspace->aspace, l->address))
9253                     {
9254                       l->enabled = 0;
9255                       break;
9256                     }
9257               }
9258             else
9259               {
9260                 for (; l; l = l->next)
9261                   if (l->function_name
9262                       && strcmp (e->function_name, l->function_name) == 0)
9263                     {
9264                       l->enabled = 0;
9265                       break;
9266                     }
9267               }
9268           }
9269       }
9270   }
9271
9272   update_global_location_list (1);
9273 }
9274
9275
9276 /* Reset a breakpoint given it's struct breakpoint * BINT.
9277    The value we return ends up being the return value from catch_errors.
9278    Unused in this case.  */
9279
9280 static int
9281 breakpoint_re_set_one (void *bint)
9282 {
9283   /* get past catch_errs */
9284   struct breakpoint *b = (struct breakpoint *) bint;
9285   struct value *mark;
9286   int i;
9287   int not_found = 0;
9288   int *not_found_ptr = &not_found;
9289   struct symtabs_and_lines sals = {0};
9290   struct symtabs_and_lines expanded = {0};
9291   char *s;
9292   enum enable_state save_enable;
9293   struct gdb_exception e;
9294   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
9295
9296   switch (b->type)
9297     {
9298     case bp_none:
9299       warning (_("attempted to reset apparently deleted breakpoint #%d?"),
9300                b->number);
9301       return 0;
9302     case bp_breakpoint:
9303     case bp_hardware_breakpoint:
9304     case bp_tracepoint:
9305     case bp_fast_tracepoint:
9306       /* Do not attempt to re-set breakpoints disabled during startup.  */
9307       if (b->enable_state == bp_startup_disabled)
9308         return 0;
9309
9310       if (b->addr_string == NULL)
9311         {
9312           /* Anything without a string can't be re-set. */
9313           delete_breakpoint (b);
9314           return 0;
9315         }
9316
9317       set_language (b->language);
9318       input_radix = b->input_radix;
9319       s = b->addr_string;
9320
9321       save_current_space_and_thread ();
9322       switch_to_program_space_and_thread (b->pspace);
9323
9324       TRY_CATCH (e, RETURN_MASK_ERROR)
9325         {
9326           sals = decode_line_1 (&s, 1, (struct symtab *) NULL, 0, (char ***) NULL,
9327                                 not_found_ptr);
9328         }
9329       if (e.reason < 0)
9330         {
9331           int not_found_and_ok = 0;
9332           /* For pending breakpoints, it's expected that parsing
9333              will fail until the right shared library is loaded.
9334              User has already told to create pending breakpoints and
9335              don't need extra messages.  If breakpoint is in bp_shlib_disabled
9336              state, then user already saw the message about that breakpoint
9337              being disabled, and don't want to see more errors.  */
9338           if (not_found 
9339               && (b->condition_not_parsed 
9340                   || (b->loc && b->loc->shlib_disabled)
9341                   || b->enable_state == bp_disabled))
9342             not_found_and_ok = 1;
9343
9344           if (!not_found_and_ok)
9345             {
9346               /* We surely don't want to warn about the same breakpoint
9347                  10 times.  One solution, implemented here, is disable
9348                  the breakpoint on error.  Another solution would be to
9349                  have separate 'warning emitted' flag.  Since this
9350                  happens only when a binary has changed, I don't know
9351                  which approach is better.  */
9352               b->enable_state = bp_disabled;
9353               throw_exception (e);
9354             }
9355         }
9356
9357       if (!not_found)
9358         {
9359           gdb_assert (sals.nelts == 1);
9360
9361           resolve_sal_pc (&sals.sals[0]);
9362           if (b->condition_not_parsed && s && s[0])
9363             {
9364               char *cond_string = 0;
9365               int thread = -1;
9366               int task = 0;
9367
9368               find_condition_and_thread (s, sals.sals[0].pc,
9369                                          &cond_string, &thread, &task);
9370               if (cond_string)
9371                 b->cond_string = cond_string;
9372               b->thread = thread;
9373               b->task = task;
9374               b->condition_not_parsed = 0;
9375             }
9376
9377           expanded = expand_line_sal_maybe (sals.sals[0]);
9378         }
9379
9380       make_cleanup (xfree, sals.sals);
9381       update_breakpoint_locations (b, expanded);
9382       break;
9383
9384     case bp_watchpoint:
9385     case bp_hardware_watchpoint:
9386     case bp_read_watchpoint:
9387     case bp_access_watchpoint:
9388       /* Watchpoint can be either on expression using entirely global variables,
9389          or it can be on local variables.
9390
9391          Watchpoints of the first kind are never auto-deleted, and even persist
9392          across program restarts. Since they can use variables from shared 
9393          libraries, we need to reparse expression as libraries are loaded
9394          and unloaded.
9395
9396          Watchpoints on local variables can also change meaning as result
9397          of solib event. For example, if a watchpoint uses both a local and
9398          a global variables in expression, it's a local watchpoint, but
9399          unloading of a shared library will make the expression invalid.
9400          This is not a very common use case, but we still re-evaluate
9401          expression, to avoid surprises to the user. 
9402
9403          Note that for local watchpoints, we re-evaluate it only if
9404          watchpoints frame id is still valid.  If it's not, it means
9405          the watchpoint is out of scope and will be deleted soon. In fact,
9406          I'm not sure we'll ever be called in this case.  
9407
9408          If a local watchpoint's frame id is still valid, then
9409          b->exp_valid_block is likewise valid, and we can safely use it.  
9410          
9411          Don't do anything about disabled watchpoints, since they will
9412          be reevaluated again when enabled.  */
9413       update_watchpoint (b, 1 /* reparse */);
9414       break;
9415       /* We needn't really do anything to reset these, since the mask
9416          that requests them is unaffected by e.g., new libraries being
9417          loaded. */
9418     case bp_catchpoint:
9419       break;
9420
9421     default:
9422       printf_filtered (_("Deleting unknown breakpoint type %d\n"), b->type);
9423       /* fall through */
9424       /* Delete overlay event and longjmp master breakpoints; they will be
9425          reset later by breakpoint_re_set.  */
9426     case bp_overlay_event:
9427     case bp_longjmp_master:
9428       delete_breakpoint (b);
9429       break;
9430
9431       /* This breakpoint is special, it's set up when the inferior
9432          starts and we really don't want to touch it.  */
9433     case bp_shlib_event:
9434
9435       /* Like bp_shlib_event, this breakpoint type is special.
9436          Once it is set up, we do not want to touch it.  */
9437     case bp_thread_event:
9438
9439       /* Keep temporary breakpoints, which can be encountered when we step
9440          over a dlopen call and SOLIB_ADD is resetting the breakpoints.
9441          Otherwise these should have been blown away via the cleanup chain
9442          or by breakpoint_init_inferior when we rerun the executable.  */
9443     case bp_until:
9444     case bp_finish:
9445     case bp_watchpoint_scope:
9446     case bp_call_dummy:
9447     case bp_step_resume:
9448     case bp_longjmp:
9449     case bp_longjmp_resume:
9450     case bp_jit_event:
9451       break;
9452     }
9453
9454   do_cleanups (cleanups);
9455   return 0;
9456 }
9457
9458 /* Re-set all breakpoints after symbols have been re-loaded.  */
9459 void
9460 breakpoint_re_set (void)
9461 {
9462   struct breakpoint *b, *temp;
9463   enum language save_language;
9464   int save_input_radix;
9465   struct cleanup *old_chain;
9466
9467   save_language = current_language->la_language;
9468   save_input_radix = input_radix;
9469   old_chain = save_current_program_space ();
9470
9471   ALL_BREAKPOINTS_SAFE (b, temp)
9472   {
9473     /* Format possible error msg */
9474     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
9475                                 b->number);
9476     struct cleanup *cleanups = make_cleanup (xfree, message);
9477     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
9478     do_cleanups (cleanups);
9479   }
9480   set_language (save_language);
9481   input_radix = save_input_radix;
9482
9483   jit_breakpoint_re_set ();
9484
9485   do_cleanups (old_chain);
9486
9487   create_overlay_event_breakpoint ("_ovly_debug_event");
9488   create_longjmp_master_breakpoint ("longjmp");
9489   create_longjmp_master_breakpoint ("_longjmp");
9490   create_longjmp_master_breakpoint ("siglongjmp");
9491   create_longjmp_master_breakpoint ("_siglongjmp");
9492 }
9493 \f
9494 /* Reset the thread number of this breakpoint:
9495
9496    - If the breakpoint is for all threads, leave it as-is.
9497    - Else, reset it to the current thread for inferior_ptid. */
9498 void
9499 breakpoint_re_set_thread (struct breakpoint *b)
9500 {
9501   if (b->thread != -1)
9502     {
9503       if (in_thread_list (inferior_ptid))
9504         b->thread = pid_to_thread_id (inferior_ptid);
9505
9506       /* We're being called after following a fork.  The new fork is
9507          selected as current, and unless this was a vfork will have a
9508          different program space from the original thread.  Reset that
9509          as well.  */
9510       b->loc->pspace = current_program_space;
9511     }
9512 }
9513
9514 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
9515    If from_tty is nonzero, it prints a message to that effect,
9516    which ends with a period (no newline).  */
9517
9518 void
9519 set_ignore_count (int bptnum, int count, int from_tty)
9520 {
9521   struct breakpoint *b;
9522
9523   if (count < 0)
9524     count = 0;
9525
9526   ALL_BREAKPOINTS (b)
9527     if (b->number == bptnum)
9528     {
9529       b->ignore_count = count;
9530       if (from_tty)
9531         {
9532           if (count == 0)
9533             printf_filtered (_("Will stop next time breakpoint %d is reached."),
9534                              bptnum);
9535           else if (count == 1)
9536             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
9537                              bptnum);
9538           else
9539             printf_filtered (_("Will ignore next %d crossings of breakpoint %d."),
9540                              count, bptnum);
9541         }
9542       breakpoints_changed ();
9543       observer_notify_breakpoint_modified (b->number);
9544       return;
9545     }
9546
9547   error (_("No breakpoint number %d."), bptnum);
9548 }
9549
9550 void
9551 make_breakpoint_silent (struct breakpoint *b)
9552 {
9553   /* Silence the breakpoint.  */
9554   b->silent = 1;
9555 }
9556
9557 /* Command to set ignore-count of breakpoint N to COUNT.  */
9558
9559 static void
9560 ignore_command (char *args, int from_tty)
9561 {
9562   char *p = args;
9563   int num;
9564
9565   if (p == 0)
9566     error_no_arg (_("a breakpoint number"));
9567
9568   num = get_number (&p);
9569   if (num == 0)
9570     error (_("bad breakpoint number: '%s'"), args);
9571   if (*p == 0)
9572     error (_("Second argument (specified ignore-count) is missing."));
9573
9574   set_ignore_count (num,
9575                     longest_to_int (value_as_long (parse_and_eval (p))),
9576                     from_tty);
9577   if (from_tty)
9578     printf_filtered ("\n");
9579 }
9580 \f
9581 /* Call FUNCTION on each of the breakpoints
9582    whose numbers are given in ARGS.  */
9583
9584 static void
9585 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *))
9586 {
9587   char *p = args;
9588   char *p1;
9589   int num;
9590   struct breakpoint *b, *tmp;
9591   int match;
9592
9593   if (p == 0)
9594     error_no_arg (_("one or more breakpoint numbers"));
9595
9596   while (*p)
9597     {
9598       match = 0;
9599       p1 = p;
9600
9601       num = get_number_or_range (&p1);
9602       if (num == 0)
9603         {
9604           warning (_("bad breakpoint number at or near '%s'"), p);
9605         }
9606       else
9607         {
9608           ALL_BREAKPOINTS_SAFE (b, tmp)
9609             if (b->number == num)
9610               {
9611                 struct breakpoint *related_breakpoint = b->related_breakpoint;
9612                 match = 1;
9613                 function (b);
9614                 if (related_breakpoint)
9615                   function (related_breakpoint);
9616                 break;
9617               }
9618           if (match == 0)
9619             printf_unfiltered (_("No breakpoint number %d.\n"), num);
9620         }
9621       p = p1;
9622     }
9623 }
9624
9625 static struct bp_location *
9626 find_location_by_number (char *number)
9627 {
9628   char *dot = strchr (number, '.');
9629   char *p1;
9630   int bp_num;
9631   int loc_num;
9632   struct breakpoint *b;
9633   struct bp_location *loc;  
9634
9635   *dot = '\0';
9636
9637   p1 = number;
9638   bp_num = get_number_or_range (&p1);
9639   if (bp_num == 0)
9640     error (_("Bad breakpoint number '%s'"), number);
9641
9642   ALL_BREAKPOINTS (b)
9643     if (b->number == bp_num)
9644       {
9645         break;
9646       }
9647
9648   if (!b || b->number != bp_num)
9649     error (_("Bad breakpoint number '%s'"), number);
9650   
9651   p1 = dot+1;
9652   loc_num = get_number_or_range (&p1);
9653   if (loc_num == 0)
9654     error (_("Bad breakpoint location number '%s'"), number);
9655
9656   --loc_num;
9657   loc = b->loc;
9658   for (;loc_num && loc; --loc_num, loc = loc->next)
9659     ;
9660   if (!loc)
9661     error (_("Bad breakpoint location number '%s'"), dot+1);
9662     
9663   return loc;  
9664 }
9665
9666
9667 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
9668    If from_tty is nonzero, it prints a message to that effect,
9669    which ends with a period (no newline).  */
9670
9671 void
9672 disable_breakpoint (struct breakpoint *bpt)
9673 {
9674   /* Never disable a watchpoint scope breakpoint; we want to
9675      hit them when we leave scope so we can delete both the
9676      watchpoint and its scope breakpoint at that time.  */
9677   if (bpt->type == bp_watchpoint_scope)
9678     return;
9679
9680   /* You can't disable permanent breakpoints.  */
9681   if (bpt->enable_state == bp_permanent)
9682     return;
9683
9684   bpt->enable_state = bp_disabled;
9685
9686   update_global_location_list (0);
9687
9688   observer_notify_breakpoint_modified (bpt->number);
9689 }
9690
9691 static void
9692 disable_command (char *args, int from_tty)
9693 {
9694   struct breakpoint *bpt;
9695   if (args == 0)
9696     ALL_BREAKPOINTS (bpt)
9697       switch (bpt->type)
9698       {
9699       case bp_none:
9700         warning (_("attempted to disable apparently deleted breakpoint #%d?"),
9701                  bpt->number);
9702         continue;
9703       case bp_breakpoint:
9704       case bp_tracepoint:
9705       case bp_fast_tracepoint:
9706       case bp_catchpoint:
9707       case bp_hardware_breakpoint:
9708       case bp_watchpoint:
9709       case bp_hardware_watchpoint:
9710       case bp_read_watchpoint:
9711       case bp_access_watchpoint:
9712         disable_breakpoint (bpt);
9713       default:
9714         continue;
9715       }
9716   else if (strchr (args, '.'))
9717     {
9718       struct bp_location *loc = find_location_by_number (args);
9719       if (loc)
9720         loc->enabled = 0;
9721       update_global_location_list (0);
9722     }
9723   else
9724     map_breakpoint_numbers (args, disable_breakpoint);
9725 }
9726
9727 static void
9728 do_enable_breakpoint (struct breakpoint *bpt, enum bpdisp disposition)
9729 {
9730   int target_resources_ok, other_type_used;
9731   struct value *mark;
9732
9733   if (bpt->type == bp_hardware_breakpoint)
9734     {
9735       int i;
9736       i = hw_breakpoint_used_count ();
9737       target_resources_ok = 
9738         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
9739                                             i + 1, 0);
9740       if (target_resources_ok == 0)
9741         error (_("No hardware breakpoint support in the target."));
9742       else if (target_resources_ok < 0)
9743         error (_("Hardware breakpoints used exceeds limit."));
9744     }
9745
9746   if (bpt->type == bp_watchpoint
9747       || bpt->type == bp_hardware_watchpoint
9748       || bpt->type == bp_read_watchpoint
9749       || bpt->type == bp_access_watchpoint)
9750     {
9751       struct gdb_exception e;
9752
9753       TRY_CATCH (e, RETURN_MASK_ALL)
9754         {
9755           update_watchpoint (bpt, 1 /* reparse */);
9756         }
9757       if (e.reason < 0)
9758         {
9759           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
9760                              bpt->number);
9761           return;
9762         }
9763     }
9764
9765   if (bpt->enable_state != bp_permanent)
9766     bpt->enable_state = bp_enabled;
9767   bpt->disposition = disposition;
9768   update_global_location_list (1);
9769   breakpoints_changed ();
9770   
9771   observer_notify_breakpoint_modified (bpt->number);
9772 }
9773
9774
9775 void
9776 enable_breakpoint (struct breakpoint *bpt)
9777 {
9778   do_enable_breakpoint (bpt, bpt->disposition);
9779 }
9780
9781 /* The enable command enables the specified breakpoints (or all defined
9782    breakpoints) so they once again become (or continue to be) effective
9783    in stopping the inferior.  */
9784
9785 static void
9786 enable_command (char *args, int from_tty)
9787 {
9788   struct breakpoint *bpt;
9789   if (args == 0)
9790     ALL_BREAKPOINTS (bpt)
9791       switch (bpt->type)
9792       {
9793       case bp_none:
9794         warning (_("attempted to enable apparently deleted breakpoint #%d?"),
9795                  bpt->number);
9796         continue;
9797       case bp_breakpoint:
9798       case bp_tracepoint:
9799       case bp_fast_tracepoint:
9800       case bp_catchpoint:
9801       case bp_hardware_breakpoint:
9802       case bp_watchpoint:
9803       case bp_hardware_watchpoint:
9804       case bp_read_watchpoint:
9805       case bp_access_watchpoint:
9806         enable_breakpoint (bpt);
9807       default:
9808         continue;
9809       }
9810   else if (strchr (args, '.'))
9811     {
9812       struct bp_location *loc = find_location_by_number (args);
9813       if (loc)
9814         loc->enabled = 1;
9815       update_global_location_list (1);
9816     }
9817   else
9818     map_breakpoint_numbers (args, enable_breakpoint);
9819 }
9820
9821 static void
9822 enable_once_breakpoint (struct breakpoint *bpt)
9823 {
9824   do_enable_breakpoint (bpt, disp_disable);
9825 }
9826
9827 static void
9828 enable_once_command (char *args, int from_tty)
9829 {
9830   map_breakpoint_numbers (args, enable_once_breakpoint);
9831 }
9832
9833 static void
9834 enable_delete_breakpoint (struct breakpoint *bpt)
9835 {
9836   do_enable_breakpoint (bpt, disp_del);
9837 }
9838
9839 static void
9840 enable_delete_command (char *args, int from_tty)
9841 {
9842   map_breakpoint_numbers (args, enable_delete_breakpoint);
9843 }
9844 \f
9845 static void
9846 set_breakpoint_cmd (char *args, int from_tty)
9847 {
9848 }
9849
9850 static void
9851 show_breakpoint_cmd (char *args, int from_tty)
9852 {
9853 }
9854
9855 /* Invalidate last known value of any hardware watchpoint if
9856    the memory which that value represents has been written to by
9857    GDB itself.  */
9858
9859 static void
9860 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
9861                                       const bfd_byte *data)
9862 {
9863   struct breakpoint *bp;
9864
9865   ALL_BREAKPOINTS (bp)
9866     if (bp->enable_state == bp_enabled
9867         && bp->type == bp_hardware_watchpoint
9868         && bp->val_valid && bp->val)
9869       {
9870         struct bp_location *loc;
9871
9872         for (loc = bp->loc; loc != NULL; loc = loc->next)
9873           if (loc->loc_type == bp_loc_hardware_watchpoint
9874               && loc->address + loc->length > addr
9875               && addr + len > loc->address)
9876             {
9877               value_free (bp->val);
9878               bp->val = NULL;
9879               bp->val_valid = 0;
9880             }
9881       }
9882 }
9883
9884 /* Use default_breakpoint_'s, or nothing if they aren't valid.  */
9885
9886 struct symtabs_and_lines
9887 decode_line_spec_1 (char *string, int funfirstline)
9888 {
9889   struct symtabs_and_lines sals;
9890   if (string == 0)
9891     error (_("Empty line specification."));
9892   if (default_breakpoint_valid)
9893     sals = decode_line_1 (&string, funfirstline,
9894                           default_breakpoint_symtab,
9895                           default_breakpoint_line,
9896                           (char ***) NULL, NULL);
9897   else
9898     sals = decode_line_1 (&string, funfirstline,
9899                           (struct symtab *) NULL, 0, (char ***) NULL, NULL);
9900   if (*string)
9901     error (_("Junk at end of line specification: %s"), string);
9902   return sals;
9903 }
9904
9905 /* Create and insert a raw software breakpoint at PC.  Return an
9906    identifier, which should be used to remove the breakpoint later.
9907    In general, places which call this should be using something on the
9908    breakpoint chain instead; this function should be eliminated
9909    someday.  */
9910
9911 void *
9912 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
9913                                   struct address_space *aspace, CORE_ADDR pc)
9914 {
9915   struct bp_target_info *bp_tgt;
9916
9917   bp_tgt = XZALLOC (struct bp_target_info);
9918
9919   bp_tgt->placed_address_space = aspace;
9920   bp_tgt->placed_address = pc;
9921
9922   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
9923     {
9924       /* Could not insert the breakpoint.  */
9925       xfree (bp_tgt);
9926       return NULL;
9927     }
9928
9929   return bp_tgt;
9930 }
9931
9932 /* Remove a breakpoint BP inserted by deprecated_insert_raw_breakpoint.  */
9933
9934 int
9935 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
9936 {
9937   struct bp_target_info *bp_tgt = bp;
9938   int ret;
9939
9940   ret = target_remove_breakpoint (gdbarch, bp_tgt);
9941   xfree (bp_tgt);
9942
9943   return ret;
9944 }
9945
9946 /* One (or perhaps two) breakpoints used for software single stepping.  */
9947
9948 static void *single_step_breakpoints[2];
9949 static struct gdbarch *single_step_gdbarch[2];
9950
9951 /* Create and insert a breakpoint for software single step.  */
9952
9953 void
9954 insert_single_step_breakpoint (struct gdbarch *gdbarch,
9955                                struct address_space *aspace, CORE_ADDR next_pc)
9956 {
9957   void **bpt_p;
9958
9959   if (single_step_breakpoints[0] == NULL)
9960     {
9961       bpt_p = &single_step_breakpoints[0];
9962       single_step_gdbarch[0] = gdbarch;
9963     }
9964   else
9965     {
9966       gdb_assert (single_step_breakpoints[1] == NULL);
9967       bpt_p = &single_step_breakpoints[1];
9968       single_step_gdbarch[1] = gdbarch;
9969     }
9970
9971   /* NOTE drow/2006-04-11: A future improvement to this function would be
9972      to only create the breakpoints once, and actually put them on the
9973      breakpoint chain.  That would let us use set_raw_breakpoint.  We could
9974      adjust the addresses each time they were needed.  Doing this requires
9975      corresponding changes elsewhere where single step breakpoints are
9976      handled, however.  So, for now, we use this.  */
9977
9978   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
9979   if (*bpt_p == NULL)
9980     error (_("Could not insert single-step breakpoint at %s"),
9981              paddress (gdbarch, next_pc));
9982 }
9983
9984 /* Remove and delete any breakpoints used for software single step.  */
9985
9986 void
9987 remove_single_step_breakpoints (void)
9988 {
9989   gdb_assert (single_step_breakpoints[0] != NULL);
9990
9991   /* See insert_single_step_breakpoint for more about this deprecated
9992      call.  */
9993   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
9994                                     single_step_breakpoints[0]);
9995   single_step_gdbarch[0] = NULL;
9996   single_step_breakpoints[0] = NULL;
9997
9998   if (single_step_breakpoints[1] != NULL)
9999     {
10000       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
10001                                         single_step_breakpoints[1]);
10002       single_step_gdbarch[1] = NULL;
10003       single_step_breakpoints[1] = NULL;
10004     }
10005 }
10006
10007 /* Check whether a software single-step breakpoint is inserted at PC.  */
10008
10009 static int
10010 single_step_breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
10011 {
10012   int i;
10013
10014   for (i = 0; i < 2; i++)
10015     {
10016       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
10017       if (bp_tgt
10018           && breakpoint_address_match (bp_tgt->placed_address_space,
10019                                        bp_tgt->placed_address,
10020                                        aspace, pc))
10021         return 1;
10022     }
10023
10024   return 0;
10025 }
10026
10027 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
10028    non-zero otherwise.  */
10029 static int
10030 is_syscall_catchpoint_enabled (struct breakpoint *bp)
10031 {
10032   if (syscall_catchpoint_p (bp)
10033       && bp->enable_state != bp_disabled
10034       && bp->enable_state != bp_call_disabled)
10035     return 1;
10036   else
10037     return 0;
10038 }
10039
10040 int
10041 catch_syscall_enabled (void)
10042 {
10043   struct inferior *inf = current_inferior ();
10044
10045   return inf->total_syscalls_count != 0;
10046 }
10047
10048 int
10049 catching_syscall_number (int syscall_number)
10050 {
10051   struct breakpoint *bp;
10052
10053   ALL_BREAKPOINTS (bp)
10054     if (is_syscall_catchpoint_enabled (bp))
10055       {
10056         if (bp->syscalls_to_be_caught)
10057           {
10058             int i, iter;
10059             for (i = 0;
10060                  VEC_iterate (int, bp->syscalls_to_be_caught, i, iter);
10061                  i++)
10062               if (syscall_number == iter)
10063                 return 1;
10064           }
10065         else
10066           return 1;
10067       }
10068
10069   return 0;
10070 }
10071
10072 /* Complete syscall names.  Used by "catch syscall".  */
10073 static char **
10074 catch_syscall_completer (struct cmd_list_element *cmd,
10075                          char *text, char *word)
10076 {
10077   const char **list = get_syscall_names ();
10078   return (list == NULL) ? NULL : complete_on_enum (list, text, word);
10079 }
10080
10081 /* Tracepoint-specific operations.  */
10082
10083 /* Set tracepoint count to NUM.  */
10084 static void
10085 set_tracepoint_count (int num)
10086 {
10087   tracepoint_count = num;
10088   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
10089 }
10090
10091 void
10092 trace_command (char *arg, int from_tty)
10093 {
10094   if (create_breakpoint (get_current_arch (),
10095                          arg,
10096                          NULL, 0, 1 /* parse arg */,
10097                          0 /* tempflag */, 0 /* hardwareflag */,
10098                          1 /* traceflag */,
10099                          0 /* Ignore count */,
10100                          pending_break_support,
10101                          NULL,
10102                          from_tty,
10103                          1 /* enabled */))
10104     set_tracepoint_count (breakpoint_count);
10105 }
10106
10107 void
10108 ftrace_command (char *arg, int from_tty)
10109 {
10110   if (create_breakpoint (get_current_arch (),
10111                          arg,
10112                          NULL, 0, 1 /* parse arg */,
10113                          0 /* tempflag */, 1 /* hardwareflag */,
10114                          1 /* traceflag */,
10115                          0 /* Ignore count */,
10116                          pending_break_support,
10117                          NULL,
10118                          from_tty,
10119                          1 /* enabled */))
10120     set_tracepoint_count (breakpoint_count);
10121 }
10122
10123 /* Given information about a tracepoint as recorded on a target (which
10124    can be either a live system or a trace file), attempt to create an
10125    equivalent GDB tracepoint.  This is not a reliable process, since
10126    the target does not necessarily have all the information used when
10127    the tracepoint was originally defined.  */
10128   
10129 struct breakpoint *
10130 create_tracepoint_from_upload (struct uploaded_tp *utp)
10131 {
10132   char buf[100];
10133   struct breakpoint *tp;
10134
10135   /* In the absence of a source location, fall back to raw address.  */
10136   sprintf (buf, "*%s", paddress (get_current_arch(), utp->addr));
10137
10138   if (!create_breakpoint (get_current_arch (),
10139                           buf,
10140                           NULL, 0, 1 /* parse arg */,
10141                           0 /* tempflag */,
10142                           (utp->type == bp_fast_tracepoint) /* hardwareflag */,
10143                           1 /* traceflag */,
10144                           0 /* Ignore count */,
10145                           pending_break_support,
10146                           NULL,
10147                           0 /* from_tty */,
10148                           utp->enabled /* enabled */))
10149     return NULL;
10150
10151   set_tracepoint_count (breakpoint_count);
10152   
10153   tp = get_tracepoint (tracepoint_count);
10154   gdb_assert (tp != NULL);
10155
10156   if (utp->pass > 0)
10157     {
10158       sprintf (buf, "%d %d", utp->pass, tp->number);
10159
10160       trace_pass_command (buf, 0);
10161     }
10162
10163   if (utp->cond)
10164     {
10165       printf_filtered ("Want to restore a condition\n");
10166     }
10167
10168   if (utp->numactions > 0)
10169     {
10170       printf_filtered ("Want to restore action list\n");
10171     }
10172
10173   if (utp->num_step_actions > 0)
10174     {
10175       printf_filtered ("Want to restore action list\n");
10176     }
10177
10178   return tp;
10179   }
10180   
10181 /* Print information on tracepoint number TPNUM_EXP, or all if
10182    omitted.  */
10183
10184 static void
10185 tracepoints_info (char *tpnum_exp, int from_tty)
10186 {
10187   struct breakpoint *b;
10188   int tps_to_list = 0;
10189
10190   /* In the no-arguments case, say "No tracepoints" if none found.  */
10191   if (tpnum_exp == 0)
10192     {
10193       ALL_TRACEPOINTS (b)
10194       {
10195         if (b->number >= 0)
10196           {
10197             tps_to_list = 1;
10198             break;
10199           }
10200       }
10201       if (!tps_to_list)
10202         {
10203           ui_out_message (uiout, 0, "No tracepoints.\n");
10204           return;
10205         }
10206     }
10207
10208   /* Otherwise be the same as "info break".  */
10209   breakpoints_info (tpnum_exp, from_tty);
10210 }
10211
10212 /* The 'enable trace' command enables tracepoints.  
10213    Not supported by all targets.  */
10214 static void
10215 enable_trace_command (char *args, int from_tty)
10216 {
10217   enable_command (args, from_tty);
10218 }
10219
10220 /* The 'disable trace' command disables tracepoints.  
10221    Not supported by all targets.  */
10222 static void
10223 disable_trace_command (char *args, int from_tty)
10224 {
10225   disable_command (args, from_tty);
10226 }
10227
10228 /* Remove a tracepoint (or all if no argument) */
10229 static void
10230 delete_trace_command (char *arg, int from_tty)
10231 {
10232   struct breakpoint *b, *temp;
10233
10234   dont_repeat ();
10235
10236   if (arg == 0)
10237     {
10238       int breaks_to_delete = 0;
10239
10240       /* Delete all breakpoints if no argument.
10241          Do not delete internal or call-dummy breakpoints, these
10242          have to be deleted with an explicit breakpoint number argument.  */
10243       ALL_TRACEPOINTS (b)
10244       {
10245         if (b->number >= 0)
10246           {
10247             breaks_to_delete = 1;
10248             break;
10249           }
10250       }
10251
10252       /* Ask user only if there are some breakpoints to delete.  */
10253       if (!from_tty
10254           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
10255         {
10256           ALL_BREAKPOINTS_SAFE (b, temp)
10257           {
10258             if (tracepoint_type (b)
10259                 && b->number >= 0)
10260               delete_breakpoint (b);
10261           }
10262         }
10263     }
10264   else
10265     map_breakpoint_numbers (arg, delete_breakpoint);
10266 }
10267
10268 /* Set passcount for tracepoint.
10269
10270    First command argument is passcount, second is tracepoint number.
10271    If tracepoint number omitted, apply to most recently defined.
10272    Also accepts special argument "all".  */
10273
10274 static void
10275 trace_pass_command (char *args, int from_tty)
10276 {
10277   struct breakpoint *t1 = (struct breakpoint *) -1, *t2;
10278   unsigned int count;
10279   int all = 0;
10280
10281   if (args == 0 || *args == 0)
10282     error (_("passcount command requires an argument (count + optional TP num)"));
10283
10284   count = strtoul (args, &args, 10);    /* Count comes first, then TP num. */
10285
10286   while (*args && isspace ((int) *args))
10287     args++;
10288
10289   if (*args && strncasecmp (args, "all", 3) == 0)
10290     {
10291       args += 3;                        /* Skip special argument "all".  */
10292       all = 1;
10293       if (*args)
10294         error (_("Junk at end of arguments."));
10295     }
10296   else
10297     t1 = get_tracepoint_by_number (&args, 1, 1);
10298
10299   do
10300     {
10301       if (t1)
10302         {
10303           ALL_TRACEPOINTS (t2)
10304             if (t1 == (struct breakpoint *) -1 || t1 == t2)
10305               {
10306                 t2->pass_count = count;
10307                 observer_notify_tracepoint_modified (t2->number);
10308                 if (from_tty)
10309                   printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
10310                                    t2->number, count);
10311               }
10312           if (! all && *args)
10313             t1 = get_tracepoint_by_number (&args, 1, 0);
10314         }
10315     }
10316   while (*args);
10317 }
10318
10319 struct breakpoint *
10320 get_tracepoint (int num)
10321 {
10322   struct breakpoint *t;
10323
10324   ALL_TRACEPOINTS (t)
10325     if (t->number == num)
10326       return t;
10327
10328   return NULL;
10329 }
10330
10331 /* Find the tracepoint with the given target-side number (which may be
10332    different from the tracepoint number after disconnecting and
10333    reconnecting).  */
10334
10335 struct breakpoint *
10336 get_tracepoint_by_number_on_target (int num)
10337 {
10338   struct breakpoint *t;
10339
10340   ALL_TRACEPOINTS (t)
10341     if (t->number_on_target == num)
10342       return t;
10343
10344   return NULL;
10345 }
10346
10347 /* Utility: parse a tracepoint number and look it up in the list.
10348    If MULTI_P is true, there might be a range of tracepoints in ARG.
10349    if OPTIONAL_P is true, then if the argument is missing, the most
10350    recent tracepoint (tracepoint_count) is returned.  */
10351 struct breakpoint *
10352 get_tracepoint_by_number (char **arg, int multi_p, int optional_p)
10353 {
10354   extern int tracepoint_count;
10355   struct breakpoint *t;
10356   int tpnum;
10357   char *instring = arg == NULL ? NULL : *arg;
10358
10359   if (arg == NULL || *arg == NULL || ! **arg)
10360     {
10361       if (optional_p)
10362         tpnum = tracepoint_count;
10363       else
10364         error_no_arg (_("tracepoint number"));
10365     }
10366   else
10367     tpnum = multi_p ? get_number_or_range (arg) : get_number (arg);
10368
10369   if (tpnum <= 0)
10370     {
10371       if (instring && *instring)
10372         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
10373                          instring);
10374       else
10375         printf_filtered (_("Tracepoint argument missing and no previous tracepoint\n"));
10376       return NULL;
10377     }
10378
10379   ALL_TRACEPOINTS (t)
10380     if (t->number == tpnum)
10381     {
10382       return t;
10383     }
10384
10385   /* FIXME: if we are in the middle of a range we don't want to give
10386      a message.  The current interface to get_number_or_range doesn't
10387      allow us to discover this.  */
10388   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
10389   return NULL;
10390 }
10391
10392 /* save-tracepoints command */
10393 static void
10394 tracepoint_save_command (char *args, int from_tty)
10395 {
10396   struct breakpoint *tp;
10397   int any_tp = 0;
10398   struct command_line *line;
10399   char *pathname;
10400   char tmp[40];
10401   struct cleanup *cleanup;
10402   struct ui_file *fp;
10403
10404   if (args == 0 || *args == 0)
10405     error (_("Argument required (file name in which to save tracepoints)"));
10406
10407   /* See if we have anything to save.  */
10408   ALL_TRACEPOINTS (tp)
10409   {
10410     any_tp = 1;
10411     break;
10412   }
10413   if (!any_tp)
10414     {
10415       warning (_("save-tracepoints: no tracepoints to save."));
10416       return;
10417     }
10418
10419   pathname = tilde_expand (args);
10420   cleanup = make_cleanup (xfree, pathname);
10421   fp = gdb_fopen (pathname, "w");
10422   if (!fp)
10423     error (_("Unable to open file '%s' for saving tracepoints (%s)"),
10424            args, safe_strerror (errno));
10425   make_cleanup_ui_file_delete (fp);
10426   
10427   ALL_TRACEPOINTS (tp)
10428   {
10429     if (tp->addr_string)
10430       fprintf_unfiltered (fp, "trace %s\n", tp->addr_string);
10431     else
10432       {
10433         sprintf_vma (tmp, tp->loc->address);
10434         fprintf_unfiltered (fp, "trace *0x%s\n", tmp);
10435       }
10436
10437     if (tp->pass_count)
10438       fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
10439
10440     if (tp->commands)
10441       {
10442         volatile struct gdb_exception ex;       
10443
10444         fprintf_unfiltered (fp, "  actions\n");
10445         
10446         ui_out_redirect (uiout, fp);
10447         TRY_CATCH (ex, RETURN_MASK_ERROR)
10448           {
10449             print_command_lines (uiout, tp->commands, 2);
10450           }
10451         ui_out_redirect (uiout, NULL);
10452
10453         if (ex.reason < 0)
10454           throw_exception (ex);
10455
10456         fprintf_unfiltered (fp, "  end\n");
10457       }
10458   }
10459   do_cleanups (cleanup);
10460   if (from_tty)
10461     printf_filtered (_("Tracepoints saved to file '%s'.\n"), args);
10462   return;
10463 }
10464
10465 /* Create a vector of all tracepoints.  */
10466
10467 VEC(breakpoint_p) *
10468 all_tracepoints ()
10469 {
10470   VEC(breakpoint_p) *tp_vec = 0;
10471   struct breakpoint *tp;
10472
10473   ALL_TRACEPOINTS (tp)
10474   {
10475     VEC_safe_push (breakpoint_p, tp_vec, tp);
10476   }
10477
10478   return tp_vec;
10479 }
10480
10481 \f
10482 /* This help string is used for the break, hbreak, tbreak and thbreak commands.
10483    It is defined as a macro to prevent duplication.
10484    COMMAND should be a string constant containing the name of the command.  */
10485 #define BREAK_ARGS_HELP(command) \
10486 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
10487 LOCATION may be a line number, function name, or \"*\" and an address.\n\
10488 If a line number is specified, break at start of code for that line.\n\
10489 If a function is specified, break at start of code for that function.\n\
10490 If an address is specified, break at that exact address.\n\
10491 With no LOCATION, uses current execution address of selected stack frame.\n\
10492 This is useful for breaking on return to a stack frame.\n\
10493 \n\
10494 THREADNUM is the number from \"info threads\".\n\
10495 CONDITION is a boolean expression.\n\
10496 \n\
10497 Multiple breakpoints at one place are permitted, and useful if conditional.\n\
10498 \n\
10499 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
10500
10501 /* List of subcommands for "catch".  */
10502 static struct cmd_list_element *catch_cmdlist;
10503
10504 /* List of subcommands for "tcatch".  */
10505 static struct cmd_list_element *tcatch_cmdlist;
10506
10507 /* Like add_cmd, but add the command to both the "catch" and "tcatch"
10508    lists, and pass some additional user data to the command function.  */
10509 static void
10510 add_catch_command (char *name, char *docstring,
10511                    void (*sfunc) (char *args, int from_tty,
10512                                   struct cmd_list_element *command),
10513                    char **(*completer) (struct cmd_list_element *cmd,
10514                                          char *text, char *word),
10515                    void *user_data_catch,
10516                    void *user_data_tcatch)
10517 {
10518   struct cmd_list_element *command;
10519
10520   command = add_cmd (name, class_breakpoint, NULL, docstring,
10521                      &catch_cmdlist);
10522   set_cmd_sfunc (command, sfunc);
10523   set_cmd_context (command, user_data_catch);
10524   set_cmd_completer (command, completer);
10525
10526   command = add_cmd (name, class_breakpoint, NULL, docstring,
10527                      &tcatch_cmdlist);
10528   set_cmd_sfunc (command, sfunc);
10529   set_cmd_context (command, user_data_tcatch);
10530   set_cmd_completer (command, completer);
10531 }
10532
10533 static void
10534 clear_syscall_counts (struct inferior *inf)
10535 {
10536   inf->total_syscalls_count = 0;
10537   inf->any_syscall_count = 0;
10538   VEC_free (int, inf->syscalls_counts);
10539 }
10540
10541 void
10542 _initialize_breakpoint (void)
10543 {
10544   static struct cmd_list_element *breakpoint_set_cmdlist;
10545   static struct cmd_list_element *breakpoint_show_cmdlist;
10546   struct cmd_list_element *c;
10547
10548   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
10549   observer_attach_inferior_exit (clear_syscall_counts);
10550   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
10551
10552   breakpoint_chain = 0;
10553   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
10554      before a breakpoint is set.  */
10555   breakpoint_count = 0;
10556
10557   tracepoint_count = 0;
10558
10559   add_com ("ignore", class_breakpoint, ignore_command, _("\
10560 Set ignore-count of breakpoint number N to COUNT.\n\
10561 Usage is `ignore N COUNT'."));
10562   if (xdb_commands)
10563     add_com_alias ("bc", "ignore", class_breakpoint, 1);
10564
10565   add_com ("commands", class_breakpoint, commands_command, _("\
10566 Set commands to be executed when a breakpoint is hit.\n\
10567 Give breakpoint number as argument after \"commands\".\n\
10568 With no argument, the targeted breakpoint is the last one set.\n\
10569 The commands themselves follow starting on the next line.\n\
10570 Type a line containing \"end\" to indicate the end of them.\n\
10571 Give \"silent\" as the first line to make the breakpoint silent;\n\
10572 then no output is printed when it is hit, except what the commands print."));
10573
10574   add_com ("condition", class_breakpoint, condition_command, _("\
10575 Specify breakpoint number N to break only if COND is true.\n\
10576 Usage is `condition N COND', where N is an integer and COND is an\n\
10577 expression to be evaluated whenever breakpoint N is reached."));
10578
10579   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
10580 Set a temporary breakpoint.\n\
10581 Like \"break\" except the breakpoint is only temporary,\n\
10582 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
10583 by using \"enable delete\" on the breakpoint number.\n\
10584 \n"
10585 BREAK_ARGS_HELP ("tbreak")));
10586   set_cmd_completer (c, location_completer);
10587
10588   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
10589 Set a hardware assisted  breakpoint.\n\
10590 Like \"break\" except the breakpoint requires hardware support,\n\
10591 some target hardware may not have this support.\n\
10592 \n"
10593 BREAK_ARGS_HELP ("hbreak")));
10594   set_cmd_completer (c, location_completer);
10595
10596   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
10597 Set a temporary hardware assisted breakpoint.\n\
10598 Like \"hbreak\" except the breakpoint is only temporary,\n\
10599 so it will be deleted when hit.\n\
10600 \n"
10601 BREAK_ARGS_HELP ("thbreak")));
10602   set_cmd_completer (c, location_completer);
10603
10604   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
10605 Enable some breakpoints.\n\
10606 Give breakpoint numbers (separated by spaces) as arguments.\n\
10607 With no subcommand, breakpoints are enabled until you command otherwise.\n\
10608 This is used to cancel the effect of the \"disable\" command.\n\
10609 With a subcommand you can enable temporarily."),
10610                   &enablelist, "enable ", 1, &cmdlist);
10611   if (xdb_commands)
10612     add_com ("ab", class_breakpoint, enable_command, _("\
10613 Enable some breakpoints.\n\
10614 Give breakpoint numbers (separated by spaces) as arguments.\n\
10615 With no subcommand, breakpoints are enabled until you command otherwise.\n\
10616 This is used to cancel the effect of the \"disable\" command.\n\
10617 With a subcommand you can enable temporarily."));
10618
10619   add_com_alias ("en", "enable", class_breakpoint, 1);
10620
10621   add_abbrev_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
10622 Enable some breakpoints.\n\
10623 Give breakpoint numbers (separated by spaces) as arguments.\n\
10624 This is used to cancel the effect of the \"disable\" command.\n\
10625 May be abbreviated to simply \"enable\".\n"),
10626                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
10627
10628   add_cmd ("once", no_class, enable_once_command, _("\
10629 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
10630 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
10631            &enablebreaklist);
10632
10633   add_cmd ("delete", no_class, enable_delete_command, _("\
10634 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
10635 If a breakpoint is hit while enabled in this fashion, it is deleted."),
10636            &enablebreaklist);
10637
10638   add_cmd ("delete", no_class, enable_delete_command, _("\
10639 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
10640 If a breakpoint is hit while enabled in this fashion, it is deleted."),
10641            &enablelist);
10642
10643   add_cmd ("once", no_class, enable_once_command, _("\
10644 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
10645 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
10646            &enablelist);
10647
10648   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
10649 Disable some breakpoints.\n\
10650 Arguments are breakpoint numbers with spaces in between.\n\
10651 To disable all breakpoints, give no argument.\n\
10652 A disabled breakpoint is not forgotten, but has no effect until reenabled."),
10653                   &disablelist, "disable ", 1, &cmdlist);
10654   add_com_alias ("dis", "disable", class_breakpoint, 1);
10655   add_com_alias ("disa", "disable", class_breakpoint, 1);
10656   if (xdb_commands)
10657     add_com ("sb", class_breakpoint, disable_command, _("\
10658 Disable some breakpoints.\n\
10659 Arguments are breakpoint numbers with spaces in between.\n\
10660 To disable all breakpoints, give no argument.\n\
10661 A disabled breakpoint is not forgotten, but has no effect until reenabled."));
10662
10663   add_cmd ("breakpoints", class_alias, disable_command, _("\
10664 Disable some breakpoints.\n\
10665 Arguments are breakpoint numbers with spaces in between.\n\
10666 To disable all breakpoints, give no argument.\n\
10667 A disabled breakpoint is not forgotten, but has no effect until reenabled.\n\
10668 This command may be abbreviated \"disable\"."),
10669            &disablelist);
10670
10671   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
10672 Delete some breakpoints or auto-display expressions.\n\
10673 Arguments are breakpoint numbers with spaces in between.\n\
10674 To delete all breakpoints, give no argument.\n\
10675 \n\
10676 Also a prefix command for deletion of other GDB objects.\n\
10677 The \"unset\" command is also an alias for \"delete\"."),
10678                   &deletelist, "delete ", 1, &cmdlist);
10679   add_com_alias ("d", "delete", class_breakpoint, 1);
10680   add_com_alias ("del", "delete", class_breakpoint, 1);
10681   if (xdb_commands)
10682     add_com ("db", class_breakpoint, delete_command, _("\
10683 Delete some breakpoints.\n\
10684 Arguments are breakpoint numbers with spaces in between.\n\
10685 To delete all breakpoints, give no argument.\n"));
10686
10687   add_cmd ("breakpoints", class_alias, delete_command, _("\
10688 Delete some breakpoints or auto-display expressions.\n\
10689 Arguments are breakpoint numbers with spaces in between.\n\
10690 To delete all breakpoints, give no argument.\n\
10691 This command may be abbreviated \"delete\"."),
10692            &deletelist);
10693
10694   add_com ("clear", class_breakpoint, clear_command, _("\
10695 Clear breakpoint at specified line or function.\n\
10696 Argument may be line number, function name, or \"*\" and an address.\n\
10697 If line number is specified, all breakpoints in that line are cleared.\n\
10698 If function is specified, breakpoints at beginning of function are cleared.\n\
10699 If an address is specified, breakpoints at that address are cleared.\n\
10700 \n\
10701 With no argument, clears all breakpoints in the line that the selected frame\n\
10702 is executing in.\n\
10703 \n\
10704 See also the \"delete\" command which clears breakpoints by number."));
10705
10706   c = add_com ("break", class_breakpoint, break_command, _("\
10707 Set breakpoint at specified line or function.\n"
10708 BREAK_ARGS_HELP ("break")));
10709   set_cmd_completer (c, location_completer);
10710
10711   add_com_alias ("b", "break", class_run, 1);
10712   add_com_alias ("br", "break", class_run, 1);
10713   add_com_alias ("bre", "break", class_run, 1);
10714   add_com_alias ("brea", "break", class_run, 1);
10715
10716   if (xdb_commands)
10717    add_com_alias ("ba", "break", class_breakpoint, 1);
10718
10719   if (dbx_commands)
10720     {
10721       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
10722 Break in function/address or break at a line in the current file."),
10723                              &stoplist, "stop ", 1, &cmdlist);
10724       add_cmd ("in", class_breakpoint, stopin_command,
10725                _("Break in function or address."), &stoplist);
10726       add_cmd ("at", class_breakpoint, stopat_command,
10727                _("Break at a line in the current file."), &stoplist);
10728       add_com ("status", class_info, breakpoints_info, _("\
10729 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
10730 The \"Type\" column indicates one of:\n\
10731 \tbreakpoint     - normal breakpoint\n\
10732 \twatchpoint     - watchpoint\n\
10733 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
10734 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
10735 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
10736 address and file/line number respectively.\n\
10737 \n\
10738 Convenience variable \"$_\" and default examine address for \"x\"\n\
10739 are set to the address of the last breakpoint listed unless the command\n\
10740 is prefixed with \"server \".\n\n\
10741 Convenience variable \"$bpnum\" contains the number of the last\n\
10742 breakpoint set."));
10743     }
10744
10745   add_info ("breakpoints", breakpoints_info, _("\
10746 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
10747 The \"Type\" column indicates one of:\n\
10748 \tbreakpoint     - normal breakpoint\n\
10749 \twatchpoint     - watchpoint\n\
10750 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
10751 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
10752 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
10753 address and file/line number respectively.\n\
10754 \n\
10755 Convenience variable \"$_\" and default examine address for \"x\"\n\
10756 are set to the address of the last breakpoint listed unless the command\n\
10757 is prefixed with \"server \".\n\n\
10758 Convenience variable \"$bpnum\" contains the number of the last\n\
10759 breakpoint set."));
10760
10761   add_info_alias ("b", "breakpoints", 1);
10762
10763   if (xdb_commands)
10764     add_com ("lb", class_breakpoint, breakpoints_info, _("\
10765 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
10766 The \"Type\" column indicates one of:\n\
10767 \tbreakpoint     - normal breakpoint\n\
10768 \twatchpoint     - watchpoint\n\
10769 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
10770 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
10771 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
10772 address and file/line number respectively.\n\
10773 \n\
10774 Convenience variable \"$_\" and default examine address for \"x\"\n\
10775 are set to the address of the last breakpoint listed unless the command\n\
10776 is prefixed with \"server \".\n\n\
10777 Convenience variable \"$bpnum\" contains the number of the last\n\
10778 breakpoint set."));
10779
10780   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
10781 Status of all breakpoints, or breakpoint number NUMBER.\n\
10782 The \"Type\" column indicates one of:\n\
10783 \tbreakpoint     - normal breakpoint\n\
10784 \twatchpoint     - watchpoint\n\
10785 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
10786 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
10787 \tuntil          - internal breakpoint used by the \"until\" command\n\
10788 \tfinish         - internal breakpoint used by the \"finish\" command\n\
10789 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
10790 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
10791 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
10792 address and file/line number respectively.\n\
10793 \n\
10794 Convenience variable \"$_\" and default examine address for \"x\"\n\
10795 are set to the address of the last breakpoint listed unless the command\n\
10796 is prefixed with \"server \".\n\n\
10797 Convenience variable \"$bpnum\" contains the number of the last\n\
10798 breakpoint set."),
10799            &maintenanceinfolist);
10800
10801   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
10802 Set catchpoints to catch events."),
10803                   &catch_cmdlist, "catch ",
10804                   0/*allow-unknown*/, &cmdlist);
10805
10806   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
10807 Set temporary catchpoints to catch events."),
10808                   &tcatch_cmdlist, "tcatch ",
10809                   0/*allow-unknown*/, &cmdlist);
10810
10811   /* Add catch and tcatch sub-commands.  */
10812   add_catch_command ("catch", _("\
10813 Catch an exception, when caught.\n\
10814 With an argument, catch only exceptions with the given name."),
10815                      catch_catch_command,
10816                      NULL,
10817                      CATCH_PERMANENT,
10818                      CATCH_TEMPORARY);
10819   add_catch_command ("throw", _("\
10820 Catch an exception, when thrown.\n\
10821 With an argument, catch only exceptions with the given name."),
10822                      catch_throw_command,
10823                      NULL,
10824                      CATCH_PERMANENT,
10825                      CATCH_TEMPORARY);
10826   add_catch_command ("fork", _("Catch calls to fork."),
10827                      catch_fork_command_1,
10828                      NULL,
10829                      (void *) (uintptr_t) catch_fork_permanent,
10830                      (void *) (uintptr_t) catch_fork_temporary);
10831   add_catch_command ("vfork", _("Catch calls to vfork."),
10832                      catch_fork_command_1,
10833                      NULL,
10834                      (void *) (uintptr_t) catch_vfork_permanent,
10835                      (void *) (uintptr_t) catch_vfork_temporary);
10836   add_catch_command ("exec", _("Catch calls to exec."),
10837                      catch_exec_command_1,
10838                      NULL,
10839                      CATCH_PERMANENT,
10840                      CATCH_TEMPORARY);
10841   add_catch_command ("syscall", _("\
10842 Catch system calls by their names and/or numbers.\n\
10843 Arguments say which system calls to catch.  If no arguments\n\
10844 are given, every system call will be caught.\n\
10845 Arguments, if given, should be one or more system call names\n\
10846 (if your system supports that), or system call numbers."),
10847                      catch_syscall_command_1,
10848                      catch_syscall_completer,
10849                      CATCH_PERMANENT,
10850                      CATCH_TEMPORARY);
10851   add_catch_command ("exception", _("\
10852 Catch Ada exceptions, when raised.\n\
10853 With an argument, catch only exceptions with the given name."),
10854                      catch_ada_exception_command,
10855                      NULL,
10856                      CATCH_PERMANENT,
10857                      CATCH_TEMPORARY);
10858   add_catch_command ("assert", _("\
10859 Catch failed Ada assertions, when raised.\n\
10860 With an argument, catch only exceptions with the given name."),
10861                      catch_assert_command,
10862                      NULL,
10863                      CATCH_PERMANENT,
10864                      CATCH_TEMPORARY);
10865
10866   c = add_com ("watch", class_breakpoint, watch_command, _("\
10867 Set a watchpoint for an expression.\n\
10868 A watchpoint stops execution of your program whenever the value of\n\
10869 an expression changes."));
10870   set_cmd_completer (c, expression_completer);
10871
10872   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
10873 Set a read watchpoint for an expression.\n\
10874 A watchpoint stops execution of your program whenever the value of\n\
10875 an expression is read."));
10876   set_cmd_completer (c, expression_completer);
10877
10878   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
10879 Set a watchpoint for an expression.\n\
10880 A watchpoint stops execution of your program whenever the value of\n\
10881 an expression is either read or written."));
10882   set_cmd_completer (c, expression_completer);
10883
10884   add_info ("watchpoints", breakpoints_info,
10885             _("Synonym for ``info breakpoints''."));
10886
10887
10888   /* XXX: cagney/2005-02-23: This should be a boolean, and should
10889      respond to changes - contrary to the description.  */
10890   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
10891                             &can_use_hw_watchpoints, _("\
10892 Set debugger's willingness to use watchpoint hardware."), _("\
10893 Show debugger's willingness to use watchpoint hardware."), _("\
10894 If zero, gdb will not use hardware for new watchpoints, even if\n\
10895 such is available.  (However, any hardware watchpoints that were\n\
10896 created before setting this to nonzero, will continue to use watchpoint\n\
10897 hardware.)"),
10898                             NULL,
10899                             show_can_use_hw_watchpoints,
10900                             &setlist, &showlist);
10901
10902   can_use_hw_watchpoints = 1;
10903
10904   /* Tracepoint manipulation commands.  */
10905
10906   c = add_com ("trace", class_breakpoint, trace_command, _("\
10907 Set a tracepoint at specified line or function.\n\
10908 \n"
10909 BREAK_ARGS_HELP ("trace") "\n\
10910 Do \"help tracepoints\" for info on other tracepoint commands."));
10911   set_cmd_completer (c, location_completer);
10912
10913   add_com_alias ("tp", "trace", class_alias, 0);
10914   add_com_alias ("tr", "trace", class_alias, 1);
10915   add_com_alias ("tra", "trace", class_alias, 1);
10916   add_com_alias ("trac", "trace", class_alias, 1);
10917
10918   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
10919 Set a fast tracepoint at specified line or function.\n\
10920 \n"
10921 BREAK_ARGS_HELP ("ftrace") "\n\
10922 Do \"help tracepoints\" for info on other tracepoint commands."));
10923   set_cmd_completer (c, location_completer);
10924
10925   add_info ("tracepoints", tracepoints_info, _("\
10926 Status of tracepoints, or tracepoint number NUMBER.\n\
10927 Convenience variable \"$tpnum\" contains the number of the\n\
10928 last tracepoint set."));
10929
10930   add_info_alias ("tp", "tracepoints", 1);
10931
10932   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
10933 Delete specified tracepoints.\n\
10934 Arguments are tracepoint numbers, separated by spaces.\n\
10935 No argument means delete all tracepoints."),
10936            &deletelist);
10937
10938   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
10939 Disable specified tracepoints.\n\
10940 Arguments are tracepoint numbers, separated by spaces.\n\
10941 No argument means disable all tracepoints."),
10942            &disablelist);
10943   deprecate_cmd (c, "disable");
10944
10945   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
10946 Enable specified tracepoints.\n\
10947 Arguments are tracepoint numbers, separated by spaces.\n\
10948 No argument means enable all tracepoints."),
10949            &enablelist);
10950   deprecate_cmd (c, "enable");
10951
10952   add_com ("passcount", class_trace, trace_pass_command, _("\
10953 Set the passcount for a tracepoint.\n\
10954 The trace will end when the tracepoint has been passed 'count' times.\n\
10955 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
10956 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
10957
10958   c = add_com ("save-tracepoints", class_trace, tracepoint_save_command, _("\
10959 Save current tracepoint definitions as a script.\n\
10960 Use the 'source' command in another debug session to restore them."));
10961   set_cmd_completer (c, filename_completer);
10962
10963   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
10964 Breakpoint specific settings\n\
10965 Configure various breakpoint-specific variables such as\n\
10966 pending breakpoint behavior"),
10967                   &breakpoint_set_cmdlist, "set breakpoint ",
10968                   0/*allow-unknown*/, &setlist);
10969   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
10970 Breakpoint specific settings\n\
10971 Configure various breakpoint-specific variables such as\n\
10972 pending breakpoint behavior"),
10973                   &breakpoint_show_cmdlist, "show breakpoint ",
10974                   0/*allow-unknown*/, &showlist);
10975
10976   add_setshow_auto_boolean_cmd ("pending", no_class,
10977                                 &pending_break_support, _("\
10978 Set debugger's behavior regarding pending breakpoints."), _("\
10979 Show debugger's behavior regarding pending breakpoints."), _("\
10980 If on, an unrecognized breakpoint location will cause gdb to create a\n\
10981 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
10982 an error.  If auto, an unrecognized breakpoint location results in a\n\
10983 user-query to see if a pending breakpoint should be created."),
10984                                 NULL,
10985                                 show_pending_break_support,
10986                                 &breakpoint_set_cmdlist,
10987                                 &breakpoint_show_cmdlist);
10988
10989   pending_break_support = AUTO_BOOLEAN_AUTO;
10990
10991   add_setshow_boolean_cmd ("auto-hw", no_class,
10992                            &automatic_hardware_breakpoints, _("\
10993 Set automatic usage of hardware breakpoints."), _("\
10994 Show automatic usage of hardware breakpoints."), _("\
10995 If set, the debugger will automatically use hardware breakpoints for\n\
10996 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
10997 a warning will be emitted for such breakpoints."),
10998                            NULL,
10999                            show_automatic_hardware_breakpoints,
11000                            &breakpoint_set_cmdlist,
11001                            &breakpoint_show_cmdlist);
11002
11003   add_setshow_enum_cmd ("always-inserted", class_support,
11004                         always_inserted_enums, &always_inserted_mode, _("\
11005 Set mode for inserting breakpoints."), _("\
11006 Show mode for inserting breakpoints."), _("\
11007 When this mode is off, breakpoints are inserted in inferior when it is\n\
11008 resumed, and removed when execution stops.  When this mode is on,\n\
11009 breakpoints are inserted immediately and removed only when the user\n\
11010 deletes the breakpoint.  When this mode is auto (which is the default),\n\
11011 the behaviour depends on the non-stop setting (see help set non-stop).\n\
11012 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
11013 behaves as if always-inserted mode is on; if gdb is controlling the\n\
11014 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
11015                            NULL,
11016                            &show_always_inserted_mode,
11017                            &breakpoint_set_cmdlist,
11018                            &breakpoint_show_cmdlist);
11019   
11020   automatic_hardware_breakpoints = 1;
11021
11022   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
11023 }