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