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