Upgrade GDB from 7.0 and 7.2 on the vendor branch
[dragonfly.git] / contrib / gdb-7 / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
4    1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
5    2008, 2009, 2010 Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "arch-utils.h"
24 #include <ctype.h>
25 #include "hashtab.h"
26 #include "symtab.h"
27 #include "frame.h"
28 #include "breakpoint.h"
29 #include "tracepoint.h"
30 #include "gdbtypes.h"
31 #include "expression.h"
32 #include "gdbcore.h"
33 #include "gdbcmd.h"
34 #include "value.h"
35 #include "command.h"
36 #include "inferior.h"
37 #include "gdbthread.h"
38 #include "target.h"
39 #include "language.h"
40 #include "gdb_string.h"
41 #include "demangle.h"
42 #include "annotate.h"
43 #include "symfile.h"
44 #include "objfiles.h"
45 #include "source.h"
46 #include "linespec.h"
47 #include "completer.h"
48 #include "gdb.h"
49 #include "ui-out.h"
50 #include "cli/cli-script.h"
51 #include "gdb_assert.h"
52 #include "block.h"
53 #include "solib.h"
54 #include "solist.h"
55 #include "observer.h"
56 #include "exceptions.h"
57 #include "memattr.h"
58 #include "ada-lang.h"
59 #include "top.h"
60 #include "wrapper.h"
61 #include "valprint.h"
62 #include "jit.h"
63 #include "xml-syscall.h"
64 #include "parser-defs.h"
65
66 /* readline include files */
67 #include "readline/readline.h"
68 #include "readline/history.h"
69
70 /* readline defines this.  */
71 #undef savestring
72
73 #include "mi/mi-common.h"
74
75 /* Arguments to pass as context to some catch command handlers.  */
76 #define CATCH_PERMANENT ((void *) (uintptr_t) 0)
77 #define CATCH_TEMPORARY ((void *) (uintptr_t) 1)
78
79 /* Prototypes for local functions. */
80
81 static void enable_delete_command (char *, int);
82
83 static void enable_once_command (char *, int);
84
85 static void disable_command (char *, int);
86
87 static void enable_command (char *, int);
88
89 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
90                                                       void *),
91                                     void *);
92
93 static void ignore_command (char *, int);
94
95 static int breakpoint_re_set_one (void *);
96
97 static void clear_command (char *, int);
98
99 static void catch_command (char *, int);
100
101 static void watch_command (char *, int);
102
103 static int can_use_hardware_watchpoint (struct value *);
104
105 static void break_command_1 (char *, int, int);
106
107 static void mention (struct breakpoint *);
108
109 /* This function is used in gdbtk sources and thus can not be made static.  */
110 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
111                                               struct symtab_and_line,
112                                               enum bptype);
113
114 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
115
116 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
117                                             CORE_ADDR bpaddr,
118                                             enum bptype bptype);
119
120 static void describe_other_breakpoints (struct gdbarch *,
121                                         struct program_space *, CORE_ADDR,
122                                         struct obj_section *, int);
123
124 static int breakpoint_address_match (struct address_space *aspace1,
125                                      CORE_ADDR addr1,
126                                      struct address_space *aspace2,
127                                      CORE_ADDR addr2);
128
129 static int watchpoint_locations_match (struct bp_location *loc1,
130                                        struct bp_location *loc2);
131
132 static void breakpoints_info (char *, int);
133
134 static void watchpoints_info (char *, int);
135
136 static int breakpoint_1 (int, int, int (*) (const struct breakpoint *));
137
138 static bpstat bpstat_alloc (const struct bp_location *, bpstat);
139
140 static int breakpoint_cond_eval (void *);
141
142 static void cleanup_executing_breakpoints (void *);
143
144 static void commands_command (char *, int);
145
146 static void condition_command (char *, int);
147
148 static int get_number_trailer (char **, int);
149
150 typedef enum
151   {
152     mark_inserted,
153     mark_uninserted
154   }
155 insertion_state_t;
156
157 static int remove_breakpoint (struct bp_location *, insertion_state_t);
158 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
159
160 static enum print_stop_action print_it_typical (bpstat);
161
162 static enum print_stop_action print_bp_stop_message (bpstat bs);
163
164 static int watchpoint_check (void *);
165
166 static void maintenance_info_breakpoints (char *, int);
167
168 static int hw_breakpoint_used_count (void);
169
170 static int hw_watchpoint_used_count (enum bptype, int *);
171
172 static void hbreak_command (char *, int);
173
174 static void thbreak_command (char *, int);
175
176 static void watch_command_1 (char *, int, int);
177
178 static void rwatch_command (char *, int);
179
180 static void awatch_command (char *, int);
181
182 static void do_enable_breakpoint (struct breakpoint *, enum bpdisp);
183
184 static void stop_command (char *arg, int from_tty);
185
186 static void stopin_command (char *arg, int from_tty);
187
188 static void stopat_command (char *arg, int from_tty);
189
190 static char *ep_parse_optional_if_clause (char **arg);
191
192 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
193                                        char *arg, int tempflag, int from_tty);
194
195 static void tcatch_command (char *arg, int from_tty);
196
197 static void ep_skip_leading_whitespace (char **s);
198
199 static void detach_single_step_breakpoints (void);
200
201 static int single_step_breakpoint_inserted_here_p (struct address_space *,
202                                                    CORE_ADDR pc);
203
204 static void free_bp_location (struct bp_location *loc);
205
206 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
207
208 static void update_global_location_list (int);
209
210 static void update_global_location_list_nothrow (int);
211
212 static int bpstat_remove_bp_location_callback (struct thread_info *th,
213                                                void *data);
214
215 static int is_hardware_watchpoint (const struct breakpoint *bpt);
216
217 static int is_watchpoint (const struct breakpoint *bpt);
218
219 static void insert_breakpoint_locations (void);
220
221 static int syscall_catchpoint_p (struct breakpoint *b);
222
223 static void tracepoints_info (char *, int);
224
225 static void delete_trace_command (char *, int);
226
227 static void enable_trace_command (char *, int);
228
229 static void disable_trace_command (char *, int);
230
231 static void trace_pass_command (char *, int);
232
233 /* Assuming we're creating a static tracepoint, does S look like a
234    static tracepoint marker spec ("-m MARKER_ID")?  */
235 #define is_marker_spec(s)                                               \
236   (strncmp (s, "-m", 2) == 0 && ((s)[2] == ' ' || (s)[2] == '\t'))
237
238 /* A reference-counted struct command_line.  This lets multiple
239    breakpoints share a single command list.  */
240 struct counted_command_line
241 {
242   /* The reference count.  */
243   int refc;
244
245   /* The command list.  */
246   struct command_line *commands;
247 };
248
249 struct command_line *
250 breakpoint_commands (struct breakpoint *b)
251 {
252   return b->commands ? b->commands->commands : NULL;
253 }
254
255 /* Flag indicating that a command has proceeded the inferior past the
256    current breakpoint.  */
257
258 static int breakpoint_proceeded;
259
260 static const char *
261 bpdisp_text (enum bpdisp disp)
262 {
263   /* NOTE: the following values are a part of MI protocol and represent
264      values of 'disp' field returned when inferior stops at a breakpoint.  */
265   static char *bpdisps[] = {"del", "dstp", "dis", "keep"};
266
267   return bpdisps[(int) disp];
268 }
269
270 /* Prototypes for exported functions. */
271 /* If FALSE, gdb will not use hardware support for watchpoints, even
272    if such is available. */
273 static int can_use_hw_watchpoints;
274
275 static void
276 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
277                              struct cmd_list_element *c,
278                              const char *value)
279 {
280   fprintf_filtered (file, _("\
281 Debugger's willingness to use watchpoint hardware is %s.\n"),
282                     value);
283 }
284
285 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
286    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
287    for unrecognized breakpoint locations.  
288    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
289 static enum auto_boolean pending_break_support;
290 static void
291 show_pending_break_support (struct ui_file *file, int from_tty,
292                             struct cmd_list_element *c,
293                             const char *value)
294 {
295   fprintf_filtered (file, _("\
296 Debugger's behavior regarding pending breakpoints is %s.\n"),
297                     value);
298 }
299
300 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
301    set with "break" but falling in read-only memory. 
302    If 0, gdb will warn about such breakpoints, but won't automatically
303    use hardware breakpoints.  */
304 static int automatic_hardware_breakpoints;
305 static void
306 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
307                                      struct cmd_list_element *c,
308                                      const char *value)
309 {
310   fprintf_filtered (file, _("\
311 Automatic usage of hardware breakpoints is %s.\n"),
312                     value);
313 }
314
315 /* If on, gdb will keep breakpoints inserted even as inferior is
316    stopped, and immediately insert any new breakpoints.  If off, gdb
317    will insert breakpoints into inferior only when resuming it, and
318    will remove breakpoints upon stop.  If auto, GDB will behave as ON
319    if in non-stop mode, and as OFF if all-stop mode.*/
320
321 static const char always_inserted_auto[] = "auto";
322 static const char always_inserted_on[] = "on";
323 static const char always_inserted_off[] = "off";
324 static const char *always_inserted_enums[] = {
325   always_inserted_auto,
326   always_inserted_off,
327   always_inserted_on,
328   NULL
329 };
330 static const char *always_inserted_mode = always_inserted_auto;
331 static void
332 show_always_inserted_mode (struct ui_file *file, int from_tty,
333                      struct cmd_list_element *c, const char *value)
334 {
335   if (always_inserted_mode == always_inserted_auto)
336     fprintf_filtered (file, _("\
337 Always inserted breakpoint mode is %s (currently %s).\n"),
338                       value,
339                       breakpoints_always_inserted_mode () ? "on" : "off");
340   else
341     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"), value);
342 }
343
344 int
345 breakpoints_always_inserted_mode (void)
346 {
347   return (always_inserted_mode == always_inserted_on
348           || (always_inserted_mode == always_inserted_auto && non_stop));
349 }
350
351 void _initialize_breakpoint (void);
352
353 /* Are we executing breakpoint commands?  */
354 static int executing_breakpoint_commands;
355
356 /* Are overlay event breakpoints enabled? */
357 static int overlay_events_enabled;
358
359 /* Walk the following statement or block through all breakpoints.
360    ALL_BREAKPOINTS_SAFE does so even if the statment deletes the current
361    breakpoint.  */
362
363 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
364
365 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
366         for (B = breakpoint_chain;      \
367              B ? (TMP=B->next, 1): 0;   \
368              B = TMP)
369
370 /* Similar iterator for the low-level breakpoints.  SAFE variant is not
371    provided so update_global_location_list must not be called while executing
372    the block of ALL_BP_LOCATIONS.  */
373
374 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
375         for (BP_TMP = bp_location;                                      \
376              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
377              BP_TMP++)
378
379 /* Iterator for tracepoints only.  */
380
381 #define ALL_TRACEPOINTS(B)  \
382   for (B = breakpoint_chain; B; B = B->next)  \
383     if (is_tracepoint (B))
384
385 /* Chains of all breakpoints defined.  */
386
387 struct breakpoint *breakpoint_chain;
388
389 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
390
391 static struct bp_location **bp_location;
392
393 /* Number of elements of BP_LOCATION.  */
394
395 static unsigned bp_location_count;
396
397 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and ADDRESS
398    for the current elements of BP_LOCATION which get a valid result from
399    bp_location_has_shadow.  You can use it for roughly limiting the subrange of
400    BP_LOCATION to scan for shadow bytes for an address you need to read.  */
401
402 static CORE_ADDR bp_location_placed_address_before_address_max;
403
404 /* Maximum offset plus alignment between
405    bp_target_info.PLACED_ADDRESS + bp_target_info.SHADOW_LEN and ADDRESS for
406    the current elements of BP_LOCATION which get a valid result from
407    bp_location_has_shadow.  You can use it for roughly limiting the subrange of
408    BP_LOCATION to scan for shadow bytes for an address you need to read.  */
409
410 static CORE_ADDR bp_location_shadow_len_after_address_max;
411
412 /* The locations that no longer correspond to any breakpoint,
413    unlinked from bp_location array, but for which a hit
414    may still be reported by a target.  */
415 VEC(bp_location_p) *moribund_locations = NULL;
416
417 /* Number of last breakpoint made.  */
418
419 static int breakpoint_count;
420
421 /* The value of `breakpoint_count' before the last command that
422    created breakpoints.  If the last (break-like) command created more
423    than one breakpoint, then the difference between BREAKPOINT_COUNT
424    and PREV_BREAKPOINT_COUNT is more than one.  */
425 static int prev_breakpoint_count;
426
427 /* Number of last tracepoint made.  */
428
429 static int tracepoint_count;
430
431 static struct cmd_list_element *breakpoint_set_cmdlist;
432 static struct cmd_list_element *breakpoint_show_cmdlist;
433 static struct cmd_list_element *save_cmdlist;
434
435 /* Return whether a breakpoint is an active enabled breakpoint.  */
436 static int
437 breakpoint_enabled (struct breakpoint *b)
438 {
439   return (b->enable_state == bp_enabled);
440 }
441
442 /* Set breakpoint count to NUM.  */
443
444 static void
445 set_breakpoint_count (int num)
446 {
447   prev_breakpoint_count = breakpoint_count;
448   breakpoint_count = num;
449   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
450 }
451
452 /* Used by `start_rbreak_breakpoints' below, to record the current
453    breakpoint count before "rbreak" creates any breakpoint.  */
454 static int rbreak_start_breakpoint_count;
455
456 /* Called at the start an "rbreak" command to record the first
457    breakpoint made.  */
458
459 void
460 start_rbreak_breakpoints (void)
461 {
462   rbreak_start_breakpoint_count = breakpoint_count;
463 }
464
465 /* Called at the end of an "rbreak" command to record the last
466    breakpoint made.  */
467
468 void
469 end_rbreak_breakpoints (void)
470 {
471   prev_breakpoint_count = rbreak_start_breakpoint_count;
472 }
473
474 /* Used in run_command to zero the hit count when a new run starts. */
475
476 void
477 clear_breakpoint_hit_counts (void)
478 {
479   struct breakpoint *b;
480
481   ALL_BREAKPOINTS (b)
482     b->hit_count = 0;
483 }
484
485 /* Allocate a new counted_command_line with reference count of 1.
486    The new structure owns COMMANDS.  */
487
488 static struct counted_command_line *
489 alloc_counted_command_line (struct command_line *commands)
490 {
491   struct counted_command_line *result
492     = xmalloc (sizeof (struct counted_command_line));
493
494   result->refc = 1;
495   result->commands = commands;
496   return result;
497 }
498
499 /* Increment reference count.  This does nothing if CMD is NULL.  */
500
501 static void
502 incref_counted_command_line (struct counted_command_line *cmd)
503 {
504   if (cmd)
505     ++cmd->refc;
506 }
507
508 /* Decrement reference count.  If the reference count reaches 0,
509    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
510    nothing if *CMDP is NULL.  */
511
512 static void
513 decref_counted_command_line (struct counted_command_line **cmdp)
514 {
515   if (*cmdp)
516     {
517       if (--(*cmdp)->refc == 0)
518         {
519           free_command_lines (&(*cmdp)->commands);
520           xfree (*cmdp);
521         }
522       *cmdp = NULL;
523     }
524 }
525
526 /* A cleanup function that calls decref_counted_command_line.  */
527
528 static void
529 do_cleanup_counted_command_line (void *arg)
530 {
531   decref_counted_command_line (arg);
532 }
533
534 /* Create a cleanup that calls decref_counted_command_line on the
535    argument.  */
536
537 static struct cleanup *
538 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
539 {
540   return make_cleanup (do_cleanup_counted_command_line, cmdp);
541 }
542
543 /* Default address, symtab and line to put a breakpoint at
544    for "break" command with no arg.
545    if default_breakpoint_valid is zero, the other three are
546    not valid, and "break" with no arg is an error.
547
548    This set by print_stack_frame, which calls set_default_breakpoint.  */
549
550 int default_breakpoint_valid;
551 CORE_ADDR default_breakpoint_address;
552 struct symtab *default_breakpoint_symtab;
553 int default_breakpoint_line;
554 struct program_space *default_breakpoint_pspace;
555
556 \f
557 /* *PP is a string denoting a breakpoint.  Get the number of the breakpoint.
558    Advance *PP after the string and any trailing whitespace.
559
560    Currently the string can either be a number or "$" followed by the name
561    of a convenience variable.  Making it an expression wouldn't work well
562    for map_breakpoint_numbers (e.g. "4 + 5 + 6").
563
564    If the string is a NULL pointer, that denotes the last breakpoint.
565    
566    TRAILER is a character which can be found after the number; most
567    commonly this is `-'.  If you don't want a trailer, use \0.  */ 
568 static int
569 get_number_trailer (char **pp, int trailer)
570 {
571   int retval = 0;       /* default */
572   char *p = *pp;
573
574   if (p == NULL)
575     /* Empty line means refer to the last breakpoint.  */
576     return breakpoint_count;
577   else if (*p == '$')
578     {
579       /* Make a copy of the name, so we can null-terminate it
580          to pass to lookup_internalvar().  */
581       char *varname;
582       char *start = ++p;
583       LONGEST val;
584
585       while (isalnum (*p) || *p == '_')
586         p++;
587       varname = (char *) alloca (p - start + 1);
588       strncpy (varname, start, p - start);
589       varname[p - start] = '\0';
590       if (get_internalvar_integer (lookup_internalvar (varname), &val))
591         retval = (int) val;
592       else
593         {
594           printf_filtered (_("Convenience variable must have integer value.\n"));
595           retval = 0;
596         }
597     }
598   else
599     {
600       if (*p == '-')
601         ++p;
602       while (*p >= '0' && *p <= '9')
603         ++p;
604       if (p == *pp)
605         /* There is no number here.  (e.g. "cond a == b").  */
606         {
607           /* Skip non-numeric token */
608           while (*p && !isspace((int) *p))
609             ++p;
610           /* Return zero, which caller must interpret as error. */
611           retval = 0;
612         }
613       else
614         retval = atoi (*pp);
615     }
616   if (!(isspace (*p) || *p == '\0' || *p == trailer))
617     {
618       /* Trailing junk: return 0 and let caller print error msg. */
619       while (!(isspace (*p) || *p == '\0' || *p == trailer))
620         ++p;
621       retval = 0;
622     }
623   while (isspace (*p))
624     p++;
625   *pp = p;
626   return retval;
627 }
628
629
630 /* Like get_number_trailer, but don't allow a trailer.  */
631 int
632 get_number (char **pp)
633 {
634   return get_number_trailer (pp, '\0');
635 }
636
637 /* Parse a number or a range.
638  * A number will be of the form handled by get_number.
639  * A range will be of the form <number1> - <number2>, and 
640  * will represent all the integers between number1 and number2,
641  * inclusive.
642  *
643  * While processing a range, this fuction is called iteratively;
644  * At each call it will return the next value in the range.
645  *
646  * At the beginning of parsing a range, the char pointer PP will
647  * be advanced past <number1> and left pointing at the '-' token.
648  * Subsequent calls will not advance the pointer until the range
649  * is completed.  The call that completes the range will advance
650  * pointer PP past <number2>.
651  */
652
653 int 
654 get_number_or_range (char **pp)
655 {
656   static int last_retval, end_value;
657   static char *end_ptr;
658   static int in_range = 0;
659
660   if (**pp != '-')
661     {
662       /* Default case: pp is pointing either to a solo number, 
663          or to the first number of a range.  */
664       last_retval = get_number_trailer (pp, '-');
665       if (**pp == '-')
666         {
667           char **temp;
668
669           /* This is the start of a range (<number1> - <number2>).
670              Skip the '-', parse and remember the second number,
671              and also remember the end of the final token.  */
672
673           temp = &end_ptr; 
674           end_ptr = *pp + 1; 
675           while (isspace ((int) *end_ptr))
676             end_ptr++;  /* skip white space */
677           end_value = get_number (temp);
678           if (end_value < last_retval) 
679             {
680               error (_("inverted range"));
681             }
682           else if (end_value == last_retval)
683             {
684               /* degenerate range (number1 == number2).  Advance the
685                  token pointer so that the range will be treated as a
686                  single number.  */ 
687               *pp = end_ptr;
688             }
689           else
690             in_range = 1;
691         }
692     }
693   else if (! in_range)
694     error (_("negative value"));
695   else
696     {
697       /* pp points to the '-' that betokens a range.  All
698          number-parsing has already been done.  Return the next
699          integer value (one greater than the saved previous value).
700          Do not advance the token pointer 'pp' until the end of range
701          is reached.  */
702
703       if (++last_retval == end_value)
704         {
705           /* End of range reached; advance token pointer.  */
706           *pp = end_ptr;
707           in_range = 0;
708         }
709     }
710   return last_retval;
711 }
712
713 /* Return the breakpoint with the specified number, or NULL
714    if the number does not refer to an existing breakpoint.  */
715
716 struct breakpoint *
717 get_breakpoint (int num)
718 {
719   struct breakpoint *b;
720
721   ALL_BREAKPOINTS (b)
722     if (b->number == num)
723       return b;
724   
725   return NULL;
726 }
727
728 \f
729
730 void
731 set_breakpoint_condition (struct breakpoint *b, char *exp,
732                           int from_tty)
733 {
734   struct bp_location *loc = b->loc;
735
736   for (; loc; loc = loc->next)
737     {
738       xfree (loc->cond);
739       loc->cond = NULL;
740     }
741   xfree (b->cond_string);
742   b->cond_string = NULL;
743   xfree (b->cond_exp);
744   b->cond_exp = NULL;
745
746   if (*exp == 0)
747     {
748       if (from_tty)
749         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
750     }
751   else
752     {
753       char *arg = exp;
754
755       /* I don't know if it matters whether this is the string the user
756          typed in or the decompiled expression.  */
757       b->cond_string = xstrdup (arg);
758       b->condition_not_parsed = 0;
759
760       if (is_watchpoint (b))
761         {
762           innermost_block = NULL;
763           arg = exp;
764           b->cond_exp = parse_exp_1 (&arg, 0, 0);
765           if (*arg)
766             error (_("Junk at end of expression"));
767           b->cond_exp_valid_block = innermost_block;
768         }
769       else
770         {
771           for (loc = b->loc; loc; loc = loc->next)
772             {
773               arg = exp;
774               loc->cond =
775                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
776               if (*arg)
777                 error (_("Junk at end of expression"));
778             }
779         }
780     }
781   breakpoints_changed ();
782   observer_notify_breakpoint_modified (b->number);
783 }
784
785 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
786
787 static void
788 condition_command (char *arg, int from_tty)
789 {
790   struct breakpoint *b;
791   char *p;
792   int bnum;
793
794   if (arg == 0)
795     error_no_arg (_("breakpoint number"));
796
797   p = arg;
798   bnum = get_number (&p);
799   if (bnum == 0)
800     error (_("Bad breakpoint argument: '%s'"), arg);
801
802   ALL_BREAKPOINTS (b)
803     if (b->number == bnum)
804       {
805         set_breakpoint_condition (b, p, from_tty);
806         return;
807       }
808
809   error (_("No breakpoint number %d."), bnum);
810 }
811
812 /* Check that COMMAND do not contain commands that are suitable
813    only for tracepoints and not suitable for ordinary breakpoints.
814    Throw if any such commands is found.
815 */
816 static void
817 check_no_tracepoint_commands (struct command_line *commands)
818 {
819   struct command_line *c;
820
821   for (c = commands; c; c = c->next)
822     {
823       int i;
824
825       if (c->control_type == while_stepping_control)
826         error (_("The 'while-stepping' command can only be used for tracepoints"));
827
828       for (i = 0; i < c->body_count; ++i)
829         check_no_tracepoint_commands ((c->body_list)[i]);
830
831       /* Not that command parsing removes leading whitespace and comment
832          lines and also empty lines. So, we only need to check for
833          command directly.  */
834       if (strstr (c->line, "collect ") == c->line)
835         error (_("The 'collect' command can only be used for tracepoints"));
836
837       if (strstr (c->line, "teval ") == c->line)
838         error (_("The 'teval' command can only be used for tracepoints"));
839     }
840 }
841
842 /* Encapsulate tests for different types of tracepoints.  */
843
844 int
845 is_tracepoint (const struct breakpoint *b)
846 {
847   return (b->type == bp_tracepoint
848           || b->type == bp_fast_tracepoint
849           || b->type == bp_static_tracepoint);
850 }
851   
852 /* A helper function that validsates that COMMANDS are valid for a
853    breakpoint.  This function will throw an exception if a problem is
854    found.  */
855
856 static void
857 validate_commands_for_breakpoint (struct breakpoint *b,
858                                   struct command_line *commands)
859 {
860   if (is_tracepoint (b))
861     {
862       /* We need to verify that each top-level element of commands
863          is valid for tracepoints, that there's at most one while-stepping
864          element, and that while-stepping's body has valid tracing commands
865          excluding nested while-stepping.  */
866       struct command_line *c;
867       struct command_line *while_stepping = 0;
868       for (c = commands; c; c = c->next)
869         {
870           if (c->control_type == while_stepping_control)
871             {
872               if (b->type == bp_fast_tracepoint)
873                 error (_("\
874 The 'while-stepping' command cannot be used for fast tracepoint"));
875               else if (b->type == bp_static_tracepoint)
876                 error (_("\
877 The 'while-stepping' command cannot be used for static tracepoint"));
878
879               if (while_stepping)
880                 error (_("The 'while-stepping' command can be used only once"));
881               else
882                 while_stepping = c;
883             }
884         }
885       if (while_stepping)
886         {
887           struct command_line *c2;
888
889           gdb_assert (while_stepping->body_count == 1);
890           c2 = while_stepping->body_list[0];
891           for (; c2; c2 = c2->next)
892             {
893               if (c2->control_type == while_stepping_control)
894                 error (_("The 'while-stepping' command cannot be nested"));
895             }
896         }
897     }
898   else
899     {
900       check_no_tracepoint_commands (commands);
901     }
902 }
903
904 /* Return a vector of all the static tracepoints set at ADDR.  The
905    caller is responsible for releasing the vector.  */
906
907 VEC(breakpoint_p) *
908 static_tracepoints_here (CORE_ADDR addr)
909 {
910   struct breakpoint *b;
911   VEC(breakpoint_p) *found = 0;
912   struct bp_location *loc;
913
914   ALL_BREAKPOINTS (b)
915     if (b->type == bp_static_tracepoint)
916       {
917         for (loc = b->loc; loc; loc = loc->next)
918           if (loc->address == addr)
919             VEC_safe_push(breakpoint_p, found, b);
920       }
921
922   return found;
923 }
924
925 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
926    validate that only allowed commands are included.
927 */
928
929 void
930 breakpoint_set_commands (struct breakpoint *b, struct command_line *commands)
931 {
932   validate_commands_for_breakpoint (b, commands);
933
934   decref_counted_command_line (&b->commands);
935   b->commands = alloc_counted_command_line (commands);
936   breakpoints_changed ();
937   observer_notify_breakpoint_modified (b->number);
938 }
939
940 void
941 check_tracepoint_command (char *line, void *closure)
942 {
943   struct breakpoint *b = closure;
944
945   validate_actionline (&line, b);
946 }
947
948 /* A structure used to pass information through
949    map_breakpoint_numbers.  */
950
951 struct commands_info
952 {
953   /* True if the command was typed at a tty.  */
954   int from_tty;
955
956   /* The breakpoint range spec.  */
957   char *arg;
958
959   /* Non-NULL if the body of the commands are being read from this
960      already-parsed command.  */
961   struct command_line *control;
962
963   /* The command lines read from the user, or NULL if they have not
964      yet been read.  */
965   struct counted_command_line *cmd;
966 };
967
968 /* A callback for map_breakpoint_numbers that sets the commands for
969    commands_command.  */
970
971 static void
972 do_map_commands_command (struct breakpoint *b, void *data)
973 {
974   struct commands_info *info = data;
975
976   if (info->cmd == NULL)
977     {
978       struct command_line *l;
979
980       if (info->control != NULL)
981         l = copy_command_lines (info->control->body_list[0]);
982       else
983         {
984           struct cleanup *old_chain;
985           char *str;
986
987           str = xstrprintf (_("Type commands for breakpoint(s) %s, one per line."),
988                             info->arg);
989
990           old_chain = make_cleanup (xfree, str);
991
992           l = read_command_lines (str,
993                                   info->from_tty, 1,
994                                   (is_tracepoint (b)
995                                    ? check_tracepoint_command : 0),
996                                   b);
997
998           do_cleanups (old_chain);
999         }
1000
1001       info->cmd = alloc_counted_command_line (l);
1002     }
1003
1004   /* If a breakpoint was on the list more than once, we don't need to
1005      do anything.  */
1006   if (b->commands != info->cmd)
1007     {
1008       validate_commands_for_breakpoint (b, info->cmd->commands);
1009       incref_counted_command_line (info->cmd);
1010       decref_counted_command_line (&b->commands);
1011       b->commands = info->cmd;
1012       breakpoints_changed ();
1013       observer_notify_breakpoint_modified (b->number);
1014     }
1015 }
1016
1017 static void
1018 commands_command_1 (char *arg, int from_tty, struct command_line *control)
1019 {
1020   struct cleanup *cleanups;
1021   struct commands_info info;
1022
1023   info.from_tty = from_tty;
1024   info.control = control;
1025   info.cmd = NULL;
1026   /* If we read command lines from the user, then `info' will hold an
1027      extra reference to the commands that we must clean up.  */
1028   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1029
1030   if (arg == NULL || !*arg)
1031     {
1032       if (breakpoint_count - prev_breakpoint_count > 1)
1033         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, breakpoint_count);
1034       else if (breakpoint_count > 0)
1035         arg = xstrprintf ("%d", breakpoint_count);
1036       else
1037         {
1038           /* So that we don't try to free the incoming non-NULL
1039              argument in the cleanup below.  Mapping breakpoint
1040              numbers will fail in this case.  */
1041           arg = NULL;
1042         }
1043     }
1044   else
1045     /* The command loop has some static state, so we need to preserve
1046        our argument.  */
1047     arg = xstrdup (arg);
1048
1049   if (arg != NULL)
1050     make_cleanup (xfree, arg);
1051
1052   info.arg = arg;
1053
1054   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1055
1056   if (info.cmd == NULL)
1057     error (_("No breakpoints specified."));
1058
1059   do_cleanups (cleanups);
1060 }
1061
1062 static void
1063 commands_command (char *arg, int from_tty)
1064 {
1065   commands_command_1 (arg, from_tty, NULL);
1066 }
1067
1068 /* Like commands_command, but instead of reading the commands from
1069    input stream, takes them from an already parsed command structure.
1070
1071    This is used by cli-script.c to DTRT with breakpoint commands
1072    that are part of if and while bodies.  */
1073 enum command_control_type
1074 commands_from_control_command (char *arg, struct command_line *cmd)
1075 {
1076   commands_command_1 (arg, 0, cmd);
1077   return simple_control;
1078 }
1079
1080 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1081
1082 static int
1083 bp_location_has_shadow (struct bp_location *bl)
1084 {
1085   if (bl->loc_type != bp_loc_software_breakpoint)
1086     return 0;
1087   if (!bl->inserted)
1088     return 0;
1089   if (bl->target_info.shadow_len == 0)
1090     /* bp isn't valid, or doesn't shadow memory.  */
1091     return 0;
1092   return 1;
1093 }
1094
1095 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1096    by replacing any memory breakpoints with their shadowed contents.
1097
1098    The range of shadowed area by each bp_location is:
1099      b->address - bp_location_placed_address_before_address_max
1100      up to b->address + bp_location_shadow_len_after_address_max
1101    The range we were requested to resolve shadows for is:
1102      memaddr ... memaddr + len
1103    Thus the safe cutoff boundaries for performance optimization are
1104      memaddr + len <= b->address - bp_location_placed_address_before_address_max
1105    and:
1106      b->address + bp_location_shadow_len_after_address_max <= memaddr  */
1107
1108 void
1109 breakpoint_restore_shadows (gdb_byte *buf, ULONGEST memaddr, LONGEST len)
1110 {
1111   /* Left boundary, right boundary and median element of our binary search.  */
1112   unsigned bc_l, bc_r, bc;
1113
1114   /* Find BC_L which is a leftmost element which may affect BUF content.  It is
1115      safe to report lower value but a failure to report higher one.  */
1116
1117   bc_l = 0;
1118   bc_r = bp_location_count;
1119   while (bc_l + 1 < bc_r)
1120     {
1121       struct bp_location *b;
1122
1123       bc = (bc_l + bc_r) / 2;
1124       b = bp_location[bc];
1125
1126       /* Check first B->ADDRESS will not overflow due to the added constant.
1127          Then advance the left boundary only if we are sure the BC element can
1128          in no way affect the BUF content (MEMADDR to MEMADDR + LEN range).
1129
1130          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety offset so that
1131          we cannot miss a breakpoint with its shadow range tail still reaching
1132          MEMADDR.  */
1133
1134       if (b->address + bp_location_shadow_len_after_address_max >= b->address
1135           && b->address + bp_location_shadow_len_after_address_max <= memaddr)
1136         bc_l = bc;
1137       else
1138         bc_r = bc;
1139     }
1140
1141   /* Now do full processing of the found relevant range of elements.  */
1142
1143   for (bc = bc_l; bc < bp_location_count; bc++)
1144   {
1145     struct bp_location *b = bp_location[bc];
1146     CORE_ADDR bp_addr = 0;
1147     int bp_size = 0;
1148     int bptoffset = 0;
1149
1150     /* bp_location array has B->OWNER always non-NULL.  */
1151     if (b->owner->type == bp_none)
1152       warning (_("reading through apparently deleted breakpoint #%d?"),
1153               b->owner->number);
1154
1155     /* Performance optimization: any futher element can no longer affect BUF
1156        content.  */
1157
1158     if (b->address >= bp_location_placed_address_before_address_max
1159         && memaddr + len <= b->address
1160                             - bp_location_placed_address_before_address_max)
1161       break;
1162
1163     if (!bp_location_has_shadow (b))
1164       continue;
1165     if (!breakpoint_address_match (b->target_info.placed_address_space, 0,
1166                                    current_program_space->aspace, 0))
1167       continue;
1168
1169     /* Addresses and length of the part of the breakpoint that
1170        we need to copy.  */
1171     bp_addr = b->target_info.placed_address;
1172     bp_size = b->target_info.shadow_len;
1173
1174     if (bp_addr + bp_size <= memaddr)
1175       /* The breakpoint is entirely before the chunk of memory we
1176          are reading.  */
1177       continue;
1178
1179     if (bp_addr >= memaddr + len)
1180       /* The breakpoint is entirely after the chunk of memory we are
1181          reading. */
1182       continue;
1183
1184     /* Offset within shadow_contents.  */
1185     if (bp_addr < memaddr)
1186       {
1187         /* Only copy the second part of the breakpoint.  */
1188         bp_size -= memaddr - bp_addr;
1189         bptoffset = memaddr - bp_addr;
1190         bp_addr = memaddr;
1191       }
1192
1193     if (bp_addr + bp_size > memaddr + len)
1194       {
1195         /* Only copy the first part of the breakpoint.  */
1196         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1197       }
1198
1199     memcpy (buf + bp_addr - memaddr,
1200             b->target_info.shadow_contents + bptoffset, bp_size);
1201   }
1202 }
1203 \f
1204
1205 /* A wrapper function for inserting catchpoints.  */
1206 static void
1207 insert_catchpoint (struct ui_out *uo, void *args)
1208 {
1209   struct breakpoint *b = (struct breakpoint *) args;
1210
1211   gdb_assert (b->type == bp_catchpoint);
1212   gdb_assert (b->ops != NULL && b->ops->insert != NULL);
1213
1214   b->ops->insert (b);
1215 }
1216
1217 /* Return true if BPT is of any hardware watchpoint kind.  */
1218
1219 static int
1220 is_hardware_watchpoint (const struct breakpoint *bpt)
1221 {
1222   return (bpt->type == bp_hardware_watchpoint
1223           || bpt->type == bp_read_watchpoint
1224           || bpt->type == bp_access_watchpoint);
1225 }
1226
1227 /* Return true if BPT is of any watchpoint kind, hardware or
1228    software.  */
1229
1230 static int
1231 is_watchpoint (const struct breakpoint *bpt)
1232 {
1233   return (is_hardware_watchpoint (bpt)
1234           || bpt->type == bp_watchpoint);
1235 }
1236
1237 /* 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 /* Print B to gdb_stdout. */
4437 static void
4438 print_one_breakpoint_location (struct breakpoint *b,
4439                                struct bp_location *loc,
4440                                int loc_number,
4441                                struct bp_location **last_loc,
4442                                int print_address_bits,
4443                                int allflag)
4444 {
4445   struct command_line *l;
4446   struct ep_type_description
4447     {
4448       enum bptype type;
4449       char *description;
4450     };
4451   static struct ep_type_description bptypes[] =
4452   {
4453     {bp_none, "?deleted?"},
4454     {bp_breakpoint, "breakpoint"},
4455     {bp_hardware_breakpoint, "hw breakpoint"},
4456     {bp_until, "until"},
4457     {bp_finish, "finish"},
4458     {bp_watchpoint, "watchpoint"},
4459     {bp_hardware_watchpoint, "hw watchpoint"},
4460     {bp_read_watchpoint, "read watchpoint"},
4461     {bp_access_watchpoint, "acc watchpoint"},
4462     {bp_longjmp, "longjmp"},
4463     {bp_longjmp_resume, "longjmp resume"},
4464     {bp_step_resume, "step resume"},
4465     {bp_watchpoint_scope, "watchpoint scope"},
4466     {bp_call_dummy, "call dummy"},
4467     {bp_std_terminate, "std::terminate"},
4468     {bp_shlib_event, "shlib events"},
4469     {bp_thread_event, "thread events"},
4470     {bp_overlay_event, "overlay events"},
4471     {bp_longjmp_master, "longjmp master"},
4472     {bp_std_terminate_master, "std::terminate master"},
4473     {bp_catchpoint, "catchpoint"},
4474     {bp_tracepoint, "tracepoint"},
4475     {bp_fast_tracepoint, "fast tracepoint"},
4476     {bp_static_tracepoint, "static tracepoint"},
4477     {bp_jit_event, "jit events"},
4478   };
4479   
4480   static char bpenables[] = "nynny";
4481   char wrap_indent[80];
4482   struct ui_stream *stb = ui_out_stream_new (uiout);
4483   struct cleanup *old_chain = make_cleanup_ui_out_stream_delete (stb);
4484   struct cleanup *bkpt_chain;
4485
4486   int header_of_multiple = 0;
4487   int part_of_multiple = (loc != NULL);
4488   struct value_print_options opts;
4489
4490   get_user_print_options (&opts);
4491
4492   gdb_assert (!loc || loc_number != 0);
4493   /* See comment in print_one_breakpoint concerning
4494      treatment of breakpoints with single disabled
4495      location.  */
4496   if (loc == NULL 
4497       && (b->loc != NULL 
4498           && (b->loc->next != NULL || !b->loc->enabled)))
4499     header_of_multiple = 1;
4500   if (loc == NULL)
4501     loc = b->loc;
4502
4503   annotate_record ();
4504   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
4505
4506   /* 1 */
4507   annotate_field (0);
4508   if (part_of_multiple)
4509     {
4510       char *formatted;
4511       formatted = xstrprintf ("%d.%d", b->number, loc_number);
4512       ui_out_field_string (uiout, "number", formatted);
4513       xfree (formatted);
4514     }
4515   else
4516     {
4517       ui_out_field_int (uiout, "number", b->number);
4518     }
4519
4520   /* 2 */
4521   annotate_field (1);
4522   if (part_of_multiple)
4523     ui_out_field_skip (uiout, "type");
4524   else 
4525     {
4526       if (((int) b->type >= (sizeof (bptypes) / sizeof (bptypes[0])))
4527           || ((int) b->type != bptypes[(int) b->type].type))
4528         internal_error (__FILE__, __LINE__,
4529                         _("bptypes table does not describe type #%d."),
4530                         (int) b->type);
4531       ui_out_field_string (uiout, "type", bptypes[(int) b->type].description);
4532     }
4533
4534   /* 3 */
4535   annotate_field (2);
4536   if (part_of_multiple)
4537     ui_out_field_skip (uiout, "disp");
4538   else
4539     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
4540
4541
4542   /* 4 */
4543   annotate_field (3);
4544   if (part_of_multiple)
4545     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
4546   else
4547       ui_out_field_fmt (uiout, "enabled", "%c", 
4548                         bpenables[(int) b->enable_state]);
4549   ui_out_spaces (uiout, 2);
4550
4551   
4552   /* 5 and 6 */
4553   strcpy (wrap_indent, "                           ");
4554   if (opts.addressprint)
4555     {
4556       if (print_address_bits <= 32)
4557         strcat (wrap_indent, "           ");
4558       else
4559         strcat (wrap_indent, "                   ");
4560     }
4561
4562   if (b->ops != NULL && b->ops->print_one != NULL)
4563     {
4564       /* Although the print_one can possibly print
4565          all locations,  calling it here is not likely
4566          to get any nice result.  So, make sure there's
4567          just one location.  */
4568       gdb_assert (b->loc == NULL || b->loc->next == NULL);
4569       b->ops->print_one (b, last_loc);
4570     }
4571   else
4572     switch (b->type)
4573       {
4574       case bp_none:
4575         internal_error (__FILE__, __LINE__,
4576                         _("print_one_breakpoint: bp_none encountered\n"));
4577         break;
4578
4579       case bp_watchpoint:
4580       case bp_hardware_watchpoint:
4581       case bp_read_watchpoint:
4582       case bp_access_watchpoint:
4583         /* Field 4, the address, is omitted (which makes the columns
4584            not line up too nicely with the headers, but the effect
4585            is relatively readable).  */
4586         if (opts.addressprint)
4587           ui_out_field_skip (uiout, "addr");
4588         annotate_field (5);
4589         ui_out_field_string (uiout, "what", b->exp_string);
4590         break;
4591
4592       case bp_breakpoint:
4593       case bp_hardware_breakpoint:
4594       case bp_until:
4595       case bp_finish:
4596       case bp_longjmp:
4597       case bp_longjmp_resume:
4598       case bp_step_resume:
4599       case bp_watchpoint_scope:
4600       case bp_call_dummy:
4601       case bp_std_terminate:
4602       case bp_shlib_event:
4603       case bp_thread_event:
4604       case bp_overlay_event:
4605       case bp_longjmp_master:
4606       case bp_std_terminate_master:
4607       case bp_tracepoint:
4608       case bp_fast_tracepoint:
4609       case bp_static_tracepoint:
4610       case bp_jit_event:
4611         if (opts.addressprint)
4612           {
4613             annotate_field (4);
4614             if (header_of_multiple)
4615               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
4616             else if (b->loc == NULL || loc->shlib_disabled)
4617               ui_out_field_string (uiout, "addr", "<PENDING>");
4618             else
4619               ui_out_field_core_addr (uiout, "addr",
4620                                       loc->gdbarch, loc->address);
4621           }
4622         annotate_field (5);
4623         if (!header_of_multiple)
4624           print_breakpoint_location (b, loc, wrap_indent, stb);
4625         if (b->loc)
4626           *last_loc = b->loc;
4627         break;
4628       }
4629
4630
4631   /* For backward compatibility, don't display inferiors unless there
4632      are several.  */
4633   if (loc != NULL
4634       && !header_of_multiple
4635       && (allflag
4636           || (!gdbarch_has_global_breakpoints (target_gdbarch)
4637               && (number_of_program_spaces () > 1
4638                   || number_of_inferiors () > 1)
4639               /* LOC is for existing B, it cannot be in moribund_locations and
4640                  thus having NULL OWNER.  */
4641               && loc->owner->type != bp_catchpoint)))
4642     {
4643       struct inferior *inf;
4644       int first = 1;
4645
4646       for (inf = inferior_list; inf != NULL; inf = inf->next)
4647         {
4648           if (inf->pspace == loc->pspace)
4649             {
4650               if (first)
4651                 {
4652                   first = 0;
4653                   ui_out_text (uiout, " inf ");
4654                 }
4655               else
4656                 ui_out_text (uiout, ", ");
4657               ui_out_text (uiout, plongest (inf->num));
4658             }
4659         }
4660     }
4661
4662   if (!part_of_multiple)
4663     {
4664       if (b->thread != -1)
4665         {
4666           /* FIXME: This seems to be redundant and lost here; see the
4667              "stop only in" line a little further down. */
4668           ui_out_text (uiout, " thread ");
4669           ui_out_field_int (uiout, "thread", b->thread);
4670         }
4671       else if (b->task != 0)
4672         {
4673           ui_out_text (uiout, " task ");
4674           ui_out_field_int (uiout, "task", b->task);
4675         }
4676     }
4677   
4678   ui_out_text (uiout, "\n");
4679   
4680   if (!part_of_multiple && b->static_trace_marker_id)
4681     {
4682       gdb_assert (b->type == bp_static_tracepoint);
4683
4684       ui_out_text (uiout, "\tmarker id is ");
4685       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
4686                            b->static_trace_marker_id);
4687       ui_out_text (uiout, "\n");
4688     }
4689
4690   if (part_of_multiple && frame_id_p (b->frame_id))
4691     {
4692       annotate_field (6);
4693       ui_out_text (uiout, "\tstop only in stack frame at ");
4694       /* FIXME: cagney/2002-12-01: Shouldn't be poeking around inside
4695          the frame ID.  */
4696       ui_out_field_core_addr (uiout, "frame",
4697                               b->gdbarch, b->frame_id.stack_addr);
4698       ui_out_text (uiout, "\n");
4699     }
4700   
4701   if (!part_of_multiple && b->cond_string && !ada_exception_catchpoint_p (b))
4702     {
4703       /* We do not print the condition for Ada exception catchpoints
4704          because the condition is an internal implementation detail
4705          that we do not want to expose to the user.  */
4706       annotate_field (7);
4707       if (is_tracepoint (b))
4708         ui_out_text (uiout, "\ttrace only if ");
4709       else
4710         ui_out_text (uiout, "\tstop only if ");
4711       ui_out_field_string (uiout, "cond", b->cond_string);
4712       ui_out_text (uiout, "\n");
4713     }
4714
4715   if (!part_of_multiple && b->thread != -1)
4716     {
4717       /* FIXME should make an annotation for this */
4718       ui_out_text (uiout, "\tstop only in thread ");
4719       ui_out_field_int (uiout, "thread", b->thread);
4720       ui_out_text (uiout, "\n");
4721     }
4722   
4723   if (!part_of_multiple && b->hit_count)
4724     {
4725       /* FIXME should make an annotation for this */
4726       if (ep_is_catchpoint (b))
4727         ui_out_text (uiout, "\tcatchpoint");
4728       else
4729         ui_out_text (uiout, "\tbreakpoint");
4730       ui_out_text (uiout, " already hit ");
4731       ui_out_field_int (uiout, "times", b->hit_count);
4732       if (b->hit_count == 1)
4733         ui_out_text (uiout, " time\n");
4734       else
4735         ui_out_text (uiout, " times\n");
4736     }
4737   
4738   /* Output the count also if it is zero, but only if this is
4739      mi. FIXME: Should have a better test for this. */
4740   if (ui_out_is_mi_like_p (uiout))
4741     if (!part_of_multiple && b->hit_count == 0)
4742       ui_out_field_int (uiout, "times", b->hit_count);
4743
4744   if (!part_of_multiple && b->ignore_count)
4745     {
4746       annotate_field (8);
4747       ui_out_text (uiout, "\tignore next ");
4748       ui_out_field_int (uiout, "ignore", b->ignore_count);
4749       ui_out_text (uiout, " hits\n");
4750     }
4751
4752   l = b->commands ? b->commands->commands : NULL;
4753   if (!part_of_multiple && l)
4754     {
4755       struct cleanup *script_chain;
4756
4757       annotate_field (9);
4758       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
4759       print_command_lines (uiout, l, 4);
4760       do_cleanups (script_chain);
4761     }
4762
4763   if (!part_of_multiple && b->pass_count)
4764     {
4765       annotate_field (10);
4766       ui_out_text (uiout, "\tpass count ");
4767       ui_out_field_int (uiout, "pass", b->pass_count);
4768       ui_out_text (uiout, " \n");
4769     }
4770
4771   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
4772     {
4773       if (b->addr_string)
4774         ui_out_field_string (uiout, "original-location", b->addr_string);
4775       else if (b->exp_string)
4776         ui_out_field_string (uiout, "original-location", b->exp_string);
4777     }
4778         
4779   do_cleanups (bkpt_chain);
4780   do_cleanups (old_chain);
4781 }
4782
4783 static void
4784 print_one_breakpoint (struct breakpoint *b,
4785                       struct bp_location **last_loc, int print_address_bits,
4786                       int allflag)
4787 {
4788   print_one_breakpoint_location (b, NULL, 0, last_loc,
4789                                  print_address_bits, allflag);
4790
4791   /* If this breakpoint has custom print function,
4792      it's already printed.  Otherwise, print individual
4793      locations, if any.  */
4794   if (b->ops == NULL || b->ops->print_one == NULL)
4795     {
4796       /* If breakpoint has a single location that is
4797          disabled, we print it as if it had
4798          several locations, since otherwise it's hard to
4799          represent "breakpoint enabled, location disabled"
4800          situation.  
4801          Note that while hardware watchpoints have
4802          several locations internally, that's no a property
4803          exposed to user.  */
4804       if (b->loc 
4805           && !is_hardware_watchpoint (b)
4806           && (b->loc->next || !b->loc->enabled)
4807           && !ui_out_is_mi_like_p (uiout)) 
4808         {
4809           struct bp_location *loc;
4810           int n = 1;
4811           for (loc = b->loc; loc; loc = loc->next, ++n)
4812             print_one_breakpoint_location (b, loc, n, last_loc,
4813                                            print_address_bits, allflag);
4814         }
4815     }
4816 }
4817
4818 static int
4819 breakpoint_address_bits (struct breakpoint *b)
4820 {
4821   int print_address_bits = 0;
4822   struct bp_location *loc;
4823
4824   for (loc = b->loc; loc; loc = loc->next)
4825     {
4826       int addr_bit;
4827
4828       /* Software watchpoints that aren't watching memory don't have
4829          an address to print.  */
4830       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
4831         continue;
4832
4833       addr_bit = gdbarch_addr_bit (loc->gdbarch);
4834       if (addr_bit > print_address_bits)
4835         print_address_bits = addr_bit;
4836     }
4837
4838   return print_address_bits;
4839 }
4840
4841 struct captured_breakpoint_query_args
4842   {
4843     int bnum;
4844   };
4845
4846 static int
4847 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
4848 {
4849   struct captured_breakpoint_query_args *args = data;
4850   struct breakpoint *b;
4851   struct bp_location *dummy_loc = NULL;
4852
4853   ALL_BREAKPOINTS (b)
4854     {
4855       if (args->bnum == b->number)
4856         {
4857           int print_address_bits = breakpoint_address_bits (b);
4858
4859           print_one_breakpoint (b, &dummy_loc, print_address_bits, 0);
4860           return GDB_RC_OK;
4861         }
4862     }
4863   return GDB_RC_NONE;
4864 }
4865
4866 enum gdb_rc
4867 gdb_breakpoint_query (struct ui_out *uiout, int bnum, char **error_message)
4868 {
4869   struct captured_breakpoint_query_args args;
4870
4871   args.bnum = bnum;
4872   /* For the moment we don't trust print_one_breakpoint() to not throw
4873      an error. */
4874   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
4875                                  error_message, RETURN_MASK_ALL) < 0)
4876     return GDB_RC_FAIL;
4877   else
4878     return GDB_RC_OK;
4879 }
4880
4881 /* Return non-zero if B is user settable (breakpoints, watchpoints,
4882    catchpoints, et.al.). */
4883
4884 static int
4885 user_settable_breakpoint (const struct breakpoint *b)
4886 {
4887   return (b->type == bp_breakpoint
4888           || b->type == bp_catchpoint
4889           || b->type == bp_hardware_breakpoint
4890           || is_tracepoint (b)
4891           || is_watchpoint (b));
4892 }
4893         
4894 /* Print information on user settable breakpoint (watchpoint, etc)
4895    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
4896    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
4897    FILTER is non-NULL, call it on each breakpoint and only include the
4898    ones for which it returns non-zero.  Return the total number of
4899    breakpoints listed.  */
4900
4901 static int
4902 breakpoint_1 (int bnum, int allflag, int (*filter) (const struct breakpoint *))
4903 {
4904   struct breakpoint *b;
4905   struct bp_location *last_loc = NULL;
4906   int nr_printable_breakpoints;
4907   struct cleanup *bkpttbl_chain;
4908   struct value_print_options opts;
4909   int print_address_bits = 0;
4910   
4911   get_user_print_options (&opts);
4912
4913   /* Compute the number of rows in the table, as well as the
4914      size required for address fields.  */
4915   nr_printable_breakpoints = 0;
4916   ALL_BREAKPOINTS (b)
4917     if (bnum == -1
4918         || bnum == b->number)
4919       {
4920         /* If we have a filter, only list the breakpoints it accepts.  */
4921         if (filter && !filter (b))
4922           continue;
4923         
4924         if (allflag || user_settable_breakpoint (b))
4925           {
4926             int addr_bit = breakpoint_address_bits (b);
4927             if (addr_bit > print_address_bits)
4928               print_address_bits = addr_bit;
4929
4930             nr_printable_breakpoints++;
4931           }
4932       }
4933
4934   if (opts.addressprint)
4935     bkpttbl_chain 
4936       = make_cleanup_ui_out_table_begin_end (uiout, 6, nr_printable_breakpoints,
4937                                              "BreakpointTable");
4938   else
4939     bkpttbl_chain 
4940       = make_cleanup_ui_out_table_begin_end (uiout, 5, nr_printable_breakpoints,
4941                                              "BreakpointTable");
4942
4943   if (nr_printable_breakpoints > 0)
4944     annotate_breakpoints_headers ();
4945   if (nr_printable_breakpoints > 0)
4946     annotate_field (0);
4947   ui_out_table_header (uiout, 7, ui_left, "number", "Num");             /* 1 */
4948   if (nr_printable_breakpoints > 0)
4949     annotate_field (1);
4950   ui_out_table_header (uiout, 14, ui_left, "type", "Type");             /* 2 */
4951   if (nr_printable_breakpoints > 0)
4952     annotate_field (2);
4953   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");              /* 3 */
4954   if (nr_printable_breakpoints > 0)
4955     annotate_field (3);
4956   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
4957   if (opts.addressprint)
4958         {
4959           if (nr_printable_breakpoints > 0)
4960             annotate_field (4);
4961           if (print_address_bits <= 32)
4962             ui_out_table_header (uiout, 10, ui_left, "addr", "Address");/* 5 */
4963           else
4964             ui_out_table_header (uiout, 18, ui_left, "addr", "Address");/* 5 */
4965         }
4966   if (nr_printable_breakpoints > 0)
4967     annotate_field (5);
4968   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
4969   ui_out_table_body (uiout);
4970   if (nr_printable_breakpoints > 0)
4971     annotate_breakpoints_table ();
4972
4973   ALL_BREAKPOINTS (b)
4974   {
4975     QUIT;
4976     if (bnum == -1
4977         || bnum == b->number)
4978       {
4979         /* If we have a filter, only list the breakpoints it accepts.  */
4980         if (filter && !filter (b))
4981           continue;
4982         
4983         /* We only print out user settable breakpoints unless the
4984            allflag is set. */
4985         if (allflag || user_settable_breakpoint (b))
4986           print_one_breakpoint (b, &last_loc, print_address_bits, allflag);
4987       }
4988   }
4989   
4990   do_cleanups (bkpttbl_chain);
4991
4992   if (nr_printable_breakpoints == 0)
4993     {
4994       /* If there's a filter, let the caller decide how to report empty list.  */
4995       if (!filter)
4996         {
4997           if (bnum == -1)
4998             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
4999           else
5000             ui_out_message (uiout, 0, "No breakpoint or watchpoint number %d.\n",
5001                             bnum);
5002         }
5003     }
5004   else
5005     {
5006       if (last_loc && !server_command)
5007         set_next_address (last_loc->gdbarch, last_loc->address);
5008     }
5009
5010   /* FIXME? Should this be moved up so that it is only called when
5011      there have been breakpoints? */
5012   annotate_breakpoints_table_end ();
5013
5014   return nr_printable_breakpoints;
5015 }
5016
5017 /* Display the value of default-collect in a way that is generally
5018    compatible with the breakpoint list.  */
5019
5020 static void
5021 default_collect_info (void)
5022 {
5023   /* If it has no value (which is frequently the case), say nothing; a
5024      message like "No default-collect." gets in user's face when it's
5025      not wanted.  */
5026   if (!*default_collect)
5027     return;
5028
5029   /* The following phrase lines up nicely with per-tracepoint collect
5030      actions.  */
5031   ui_out_text (uiout, "default collect ");
5032   ui_out_field_string (uiout, "default-collect", default_collect);
5033   ui_out_text (uiout, " \n");
5034 }
5035   
5036 static void
5037 breakpoints_info (char *bnum_exp, int from_tty)
5038 {
5039   int bnum = -1;
5040
5041   if (bnum_exp)
5042     bnum = parse_and_eval_long (bnum_exp);
5043
5044   breakpoint_1 (bnum, 0, NULL);
5045
5046   default_collect_info ();
5047 }
5048
5049 static void
5050 watchpoints_info (char *wpnum_exp, int from_tty)
5051 {
5052   int wpnum = -1, num_printed;
5053
5054   if (wpnum_exp)
5055     wpnum = parse_and_eval_long (wpnum_exp);
5056
5057   num_printed = breakpoint_1 (wpnum, 0, is_watchpoint);
5058
5059   if (num_printed == 0)
5060     {
5061       if (wpnum == -1)
5062         ui_out_message (uiout, 0, "No watchpoints.\n");
5063       else
5064         ui_out_message (uiout, 0, "No watchpoint number %d.\n", wpnum);
5065     }
5066 }
5067
5068 static void
5069 maintenance_info_breakpoints (char *bnum_exp, int from_tty)
5070 {
5071   int bnum = -1;
5072
5073   if (bnum_exp)
5074     bnum = parse_and_eval_long (bnum_exp);
5075
5076   breakpoint_1 (bnum, 1, NULL);
5077
5078   default_collect_info ();
5079 }
5080
5081 static int
5082 breakpoint_has_pc (struct breakpoint *b,
5083                    struct program_space *pspace,
5084                    CORE_ADDR pc, struct obj_section *section)
5085 {
5086   struct bp_location *bl = b->loc;
5087
5088   for (; bl; bl = bl->next)
5089     {
5090       if (bl->pspace == pspace
5091           && bl->address == pc
5092           && (!overlay_debugging || bl->section == section))
5093         return 1;         
5094     }
5095   return 0;
5096 }
5097
5098 /* Print a message describing any breakpoints set at PC.  This
5099    concerns with logical breakpoints, so we match program spaces, not
5100    address spaces.  */
5101
5102 static void
5103 describe_other_breakpoints (struct gdbarch *gdbarch,
5104                             struct program_space *pspace, CORE_ADDR pc,
5105                             struct obj_section *section, int thread)
5106 {
5107   int others = 0;
5108   struct breakpoint *b;
5109
5110   ALL_BREAKPOINTS (b)
5111     others += breakpoint_has_pc (b, pspace, pc, section);
5112   if (others > 0)
5113     {
5114       if (others == 1)
5115         printf_filtered (_("Note: breakpoint "));
5116       else /* if (others == ???) */
5117         printf_filtered (_("Note: breakpoints "));
5118       ALL_BREAKPOINTS (b)
5119         if (breakpoint_has_pc (b, pspace, pc, section))
5120           {
5121             others--;
5122             printf_filtered ("%d", b->number);
5123             if (b->thread == -1 && thread != -1)
5124               printf_filtered (" (all threads)");
5125             else if (b->thread != -1)
5126               printf_filtered (" (thread %d)", b->thread);
5127             printf_filtered ("%s%s ",
5128                              ((b->enable_state == bp_disabled
5129                                || b->enable_state == bp_call_disabled
5130                                || b->enable_state == bp_startup_disabled)
5131                               ? " (disabled)"
5132                               : b->enable_state == bp_permanent 
5133                               ? " (permanent)"
5134                               : ""),
5135                              (others > 1) ? "," 
5136                              : ((others == 1) ? " and" : ""));
5137           }
5138       printf_filtered (_("also set at pc "));
5139       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
5140       printf_filtered (".\n");
5141     }
5142 }
5143 \f
5144 /* Set the default place to put a breakpoint
5145    for the `break' command with no arguments.  */
5146
5147 void
5148 set_default_breakpoint (int valid, struct program_space *pspace,
5149                         CORE_ADDR addr, struct symtab *symtab,
5150                         int line)
5151 {
5152   default_breakpoint_valid = valid;
5153   default_breakpoint_pspace = pspace;
5154   default_breakpoint_address = addr;
5155   default_breakpoint_symtab = symtab;
5156   default_breakpoint_line = line;
5157 }
5158
5159 /* Return true iff it is meaningful to use the address member of
5160    BPT.  For some breakpoint types, the address member is irrelevant
5161    and it makes no sense to attempt to compare it to other addresses
5162    (or use it for any other purpose either).
5163
5164    More specifically, each of the following breakpoint types will always
5165    have a zero valued address and we don't want to mark breakpoints of any of
5166    these types to be a duplicate of an actual breakpoint at address zero:
5167
5168       bp_watchpoint
5169       bp_catchpoint
5170
5171 */
5172
5173 static int
5174 breakpoint_address_is_meaningful (struct breakpoint *bpt)
5175 {
5176   enum bptype type = bpt->type;
5177
5178   return (type != bp_watchpoint && type != bp_catchpoint);
5179 }
5180
5181 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
5182    true if LOC1 and LOC2 represent the same watchpoint location.  */
5183
5184 static int
5185 watchpoint_locations_match (struct bp_location *loc1, struct bp_location *loc2)
5186 {
5187   /* Both of them must not be in moribund_locations.  */
5188   gdb_assert (loc1->owner != NULL);
5189   gdb_assert (loc2->owner != NULL);
5190
5191   /* If the target can evaluate the condition expression in hardware, then we
5192      we need to insert both watchpoints even if they are at the same place.
5193      Otherwise the watchpoint will only trigger when the condition of whichever
5194      watchpoint was inserted evaluates to true, not giving a chance for GDB to
5195      check the condition of the other watchpoint.  */
5196   if ((loc1->owner->cond_exp
5197        && target_can_accel_watchpoint_condition (loc1->address, loc1->length,
5198                                                  loc1->watchpoint_type,
5199                                                  loc1->owner->cond_exp))
5200       || (loc2->owner->cond_exp
5201           && target_can_accel_watchpoint_condition (loc2->address, loc2->length,
5202                                                     loc2->watchpoint_type,
5203                                                     loc2->owner->cond_exp)))
5204     return 0;
5205
5206   /* Note that this checks the owner's type, not the location's.  In
5207      case the target does not support read watchpoints, but does
5208      support access watchpoints, we'll have bp_read_watchpoint
5209      watchpoints with hw_access locations.  Those should be considered
5210      duplicates of hw_read locations.  The hw_read locations will
5211      become hw_access locations later.  */
5212   return (loc1->owner->type == loc2->owner->type
5213           && loc1->pspace->aspace == loc2->pspace->aspace
5214           && loc1->address == loc2->address
5215           && loc1->length == loc2->length);
5216 }
5217
5218 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
5219    same breakpoint location.  In most targets, this can only be true
5220    if ASPACE1 matches ASPACE2.  On targets that have global
5221    breakpoints, the address space doesn't really matter.  */
5222
5223 static int
5224 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
5225                           struct address_space *aspace2, CORE_ADDR addr2)
5226 {
5227   return ((gdbarch_has_global_breakpoints (target_gdbarch)
5228            || aspace1 == aspace2)
5229           && addr1 == addr2);
5230 }
5231
5232 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
5233    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
5234    represent the same location.  */
5235
5236 static int
5237 breakpoint_locations_match (struct bp_location *loc1, struct bp_location *loc2)
5238 {
5239   int hw_point1, hw_point2;
5240
5241   /* Both of them must not be in moribund_locations.  */
5242   gdb_assert (loc1->owner != NULL);
5243   gdb_assert (loc2->owner != NULL);
5244
5245   hw_point1 = is_hardware_watchpoint (loc1->owner);
5246   hw_point2 = is_hardware_watchpoint (loc2->owner);
5247
5248   if (hw_point1 != hw_point2)
5249     return 0;
5250   else if (hw_point1)
5251     return watchpoint_locations_match (loc1, loc2);
5252   else
5253     return breakpoint_address_match (loc1->pspace->aspace, loc1->address,
5254                                      loc2->pspace->aspace, loc2->address);
5255 }
5256
5257 static void
5258 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
5259                                int bnum, int have_bnum)
5260 {
5261   char astr1[40];
5262   char astr2[40];
5263
5264   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
5265   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
5266   if (have_bnum)
5267     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
5268              bnum, astr1, astr2);
5269   else
5270     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
5271 }
5272
5273 /* Adjust a breakpoint's address to account for architectural constraints
5274    on breakpoint placement.  Return the adjusted address.  Note: Very
5275    few targets require this kind of adjustment.  For most targets,
5276    this function is simply the identity function.  */
5277
5278 static CORE_ADDR
5279 adjust_breakpoint_address (struct gdbarch *gdbarch,
5280                            CORE_ADDR bpaddr, enum bptype bptype)
5281 {
5282   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
5283     {
5284       /* Very few targets need any kind of breakpoint adjustment.  */
5285       return bpaddr;
5286     }
5287   else if (bptype == bp_watchpoint
5288            || bptype == bp_hardware_watchpoint
5289            || bptype == bp_read_watchpoint
5290            || bptype == bp_access_watchpoint
5291            || bptype == bp_catchpoint)
5292     {
5293       /* Watchpoints and the various bp_catch_* eventpoints should not
5294          have their addresses modified.  */
5295       return bpaddr;
5296     }
5297   else
5298     {
5299       CORE_ADDR adjusted_bpaddr;
5300
5301       /* Some targets have architectural constraints on the placement
5302          of breakpoint instructions.  Obtain the adjusted address.  */
5303       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
5304
5305       /* An adjusted breakpoint address can significantly alter
5306          a user's expectations.  Print a warning if an adjustment
5307          is required.  */
5308       if (adjusted_bpaddr != bpaddr)
5309         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
5310
5311       return adjusted_bpaddr;
5312     }
5313 }
5314
5315 /* Allocate a struct bp_location.  */
5316
5317 static struct bp_location *
5318 allocate_bp_location (struct breakpoint *bpt)
5319 {
5320   struct bp_location *loc;
5321
5322   loc = xmalloc (sizeof (struct bp_location));
5323   memset (loc, 0, sizeof (*loc));
5324
5325   loc->owner = bpt;
5326   loc->cond = NULL;
5327   loc->shlib_disabled = 0;
5328   loc->enabled = 1;
5329
5330   switch (bpt->type)
5331     {
5332     case bp_breakpoint:
5333     case bp_until:
5334     case bp_finish:
5335     case bp_longjmp:
5336     case bp_longjmp_resume:
5337     case bp_step_resume:
5338     case bp_watchpoint_scope:
5339     case bp_call_dummy:
5340     case bp_std_terminate:
5341     case bp_shlib_event:
5342     case bp_thread_event:
5343     case bp_overlay_event:
5344     case bp_jit_event:
5345     case bp_longjmp_master:
5346     case bp_std_terminate_master:
5347       loc->loc_type = bp_loc_software_breakpoint;
5348       break;
5349     case bp_hardware_breakpoint:
5350       loc->loc_type = bp_loc_hardware_breakpoint;
5351       break;
5352     case bp_hardware_watchpoint:
5353     case bp_read_watchpoint:
5354     case bp_access_watchpoint:
5355       loc->loc_type = bp_loc_hardware_watchpoint;
5356       break;
5357     case bp_watchpoint:
5358     case bp_catchpoint:
5359     case bp_tracepoint:
5360     case bp_fast_tracepoint:
5361     case bp_static_tracepoint:
5362       loc->loc_type = bp_loc_other;
5363       break;
5364     default:
5365       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
5366     }
5367
5368   return loc;
5369 }
5370
5371 static void free_bp_location (struct bp_location *loc)
5372 {
5373   /* Be sure no bpstat's are pointing at it after it's been freed.  */
5374   /* FIXME, how can we find all bpstat's?
5375      We just check stop_bpstat for now.  Note that we cannot just
5376      remove bpstats pointing at bpt from the stop_bpstat list
5377      entirely, as breakpoint commands are associated with the bpstat;
5378      if we remove it here, then the later call to
5379          bpstat_do_actions (&stop_bpstat);
5380      in event-top.c won't do anything, and temporary breakpoints
5381      with commands won't work.  */
5382
5383   iterate_over_threads (bpstat_remove_bp_location_callback, loc);
5384
5385   if (loc->cond)
5386     xfree (loc->cond);
5387
5388   if (loc->function_name)
5389     xfree (loc->function_name);
5390   
5391   xfree (loc);
5392 }
5393
5394 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
5395    that has type BPTYPE and has no locations as yet.  */
5396 /* This function is used in gdbtk sources and thus can not be made static.  */
5397
5398 static struct breakpoint *
5399 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
5400                                      enum bptype bptype)
5401 {
5402   struct breakpoint *b, *b1;
5403
5404   b = (struct breakpoint *) xmalloc (sizeof (struct breakpoint));
5405   memset (b, 0, sizeof (*b));
5406
5407   b->type = bptype;
5408   b->gdbarch = gdbarch;
5409   b->language = current_language->la_language;
5410   b->input_radix = input_radix;
5411   b->thread = -1;
5412   b->enable_state = bp_enabled;
5413   b->next = 0;
5414   b->silent = 0;
5415   b->ignore_count = 0;
5416   b->commands = NULL;
5417   b->frame_id = null_frame_id;
5418   b->forked_inferior_pid = null_ptid;
5419   b->exec_pathname = NULL;
5420   b->syscalls_to_be_caught = NULL;
5421   b->ops = NULL;
5422   b->condition_not_parsed = 0;
5423
5424   /* Add this breakpoint to the end of the chain
5425      so that a list of breakpoints will come out in order
5426      of increasing numbers.  */
5427
5428   b1 = breakpoint_chain;
5429   if (b1 == 0)
5430     breakpoint_chain = b;
5431   else
5432     {
5433       while (b1->next)
5434         b1 = b1->next;
5435       b1->next = b;
5436     }
5437   return b;
5438 }
5439
5440 /* Initialize loc->function_name.  */
5441 static void
5442 set_breakpoint_location_function (struct bp_location *loc)
5443 {
5444   gdb_assert (loc->owner != NULL);
5445
5446   if (loc->owner->type == bp_breakpoint
5447       || loc->owner->type == bp_hardware_breakpoint
5448       || is_tracepoint (loc->owner))
5449     {
5450       find_pc_partial_function (loc->address, &(loc->function_name), 
5451                                 NULL, NULL);
5452       if (loc->function_name)
5453         loc->function_name = xstrdup (loc->function_name);
5454     }
5455 }
5456
5457 /* Attempt to determine architecture of location identified by SAL.  */
5458 static struct gdbarch *
5459 get_sal_arch (struct symtab_and_line sal)
5460 {
5461   if (sal.section)
5462     return get_objfile_arch (sal.section->objfile);
5463   if (sal.symtab)
5464     return get_objfile_arch (sal.symtab->objfile);
5465
5466   return NULL;
5467 }
5468
5469 /* set_raw_breakpoint is a low level routine for allocating and
5470    partially initializing a breakpoint of type BPTYPE.  The newly
5471    created breakpoint's address, section, source file name, and line
5472    number are provided by SAL.  The newly created and partially
5473    initialized breakpoint is added to the breakpoint chain and
5474    is also returned as the value of this function.
5475
5476    It is expected that the caller will complete the initialization of
5477    the newly created breakpoint struct as well as output any status
5478    information regarding the creation of a new breakpoint.  In
5479    particular, set_raw_breakpoint does NOT set the breakpoint
5480    number!  Care should be taken to not allow an error to occur
5481    prior to completing the initialization of the breakpoint.  If this
5482    should happen, a bogus breakpoint will be left on the chain.  */
5483
5484 struct breakpoint *
5485 set_raw_breakpoint (struct gdbarch *gdbarch,
5486                     struct symtab_and_line sal, enum bptype bptype)
5487 {
5488   struct breakpoint *b = set_raw_breakpoint_without_location (gdbarch, bptype);
5489   CORE_ADDR adjusted_address;
5490   struct gdbarch *loc_gdbarch;
5491
5492   loc_gdbarch = get_sal_arch (sal);
5493   if (!loc_gdbarch)
5494     loc_gdbarch = b->gdbarch;
5495
5496   if (bptype != bp_catchpoint)
5497     gdb_assert (sal.pspace != NULL);
5498
5499   /* Adjust the breakpoint's address prior to allocating a location.
5500      Once we call allocate_bp_location(), that mostly uninitialized
5501      location will be placed on the location chain.  Adjustment of the
5502      breakpoint may cause target_read_memory() to be called and we do
5503      not want its scan of the location chain to find a breakpoint and
5504      location that's only been partially initialized.  */
5505   adjusted_address = adjust_breakpoint_address (loc_gdbarch, sal.pc, b->type);
5506
5507   b->loc = allocate_bp_location (b);
5508   b->loc->gdbarch = loc_gdbarch;
5509   b->loc->requested_address = sal.pc;
5510   b->loc->address = adjusted_address;
5511   b->loc->pspace = sal.pspace;
5512
5513   /* Store the program space that was used to set the breakpoint, for
5514      breakpoint resetting.  */
5515   b->pspace = sal.pspace;
5516
5517   if (sal.symtab == NULL)
5518     b->source_file = NULL;
5519   else
5520     b->source_file = xstrdup (sal.symtab->filename);
5521   b->loc->section = sal.section;
5522   b->line_number = sal.line;
5523
5524   set_breakpoint_location_function (b->loc);
5525
5526   breakpoints_changed ();
5527
5528   return b;
5529 }
5530
5531
5532 /* Note that the breakpoint object B describes a permanent breakpoint
5533    instruction, hard-wired into the inferior's code.  */
5534 void
5535 make_breakpoint_permanent (struct breakpoint *b)
5536 {
5537   struct bp_location *bl;
5538
5539   b->enable_state = bp_permanent;
5540
5541   /* By definition, permanent breakpoints are already present in the code. 
5542      Mark all locations as inserted.  For now, make_breakpoint_permanent
5543      is called in just one place, so it's hard to say if it's reasonable
5544      to have permanent breakpoint with multiple locations or not,
5545      but it's easy to implmement.  */
5546   for (bl = b->loc; bl; bl = bl->next)
5547     bl->inserted = 1;
5548 }
5549
5550 /* Call this routine when stepping and nexting to enable a breakpoint
5551    if we do a longjmp() in THREAD.  When we hit that breakpoint, call
5552    set_longjmp_resume_breakpoint() to figure out where we are going. */
5553
5554 void
5555 set_longjmp_breakpoint (int thread)
5556 {
5557   struct breakpoint *b, *temp;
5558
5559   /* To avoid having to rescan all objfile symbols at every step,
5560      we maintain a list of continually-inserted but always disabled
5561      longjmp "master" breakpoints.  Here, we simply create momentary
5562      clones of those and enable them for the requested thread.  */
5563   ALL_BREAKPOINTS_SAFE (b, temp)
5564     if (b->pspace == current_program_space
5565         && b->type == bp_longjmp_master)
5566       {
5567         struct breakpoint *clone = clone_momentary_breakpoint (b);
5568
5569         clone->type = bp_longjmp;
5570         clone->thread = thread;
5571       }
5572 }
5573
5574 /* Delete all longjmp breakpoints from THREAD.  */
5575 void
5576 delete_longjmp_breakpoint (int thread)
5577 {
5578   struct breakpoint *b, *temp;
5579
5580   ALL_BREAKPOINTS_SAFE (b, temp)
5581     if (b->type == bp_longjmp)
5582       {
5583         if (b->thread == thread)
5584           delete_breakpoint (b);
5585       }
5586 }
5587
5588 void
5589 enable_overlay_breakpoints (void)
5590 {
5591   struct breakpoint *b;
5592
5593   ALL_BREAKPOINTS (b)
5594     if (b->type == bp_overlay_event)
5595     {
5596       b->enable_state = bp_enabled;
5597       update_global_location_list (1);
5598       overlay_events_enabled = 1;
5599     }
5600 }
5601
5602 void
5603 disable_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_disabled;
5611       update_global_location_list (0);
5612       overlay_events_enabled = 0;
5613     }
5614 }
5615
5616 /* Set an active std::terminate breakpoint for each std::terminate
5617    master breakpoint.  */
5618 void
5619 set_std_terminate_breakpoint (void)
5620 {
5621   struct breakpoint *b, *temp;
5622
5623   ALL_BREAKPOINTS_SAFE (b, temp)
5624     if (b->pspace == current_program_space
5625         && b->type == bp_std_terminate_master)
5626       {
5627         struct breakpoint *clone = clone_momentary_breakpoint (b);
5628         clone->type = bp_std_terminate;
5629       }
5630 }
5631
5632 /* Delete all the std::terminate breakpoints.  */
5633 void
5634 delete_std_terminate_breakpoint (void)
5635 {
5636   struct breakpoint *b, *temp;
5637
5638   ALL_BREAKPOINTS_SAFE (b, temp)
5639     if (b->type == bp_std_terminate)
5640       delete_breakpoint (b);
5641 }
5642
5643 struct breakpoint *
5644 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
5645 {
5646   struct breakpoint *b;
5647
5648   b = create_internal_breakpoint (gdbarch, address, bp_thread_event);
5649   
5650   b->enable_state = bp_enabled;
5651   /* addr_string has to be used or breakpoint_re_set will delete me.  */
5652   b->addr_string
5653     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
5654
5655   update_global_location_list_nothrow (1);
5656
5657   return b;
5658 }
5659
5660 void
5661 remove_thread_event_breakpoints (void)
5662 {
5663   struct breakpoint *b, *temp;
5664
5665   ALL_BREAKPOINTS_SAFE (b, temp)
5666     if (b->type == bp_thread_event
5667         && b->loc->pspace == current_program_space)
5668       delete_breakpoint (b);
5669 }
5670
5671 struct captured_parse_breakpoint_args
5672   {
5673     char **arg_p;
5674     struct symtabs_and_lines *sals_p;
5675     char ***addr_string_p;
5676     int *not_found_ptr;
5677   };
5678
5679 struct lang_and_radix
5680   {
5681     enum language lang;
5682     int radix;
5683   };
5684
5685 /* Create a breakpoint for JIT code registration and unregistration.  */
5686
5687 struct breakpoint *
5688 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
5689 {
5690   struct breakpoint *b;
5691
5692   b = create_internal_breakpoint (gdbarch, address, bp_jit_event);
5693   update_global_location_list_nothrow (1);
5694   return b;
5695 }
5696
5697 void
5698 remove_solib_event_breakpoints (void)
5699 {
5700   struct breakpoint *b, *temp;
5701
5702   ALL_BREAKPOINTS_SAFE (b, temp)
5703     if (b->type == bp_shlib_event
5704         && b->loc->pspace == current_program_space)
5705       delete_breakpoint (b);
5706 }
5707
5708 struct breakpoint *
5709 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
5710 {
5711   struct breakpoint *b;
5712
5713   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event);
5714   update_global_location_list_nothrow (1);
5715   return b;
5716 }
5717
5718 /* Disable any breakpoints that are on code in shared libraries.  Only
5719    apply to enabled breakpoints, disabled ones can just stay disabled.  */
5720
5721 void
5722 disable_breakpoints_in_shlibs (void)
5723 {
5724   struct bp_location *loc, **locp_tmp;
5725
5726   ALL_BP_LOCATIONS (loc, locp_tmp)
5727   {
5728     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
5729     struct breakpoint *b = loc->owner;
5730
5731     /* We apply the check to all breakpoints, including disabled
5732        for those with loc->duplicate set.  This is so that when breakpoint
5733        becomes enabled, or the duplicate is removed, gdb will try to insert
5734        all breakpoints.  If we don't set shlib_disabled here, we'll try
5735        to insert those breakpoints and fail.  */
5736     if (((b->type == bp_breakpoint)
5737          || (b->type == bp_jit_event)
5738          || (b->type == bp_hardware_breakpoint)
5739          || (is_tracepoint (b)))
5740         && loc->pspace == current_program_space
5741         && !loc->shlib_disabled
5742 #ifdef PC_SOLIB
5743         && PC_SOLIB (loc->address)
5744 #else
5745         && solib_name_from_address (loc->pspace, loc->address)
5746 #endif
5747         )
5748       {
5749         loc->shlib_disabled = 1;
5750       }
5751   }
5752 }
5753
5754 /* Disable any breakpoints that are in in an unloaded shared library.  Only
5755    apply to enabled breakpoints, disabled ones can just stay disabled.  */
5756
5757 static void
5758 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
5759 {
5760   struct bp_location *loc, **locp_tmp;
5761   int disabled_shlib_breaks = 0;
5762
5763   /* SunOS a.out shared libraries are always mapped, so do not
5764      disable breakpoints; they will only be reported as unloaded
5765      through clear_solib when GDB discards its shared library
5766      list.  See clear_solib for more information.  */
5767   if (exec_bfd != NULL
5768       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
5769     return;
5770
5771   ALL_BP_LOCATIONS (loc, locp_tmp)
5772   {
5773     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
5774     struct breakpoint *b = loc->owner;
5775
5776     if ((loc->loc_type == bp_loc_hardware_breakpoint
5777          || loc->loc_type == bp_loc_software_breakpoint)
5778         && solib->pspace == loc->pspace
5779         && !loc->shlib_disabled
5780         && (b->type == bp_breakpoint
5781             || b->type == bp_jit_event
5782             || b->type == bp_hardware_breakpoint)
5783         && solib_contains_address_p (solib, loc->address))
5784       {
5785         loc->shlib_disabled = 1;
5786         /* At this point, we cannot rely on remove_breakpoint
5787            succeeding so we must mark the breakpoint as not inserted
5788            to prevent future errors occurring in remove_breakpoints.  */
5789         loc->inserted = 0;
5790         if (!disabled_shlib_breaks)
5791           {
5792             target_terminal_ours_for_output ();
5793             warning (_("Temporarily disabling breakpoints for unloaded shared library \"%s\""),
5794                      solib->so_name);
5795           }
5796         disabled_shlib_breaks = 1;
5797       }
5798   }
5799 }
5800
5801 /* FORK & VFORK catchpoints.  */
5802
5803 /* Implement the "insert" breakpoint_ops method for fork catchpoints.  */
5804
5805 static void
5806 insert_catch_fork (struct breakpoint *b)
5807 {
5808   target_insert_fork_catchpoint (PIDGET (inferior_ptid));
5809 }
5810
5811 /* Implement the "remove" breakpoint_ops method for fork catchpoints.  */
5812
5813 static int
5814 remove_catch_fork (struct breakpoint *b)
5815 {
5816   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
5817 }
5818
5819 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
5820    catchpoints.  */
5821
5822 static int
5823 breakpoint_hit_catch_fork (struct breakpoint *b)
5824 {
5825   return inferior_has_forked (inferior_ptid, &b->forked_inferior_pid);
5826 }
5827
5828 /* Implement the "print_it" breakpoint_ops method for fork catchpoints.  */
5829
5830 static enum print_stop_action
5831 print_it_catch_fork (struct breakpoint *b)
5832 {
5833   annotate_catchpoint (b->number);
5834   printf_filtered (_("\nCatchpoint %d (forked process %d), "),
5835                    b->number, ptid_get_pid (b->forked_inferior_pid));
5836   return PRINT_SRC_AND_LOC;
5837 }
5838
5839 /* Implement the "print_one" breakpoint_ops method for fork catchpoints.  */
5840
5841 static void
5842 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
5843 {
5844   struct value_print_options opts;
5845
5846   get_user_print_options (&opts);
5847
5848   /* Field 4, the address, is omitted (which makes the columns
5849      not line up too nicely with the headers, but the effect
5850      is relatively readable).  */
5851   if (opts.addressprint)
5852     ui_out_field_skip (uiout, "addr");
5853   annotate_field (5);
5854   ui_out_text (uiout, "fork");
5855   if (!ptid_equal (b->forked_inferior_pid, null_ptid))
5856     {
5857       ui_out_text (uiout, ", process ");
5858       ui_out_field_int (uiout, "what",
5859                         ptid_get_pid (b->forked_inferior_pid));
5860       ui_out_spaces (uiout, 1);
5861     }
5862 }
5863
5864 /* Implement the "print_mention" breakpoint_ops method for fork
5865    catchpoints.  */
5866
5867 static void
5868 print_mention_catch_fork (struct breakpoint *b)
5869 {
5870   printf_filtered (_("Catchpoint %d (fork)"), b->number);
5871 }
5872
5873 /* Implement the "print_recreate" breakpoint_ops method for fork
5874    catchpoints.  */
5875
5876 static void
5877 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
5878 {
5879   fprintf_unfiltered (fp, "catch fork");
5880 }
5881
5882 /* The breakpoint_ops structure to be used in fork catchpoints.  */
5883
5884 static struct breakpoint_ops catch_fork_breakpoint_ops =
5885 {
5886   insert_catch_fork,
5887   remove_catch_fork,
5888   breakpoint_hit_catch_fork,
5889   print_it_catch_fork,
5890   print_one_catch_fork,
5891   print_mention_catch_fork,
5892   print_recreate_catch_fork
5893 };
5894
5895 /* Implement the "insert" breakpoint_ops method for vfork catchpoints.  */
5896
5897 static void
5898 insert_catch_vfork (struct breakpoint *b)
5899 {
5900   target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
5901 }
5902
5903 /* Implement the "remove" breakpoint_ops method for vfork catchpoints.  */
5904
5905 static int
5906 remove_catch_vfork (struct breakpoint *b)
5907 {
5908   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
5909 }
5910
5911 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
5912    catchpoints.  */
5913
5914 static int
5915 breakpoint_hit_catch_vfork (struct breakpoint *b)
5916 {
5917   return inferior_has_vforked (inferior_ptid, &b->forked_inferior_pid);
5918 }
5919
5920 /* Implement the "print_it" breakpoint_ops method for vfork catchpoints.  */
5921
5922 static enum print_stop_action
5923 print_it_catch_vfork (struct breakpoint *b)
5924 {
5925   annotate_catchpoint (b->number);
5926   printf_filtered (_("\nCatchpoint %d (vforked process %d), "),
5927                    b->number, ptid_get_pid (b->forked_inferior_pid));
5928   return PRINT_SRC_AND_LOC;
5929 }
5930
5931 /* Implement the "print_one" breakpoint_ops method for vfork catchpoints.  */
5932
5933 static void
5934 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
5935 {
5936   struct value_print_options opts;
5937
5938   get_user_print_options (&opts);
5939   /* Field 4, the address, is omitted (which makes the columns
5940      not line up too nicely with the headers, but the effect
5941      is relatively readable).  */
5942   if (opts.addressprint)
5943     ui_out_field_skip (uiout, "addr");
5944   annotate_field (5);
5945   ui_out_text (uiout, "vfork");
5946   if (!ptid_equal (b->forked_inferior_pid, null_ptid))
5947     {
5948       ui_out_text (uiout, ", process ");
5949       ui_out_field_int (uiout, "what",
5950                         ptid_get_pid (b->forked_inferior_pid));
5951       ui_out_spaces (uiout, 1);
5952     }
5953 }
5954
5955 /* Implement the "print_mention" breakpoint_ops method for vfork
5956    catchpoints.  */
5957
5958 static void
5959 print_mention_catch_vfork (struct breakpoint *b)
5960 {
5961   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
5962 }
5963
5964 /* Implement the "print_recreate" breakpoint_ops method for vfork
5965    catchpoints.  */
5966
5967 static void
5968 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
5969 {
5970   fprintf_unfiltered (fp, "catch vfork");
5971 }
5972
5973 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
5974
5975 static struct breakpoint_ops catch_vfork_breakpoint_ops =
5976 {
5977   insert_catch_vfork,
5978   remove_catch_vfork,
5979   breakpoint_hit_catch_vfork,
5980   print_it_catch_vfork,
5981   print_one_catch_vfork,
5982   print_mention_catch_vfork,
5983   print_recreate_catch_vfork
5984 };
5985
5986 /* Implement the "insert" breakpoint_ops method for syscall
5987    catchpoints.  */
5988
5989 static void
5990 insert_catch_syscall (struct breakpoint *b)
5991 {
5992   struct inferior *inf = current_inferior ();
5993
5994   ++inf->total_syscalls_count;
5995   if (!b->syscalls_to_be_caught)
5996     ++inf->any_syscall_count;
5997   else
5998     {
5999       int i, iter;
6000
6001       for (i = 0;
6002            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
6003            i++)
6004         {
6005           int elem;
6006
6007           if (iter >= VEC_length (int, inf->syscalls_counts))
6008             {
6009               int old_size = VEC_length (int, inf->syscalls_counts);
6010               uintptr_t vec_addr_offset = old_size * ((uintptr_t) sizeof (int));
6011               uintptr_t vec_addr;
6012               VEC_safe_grow (int, inf->syscalls_counts, iter + 1);
6013               vec_addr = (uintptr_t) VEC_address (int, inf->syscalls_counts) +
6014                 vec_addr_offset;
6015               memset ((void *) vec_addr, 0,
6016                       (iter + 1 - old_size) * sizeof (int));
6017             }
6018           elem = VEC_index (int, inf->syscalls_counts, iter);
6019           VEC_replace (int, inf->syscalls_counts, iter, ++elem);
6020         }
6021     }
6022
6023   target_set_syscall_catchpoint (PIDGET (inferior_ptid),
6024                                  inf->total_syscalls_count != 0,
6025                                  inf->any_syscall_count,
6026                                  VEC_length (int, inf->syscalls_counts),
6027                                  VEC_address (int, inf->syscalls_counts));
6028 }
6029
6030 /* Implement the "remove" breakpoint_ops method for syscall
6031    catchpoints.  */
6032
6033 static int
6034 remove_catch_syscall (struct breakpoint *b)
6035 {
6036   struct inferior *inf = current_inferior ();
6037
6038   --inf->total_syscalls_count;
6039   if (!b->syscalls_to_be_caught)
6040     --inf->any_syscall_count;
6041   else
6042     {
6043       int i, iter;
6044
6045       for (i = 0;
6046            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
6047            i++)
6048         {
6049           int elem;
6050           if (iter >= VEC_length (int, inf->syscalls_counts))
6051             /* Shouldn't happen.  */
6052             continue;
6053           elem = VEC_index (int, inf->syscalls_counts, iter);
6054           VEC_replace (int, inf->syscalls_counts, iter, --elem);
6055         }
6056     }
6057
6058   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
6059                                         inf->total_syscalls_count != 0,
6060                                         inf->any_syscall_count,
6061                                         VEC_length (int, inf->syscalls_counts),
6062                                         VEC_address (int, inf->syscalls_counts));
6063 }
6064
6065 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
6066    catchpoints.  */
6067
6068 static int
6069 breakpoint_hit_catch_syscall (struct breakpoint *b)
6070 {
6071   /* We must check if we are catching specific syscalls in this breakpoint.
6072      If we are, then we must guarantee that the called syscall is the same
6073      syscall we are catching.  */
6074   int syscall_number = 0;
6075
6076   if (!inferior_has_called_syscall (inferior_ptid, &syscall_number))
6077     return 0;
6078
6079   /* Now, checking if the syscall is the same.  */
6080   if (b->syscalls_to_be_caught)
6081     {
6082       int i, iter;
6083
6084       for (i = 0;
6085            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
6086            i++)
6087         if (syscall_number == iter)
6088           break;
6089       /* Not the same.  */
6090       if (!iter)
6091         return 0;
6092     }
6093
6094   return 1;
6095 }
6096
6097 /* Implement the "print_it" breakpoint_ops method for syscall
6098    catchpoints.  */
6099
6100 static enum print_stop_action
6101 print_it_catch_syscall (struct breakpoint *b)
6102 {
6103   /* These are needed because we want to know in which state a
6104      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
6105      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
6106      must print "called syscall" or "returned from syscall".  */
6107   ptid_t ptid;
6108   struct target_waitstatus last;
6109   struct syscall s;
6110   struct cleanup *old_chain;
6111   char *syscall_id;
6112
6113   get_last_target_status (&ptid, &last);
6114
6115   get_syscall_by_number (last.value.syscall_number, &s);
6116
6117   annotate_catchpoint (b->number);
6118
6119   if (s.name == NULL)
6120     syscall_id = xstrprintf ("%d", last.value.syscall_number);
6121   else
6122     syscall_id = xstrprintf ("'%s'", s.name);
6123
6124   old_chain = make_cleanup (xfree, syscall_id);
6125
6126   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
6127     printf_filtered (_("\nCatchpoint %d (call to syscall %s), "),
6128                      b->number, syscall_id);
6129   else if (last.kind == TARGET_WAITKIND_SYSCALL_RETURN)
6130     printf_filtered (_("\nCatchpoint %d (returned from syscall %s), "),
6131                      b->number, syscall_id);
6132
6133   do_cleanups (old_chain);
6134
6135   return PRINT_SRC_AND_LOC;
6136 }
6137
6138 /* Implement the "print_one" breakpoint_ops method for syscall
6139    catchpoints.  */
6140
6141 static void
6142 print_one_catch_syscall (struct breakpoint *b,
6143                          struct bp_location **last_loc)
6144 {
6145   struct value_print_options opts;
6146
6147   get_user_print_options (&opts);
6148   /* Field 4, the address, is omitted (which makes the columns
6149      not line up too nicely with the headers, but the effect
6150      is relatively readable).  */
6151   if (opts.addressprint)
6152     ui_out_field_skip (uiout, "addr");
6153   annotate_field (5);
6154
6155   if (b->syscalls_to_be_caught
6156       && VEC_length (int, b->syscalls_to_be_caught) > 1)
6157     ui_out_text (uiout, "syscalls \"");
6158   else
6159     ui_out_text (uiout, "syscall \"");
6160
6161   if (b->syscalls_to_be_caught)
6162     {
6163       int i, iter;
6164       char *text = xstrprintf ("%s", "");
6165
6166       for (i = 0;
6167            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
6168            i++)
6169         {
6170           char *x = text;
6171           struct syscall s;
6172           get_syscall_by_number (iter, &s);
6173
6174           if (s.name != NULL)
6175             text = xstrprintf ("%s%s, ", text, s.name);
6176           else
6177             text = xstrprintf ("%s%d, ", text, iter);
6178
6179           /* We have to xfree the last 'text' (now stored at 'x')
6180              because xstrprintf dinamically allocates new space for it
6181              on every call.  */
6182           xfree (x);
6183         }
6184       /* Remove the last comma.  */
6185       text[strlen (text) - 2] = '\0';
6186       ui_out_field_string (uiout, "what", text);
6187     }
6188   else
6189     ui_out_field_string (uiout, "what", "<any syscall>");
6190   ui_out_text (uiout, "\" ");
6191 }
6192
6193 /* Implement the "print_mention" breakpoint_ops method for syscall
6194    catchpoints.  */
6195
6196 static void
6197 print_mention_catch_syscall (struct breakpoint *b)
6198 {
6199   if (b->syscalls_to_be_caught)
6200     {
6201       int i, iter;
6202
6203       if (VEC_length (int, b->syscalls_to_be_caught) > 1)
6204         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
6205       else
6206         printf_filtered (_("Catchpoint %d (syscall"), b->number);
6207
6208       for (i = 0;
6209            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
6210            i++)
6211         {
6212           struct syscall s;
6213           get_syscall_by_number (iter, &s);
6214
6215           if (s.name)
6216             printf_filtered (" '%s' [%d]", s.name, s.number);
6217           else
6218             printf_filtered (" %d", s.number);
6219         }
6220       printf_filtered (")");
6221     }
6222   else
6223     printf_filtered (_("Catchpoint %d (any syscall)"),
6224                      b->number);
6225 }
6226
6227 /* Implement the "print_recreate" breakpoint_ops method for syscall
6228    catchpoints.  */
6229
6230 static void
6231 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
6232 {
6233   fprintf_unfiltered (fp, "catch syscall");
6234
6235   if (b->syscalls_to_be_caught)
6236     {
6237       int i, iter;
6238
6239       for (i = 0;
6240            VEC_iterate (int, b->syscalls_to_be_caught, i, iter);
6241            i++)
6242         {
6243           struct syscall s;
6244
6245           get_syscall_by_number (iter, &s);
6246           if (s.name)
6247             fprintf_unfiltered (fp, " %s", s.name);
6248           else
6249             fprintf_unfiltered (fp, " %d", s.number);
6250         }
6251     }
6252 }
6253
6254 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
6255
6256 static struct breakpoint_ops catch_syscall_breakpoint_ops =
6257 {
6258   insert_catch_syscall,
6259   remove_catch_syscall,
6260   breakpoint_hit_catch_syscall,
6261   print_it_catch_syscall,
6262   print_one_catch_syscall,
6263   print_mention_catch_syscall,
6264   print_recreate_catch_syscall
6265 };
6266
6267 /* Returns non-zero if 'b' is a syscall catchpoint.  */
6268
6269 static int
6270 syscall_catchpoint_p (struct breakpoint *b)
6271 {
6272   return (b->ops == &catch_syscall_breakpoint_ops);
6273 }
6274
6275 /* Create a new breakpoint of the bp_catchpoint kind and return it,
6276    but does NOT mention it nor update the global location list.
6277    This is useful if you need to fill more fields in the
6278    struct breakpoint before calling mention.
6279  
6280    If TEMPFLAG is non-zero, then make the breakpoint temporary.
6281    If COND_STRING is not NULL, then store it in the breakpoint.
6282    OPS, if not NULL, is the breakpoint_ops structure associated
6283    to the catchpoint.  */
6284
6285 static struct breakpoint *
6286 create_catchpoint_without_mention (struct gdbarch *gdbarch, int tempflag,
6287                                    char *cond_string,
6288                                    struct breakpoint_ops *ops)
6289 {
6290   struct symtab_and_line sal;
6291   struct breakpoint *b;
6292
6293   init_sal (&sal);
6294   sal.pspace = current_program_space;
6295
6296   b = set_raw_breakpoint (gdbarch, sal, bp_catchpoint);
6297   set_breakpoint_count (breakpoint_count + 1);
6298   b->number = breakpoint_count;
6299
6300   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
6301   b->thread = -1;
6302   b->addr_string = NULL;
6303   b->enable_state = bp_enabled;
6304   b->disposition = tempflag ? disp_del : disp_donttouch;
6305   b->ops = ops;
6306
6307   return b;
6308 }
6309
6310 /* Create a new breakpoint of the bp_catchpoint kind and return it.
6311  
6312    If TEMPFLAG is non-zero, then make the breakpoint temporary.
6313    If COND_STRING is not NULL, then store it in the breakpoint.
6314    OPS, if not NULL, is the breakpoint_ops structure associated
6315    to the catchpoint.  */
6316
6317 static struct breakpoint *
6318 create_catchpoint (struct gdbarch *gdbarch, int tempflag,
6319                    char *cond_string, struct breakpoint_ops *ops)
6320 {
6321   struct breakpoint *b =
6322     create_catchpoint_without_mention (gdbarch, tempflag, cond_string, ops);
6323
6324   mention (b);
6325   update_global_location_list (1);
6326
6327   return b;
6328 }
6329
6330 static void
6331 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
6332                                     int tempflag, char *cond_string,
6333                                     struct breakpoint_ops *ops)
6334 {
6335   struct breakpoint *b
6336     = create_catchpoint (gdbarch, tempflag, cond_string, ops);
6337
6338   /* FIXME: We should put this information in a breakpoint private data
6339      area.  */
6340   b->forked_inferior_pid = null_ptid;
6341 }
6342
6343 /* Exec catchpoints.  */
6344
6345 static void
6346 insert_catch_exec (struct breakpoint *b)
6347 {
6348   target_insert_exec_catchpoint (PIDGET (inferior_ptid));
6349 }
6350
6351 static int
6352 remove_catch_exec (struct breakpoint *b)
6353 {
6354   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
6355 }
6356
6357 static int
6358 breakpoint_hit_catch_exec (struct breakpoint *b)
6359 {
6360   return inferior_has_execd (inferior_ptid, &b->exec_pathname);
6361 }
6362
6363 static enum print_stop_action
6364 print_it_catch_exec (struct breakpoint *b)
6365 {
6366   annotate_catchpoint (b->number);
6367   printf_filtered (_("\nCatchpoint %d (exec'd %s), "), b->number,
6368                    b->exec_pathname);
6369   return PRINT_SRC_AND_LOC;
6370 }
6371
6372 static void
6373 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
6374 {
6375   struct value_print_options opts;
6376
6377   get_user_print_options (&opts);
6378
6379   /* Field 4, the address, is omitted (which makes the columns
6380      not line up too nicely with the headers, but the effect
6381      is relatively readable).  */
6382   if (opts.addressprint)
6383     ui_out_field_skip (uiout, "addr");
6384   annotate_field (5);
6385   ui_out_text (uiout, "exec");
6386   if (b->exec_pathname != NULL)
6387     {
6388       ui_out_text (uiout, ", program \"");
6389       ui_out_field_string (uiout, "what", b->exec_pathname);
6390       ui_out_text (uiout, "\" ");
6391     }
6392 }
6393
6394 static void
6395 print_mention_catch_exec (struct breakpoint *b)
6396 {
6397   printf_filtered (_("Catchpoint %d (exec)"), b->number);
6398 }
6399
6400 /* Implement the "print_recreate" breakpoint_ops method for exec
6401    catchpoints.  */
6402
6403 static void
6404 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
6405 {
6406   fprintf_unfiltered (fp, "catch exec");
6407 }
6408
6409 static struct breakpoint_ops catch_exec_breakpoint_ops =
6410 {
6411   insert_catch_exec,
6412   remove_catch_exec,
6413   breakpoint_hit_catch_exec,
6414   print_it_catch_exec,
6415   print_one_catch_exec,
6416   print_mention_catch_exec,
6417   print_recreate_catch_exec
6418 };
6419
6420 static void
6421 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
6422                                  struct breakpoint_ops *ops)
6423 {
6424   struct gdbarch *gdbarch = get_current_arch ();
6425   struct breakpoint *b =
6426     create_catchpoint_without_mention (gdbarch, tempflag, NULL, ops);
6427
6428   b->syscalls_to_be_caught = filter;
6429
6430   /* Now, we have to mention the breakpoint and update the global
6431      location list.  */
6432   mention (b);
6433   update_global_location_list (1);
6434 }
6435
6436 static int
6437 hw_breakpoint_used_count (void)
6438 {
6439   struct breakpoint *b;
6440   int i = 0;
6441
6442   ALL_BREAKPOINTS (b)
6443   {
6444     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
6445       i++;
6446   }
6447
6448   return i;
6449 }
6450
6451 static int
6452 hw_watchpoint_used_count (enum bptype type, int *other_type_used)
6453 {
6454   struct breakpoint *b;
6455   int i = 0;
6456
6457   *other_type_used = 0;
6458   ALL_BREAKPOINTS (b)
6459   {
6460     if (breakpoint_enabled (b))
6461       {
6462         if (b->type == type)
6463           i++;
6464         else if (is_hardware_watchpoint (b))
6465           *other_type_used = 1;
6466       }
6467   }
6468   return i;
6469 }
6470
6471 void
6472 disable_watchpoints_before_interactive_call_start (void)
6473 {
6474   struct breakpoint *b;
6475
6476   ALL_BREAKPOINTS (b)
6477   {
6478     if (is_watchpoint (b) && breakpoint_enabled (b))
6479       {
6480         b->enable_state = bp_call_disabled;
6481         update_global_location_list (0);
6482       }
6483   }
6484 }
6485
6486 void
6487 enable_watchpoints_after_interactive_call_stop (void)
6488 {
6489   struct breakpoint *b;
6490
6491   ALL_BREAKPOINTS (b)
6492   {
6493     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
6494       {
6495         b->enable_state = bp_enabled;
6496         update_global_location_list (1);
6497       }
6498   }
6499 }
6500
6501 void
6502 disable_breakpoints_before_startup (void)
6503 {
6504   struct breakpoint *b;
6505   int found = 0;
6506
6507   ALL_BREAKPOINTS (b)
6508     {
6509       if (b->pspace != current_program_space)
6510         continue;
6511
6512       if ((b->type == bp_breakpoint
6513            || b->type == bp_hardware_breakpoint)
6514           && breakpoint_enabled (b))
6515         {
6516           b->enable_state = bp_startup_disabled;
6517           found = 1;
6518         }
6519     }
6520
6521   if (found)
6522     update_global_location_list (0);
6523
6524   current_program_space->executing_startup = 1;
6525 }
6526
6527 void
6528 enable_breakpoints_after_startup (void)
6529 {
6530   struct breakpoint *b;
6531   int found = 0;
6532
6533   current_program_space->executing_startup = 0;
6534
6535   ALL_BREAKPOINTS (b)
6536     {
6537       if (b->pspace != current_program_space)
6538         continue;
6539
6540       if ((b->type == bp_breakpoint
6541            || b->type == bp_hardware_breakpoint)
6542           && b->enable_state == bp_startup_disabled)
6543         {
6544           b->enable_state = bp_enabled;
6545           found = 1;
6546         }
6547     }
6548
6549   if (found)
6550     breakpoint_re_set ();
6551 }
6552
6553
6554 /* Set a breakpoint that will evaporate an end of command
6555    at address specified by SAL.
6556    Restrict it to frame FRAME if FRAME is nonzero.  */
6557
6558 struct breakpoint *
6559 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
6560                           struct frame_id frame_id, enum bptype type)
6561 {
6562   struct breakpoint *b;
6563
6564   /* If FRAME_ID is valid, it should be a real frame, not an inlined
6565      one.  */
6566   gdb_assert (!frame_id_inlined_p (frame_id));
6567
6568   b = set_raw_breakpoint (gdbarch, sal, type);
6569   b->enable_state = bp_enabled;
6570   b->disposition = disp_donttouch;
6571   b->frame_id = frame_id;
6572
6573   /* If we're debugging a multi-threaded program, then we
6574      want momentary breakpoints to be active in only a 
6575      single thread of control.  */
6576   if (in_thread_list (inferior_ptid))
6577     b->thread = pid_to_thread_id (inferior_ptid);
6578
6579   update_global_location_list_nothrow (1);
6580
6581   return b;
6582 }
6583
6584 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
6585    ORIG is NULL.  */
6586
6587 struct breakpoint *
6588 clone_momentary_breakpoint (struct breakpoint *orig)
6589 {
6590   struct breakpoint *copy;
6591
6592   /* If there's nothing to clone, then return nothing.  */
6593   if (orig == NULL)
6594     return NULL;
6595
6596   copy = set_raw_breakpoint_without_location (orig->gdbarch, orig->type);
6597   copy->loc = allocate_bp_location (copy);
6598   set_breakpoint_location_function (copy->loc);
6599
6600   copy->loc->gdbarch = orig->loc->gdbarch;
6601   copy->loc->requested_address = orig->loc->requested_address;
6602   copy->loc->address = orig->loc->address;
6603   copy->loc->section = orig->loc->section;
6604   copy->loc->pspace = orig->loc->pspace;
6605
6606   if (orig->source_file == NULL)
6607     copy->source_file = NULL;
6608   else
6609     copy->source_file = xstrdup (orig->source_file);
6610
6611   copy->line_number = orig->line_number;
6612   copy->frame_id = orig->frame_id;
6613   copy->thread = orig->thread;
6614   copy->pspace = orig->pspace;
6615
6616   copy->enable_state = bp_enabled;
6617   copy->disposition = disp_donttouch;
6618   copy->number = internal_breakpoint_number--;
6619
6620   update_global_location_list_nothrow (0);
6621   return copy;
6622 }
6623
6624 struct breakpoint *
6625 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
6626                                 enum bptype type)
6627 {
6628   struct symtab_and_line sal;
6629
6630   sal = find_pc_line (pc, 0);
6631   sal.pc = pc;
6632   sal.section = find_pc_overlay (pc);
6633   sal.explicit_pc = 1;
6634
6635   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
6636 }
6637 \f
6638
6639 /* Tell the user we have just set a breakpoint B.  */
6640
6641 static void
6642 mention (struct breakpoint *b)
6643 {
6644   int say_where = 0;
6645   struct cleanup *ui_out_chain;
6646   struct value_print_options opts;
6647
6648   get_user_print_options (&opts);
6649
6650   /* FIXME: This is misplaced; mention() is called by things (like
6651      hitting a watchpoint) other than breakpoint creation.  It should
6652      be possible to clean this up and at the same time replace the
6653      random calls to breakpoint_changed with this hook.  */
6654   observer_notify_breakpoint_created (b->number);
6655
6656   if (b->ops != NULL && b->ops->print_mention != NULL)
6657     b->ops->print_mention (b);
6658   else
6659     switch (b->type)
6660       {
6661       case bp_none:
6662         printf_filtered (_("(apparently deleted?) Eventpoint %d: "), b->number);
6663         break;
6664       case bp_watchpoint:
6665         ui_out_text (uiout, "Watchpoint ");
6666         ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
6667         ui_out_field_int (uiout, "number", b->number);
6668         ui_out_text (uiout, ": ");
6669         ui_out_field_string (uiout, "exp", b->exp_string);
6670         do_cleanups (ui_out_chain);
6671         break;
6672       case bp_hardware_watchpoint:
6673         ui_out_text (uiout, "Hardware watchpoint ");
6674         ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
6675         ui_out_field_int (uiout, "number", b->number);
6676         ui_out_text (uiout, ": ");
6677         ui_out_field_string (uiout, "exp", b->exp_string);
6678         do_cleanups (ui_out_chain);
6679         break;
6680       case bp_read_watchpoint:
6681         ui_out_text (uiout, "Hardware read watchpoint ");
6682         ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
6683         ui_out_field_int (uiout, "number", b->number);
6684         ui_out_text (uiout, ": ");
6685         ui_out_field_string (uiout, "exp", b->exp_string);
6686         do_cleanups (ui_out_chain);
6687         break;
6688       case bp_access_watchpoint:
6689         ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
6690         ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
6691         ui_out_field_int (uiout, "number", b->number);
6692         ui_out_text (uiout, ": ");
6693         ui_out_field_string (uiout, "exp", b->exp_string);
6694         do_cleanups (ui_out_chain);
6695         break;
6696       case bp_breakpoint:
6697         if (ui_out_is_mi_like_p (uiout))
6698           {
6699             say_where = 0;
6700             break;
6701           }
6702         if (b->disposition == disp_del)
6703           printf_filtered (_("Temporary breakpoint"));
6704         else
6705           printf_filtered (_("Breakpoint"));
6706         printf_filtered (_(" %d"), b->number);
6707         say_where = 1;
6708         break;
6709       case bp_hardware_breakpoint:
6710         if (ui_out_is_mi_like_p (uiout))
6711           {
6712             say_where = 0;
6713             break;
6714           }
6715         printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
6716         say_where = 1;
6717         break;
6718       case bp_tracepoint:
6719         if (ui_out_is_mi_like_p (uiout))
6720           {
6721             say_where = 0;
6722             break;
6723           }
6724         printf_filtered (_("Tracepoint"));
6725         printf_filtered (_(" %d"), b->number);
6726         say_where = 1;
6727         break;
6728       case bp_fast_tracepoint:
6729         if (ui_out_is_mi_like_p (uiout))
6730           {
6731             say_where = 0;
6732             break;
6733           }
6734         printf_filtered (_("Fast tracepoint"));
6735         printf_filtered (_(" %d"), b->number);
6736         say_where = 1;
6737         break;
6738       case bp_static_tracepoint:
6739         if (ui_out_is_mi_like_p (uiout))
6740           {
6741             say_where = 0;
6742             break;
6743           }
6744         printf_filtered (_("Static tracepoint"));
6745         printf_filtered (_(" %d"), b->number);
6746         say_where = 1;
6747         break;
6748
6749       case bp_until:
6750       case bp_finish:
6751       case bp_longjmp:
6752       case bp_longjmp_resume:
6753       case bp_step_resume:
6754       case bp_call_dummy:
6755       case bp_std_terminate:
6756       case bp_watchpoint_scope:
6757       case bp_shlib_event:
6758       case bp_thread_event:
6759       case bp_overlay_event:
6760       case bp_jit_event:
6761       case bp_longjmp_master:
6762       case bp_std_terminate_master:
6763         break;
6764       }
6765
6766   if (say_where)
6767     {
6768       /* i18n: cagney/2005-02-11: Below needs to be merged into a
6769          single string.  */
6770       if (b->loc == NULL)
6771         {
6772           printf_filtered (_(" (%s) pending."), b->addr_string);
6773         }
6774       else
6775         {
6776           if (opts.addressprint || b->source_file == NULL)
6777             {
6778               printf_filtered (" at ");
6779               fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
6780                               gdb_stdout);
6781             }
6782           if (b->source_file)
6783             printf_filtered (": file %s, line %d.",
6784                              b->source_file, b->line_number);
6785           
6786           if (b->loc->next)
6787             {
6788               struct bp_location *loc = b->loc;
6789               int n = 0;
6790               for (; loc; loc = loc->next)
6791                 ++n;
6792               printf_filtered (" (%d locations)", n);           
6793             }
6794
6795         }
6796     }
6797   if (ui_out_is_mi_like_p (uiout))
6798     return;
6799   printf_filtered ("\n");
6800 }
6801 \f
6802
6803 static struct bp_location *
6804 add_location_to_breakpoint (struct breakpoint *b,
6805                             const struct symtab_and_line *sal)
6806 {
6807   struct bp_location *loc, **tmp;
6808
6809   loc = allocate_bp_location (b);
6810   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
6811     ;
6812   *tmp = loc;
6813   loc->gdbarch = get_sal_arch (*sal);
6814   if (!loc->gdbarch)
6815     loc->gdbarch = b->gdbarch;
6816   loc->requested_address = sal->pc;
6817   loc->address = adjust_breakpoint_address (loc->gdbarch,
6818                                             loc->requested_address, b->type);
6819   loc->pspace = sal->pspace;
6820   gdb_assert (loc->pspace != NULL);
6821   loc->section = sal->section;
6822
6823   set_breakpoint_location_function (loc);
6824   return loc;
6825 }
6826 \f
6827
6828 /* Return 1 if LOC is pointing to a permanent breakpoint, 
6829    return 0 otherwise.  */
6830
6831 static int
6832 bp_loc_is_permanent (struct bp_location *loc)
6833 {
6834   int len;
6835   CORE_ADDR addr;
6836   const gdb_byte *brk;
6837   gdb_byte *target_mem;
6838   struct cleanup *cleanup;
6839   int retval = 0;
6840
6841   gdb_assert (loc != NULL);
6842
6843   addr = loc->address;
6844   brk = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
6845
6846   /* Software breakpoints unsupported?  */
6847   if (brk == NULL)
6848     return 0;
6849
6850   target_mem = alloca (len);
6851
6852   /* Enable the automatic memory restoration from breakpoints while
6853      we read the memory.  Otherwise we could say about our temporary
6854      breakpoints they are permanent.  */
6855   cleanup = save_current_space_and_thread ();
6856
6857   switch_to_program_space_and_thread (loc->pspace);
6858   make_show_memory_breakpoints_cleanup (0);
6859
6860   if (target_read_memory (loc->address, target_mem, len) == 0
6861       && memcmp (target_mem, brk, len) == 0)
6862     retval = 1;
6863
6864   do_cleanups (cleanup);
6865
6866   return retval;
6867 }
6868
6869
6870
6871 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
6872    as textual description of the location, and COND_STRING
6873    as condition expression.  */
6874
6875 static void
6876 create_breakpoint_sal (struct gdbarch *gdbarch,
6877                        struct symtabs_and_lines sals, char *addr_string,
6878                        char *cond_string,
6879                        enum bptype type, enum bpdisp disposition,
6880                        int thread, int task, int ignore_count,
6881                        struct breakpoint_ops *ops, int from_tty, int enabled)
6882 {
6883   struct breakpoint *b = NULL;
6884   int i;
6885
6886   if (type == bp_hardware_breakpoint)
6887     {
6888       int i = hw_breakpoint_used_count ();
6889       int target_resources_ok = 
6890         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
6891                                             i + 1, 0);
6892       if (target_resources_ok == 0)
6893         error (_("No hardware breakpoint support in the target."));
6894       else if (target_resources_ok < 0)
6895         error (_("Hardware breakpoints used exceeds limit."));
6896     }
6897
6898   gdb_assert (sals.nelts > 0);
6899
6900   for (i = 0; i < sals.nelts; ++i)
6901     {
6902       struct symtab_and_line sal = sals.sals[i];
6903       struct bp_location *loc;
6904
6905       if (from_tty)
6906         {
6907           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
6908           if (!loc_gdbarch)
6909             loc_gdbarch = gdbarch;
6910
6911           describe_other_breakpoints (loc_gdbarch,
6912                                       sal.pspace, sal.pc, sal.section, thread);
6913         }
6914
6915       if (i == 0)
6916         {
6917           b = set_raw_breakpoint (gdbarch, sal, type);
6918           set_breakpoint_count (breakpoint_count + 1);
6919           b->number = breakpoint_count;
6920           b->thread = thread;
6921           b->task = task;
6922   
6923           b->cond_string = cond_string;
6924           b->ignore_count = ignore_count;
6925           b->enable_state = enabled ? bp_enabled : bp_disabled;
6926           b->disposition = disposition;
6927           b->pspace = sals.sals[0].pspace;
6928
6929           if (type == bp_static_tracepoint)
6930             {
6931               struct static_tracepoint_marker marker;
6932
6933               if (is_marker_spec (addr_string))
6934                 {
6935                   /* We already know the marker exists, otherwise, we
6936                      wouldn't see a sal for it.  */
6937                   char *p = &addr_string[3];
6938                   char *endp;
6939                   char *marker_str;
6940                   int i;
6941
6942                   while (*p == ' ' || *p == '\t')
6943                     p++;
6944
6945                   endp = p;
6946                   while (*endp != ' ' && *endp != '\t' && *endp != '\0')
6947                     endp++;
6948
6949                   marker_str = savestring (p, endp - p);
6950                   b->static_trace_marker_id = marker_str;
6951
6952                   printf_filtered (_("Probed static tracepoint marker \"%s\"\n"),
6953                                    b->static_trace_marker_id);
6954                 }
6955               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
6956                 {
6957                   b->static_trace_marker_id = xstrdup (marker.str_id);
6958                   release_static_tracepoint_marker (&marker);
6959
6960                   printf_filtered (_("Probed static tracepoint marker \"%s\"\n"),
6961                                    b->static_trace_marker_id);
6962                 }
6963               else
6964                 warning (_("\
6965 Couldn't determine the static tracepoint marker to probe"));
6966             }
6967
6968           if (enabled && b->pspace->executing_startup
6969               && (b->type == bp_breakpoint
6970                   || b->type == bp_hardware_breakpoint))
6971             b->enable_state = bp_startup_disabled;
6972
6973           loc = b->loc;
6974         }
6975       else
6976         {
6977           loc = add_location_to_breakpoint (b, &sal);
6978         }
6979
6980       if (bp_loc_is_permanent (loc))
6981         make_breakpoint_permanent (b);
6982
6983       if (b->cond_string)
6984         {
6985           char *arg = b->cond_string;
6986           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
6987           if (*arg)
6988               error (_("Garbage %s follows condition"), arg);
6989         }
6990     }   
6991
6992   if (addr_string)
6993     b->addr_string = addr_string;
6994   else
6995     /* addr_string has to be used or breakpoint_re_set will delete
6996        me.  */
6997     b->addr_string
6998       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6999
7000   b->ops = ops;
7001   mention (b);
7002 }
7003
7004 /* Remove element at INDEX_TO_REMOVE from SAL, shifting other
7005    elements to fill the void space.  */
7006 static void
7007 remove_sal (struct symtabs_and_lines *sal, int index_to_remove)
7008 {
7009   int i = index_to_remove+1;
7010   int last_index = sal->nelts-1;
7011
7012   for (;i <= last_index; ++i)
7013     sal->sals[i-1] = sal->sals[i];
7014
7015   --(sal->nelts);
7016 }
7017
7018 /* If appropriate, obtains all sals that correspond to the same file
7019    and line as SAL, in all program spaces.  Users debugging with IDEs,
7020    will want to set a breakpoint at foo.c:line, and not really care
7021    about program spaces.  This is done only if SAL does not have
7022    explicit PC and has line and file information.  If we got just a
7023    single expanded sal, return the original.
7024
7025    Otherwise, if SAL.explicit_line is not set, filter out all sals for
7026    which the name of enclosing function is different from SAL.  This
7027    makes sure that if we have breakpoint originally set in template
7028    instantiation, say foo<int>(), we won't expand SAL to locations at
7029    the same line in all existing instantiations of 'foo'.  */
7030
7031 static struct symtabs_and_lines
7032 expand_line_sal_maybe (struct symtab_and_line sal)
7033 {
7034   struct symtabs_and_lines expanded;
7035   CORE_ADDR original_pc = sal.pc;
7036   char *original_function = NULL;
7037   int found;
7038   int i;
7039   struct cleanup *old_chain;
7040
7041   /* If we have explicit pc, don't expand.
7042      If we have no line number, we can't expand.  */
7043   if (sal.explicit_pc || sal.line == 0 || sal.symtab == NULL)
7044     {
7045       expanded.nelts = 1;
7046       expanded.sals = xmalloc (sizeof (struct symtab_and_line));
7047       expanded.sals[0] = sal;
7048       return expanded;
7049     }
7050
7051   sal.pc = 0;
7052
7053   old_chain = save_current_space_and_thread ();
7054
7055   switch_to_program_space_and_thread (sal.pspace);
7056
7057   find_pc_partial_function (original_pc, &original_function, NULL, NULL);
7058
7059   /* Note that expand_line_sal visits *all* program spaces.  */
7060   expanded = expand_line_sal (sal);
7061
7062   if (expanded.nelts == 1)
7063     {
7064       /* We had one sal, we got one sal.  Return that sal, adjusting it
7065          past the function prologue if necessary.  */
7066       xfree (expanded.sals);
7067       expanded.nelts = 1;
7068       expanded.sals = xmalloc (sizeof (struct symtab_and_line));
7069       sal.pc = original_pc;
7070       expanded.sals[0] = sal;
7071       skip_prologue_sal (&expanded.sals[0]);
7072       do_cleanups (old_chain);
7073       return expanded;      
7074     }
7075
7076   if (!sal.explicit_line)
7077     {
7078       CORE_ADDR func_addr, func_end;
7079       for (i = 0; i < expanded.nelts; ++i)
7080         {
7081           CORE_ADDR pc = expanded.sals[i].pc;
7082           char *this_function;
7083
7084           /* We need to switch threads as well since we're about to
7085              read memory.  */
7086           switch_to_program_space_and_thread (expanded.sals[i].pspace);
7087
7088           if (find_pc_partial_function (pc, &this_function, 
7089                                         &func_addr, &func_end))
7090             {
7091               if (this_function
7092                   && strcmp (this_function, original_function) != 0)
7093                 {
7094                   remove_sal (&expanded, i);
7095                   --i;
7096                 }
7097             }
7098         }
7099     }
7100
7101   /* Skip the function prologue if necessary.  */
7102   for (i = 0; i < expanded.nelts; ++i)
7103     skip_prologue_sal (&expanded.sals[i]);
7104
7105   do_cleanups (old_chain);
7106
7107   if (expanded.nelts <= 1)
7108     {
7109       /* This is un ugly workaround. If we get zero
7110        expanded sals then something is really wrong.
7111       Fix that by returnign the original sal. */
7112       xfree (expanded.sals);
7113       expanded.nelts = 1;
7114       expanded.sals = xmalloc (sizeof (struct symtab_and_line));
7115       sal.pc = original_pc;
7116       expanded.sals[0] = sal;
7117       return expanded;      
7118     }
7119
7120   if (original_pc)
7121     {
7122       found = 0;
7123       for (i = 0; i < expanded.nelts; ++i)
7124         if (expanded.sals[i].pc == original_pc)
7125           {
7126             found = 1;
7127             break;
7128           }
7129       gdb_assert (found);
7130     }
7131
7132   return expanded;
7133 }
7134
7135 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
7136    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
7137    value.  COND_STRING, if not NULL, specified the condition to be
7138    used for all breakpoints.  Essentially the only case where
7139    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
7140    function.  In that case, it's still not possible to specify
7141    separate conditions for different overloaded functions, so
7142    we take just a single condition string.
7143    
7144    NOTE: If the function succeeds, the caller is expected to cleanup
7145    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
7146    array contents).  If the function fails (error() is called), the
7147    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
7148    COND and SALS arrays and each of those arrays contents. */
7149
7150 static void
7151 create_breakpoints_sal (struct gdbarch *gdbarch,
7152                         struct symtabs_and_lines sals, char **addr_string,
7153                         char *cond_string,
7154                         enum bptype type, enum bpdisp disposition,
7155                         int thread, int task, int ignore_count,
7156                         struct breakpoint_ops *ops, int from_tty,
7157                         int enabled)
7158 {
7159   int i;
7160
7161   for (i = 0; i < sals.nelts; ++i)
7162     {
7163       struct symtabs_and_lines expanded = 
7164         expand_line_sal_maybe (sals.sals[i]);
7165
7166       create_breakpoint_sal (gdbarch, expanded, addr_string[i],
7167                              cond_string, type, disposition,
7168                              thread, task, ignore_count, ops, from_tty, enabled);
7169     }
7170 }
7171
7172 /* Parse ARG which is assumed to be a SAL specification possibly
7173    followed by conditionals.  On return, SALS contains an array of SAL
7174    addresses found. ADDR_STRING contains a vector of (canonical)
7175    address strings. ARG points to the end of the SAL. */
7176
7177 static void
7178 parse_breakpoint_sals (char **address,
7179                        struct symtabs_and_lines *sals,
7180                        char ***addr_string,
7181                        int *not_found_ptr)
7182 {
7183   char *addr_start = *address;
7184
7185   *addr_string = NULL;
7186   /* If no arg given, or if first arg is 'if ', use the default
7187      breakpoint. */
7188   if ((*address) == NULL
7189       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
7190     {
7191       if (default_breakpoint_valid)
7192         {
7193           struct symtab_and_line sal;
7194
7195           init_sal (&sal);              /* initialize to zeroes */
7196           sals->sals = (struct symtab_and_line *)
7197             xmalloc (sizeof (struct symtab_and_line));
7198           sal.pc = default_breakpoint_address;
7199           sal.line = default_breakpoint_line;
7200           sal.symtab = default_breakpoint_symtab;
7201           sal.pspace = default_breakpoint_pspace;
7202           sal.section = find_pc_overlay (sal.pc);
7203
7204           /* "break" without arguments is equivalent to "break *PC" where PC is
7205              the default_breakpoint_address.  So make sure to set
7206              sal.explicit_pc to prevent GDB from trying to expand the list of
7207              sals to include all other instances with the same symtab and line.
7208            */
7209           sal.explicit_pc = 1;
7210
7211           sals->sals[0] = sal;
7212           sals->nelts = 1;
7213         }
7214       else
7215         error (_("No default breakpoint address now."));
7216     }
7217   else
7218     {
7219       /* Force almost all breakpoints to be in terms of the
7220          current_source_symtab (which is decode_line_1's default).  This
7221          should produce the results we want almost all of the time while
7222          leaving default_breakpoint_* alone.  
7223          ObjC: However, don't match an Objective-C method name which
7224          may have a '+' or '-' succeeded by a '[' */
7225          
7226       struct symtab_and_line cursal = get_current_source_symtab_and_line ();
7227                         
7228       if (default_breakpoint_valid
7229           && (!cursal.symtab
7230               || ((strchr ("+-", (*address)[0]) != NULL)
7231                   && ((*address)[1] != '['))))
7232         *sals = decode_line_1 (address, 1, default_breakpoint_symtab,
7233                                default_breakpoint_line, addr_string, 
7234                                not_found_ptr);
7235       else
7236         *sals = decode_line_1 (address, 1, (struct symtab *) NULL, 0,
7237                                addr_string, not_found_ptr);
7238     }
7239   /* For any SAL that didn't have a canonical string, fill one in. */
7240   if (sals->nelts > 0 && *addr_string == NULL)
7241     *addr_string = xcalloc (sals->nelts, sizeof (char **));
7242   if (addr_start != (*address))
7243     {
7244       int i;
7245
7246       for (i = 0; i < sals->nelts; i++)
7247         {
7248           /* Add the string if not present. */
7249           if ((*addr_string)[i] == NULL)
7250             (*addr_string)[i] = savestring (addr_start, 
7251                                             (*address) - addr_start);
7252         }
7253     }
7254 }
7255
7256
7257 /* Convert each SAL into a real PC.  Verify that the PC can be
7258    inserted as a breakpoint.  If it can't throw an error. */
7259
7260 static void
7261 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
7262 {    
7263   int i;
7264
7265   for (i = 0; i < sals->nelts; i++)
7266     resolve_sal_pc (&sals->sals[i]);
7267 }
7268
7269 /* Fast tracepoints may have restrictions on valid locations.  For
7270    instance, a fast tracepoint using a jump instead of a trap will
7271    likely have to overwrite more bytes than a trap would, and so can
7272    only be placed where the instruction is longer than the jump, or a
7273    multi-instruction sequence does not have a jump into the middle of
7274    it, etc.  */
7275
7276 static void
7277 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
7278                             struct symtabs_and_lines *sals)
7279 {
7280   int i, rslt;
7281   struct symtab_and_line *sal;
7282   char *msg;
7283   struct cleanup *old_chain;
7284
7285   for (i = 0; i < sals->nelts; i++)
7286     {
7287       sal = &sals->sals[i];
7288
7289       rslt = gdbarch_fast_tracepoint_valid_at (gdbarch, sal->pc,
7290                                                NULL, &msg);
7291       old_chain = make_cleanup (xfree, msg);
7292
7293       if (!rslt)
7294         error (_("May not have a fast tracepoint at 0x%s%s"),
7295                paddress (gdbarch, sal->pc), (msg ? msg : ""));
7296
7297       do_cleanups (old_chain);
7298     }
7299 }
7300
7301 static void
7302 do_captured_parse_breakpoint (struct ui_out *ui, void *data)
7303 {
7304   struct captured_parse_breakpoint_args *args = data;
7305   
7306   parse_breakpoint_sals (args->arg_p, args->sals_p, args->addr_string_p, 
7307                          args->not_found_ptr);
7308 }
7309
7310 /* Given TOK, a string specification of condition and thread, as
7311    accepted by the 'break' command, extract the condition
7312    string and thread number and set *COND_STRING and *THREAD.
7313    PC identifies the context at which the condition should be parsed.  
7314    If no condition is found, *COND_STRING is set to NULL.
7315    If no thread is found, *THREAD is set to -1.  */
7316 static void 
7317 find_condition_and_thread (char *tok, CORE_ADDR pc, 
7318                            char **cond_string, int *thread, int *task)
7319 {
7320   *cond_string = NULL;
7321   *thread = -1;
7322   while (tok && *tok)
7323     {
7324       char *end_tok;
7325       int toklen;
7326       char *cond_start = NULL;
7327       char *cond_end = NULL;
7328
7329       while (*tok == ' ' || *tok == '\t')
7330         tok++;
7331       
7332       end_tok = tok;
7333       
7334       while (*end_tok != ' ' && *end_tok != '\t' && *end_tok != '\000')
7335         end_tok++;
7336       
7337       toklen = end_tok - tok;
7338       
7339       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
7340         {
7341           struct expression *expr;
7342
7343           tok = cond_start = end_tok + 1;
7344           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
7345           xfree (expr);
7346           cond_end = tok;
7347           *cond_string = savestring (cond_start, 
7348                                      cond_end - cond_start);
7349         }
7350       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
7351         {
7352           char *tmptok;
7353           
7354           tok = end_tok + 1;
7355           tmptok = tok;
7356           *thread = strtol (tok, &tok, 0);
7357           if (tok == tmptok)
7358             error (_("Junk after thread keyword."));
7359           if (!valid_thread_id (*thread))
7360             error (_("Unknown thread %d."), *thread);
7361         }
7362       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
7363         {
7364           char *tmptok;
7365
7366           tok = end_tok + 1;
7367           tmptok = tok;
7368           *task = strtol (tok, &tok, 0);
7369           if (tok == tmptok)
7370             error (_("Junk after task keyword."));
7371           if (!valid_task_id (*task))
7372             error (_("Unknown task %d."), *task);
7373         }
7374       else
7375         error (_("Junk at end of arguments."));
7376     }
7377 }
7378
7379 /* Decode a static tracepoint marker spec.  */
7380
7381 static struct symtabs_and_lines
7382 decode_static_tracepoint_spec (char **arg_p)
7383 {
7384   VEC(static_tracepoint_marker_p) *markers = NULL;
7385   struct symtabs_and_lines sals;
7386   struct symtab_and_line sal;
7387   struct symbol *sym;
7388   struct cleanup *old_chain;
7389   char *p = &(*arg_p)[3];
7390   char *endp;
7391   char *marker_str;
7392   int i;
7393
7394   while (*p == ' ' || *p == '\t')
7395     p++;
7396
7397   endp = p;
7398   while (*endp != ' ' && *endp != '\t' && *endp != '\0')
7399     endp++;
7400
7401   marker_str = savestring (p, endp - p);
7402   old_chain = make_cleanup (xfree, marker_str);
7403
7404   markers = target_static_tracepoint_markers_by_strid (marker_str);
7405   if (VEC_empty(static_tracepoint_marker_p, markers))
7406     error (_("No known static tracepoint marker named %s"), marker_str);
7407
7408   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
7409   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
7410
7411   for (i = 0; i < sals.nelts; i++)
7412     {
7413       struct static_tracepoint_marker *marker;
7414
7415       marker = VEC_index (static_tracepoint_marker_p, markers, i);
7416
7417       init_sal (&sals.sals[i]);
7418
7419       sals.sals[i] = find_pc_line (marker->address, 0);
7420       sals.sals[i].pc = marker->address;
7421
7422       release_static_tracepoint_marker (marker);
7423     }
7424
7425   do_cleanups (old_chain);
7426
7427   *arg_p = endp;
7428   return sals;
7429 }
7430
7431 /* Set a breakpoint.  This function is shared between CLI and MI
7432    functions for setting a breakpoint.  This function has two major
7433    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
7434    parameter.  If non-zero, the function will parse arg, extracting
7435    breakpoint location, address and thread. Otherwise, ARG is just the
7436    location of breakpoint, with condition and thread specified by the
7437    COND_STRING and THREAD parameters.  Returns true if any breakpoint
7438    was created; false otherwise.  */
7439
7440 int
7441 create_breakpoint (struct gdbarch *gdbarch,
7442                    char *arg, char *cond_string, int thread,
7443                    int parse_condition_and_thread,
7444                    int tempflag, enum bptype type_wanted,
7445                    int ignore_count,
7446                    enum auto_boolean pending_break_support,
7447                    struct breakpoint_ops *ops,
7448                    int from_tty,
7449                    int enabled)
7450 {
7451   struct gdb_exception e;
7452   struct symtabs_and_lines sals;
7453   struct symtab_and_line pending_sal;
7454   char *copy_arg;
7455   char *addr_start = arg;
7456   char **addr_string;
7457   struct cleanup *old_chain;
7458   struct cleanup *bkpt_chain = NULL;
7459   struct captured_parse_breakpoint_args parse_args;
7460   int i;
7461   int pending = 0;
7462   int not_found = 0;
7463   int task = 0;
7464   int prev_bkpt_count = breakpoint_count;
7465
7466   sals.sals = NULL;
7467   sals.nelts = 0;
7468   addr_string = NULL;
7469
7470   parse_args.arg_p = &arg;
7471   parse_args.sals_p = &sals;
7472   parse_args.addr_string_p = &addr_string;
7473   parse_args.not_found_ptr = &not_found;
7474
7475   if (type_wanted == bp_static_tracepoint && is_marker_spec (arg))
7476     {
7477       int i;
7478
7479       sals = decode_static_tracepoint_spec (&arg);
7480
7481       copy_arg = savestring (addr_start, arg - addr_start);
7482       addr_string = xcalloc (sals.nelts, sizeof (char **));
7483       for (i = 0; i < sals.nelts; i++)
7484         addr_string[i] = xstrdup (copy_arg);
7485       goto done;
7486     }
7487
7488   e = catch_exception (uiout, do_captured_parse_breakpoint, 
7489                        &parse_args, RETURN_MASK_ALL);
7490
7491   /* If caller is interested in rc value from parse, set value.  */
7492   switch (e.reason)
7493     {
7494     case RETURN_QUIT:
7495       throw_exception (e);
7496     case RETURN_ERROR:
7497       switch (e.error)
7498         {
7499         case NOT_FOUND_ERROR:
7500
7501           /* If pending breakpoint support is turned off, throw
7502              error.  */
7503
7504           if (pending_break_support == AUTO_BOOLEAN_FALSE)
7505             throw_exception (e);
7506
7507           exception_print (gdb_stderr, e);
7508
7509           /* If pending breakpoint support is auto query and the user
7510              selects no, then simply return the error code.  */
7511           if (pending_break_support == AUTO_BOOLEAN_AUTO
7512               && !nquery ("Make breakpoint pending on future shared library load? "))
7513             return 0;
7514
7515           /* At this point, either the user was queried about setting
7516              a pending breakpoint and selected yes, or pending
7517              breakpoint behavior is on and thus a pending breakpoint
7518              is defaulted on behalf of the user.  */
7519           copy_arg = xstrdup (addr_start);
7520           addr_string = &copy_arg;
7521           sals.nelts = 1;
7522           sals.sals = &pending_sal;
7523           pending_sal.pc = 0;
7524           pending = 1;
7525           break;
7526         default:
7527           throw_exception (e);
7528         }
7529     default:
7530       if (!sals.nelts)
7531         return 0;
7532     }
7533
7534   done:
7535
7536   /* Create a chain of things that always need to be cleaned up. */
7537   old_chain = make_cleanup (null_cleanup, 0);
7538
7539   if (!pending)
7540     {
7541       /* Make sure that all storage allocated to SALS gets freed.  */
7542       make_cleanup (xfree, sals.sals);
7543       
7544       /* Cleanup the addr_string array but not its contents. */
7545       make_cleanup (xfree, addr_string);
7546     }
7547
7548   /* ----------------------------- SNIP -----------------------------
7549      Anything added to the cleanup chain beyond this point is assumed
7550      to be part of a breakpoint.  If the breakpoint create succeeds
7551      then the memory is not reclaimed.  */
7552   bkpt_chain = make_cleanup (null_cleanup, 0);
7553
7554   /* Mark the contents of the addr_string for cleanup.  These go on
7555      the bkpt_chain and only occur if the breakpoint create fails.  */
7556   for (i = 0; i < sals.nelts; i++)
7557     {
7558       if (addr_string[i] != NULL)
7559         make_cleanup (xfree, addr_string[i]);
7560     }
7561
7562   /* Resolve all line numbers to PC's and verify that the addresses
7563      are ok for the target.  */
7564   if (!pending)
7565     breakpoint_sals_to_pc (&sals);
7566
7567   /* Fast tracepoints may have additional restrictions on location.  */
7568   if (type_wanted == bp_fast_tracepoint)
7569     check_fast_tracepoint_sals (gdbarch, &sals);
7570
7571   /* Verify that condition can be parsed, before setting any
7572      breakpoints.  Allocate a separate condition expression for each
7573      breakpoint. */
7574   if (!pending)
7575     {
7576       if (parse_condition_and_thread)
7577         {
7578             /* Here we only parse 'arg' to separate condition
7579                from thread number, so parsing in context of first
7580                sal is OK.  When setting the breakpoint we'll 
7581                re-parse it in context of each sal.  */
7582             cond_string = NULL;
7583             thread = -1;
7584             find_condition_and_thread (arg, sals.sals[0].pc, &cond_string,
7585                                        &thread, &task);
7586             if (cond_string)
7587                 make_cleanup (xfree, cond_string);
7588         }
7589       else
7590         {
7591             /* Create a private copy of condition string.  */
7592             if (cond_string)
7593             {
7594                 cond_string = xstrdup (cond_string);
7595                 make_cleanup (xfree, cond_string);
7596             }
7597         }
7598
7599       /* If the user is creating a static tracepoint by marker id
7600          (strace -m MARKER_ID), then store the sals index, so that
7601          breakpoint_re_set can try to match up which of the newly
7602          found markers corresponds to this one, and, don't try to
7603          expand multiple locations for each sal, given than SALS
7604          already should contain all sals for MARKER_ID.  */
7605       if (type_wanted == bp_static_tracepoint
7606           && is_marker_spec (addr_string[0]))
7607         {
7608           int i;
7609
7610           for (i = 0; i < sals.nelts; ++i)
7611             {
7612               struct symtabs_and_lines expanded;
7613               struct breakpoint *tp;
7614               struct cleanup *old_chain;
7615
7616               expanded.nelts = 1;
7617               expanded.sals = xmalloc (sizeof (struct symtab_and_line));
7618               expanded.sals[0] = sals.sals[i];
7619               old_chain = make_cleanup (xfree, expanded.sals);
7620
7621               create_breakpoint_sal (gdbarch, expanded, addr_string[i],
7622                                      cond_string, type_wanted,
7623                                      tempflag ? disp_del : disp_donttouch,
7624                                      thread, task, ignore_count, ops,
7625                                      from_tty, enabled);
7626
7627               do_cleanups (old_chain);
7628
7629               /* Get the tracepoint we just created.  */
7630               tp = get_breakpoint (breakpoint_count);
7631               gdb_assert (tp != NULL);
7632
7633               /* Given that its possible to have multiple markers with
7634                  the same string id, if the user is creating a static
7635                  tracepoint by marker id ("strace -m MARKER_ID"), then
7636                  store the sals index, so that breakpoint_re_set can
7637                  try to match up which of the newly found markers
7638                  corresponds to this one  */
7639               tp->static_trace_marker_id_idx = i;
7640             }
7641         }
7642       else
7643         create_breakpoints_sal (gdbarch, sals, addr_string, cond_string,
7644                                 type_wanted, tempflag ? disp_del : disp_donttouch,
7645                                 thread, task, ignore_count, ops, from_tty,
7646                                 enabled);
7647     }
7648   else
7649     {
7650       struct breakpoint *b;
7651
7652       make_cleanup (xfree, copy_arg);
7653
7654       b = set_raw_breakpoint_without_location (gdbarch, type_wanted);
7655       set_breakpoint_count (breakpoint_count + 1);
7656       b->number = breakpoint_count;
7657       b->thread = -1;
7658       b->addr_string = addr_string[0];
7659       b->cond_string = NULL;
7660       b->ignore_count = ignore_count;
7661       b->disposition = tempflag ? disp_del : disp_donttouch;
7662       b->condition_not_parsed = 1;
7663       b->ops = ops;
7664       b->enable_state = enabled ? bp_enabled : bp_disabled;
7665       b->pspace = current_program_space;
7666
7667       if (enabled && b->pspace->executing_startup
7668           && (b->type == bp_breakpoint
7669               || b->type == bp_hardware_breakpoint))
7670         b->enable_state = bp_startup_disabled;
7671
7672       mention (b);
7673     }
7674   
7675   if (sals.nelts > 1)
7676     {
7677       warning (_("Multiple breakpoints were set.\n"
7678                  "Use the \"delete\" command to delete unwanted breakpoints."));
7679       prev_breakpoint_count = prev_bkpt_count;
7680     }
7681
7682   /* That's it.  Discard the cleanups for data inserted into the
7683      breakpoint.  */
7684   discard_cleanups (bkpt_chain);
7685   /* But cleanup everything else.  */
7686   do_cleanups (old_chain);
7687
7688   /* error call may happen here - have BKPT_CHAIN already discarded.  */
7689   update_global_location_list (1);
7690
7691   return 1;
7692 }
7693
7694 /* Set a breakpoint. 
7695    ARG is a string describing breakpoint address,
7696    condition, and thread.
7697    FLAG specifies if a breakpoint is hardware on,
7698    and if breakpoint is temporary, using BP_HARDWARE_FLAG
7699    and BP_TEMPFLAG.  */
7700    
7701 static void
7702 break_command_1 (char *arg, int flag, int from_tty)
7703 {
7704   int tempflag = flag & BP_TEMPFLAG;
7705   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
7706                              ? bp_hardware_breakpoint
7707                              : bp_breakpoint);
7708
7709   create_breakpoint (get_current_arch (),
7710                      arg,
7711                      NULL, 0, 1 /* parse arg */,
7712                      tempflag, type_wanted,
7713                      0 /* Ignore count */,
7714                      pending_break_support,
7715                      NULL /* breakpoint_ops */,
7716                      from_tty,
7717                      1 /* enabled */);
7718 }
7719
7720
7721 /* Helper function for break_command_1 and disassemble_command.  */
7722
7723 void
7724 resolve_sal_pc (struct symtab_and_line *sal)
7725 {
7726   CORE_ADDR pc;
7727
7728   if (sal->pc == 0 && sal->symtab != NULL)
7729     {
7730       if (!find_line_pc (sal->symtab, sal->line, &pc))
7731         error (_("No line %d in file \"%s\"."),
7732                sal->line, sal->symtab->filename);
7733       sal->pc = pc;
7734
7735       /* If this SAL corresponds to a breakpoint inserted using
7736          a line number, then skip the function prologue if necessary.  */
7737       if (sal->explicit_line)
7738         skip_prologue_sal (sal);
7739     }
7740
7741   if (sal->section == 0 && sal->symtab != NULL)
7742     {
7743       struct blockvector *bv;
7744       struct block *b;
7745       struct symbol *sym;
7746
7747       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
7748       if (bv != NULL)
7749         {
7750           sym = block_linkage_function (b);
7751           if (sym != NULL)
7752             {
7753               fixup_symbol_section (sym, sal->symtab->objfile);
7754               sal->section = SYMBOL_OBJ_SECTION (sym);
7755             }
7756           else
7757             {
7758               /* It really is worthwhile to have the section, so we'll just
7759                  have to look harder. This case can be executed if we have 
7760                  line numbers but no functions (as can happen in assembly 
7761                  source).  */
7762
7763               struct minimal_symbol *msym;
7764               struct cleanup *old_chain = save_current_space_and_thread ();
7765
7766               switch_to_program_space_and_thread (sal->pspace);
7767
7768               msym = lookup_minimal_symbol_by_pc (sal->pc);
7769               if (msym)
7770                 sal->section = SYMBOL_OBJ_SECTION (msym);
7771
7772               do_cleanups (old_chain);
7773             }
7774         }
7775     }
7776 }
7777
7778 void
7779 break_command (char *arg, int from_tty)
7780 {
7781   break_command_1 (arg, 0, from_tty);
7782 }
7783
7784 void
7785 tbreak_command (char *arg, int from_tty)
7786 {
7787   break_command_1 (arg, BP_TEMPFLAG, from_tty);
7788 }
7789
7790 static void
7791 hbreak_command (char *arg, int from_tty)
7792 {
7793   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
7794 }
7795
7796 static void
7797 thbreak_command (char *arg, int from_tty)
7798 {
7799   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
7800 }
7801
7802 static void
7803 stop_command (char *arg, int from_tty)
7804 {
7805   printf_filtered (_("Specify the type of breakpoint to set.\n\
7806 Usage: stop in <function | address>\n\
7807        stop at <line>\n"));
7808 }
7809
7810 static void
7811 stopin_command (char *arg, int from_tty)
7812 {
7813   int badInput = 0;
7814
7815   if (arg == (char *) NULL)
7816     badInput = 1;
7817   else if (*arg != '*')
7818     {
7819       char *argptr = arg;
7820       int hasColon = 0;
7821
7822       /* look for a ':'.  If this is a line number specification, then
7823          say it is bad, otherwise, it should be an address or
7824          function/method name */
7825       while (*argptr && !hasColon)
7826         {
7827           hasColon = (*argptr == ':');
7828           argptr++;
7829         }
7830
7831       if (hasColon)
7832         badInput = (*argptr != ':');    /* Not a class::method */
7833       else
7834         badInput = isdigit (*arg);      /* a simple line number */
7835     }
7836
7837   if (badInput)
7838     printf_filtered (_("Usage: stop in <function | address>\n"));
7839   else
7840     break_command_1 (arg, 0, from_tty);
7841 }
7842
7843 static void
7844 stopat_command (char *arg, int from_tty)
7845 {
7846   int badInput = 0;
7847
7848   if (arg == (char *) NULL || *arg == '*')      /* no line number */
7849     badInput = 1;
7850   else
7851     {
7852       char *argptr = arg;
7853       int hasColon = 0;
7854
7855       /* look for a ':'.  If there is a '::' then get out, otherwise
7856          it is probably a line number. */
7857       while (*argptr && !hasColon)
7858         {
7859           hasColon = (*argptr == ':');
7860           argptr++;
7861         }
7862
7863       if (hasColon)
7864         badInput = (*argptr == ':');    /* we have class::method */
7865       else
7866         badInput = !isdigit (*arg);     /* not a line number */
7867     }
7868
7869   if (badInput)
7870     printf_filtered (_("Usage: stop at <line>\n"));
7871   else
7872     break_command_1 (arg, 0, from_tty);
7873 }
7874
7875 /*  Return non-zero if EXP is verified as constant.  Returned zero means EXP is
7876     variable.  Also the constant detection may fail for some constant
7877     expressions and in such case still falsely return zero.  */
7878 static int
7879 watchpoint_exp_is_const (const struct expression *exp)
7880 {
7881   int i = exp->nelts;
7882
7883   while (i > 0)
7884     {
7885       int oplenp, argsp;
7886
7887       /* We are only interested in the descriptor of each element.  */
7888       operator_length (exp, i, &oplenp, &argsp);
7889       i -= oplenp;
7890
7891       switch (exp->elts[i].opcode)
7892         {
7893         case BINOP_ADD:
7894         case BINOP_SUB:
7895         case BINOP_MUL:
7896         case BINOP_DIV:
7897         case BINOP_REM:
7898         case BINOP_MOD:
7899         case BINOP_LSH:
7900         case BINOP_RSH:
7901         case BINOP_LOGICAL_AND:
7902         case BINOP_LOGICAL_OR:
7903         case BINOP_BITWISE_AND:
7904         case BINOP_BITWISE_IOR:
7905         case BINOP_BITWISE_XOR:
7906         case BINOP_EQUAL:
7907         case BINOP_NOTEQUAL:
7908         case BINOP_LESS:
7909         case BINOP_GTR:
7910         case BINOP_LEQ:
7911         case BINOP_GEQ:
7912         case BINOP_REPEAT:
7913         case BINOP_COMMA:
7914         case BINOP_EXP:
7915         case BINOP_MIN:
7916         case BINOP_MAX:
7917         case BINOP_INTDIV:
7918         case BINOP_CONCAT:
7919         case BINOP_IN:
7920         case BINOP_RANGE:
7921         case TERNOP_COND:
7922         case TERNOP_SLICE:
7923         case TERNOP_SLICE_COUNT:
7924
7925         case OP_LONG:
7926         case OP_DOUBLE:
7927         case OP_DECFLOAT:
7928         case OP_LAST:
7929         case OP_COMPLEX:
7930         case OP_STRING:
7931         case OP_BITSTRING:
7932         case OP_ARRAY:
7933         case OP_TYPE:
7934         case OP_NAME:
7935         case OP_OBJC_NSSTRING:
7936
7937         case UNOP_NEG:
7938         case UNOP_LOGICAL_NOT:
7939         case UNOP_COMPLEMENT:
7940         case UNOP_ADDR:
7941         case UNOP_HIGH:
7942           /* Unary, binary and ternary operators: We have to check their
7943              operands.  If they are constant, then so is the result of
7944              that operation.  For instance, if A and B are determined to be
7945              constants, then so is "A + B".
7946
7947              UNOP_IND is one exception to the rule above, because the value
7948              of *ADDR is not necessarily a constant, even when ADDR is.  */
7949           break;
7950
7951         case OP_VAR_VALUE:
7952           /* Check whether the associated symbol is a constant.
7953              We use SYMBOL_CLASS rather than TYPE_CONST because it's
7954              possible that a buggy compiler could mark a variable as constant
7955              even when it is not, and TYPE_CONST would return true in this
7956              case, while SYMBOL_CLASS wouldn't.
7957              We also have to check for function symbols because they are
7958              always constant.  */
7959           {
7960             struct symbol *s = exp->elts[i + 2].symbol;
7961
7962             if (SYMBOL_CLASS (s) != LOC_BLOCK
7963                 && SYMBOL_CLASS (s) != LOC_CONST
7964                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
7965               return 0;
7966             break;
7967           }
7968
7969         /* The default action is to return 0 because we are using
7970            the optimistic approach here: If we don't know something,
7971            then it is not a constant.  */
7972         default:
7973           return 0;
7974         }
7975     }
7976
7977   return 1;
7978 }
7979
7980 /* accessflag:  hw_write:  watch write, 
7981                 hw_read:   watch read, 
7982                 hw_access: watch access (read or write) */
7983 static void
7984 watch_command_1 (char *arg, int accessflag, int from_tty)
7985 {
7986   struct breakpoint *b, *scope_breakpoint = NULL;
7987   struct expression *exp;
7988   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
7989   struct value *val, *mark;
7990   struct frame_info *frame;
7991   char *exp_start = NULL;
7992   char *exp_end = NULL;
7993   char *tok, *id_tok_start, *end_tok;
7994   int toklen;
7995   char *cond_start = NULL;
7996   char *cond_end = NULL;
7997   int i, other_type_used, target_resources_ok = 0;
7998   enum bptype bp_type;
7999   int mem_cnt = 0;
8000   int thread = -1;
8001   int pc = 0;
8002
8003   /* Make sure that we actually have parameters to parse.  */
8004   if (arg != NULL && arg[0] != '\0')
8005     {
8006       toklen = strlen (arg); /* Size of argument list.  */
8007
8008       /* Points tok to the end of the argument list.  */
8009       tok = arg + toklen - 1;
8010
8011       /* Go backwards in the parameters list. Skip the last parameter.
8012          If we're expecting a 'thread <thread_num>' parameter, this should
8013          be the thread identifier.  */
8014       while (tok > arg && (*tok == ' ' || *tok == '\t'))
8015         tok--;
8016       while (tok > arg && (*tok != ' ' && *tok != '\t'))
8017         tok--;
8018
8019       /* Points end_tok to the beginning of the last token.  */
8020       id_tok_start = tok + 1;
8021
8022       /* Go backwards in the parameters list. Skip one more parameter.
8023          If we're expecting a 'thread <thread_num>' parameter, we should
8024          reach a "thread" token.  */
8025       while (tok > arg && (*tok == ' ' || *tok == '\t'))
8026         tok--;
8027
8028       end_tok = tok;
8029
8030       while (tok > arg && (*tok != ' ' && *tok != '\t'))
8031         tok--;
8032
8033       /* Move the pointer forward to skip the whitespace and
8034          calculate the length of the token.  */
8035       tok++;
8036       toklen = end_tok - tok;
8037
8038       if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8039         {
8040           /* At this point we've found a "thread" token, which means
8041              the user is trying to set a watchpoint that triggers
8042              only in a specific thread.  */
8043           char *endp;
8044
8045           /* Extract the thread ID from the next token.  */
8046           thread = strtol (id_tok_start, &endp, 0);
8047
8048           /* Check if the user provided a valid numeric value for the
8049              thread ID.  */
8050           if (*endp != ' ' && *endp != '\t' && *endp != '\0')
8051             error (_("Invalid thread ID specification %s."), id_tok_start);
8052
8053           /* Check if the thread actually exists.  */
8054           if (!valid_thread_id (thread))
8055             error (_("Unknown thread %d."), thread);
8056
8057           /* Truncate the string and get rid of the thread <thread_num>
8058              parameter before the parameter list is parsed by the
8059              evaluate_expression() function.  */
8060           *tok = '\0';
8061         }
8062     }
8063
8064   /* Parse the rest of the arguments.  */
8065   innermost_block = NULL;
8066   exp_start = arg;
8067   exp = parse_exp_1 (&arg, 0, 0);
8068   exp_end = arg;
8069   /* Remove trailing whitespace from the expression before saving it.
8070      This makes the eventual display of the expression string a bit
8071      prettier.  */
8072   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
8073     --exp_end;
8074
8075   /* Checking if the expression is not constant.  */
8076   if (watchpoint_exp_is_const (exp))
8077     {
8078       int len;
8079
8080       len = exp_end - exp_start;
8081       while (len > 0 && isspace (exp_start[len - 1]))
8082         len--;
8083       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
8084     }
8085
8086   exp_valid_block = innermost_block;
8087   mark = value_mark ();
8088   fetch_subexp_value (exp, &pc, &val, NULL, NULL);
8089   if (val != NULL)
8090     release_value (val);
8091
8092   tok = arg;
8093   while (*tok == ' ' || *tok == '\t')
8094     tok++;
8095   end_tok = tok;
8096
8097   while (*end_tok != ' ' && *end_tok != '\t' && *end_tok != '\000')
8098     end_tok++;
8099
8100   toklen = end_tok - tok;
8101   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8102     {
8103       struct expression *cond;
8104
8105       innermost_block = NULL;
8106       tok = cond_start = end_tok + 1;
8107       cond = parse_exp_1 (&tok, 0, 0);
8108
8109       /* The watchpoint expression may not be local, but the condition
8110          may still be.  E.g.: `watch global if local > 0'.  */
8111       cond_exp_valid_block = innermost_block;
8112
8113       xfree (cond);
8114       cond_end = tok;
8115     }
8116   if (*tok)
8117     error (_("Junk at end of command."));
8118
8119   if (accessflag == hw_read)
8120     bp_type = bp_read_watchpoint;
8121   else if (accessflag == hw_access)
8122     bp_type = bp_access_watchpoint;
8123   else
8124     bp_type = bp_hardware_watchpoint;
8125
8126   mem_cnt = can_use_hardware_watchpoint (val);
8127   if (mem_cnt == 0 && bp_type != bp_hardware_watchpoint)
8128     error (_("Expression cannot be implemented with read/access watchpoint."));
8129   if (mem_cnt != 0)
8130     {
8131       i = hw_watchpoint_used_count (bp_type, &other_type_used);
8132       target_resources_ok = 
8133         target_can_use_hardware_watchpoint (bp_type, i + mem_cnt, 
8134                                             other_type_used);
8135       if (target_resources_ok == 0 && bp_type != bp_hardware_watchpoint)
8136         error (_("Target does not support this type of hardware watchpoint."));
8137
8138       if (target_resources_ok < 0 && bp_type != bp_hardware_watchpoint)
8139         error (_("Target can only support one kind of HW watchpoint at a time."));
8140     }
8141
8142   /* Change the type of breakpoint to an ordinary watchpoint if a hardware
8143      watchpoint could not be set.  */
8144   if (!mem_cnt || target_resources_ok <= 0)
8145     bp_type = bp_watchpoint;
8146
8147   frame = block_innermost_frame (exp_valid_block);
8148
8149   /* If the expression is "local", then set up a "watchpoint scope"
8150      breakpoint at the point where we've left the scope of the watchpoint
8151      expression.  Create the scope breakpoint before the watchpoint, so
8152      that we will encounter it first in bpstat_stop_status.  */
8153   if (exp_valid_block && frame)
8154     {
8155       if (frame_id_p (frame_unwind_caller_id (frame)))
8156         {
8157           scope_breakpoint
8158             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
8159                                           frame_unwind_caller_pc (frame),
8160                                           bp_watchpoint_scope);
8161
8162           scope_breakpoint->enable_state = bp_enabled;
8163
8164           /* Automatically delete the breakpoint when it hits.  */
8165           scope_breakpoint->disposition = disp_del;
8166
8167           /* Only break in the proper frame (help with recursion).  */
8168           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
8169
8170           /* Set the address at which we will stop.  */
8171           scope_breakpoint->loc->gdbarch
8172             = frame_unwind_caller_arch (frame);
8173           scope_breakpoint->loc->requested_address
8174             = frame_unwind_caller_pc (frame);
8175           scope_breakpoint->loc->address
8176             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
8177                                          scope_breakpoint->loc->requested_address,
8178                                          scope_breakpoint->type);
8179         }
8180     }
8181
8182   /* Now set up the breakpoint.  */
8183   b = set_raw_breakpoint_without_location (NULL, bp_type);
8184   set_breakpoint_count (breakpoint_count + 1);
8185   b->number = breakpoint_count;
8186   b->thread = thread;
8187   b->disposition = disp_donttouch;
8188   b->exp = exp;
8189   b->exp_valid_block = exp_valid_block;
8190   b->cond_exp_valid_block = cond_exp_valid_block;
8191   b->exp_string = savestring (exp_start, exp_end - exp_start);
8192   b->val = val;
8193   b->val_valid = 1;
8194   if (cond_start)
8195     b->cond_string = savestring (cond_start, cond_end - cond_start);
8196   else
8197     b->cond_string = 0;
8198
8199   if (frame)
8200     {
8201       b->watchpoint_frame = get_frame_id (frame);
8202       b->watchpoint_thread = inferior_ptid;
8203     }
8204   else
8205     {
8206       b->watchpoint_frame = null_frame_id;
8207       b->watchpoint_thread = null_ptid;
8208     }
8209
8210   if (scope_breakpoint != NULL)
8211     {
8212       /* The scope breakpoint is related to the watchpoint.  We will
8213          need to act on them together.  */
8214       b->related_breakpoint = scope_breakpoint;
8215       scope_breakpoint->related_breakpoint = b;
8216     }
8217
8218   value_free_to_mark (mark);
8219
8220   /* Finally update the new watchpoint.  This creates the locations
8221      that should be inserted.  */
8222   update_watchpoint (b, 1);
8223
8224   mention (b);
8225   update_global_location_list (1);
8226 }
8227
8228 /* Return count of locations need to be watched and can be handled
8229    in hardware.  If the watchpoint can not be handled
8230    in hardware return zero.  */
8231
8232 static int
8233 can_use_hardware_watchpoint (struct value *v)
8234 {
8235   int found_memory_cnt = 0;
8236   struct value *head = v;
8237
8238   /* Did the user specifically forbid us to use hardware watchpoints? */
8239   if (!can_use_hw_watchpoints)
8240     return 0;
8241
8242   /* Make sure that the value of the expression depends only upon
8243      memory contents, and values computed from them within GDB.  If we
8244      find any register references or function calls, we can't use a
8245      hardware watchpoint.
8246
8247      The idea here is that evaluating an expression generates a series
8248      of values, one holding the value of every subexpression.  (The
8249      expression a*b+c has five subexpressions: a, b, a*b, c, and
8250      a*b+c.)  GDB's values hold almost enough information to establish
8251      the criteria given above --- they identify memory lvalues,
8252      register lvalues, computed values, etcetera.  So we can evaluate
8253      the expression, and then scan the chain of values that leaves
8254      behind to decide whether we can detect any possible change to the
8255      expression's final value using only hardware watchpoints.
8256
8257      However, I don't think that the values returned by inferior
8258      function calls are special in any way.  So this function may not
8259      notice that an expression involving an inferior function call
8260      can't be watched with hardware watchpoints.  FIXME.  */
8261   for (; v; v = value_next (v))
8262     {
8263       if (VALUE_LVAL (v) == lval_memory)
8264         {
8265           if (value_lazy (v))
8266             /* A lazy memory lvalue is one that GDB never needed to fetch;
8267                we either just used its address (e.g., `a' in `a.b') or
8268                we never needed it at all (e.g., `a' in `a,b').  */
8269             ;
8270           else
8271             {
8272               /* Ahh, memory we actually used!  Check if we can cover
8273                  it with hardware watchpoints.  */
8274               struct type *vtype = check_typedef (value_type (v));
8275
8276               /* We only watch structs and arrays if user asked for it
8277                  explicitly, never if they just happen to appear in a
8278                  middle of some value chain.  */
8279               if (v == head
8280                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
8281                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
8282                 {
8283                   CORE_ADDR vaddr = value_address (v);
8284                   int       len   = TYPE_LENGTH (value_type (v));
8285
8286                   if (!target_region_ok_for_hw_watchpoint (vaddr, len))
8287                     return 0;
8288                   else
8289                     found_memory_cnt++;
8290                 }
8291             }
8292         }
8293       else if (VALUE_LVAL (v) != not_lval
8294                && deprecated_value_modifiable (v) == 0)
8295         return 0;       /* These are values from the history (e.g., $1).  */
8296       else if (VALUE_LVAL (v) == lval_register)
8297         return 0;       /* Cannot watch a register with a HW watchpoint.  */
8298     }
8299
8300   /* The expression itself looks suitable for using a hardware
8301      watchpoint, but give the target machine a chance to reject it.  */
8302   return found_memory_cnt;
8303 }
8304
8305 void
8306 watch_command_wrapper (char *arg, int from_tty)
8307 {
8308   watch_command (arg, from_tty);
8309 }
8310
8311 static void
8312 watch_command (char *arg, int from_tty)
8313 {
8314   watch_command_1 (arg, hw_write, from_tty);
8315 }
8316
8317 void
8318 rwatch_command_wrapper (char *arg, int from_tty)
8319 {
8320   rwatch_command (arg, from_tty);
8321 }
8322
8323 static void
8324 rwatch_command (char *arg, int from_tty)
8325 {
8326   watch_command_1 (arg, hw_read, from_tty);
8327 }
8328
8329 void
8330 awatch_command_wrapper (char *arg, int from_tty)
8331 {
8332   awatch_command (arg, from_tty);
8333 }
8334
8335 static void
8336 awatch_command (char *arg, int from_tty)
8337 {
8338   watch_command_1 (arg, hw_access, from_tty);
8339 }
8340 \f
8341
8342 /* Helper routines for the until_command routine in infcmd.c.  Here
8343    because it uses the mechanisms of breakpoints.  */
8344
8345 struct until_break_command_continuation_args
8346 {
8347   struct breakpoint *breakpoint;
8348   struct breakpoint *breakpoint2;
8349 };
8350
8351 /* This function is called by fetch_inferior_event via the
8352    cmd_continuation pointer, to complete the until command. It takes
8353    care of cleaning up the temporary breakpoints set up by the until
8354    command. */
8355 static void
8356 until_break_command_continuation (void *arg)
8357 {
8358   struct until_break_command_continuation_args *a = arg;
8359
8360   delete_breakpoint (a->breakpoint);
8361   if (a->breakpoint2)
8362     delete_breakpoint (a->breakpoint2);
8363 }
8364
8365 void
8366 until_break_command (char *arg, int from_tty, int anywhere)
8367 {
8368   struct symtabs_and_lines sals;
8369   struct symtab_and_line sal;
8370   struct frame_info *frame = get_selected_frame (NULL);
8371   struct breakpoint *breakpoint;
8372   struct breakpoint *breakpoint2 = NULL;
8373   struct cleanup *old_chain;
8374
8375   clear_proceed_status ();
8376
8377   /* Set a breakpoint where the user wants it and at return from
8378      this function */
8379
8380   if (default_breakpoint_valid)
8381     sals = decode_line_1 (&arg, 1, default_breakpoint_symtab,
8382                           default_breakpoint_line, (char ***) NULL, NULL);
8383   else
8384     sals = decode_line_1 (&arg, 1, (struct symtab *) NULL, 
8385                           0, (char ***) NULL, NULL);
8386
8387   if (sals.nelts != 1)
8388     error (_("Couldn't get information on specified line."));
8389
8390   sal = sals.sals[0];
8391   xfree (sals.sals);    /* malloc'd, so freed */
8392
8393   if (*arg)
8394     error (_("Junk at end of arguments."));
8395
8396   resolve_sal_pc (&sal);
8397
8398   if (anywhere)
8399     /* If the user told us to continue until a specified location,
8400        we don't specify a frame at which we need to stop.  */
8401     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
8402                                            null_frame_id, bp_until);
8403   else
8404     /* Otherwise, specify the selected frame, because we want to stop only
8405        at the very same frame.  */
8406     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
8407                                            get_stack_frame_id (frame),
8408                                            bp_until);
8409
8410   old_chain = make_cleanup_delete_breakpoint (breakpoint);
8411
8412   /* Keep within the current frame, or in frames called by the current
8413      one.  */
8414
8415   if (frame_id_p (frame_unwind_caller_id (frame)))
8416     {
8417       sal = find_pc_line (frame_unwind_caller_pc (frame), 0);
8418       sal.pc = frame_unwind_caller_pc (frame);
8419       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
8420                                               sal,
8421                                               frame_unwind_caller_id (frame),
8422                                               bp_until);
8423       make_cleanup_delete_breakpoint (breakpoint2);
8424     }
8425
8426   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
8427
8428   /* If we are running asynchronously, and proceed call above has actually
8429      managed to start the target, arrange for breakpoints to be
8430      deleted when the target stops.  Otherwise, we're already stopped and
8431      delete breakpoints via cleanup chain.  */
8432
8433   if (target_can_async_p () && is_running (inferior_ptid))
8434     {
8435       struct until_break_command_continuation_args *args;
8436       args = xmalloc (sizeof (*args));
8437
8438       args->breakpoint = breakpoint;
8439       args->breakpoint2 = breakpoint2;
8440
8441       discard_cleanups (old_chain);
8442       add_continuation (inferior_thread (),
8443                         until_break_command_continuation, args,
8444                         xfree);
8445     }
8446   else
8447     do_cleanups (old_chain);
8448 }
8449
8450 static void
8451 ep_skip_leading_whitespace (char **s)
8452 {
8453   if ((s == NULL) || (*s == NULL))
8454     return;
8455   while (isspace (**s))
8456     *s += 1;
8457 }
8458
8459 /* This function attempts to parse an optional "if <cond>" clause
8460    from the arg string.  If one is not found, it returns NULL.
8461
8462    Else, it returns a pointer to the condition string.  (It does not
8463    attempt to evaluate the string against a particular block.)  And,
8464    it updates arg to point to the first character following the parsed
8465    if clause in the arg string. */
8466
8467 static char *
8468 ep_parse_optional_if_clause (char **arg)
8469 {
8470   char *cond_string;
8471
8472   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
8473     return NULL;
8474
8475   /* Skip the "if" keyword. */
8476   (*arg) += 2;
8477
8478   /* Skip any extra leading whitespace, and record the start of the
8479      condition string. */
8480   ep_skip_leading_whitespace (arg);
8481   cond_string = *arg;
8482
8483   /* Assume that the condition occupies the remainder of the arg string. */
8484   (*arg) += strlen (cond_string);
8485
8486   return cond_string;
8487 }
8488
8489 /* Commands to deal with catching events, such as signals, exceptions,
8490    process start/exit, etc.  */
8491
8492 typedef enum
8493 {
8494   catch_fork_temporary, catch_vfork_temporary,
8495   catch_fork_permanent, catch_vfork_permanent
8496 }
8497 catch_fork_kind;
8498
8499 static void
8500 catch_fork_command_1 (char *arg, int from_tty, 
8501                       struct cmd_list_element *command)
8502 {
8503   struct gdbarch *gdbarch = get_current_arch ();
8504   char *cond_string = NULL;
8505   catch_fork_kind fork_kind;
8506   int tempflag;
8507
8508   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
8509   tempflag = (fork_kind == catch_fork_temporary
8510               || fork_kind == catch_vfork_temporary);
8511
8512   if (!arg)
8513     arg = "";
8514   ep_skip_leading_whitespace (&arg);
8515
8516   /* The allowed syntax is:
8517      catch [v]fork
8518      catch [v]fork if <cond>
8519
8520      First, check if there's an if clause. */
8521   cond_string = ep_parse_optional_if_clause (&arg);
8522
8523   if ((*arg != '\0') && !isspace (*arg))
8524     error (_("Junk at end of arguments."));
8525
8526   /* If this target supports it, create a fork or vfork catchpoint
8527      and enable reporting of such events. */
8528   switch (fork_kind)
8529     {
8530     case catch_fork_temporary:
8531     case catch_fork_permanent:
8532       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
8533                                           &catch_fork_breakpoint_ops);
8534       break;
8535     case catch_vfork_temporary:
8536     case catch_vfork_permanent:
8537       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
8538                                           &catch_vfork_breakpoint_ops);
8539       break;
8540     default:
8541       error (_("unsupported or unknown fork kind; cannot catch it"));
8542       break;
8543     }
8544 }
8545
8546 static void
8547 catch_exec_command_1 (char *arg, int from_tty, 
8548                       struct cmd_list_element *command)
8549 {
8550   struct gdbarch *gdbarch = get_current_arch ();
8551   int tempflag;
8552   char *cond_string = NULL;
8553
8554   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8555
8556   if (!arg)
8557     arg = "";
8558   ep_skip_leading_whitespace (&arg);
8559
8560   /* The allowed syntax is:
8561      catch exec
8562      catch exec if <cond>
8563
8564      First, check if there's an if clause. */
8565   cond_string = ep_parse_optional_if_clause (&arg);
8566
8567   if ((*arg != '\0') && !isspace (*arg))
8568     error (_("Junk at end of arguments."));
8569
8570   /* If this target supports it, create an exec catchpoint
8571      and enable reporting of such events. */
8572   create_catchpoint (gdbarch, tempflag, cond_string,
8573                      &catch_exec_breakpoint_ops);
8574 }
8575
8576 static enum print_stop_action
8577 print_exception_catchpoint (struct breakpoint *b)
8578 {
8579   int bp_temp, bp_throw;
8580
8581   annotate_catchpoint (b->number);
8582
8583   bp_throw = strstr (b->addr_string, "throw") != NULL;
8584   if (b->loc->address != b->loc->requested_address)
8585     breakpoint_adjustment_warning (b->loc->requested_address,
8586                                    b->loc->address,
8587                                    b->number, 1);
8588   bp_temp = b->disposition == disp_del;
8589   ui_out_text (uiout, 
8590                bp_temp ? "Temporary catchpoint "
8591                        : "Catchpoint ");
8592   if (!ui_out_is_mi_like_p (uiout))
8593     ui_out_field_int (uiout, "bkptno", b->number);
8594   ui_out_text (uiout,
8595                bp_throw ? " (exception thrown), "
8596                         : " (exception caught), ");
8597   if (ui_out_is_mi_like_p (uiout))
8598     {
8599       ui_out_field_string (uiout, "reason", 
8600                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
8601       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8602       ui_out_field_int (uiout, "bkptno", b->number);
8603     }
8604   return PRINT_SRC_AND_LOC;
8605 }
8606
8607 static void
8608 print_one_exception_catchpoint (struct breakpoint *b, 
8609                                 struct bp_location **last_loc)
8610 {
8611   struct value_print_options opts;
8612
8613   get_user_print_options (&opts);
8614   if (opts.addressprint)
8615     {
8616       annotate_field (4);
8617       if (b->loc == NULL || b->loc->shlib_disabled)
8618         ui_out_field_string (uiout, "addr", "<PENDING>");
8619       else
8620         ui_out_field_core_addr (uiout, "addr",
8621                                 b->loc->gdbarch, b->loc->address);
8622     }
8623   annotate_field (5);
8624   if (b->loc)
8625     *last_loc = b->loc;
8626   if (strstr (b->addr_string, "throw") != NULL)
8627     ui_out_field_string (uiout, "what", "exception throw");
8628   else
8629     ui_out_field_string (uiout, "what", "exception catch");
8630 }
8631
8632 static void
8633 print_mention_exception_catchpoint (struct breakpoint *b)
8634 {
8635   int bp_temp;
8636   int bp_throw;
8637
8638   bp_temp = b->disposition == disp_del;
8639   bp_throw = strstr (b->addr_string, "throw") != NULL;
8640   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
8641                               : _("Catchpoint "));
8642   ui_out_field_int (uiout, "bkptno", b->number);
8643   ui_out_text (uiout, bp_throw ? _(" (throw)")
8644                                : _(" (catch)"));
8645 }
8646
8647 /* Implement the "print_recreate" breakpoint_ops method for throw and
8648    catch catchpoints.  */
8649
8650 static void
8651 print_recreate_exception_catchpoint (struct breakpoint *b, struct ui_file *fp)
8652 {
8653   int bp_temp;
8654   int bp_throw;
8655
8656   bp_temp = b->disposition == disp_del;
8657   bp_throw = strstr (b->addr_string, "throw") != NULL;
8658   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
8659   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
8660 }
8661
8662 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops = {
8663   NULL, /* insert */
8664   NULL, /* remove */
8665   NULL, /* breakpoint_hit */
8666   print_exception_catchpoint,
8667   print_one_exception_catchpoint,
8668   print_mention_exception_catchpoint,
8669   print_recreate_exception_catchpoint
8670 };
8671
8672 static int
8673 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
8674                           enum exception_event_kind ex_event, int from_tty)
8675 {
8676   char *trigger_func_name;
8677  
8678   if (ex_event == EX_EVENT_CATCH)
8679     trigger_func_name = "__cxa_begin_catch";
8680   else
8681     trigger_func_name = "__cxa_throw";
8682
8683   create_breakpoint (get_current_arch (),
8684                      trigger_func_name, cond_string, -1,
8685                      0 /* condition and thread are valid.  */,
8686                      tempflag, bp_breakpoint,
8687                      0,
8688                      AUTO_BOOLEAN_TRUE /* pending */,
8689                      &gnu_v3_exception_catchpoint_ops, from_tty,
8690                      1 /* enabled */);
8691
8692   return 1;
8693 }
8694
8695 /* Deal with "catch catch" and "catch throw" commands */
8696
8697 static void
8698 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
8699                            int tempflag, int from_tty)
8700 {
8701   char *cond_string = NULL;
8702
8703   if (!arg)
8704     arg = "";
8705   ep_skip_leading_whitespace (&arg);
8706
8707   cond_string = ep_parse_optional_if_clause (&arg);
8708
8709   if ((*arg != '\0') && !isspace (*arg))
8710     error (_("Junk at end of arguments."));
8711
8712   if (ex_event != EX_EVENT_THROW
8713       && ex_event != EX_EVENT_CATCH)
8714     error (_("Unsupported or unknown exception event; cannot catch it"));
8715
8716   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
8717     return;
8718
8719   warning (_("Unsupported with this platform/compiler combination."));
8720 }
8721
8722 /* Implementation of "catch catch" command.  */
8723
8724 static void
8725 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
8726 {
8727   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8728
8729   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
8730 }
8731
8732 /* Implementation of "catch throw" command.  */
8733
8734 static void
8735 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
8736 {
8737   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8738
8739   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
8740 }
8741
8742 /* Create a breakpoint struct for Ada exception catchpoints.  */
8743
8744 static void
8745 create_ada_exception_breakpoint (struct gdbarch *gdbarch,
8746                                  struct symtab_and_line sal,
8747                                  char *addr_string,
8748                                  char *exp_string,
8749                                  char *cond_string,
8750                                  struct expression *cond,
8751                                  struct breakpoint_ops *ops,
8752                                  int tempflag,
8753                                  int from_tty)
8754 {
8755   struct breakpoint *b;
8756
8757   if (from_tty)
8758     {
8759       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8760       if (!loc_gdbarch)
8761         loc_gdbarch = gdbarch;
8762
8763       describe_other_breakpoints (loc_gdbarch,
8764                                   sal.pspace, sal.pc, sal.section, -1);
8765       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
8766          version for exception catchpoints, because two catchpoints
8767          used for different exception names will use the same address.
8768          In this case, a "breakpoint ... also set at..." warning is
8769          unproductive.  Besides. the warning phrasing is also a bit
8770          inapropriate, we should use the word catchpoint, and tell
8771          the user what type of catchpoint it is.  The above is good
8772          enough for now, though.  */
8773     }
8774
8775   b = set_raw_breakpoint (gdbarch, sal, bp_breakpoint);
8776   set_breakpoint_count (breakpoint_count + 1);
8777
8778   b->enable_state = bp_enabled;
8779   b->disposition = tempflag ? disp_del : disp_donttouch;
8780   b->number = breakpoint_count;
8781   b->ignore_count = 0;
8782   b->loc->cond = cond;
8783   b->addr_string = addr_string;
8784   b->language = language_ada;
8785   b->cond_string = cond_string;
8786   b->exp_string = exp_string;
8787   b->thread = -1;
8788   b->ops = ops;
8789
8790   mention (b);
8791   update_global_location_list (1);
8792 }
8793
8794 /* Implement the "catch exception" command.  */
8795
8796 static void
8797 catch_ada_exception_command (char *arg, int from_tty,
8798                              struct cmd_list_element *command)
8799 {
8800   struct gdbarch *gdbarch = get_current_arch ();
8801   int tempflag;
8802   struct symtab_and_line sal;
8803   char *addr_string = NULL;
8804   char *exp_string = NULL;
8805   char *cond_string = NULL;
8806   struct expression *cond = NULL;
8807   struct breakpoint_ops *ops = NULL;
8808
8809   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8810
8811   if (!arg)
8812     arg = "";
8813   sal = ada_decode_exception_location (arg, &addr_string, &exp_string,
8814                                        &cond_string, &cond, &ops);
8815   create_ada_exception_breakpoint (gdbarch, sal, addr_string, exp_string,
8816                                    cond_string, cond, ops, tempflag,
8817                                    from_tty);
8818 }
8819
8820 /* Cleanup function for a syscall filter list.  */
8821 static void
8822 clean_up_filters (void *arg)
8823 {
8824   VEC(int) *iter = *(VEC(int) **) arg;
8825   VEC_free (int, iter);
8826 }
8827
8828 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
8829    filter list, or NULL if no filtering is required.  */
8830 static VEC(int) *
8831 catch_syscall_split_args (char *arg)
8832 {
8833   VEC(int) *result = NULL;
8834   struct cleanup *cleanup = make_cleanup (clean_up_filters, &result);
8835
8836   while (*arg != '\0')
8837     {
8838       int i, syscall_number;
8839       char *endptr;
8840       char cur_name[128];
8841       struct syscall s;
8842
8843       /* Skip whitespace.  */
8844       while (isspace (*arg))
8845         arg++;
8846
8847       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
8848         cur_name[i] = arg[i];
8849       cur_name[i] = '\0';
8850       arg += i;
8851
8852       /* Check if the user provided a syscall name or a number.  */
8853       syscall_number = (int) strtol (cur_name, &endptr, 0);
8854       if (*endptr == '\0')
8855         get_syscall_by_number (syscall_number, &s);
8856       else
8857         {
8858           /* We have a name.  Let's check if it's valid and convert it
8859              to a number.  */
8860           get_syscall_by_name (cur_name, &s);
8861
8862           if (s.number == UNKNOWN_SYSCALL)
8863             /* Here we have to issue an error instead of a warning, because
8864                GDB cannot do anything useful if there's no syscall number to
8865                be caught.  */
8866             error (_("Unknown syscall name '%s'."), cur_name);
8867         }
8868
8869       /* Ok, it's valid.  */
8870       VEC_safe_push (int, result, s.number);
8871     }
8872
8873   discard_cleanups (cleanup);
8874   return result;
8875 }
8876
8877 /* Implement the "catch syscall" command.  */
8878
8879 static void
8880 catch_syscall_command_1 (char *arg, int from_tty, 
8881                          struct cmd_list_element *command)
8882 {
8883   int tempflag;
8884   VEC(int) *filter;
8885   struct syscall s;
8886   struct gdbarch *gdbarch = get_current_arch ();
8887
8888   /* Checking if the feature if supported.  */
8889   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
8890     error (_("The feature 'catch syscall' is not supported on \
8891 this architeture yet."));
8892
8893   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8894
8895   ep_skip_leading_whitespace (&arg);
8896
8897   /* We need to do this first "dummy" translation in order
8898      to get the syscall XML file loaded or, most important,
8899      to display a warning to the user if there's no XML file
8900      for his/her architecture.  */
8901   get_syscall_by_number (0, &s);
8902
8903   /* The allowed syntax is:
8904      catch syscall
8905      catch syscall <name | number> [<name | number> ... <name | number>]
8906
8907      Let's check if there's a syscall name.  */
8908
8909   if (arg != NULL)
8910     filter = catch_syscall_split_args (arg);
8911   else
8912     filter = NULL;
8913
8914   create_syscall_event_catchpoint (tempflag, filter,
8915                                    &catch_syscall_breakpoint_ops);
8916 }
8917
8918 /* Implement the "catch assert" command.  */
8919
8920 static void
8921 catch_assert_command (char *arg, int from_tty, struct cmd_list_element *command)
8922 {
8923   struct gdbarch *gdbarch = get_current_arch ();
8924   int tempflag;
8925   struct symtab_and_line sal;
8926   char *addr_string = NULL;
8927   struct breakpoint_ops *ops = NULL;
8928
8929   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
8930
8931   if (!arg)
8932     arg = "";
8933   sal = ada_decode_assert_location (arg, &addr_string, &ops);
8934   create_ada_exception_breakpoint (gdbarch, sal, addr_string, NULL, NULL, NULL,
8935                                    ops, tempflag, from_tty);
8936 }
8937
8938 static void
8939 catch_command (char *arg, int from_tty)
8940 {
8941   error (_("Catch requires an event name."));
8942 }
8943 \f
8944
8945 static void
8946 tcatch_command (char *arg, int from_tty)
8947 {
8948   error (_("Catch requires an event name."));
8949 }
8950
8951 /* Delete breakpoints by address or line.  */
8952
8953 static void
8954 clear_command (char *arg, int from_tty)
8955 {
8956   struct breakpoint *b;
8957   VEC(breakpoint_p) *found = 0;
8958   int ix;
8959   int default_match;
8960   struct symtabs_and_lines sals;
8961   struct symtab_and_line sal;
8962   int i;
8963
8964   if (arg)
8965     {
8966       sals = decode_line_spec (arg, 1);
8967       default_match = 0;
8968     }
8969   else
8970     {
8971       sals.sals = (struct symtab_and_line *)
8972         xmalloc (sizeof (struct symtab_and_line));
8973       make_cleanup (xfree, sals.sals);
8974       init_sal (&sal);          /* initialize to zeroes */
8975       sal.line = default_breakpoint_line;
8976       sal.symtab = default_breakpoint_symtab;
8977       sal.pc = default_breakpoint_address;
8978       sal.pspace = default_breakpoint_pspace;
8979       if (sal.symtab == 0)
8980         error (_("No source file specified."));
8981
8982       sals.sals[0] = sal;
8983       sals.nelts = 1;
8984
8985       default_match = 1;
8986     }
8987
8988   /* We don't call resolve_sal_pc here. That's not
8989      as bad as it seems, because all existing breakpoints
8990      typically have both file/line and pc set.  So, if
8991      clear is given file/line, we can match this to existing
8992      breakpoint without obtaining pc at all.
8993
8994      We only support clearing given the address explicitly 
8995      present in breakpoint table.  Say, we've set breakpoint 
8996      at file:line. There were several PC values for that file:line,
8997      due to optimization, all in one block.
8998      We've picked one PC value. If "clear" is issued with another
8999      PC corresponding to the same file:line, the breakpoint won't
9000      be cleared.  We probably can still clear the breakpoint, but 
9001      since the other PC value is never presented to user, user
9002      can only find it by guessing, and it does not seem important
9003      to support that.  */
9004
9005   /* For each line spec given, delete bps which correspond
9006      to it.  Do it in two passes, solely to preserve the current
9007      behavior that from_tty is forced true if we delete more than
9008      one breakpoint.  */
9009
9010   found = NULL;
9011   for (i = 0; i < sals.nelts; i++)
9012     {
9013       /* If exact pc given, clear bpts at that pc.
9014          If line given (pc == 0), clear all bpts on specified line.
9015          If defaulting, clear all bpts on default line
9016          or at default pc.
9017
9018          defaulting    sal.pc != 0    tests to do
9019
9020          0              1             pc
9021          1              1             pc _and_ line
9022          0              0             line
9023          1              0             <can't happen> */
9024
9025       sal = sals.sals[i];
9026
9027       /* Find all matching breakpoints and add them to
9028          'found'.  */
9029       ALL_BREAKPOINTS (b)
9030         {
9031           int match = 0;
9032           /* Are we going to delete b? */
9033           if (b->type != bp_none && !is_watchpoint (b))
9034             {
9035               struct bp_location *loc = b->loc;
9036               for (; loc; loc = loc->next)
9037                 {
9038                   int pc_match = sal.pc
9039                     && (loc->pspace == sal.pspace)
9040                     && (loc->address == sal.pc)
9041                     && (!section_is_overlay (loc->section)
9042                         || loc->section == sal.section);
9043                   int line_match = ((default_match || (0 == sal.pc))
9044                                     && b->source_file != NULL
9045                                     && sal.symtab != NULL
9046                                     && sal.pspace == loc->pspace
9047                                     && strcmp (b->source_file, sal.symtab->filename) == 0
9048                                     && b->line_number == sal.line);
9049                   if (pc_match || line_match)
9050                     {
9051                       match = 1;
9052                       break;
9053                     }
9054                 }
9055             }
9056
9057           if (match)
9058             VEC_safe_push(breakpoint_p, found, b);
9059         }
9060     }
9061   /* Now go thru the 'found' chain and delete them.  */
9062   if (VEC_empty(breakpoint_p, found))
9063     {
9064       if (arg)
9065         error (_("No breakpoint at %s."), arg);
9066       else
9067         error (_("No breakpoint at this line."));
9068     }
9069
9070   if (VEC_length(breakpoint_p, found) > 1)
9071     from_tty = 1;               /* Always report if deleted more than one */
9072   if (from_tty)
9073     {
9074       if (VEC_length(breakpoint_p, found) == 1)
9075         printf_unfiltered (_("Deleted breakpoint "));
9076       else
9077         printf_unfiltered (_("Deleted breakpoints "));
9078     }
9079   breakpoints_changed ();
9080
9081   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
9082     {
9083       if (from_tty)
9084         printf_unfiltered ("%d ", b->number);
9085       delete_breakpoint (b);
9086     }
9087   if (from_tty)
9088     putchar_unfiltered ('\n');
9089 }
9090 \f
9091 /* Delete breakpoint in BS if they are `delete' breakpoints and
9092    all breakpoints that are marked for deletion, whether hit or not.
9093    This is called after any breakpoint is hit, or after errors.  */
9094
9095 void
9096 breakpoint_auto_delete (bpstat bs)
9097 {
9098   struct breakpoint *b, *temp;
9099
9100   for (; bs; bs = bs->next)
9101     if (bs->breakpoint_at 
9102         && bs->breakpoint_at->owner
9103         && bs->breakpoint_at->owner->disposition == disp_del
9104         && bs->stop)
9105       delete_breakpoint (bs->breakpoint_at->owner);
9106
9107   ALL_BREAKPOINTS_SAFE (b, temp)
9108   {
9109     if (b->disposition == disp_del_at_next_stop)
9110       delete_breakpoint (b);
9111   }
9112 }
9113
9114 /* A comparison function for bp_location AP and BP being interfaced to qsort.
9115    Sort elements primarily by their ADDRESS (no matter what does
9116    breakpoint_address_is_meaningful say for its OWNER), secondarily by ordering
9117    first bp_permanent OWNERed elements and terciarily just ensuring the array
9118    is sorted stable way despite qsort being an instable algorithm.  */
9119
9120 static int
9121 bp_location_compare (const void *ap, const void *bp)
9122 {
9123   struct bp_location *a = *(void **) ap;
9124   struct bp_location *b = *(void **) bp;
9125   /* A and B come from existing breakpoints having non-NULL OWNER.  */
9126   int a_perm = a->owner->enable_state == bp_permanent;
9127   int b_perm = b->owner->enable_state == bp_permanent;
9128
9129   if (a->address != b->address)
9130     return (a->address > b->address) - (a->address < b->address);
9131
9132   /* Sort permanent breakpoints first.  */
9133   if (a_perm != b_perm)
9134     return (a_perm < b_perm) - (a_perm > b_perm);
9135
9136   /* Make the user-visible order stable across GDB runs.  Locations of the same
9137      breakpoint can be sorted in arbitrary order.  */
9138
9139   if (a->owner->number != b->owner->number)
9140     return (a->owner->number > b->owner->number)
9141            - (a->owner->number < b->owner->number);
9142
9143   return (a > b) - (a < b);
9144 }
9145
9146 /* Set bp_location_placed_address_before_address_max and
9147    bp_location_shadow_len_after_address_max according to the current content of
9148    the bp_location array.  */
9149
9150 static void
9151 bp_location_target_extensions_update (void)
9152 {
9153   struct bp_location *bl, **blp_tmp;
9154
9155   bp_location_placed_address_before_address_max = 0;
9156   bp_location_shadow_len_after_address_max = 0;
9157
9158   ALL_BP_LOCATIONS (bl, blp_tmp)
9159     {
9160       CORE_ADDR start, end, addr;
9161
9162       if (!bp_location_has_shadow (bl))
9163         continue;
9164
9165       start = bl->target_info.placed_address;
9166       end = start + bl->target_info.shadow_len;
9167
9168       gdb_assert (bl->address >= start);
9169       addr = bl->address - start;
9170       if (addr > bp_location_placed_address_before_address_max)
9171         bp_location_placed_address_before_address_max = addr;
9172
9173       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
9174
9175       gdb_assert (bl->address < end);
9176       addr = end - bl->address;
9177       if (addr > bp_location_shadow_len_after_address_max)
9178         bp_location_shadow_len_after_address_max = addr;
9179     }
9180 }
9181
9182 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
9183    into the inferior, only remove already-inserted locations that no
9184    longer should be inserted.  Functions that delete a breakpoint or
9185    breakpoints should pass false, so that deleting a breakpoint
9186    doesn't have the side effect of inserting the locations of other
9187    breakpoints that are marked not-inserted, but should_be_inserted
9188    returns true on them.
9189
9190    This behaviour is useful is situations close to tear-down -- e.g.,
9191    after an exec, while the target still has execution, but breakpoint
9192    shadows of the previous executable image should *NOT* be restored
9193    to the new image; or before detaching, where the target still has
9194    execution and wants to delete breakpoints from GDB's lists, and all
9195    breakpoints had already been removed from the inferior.  */
9196
9197 static void
9198 update_global_location_list (int should_insert)
9199 {
9200   struct breakpoint *b;
9201   struct bp_location **locp, *loc;
9202   struct cleanup *cleanups;
9203
9204   /* Used in the duplicates detection below.  When iterating over all
9205      bp_locations, points to the first bp_location of a given address.
9206      Breakpoints and watchpoints of different types are never
9207      duplicates of each other.  Keep one pointer for each type of
9208      breakpoint/watchpoint, so we only need to loop over all locations
9209      once.  */
9210   struct bp_location *bp_loc_first;  /* breakpoint */
9211   struct bp_location *wp_loc_first;  /* hardware watchpoint */
9212   struct bp_location *awp_loc_first; /* access watchpoint */
9213   struct bp_location *rwp_loc_first; /* read watchpoint */
9214
9215   /* Saved former bp_location array which we compare against the newly built
9216      bp_location from the current state of ALL_BREAKPOINTS.  */
9217   struct bp_location **old_location, **old_locp;
9218   unsigned old_location_count;
9219
9220   old_location = bp_location;
9221   old_location_count = bp_location_count;
9222   bp_location = NULL;
9223   bp_location_count = 0;
9224   cleanups = make_cleanup (xfree, old_location);
9225
9226   ALL_BREAKPOINTS (b)
9227     for (loc = b->loc; loc; loc = loc->next)
9228       bp_location_count++;
9229
9230   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
9231   locp = bp_location;
9232   ALL_BREAKPOINTS (b)
9233     for (loc = b->loc; loc; loc = loc->next)
9234       *locp++ = loc;
9235   qsort (bp_location, bp_location_count, sizeof (*bp_location),
9236          bp_location_compare);
9237
9238   bp_location_target_extensions_update ();
9239
9240   /* Identify bp_location instances that are no longer present in the new
9241      list, and therefore should be freed.  Note that it's not necessary that
9242      those locations should be removed from inferior -- if there's another
9243      location at the same address (previously marked as duplicate),
9244      we don't need to remove/insert the location.
9245      
9246      LOCP is kept in sync with OLD_LOCP, each pointing to the current and
9247      former bp_location array state respectively.  */
9248
9249   locp = bp_location;
9250   for (old_locp = old_location; old_locp < old_location + old_location_count;
9251        old_locp++)
9252     {
9253       struct bp_location *old_loc = *old_locp;
9254       struct bp_location **loc2p;
9255
9256       /* Tells if 'old_loc' is found amoung the new locations.  If not, we
9257          have to free it.  */
9258       int found_object = 0;
9259       /* Tells if the location should remain inserted in the target.  */
9260       int keep_in_target = 0;
9261       int removed = 0;
9262
9263       /* Skip LOCP entries which will definitely never be needed.  Stop either
9264          at or being the one matching OLD_LOC.  */
9265       while (locp < bp_location + bp_location_count
9266              && (*locp)->address < old_loc->address)
9267         locp++;
9268
9269       for (loc2p = locp;
9270            (loc2p < bp_location + bp_location_count
9271             && (*loc2p)->address == old_loc->address);
9272            loc2p++)
9273         {
9274           if (*loc2p == old_loc)
9275             {
9276               found_object = 1;
9277               break;
9278             }
9279         }
9280
9281       /* If this location is no longer present, and inserted, look if there's
9282          maybe a new location at the same address.  If so, mark that one 
9283          inserted, and don't remove this one.  This is needed so that we 
9284          don't have a time window where a breakpoint at certain location is not
9285          inserted.  */
9286
9287       if (old_loc->inserted)
9288         {
9289           /* If the location is inserted now, we might have to remove it.  */
9290
9291           if (found_object && should_be_inserted (old_loc))
9292             {
9293               /* The location is still present in the location list, and still
9294                  should be inserted.  Don't do anything.  */
9295               keep_in_target = 1;
9296             }
9297           else
9298             {
9299               /* The location is either no longer present, or got disabled.
9300                  See if there's another location at the same address, in which 
9301                  case we don't need to remove this one from the target.  */
9302
9303               /* OLD_LOC comes from existing struct breakpoint.  */
9304               if (breakpoint_address_is_meaningful (old_loc->owner))
9305                 {
9306                   for (loc2p = locp;
9307                        (loc2p < bp_location + bp_location_count
9308                         && (*loc2p)->address == old_loc->address);
9309                        loc2p++)
9310                     {
9311                       struct bp_location *loc2 = *loc2p;
9312
9313                       if (breakpoint_locations_match (loc2, old_loc))
9314                         {
9315                           /* For the sake of should_be_inserted.
9316                              Duplicates check below will fix up this later.  */
9317                           loc2->duplicate = 0;
9318
9319                           /* Read watchpoint locations are switched to
9320                              access watchpoints, if the former are not
9321                              supported, but the latter are.  */
9322                           if (is_hardware_watchpoint (old_loc->owner))
9323                             {
9324                               gdb_assert (is_hardware_watchpoint (loc2->owner));
9325                               loc2->watchpoint_type = old_loc->watchpoint_type;
9326                             }
9327
9328                           if (loc2 != old_loc && should_be_inserted (loc2))
9329                             {
9330                               loc2->inserted = 1;
9331                               loc2->target_info = old_loc->target_info;
9332                               keep_in_target = 1;
9333                               break;
9334                             }
9335                         }
9336                     }
9337                 }
9338             }
9339
9340           if (!keep_in_target)
9341             {
9342               if (remove_breakpoint (old_loc, mark_uninserted))
9343                 {
9344                   /* This is just about all we can do.  We could keep this
9345                      location on the global list, and try to remove it next
9346                      time, but there's no particular reason why we will
9347                      succeed next time.  
9348                      
9349                      Note that at this point, old_loc->owner is still valid,
9350                      as delete_breakpoint frees the breakpoint only
9351                      after calling us.  */
9352                   printf_filtered (_("warning: Error removing breakpoint %d\n"), 
9353                                    old_loc->owner->number);
9354                 }
9355               removed = 1;
9356             }
9357         }
9358
9359       if (!found_object)
9360         {
9361           if (removed && non_stop
9362               && breakpoint_address_is_meaningful (old_loc->owner)
9363               && !is_hardware_watchpoint (old_loc->owner))
9364             {
9365               /* This location was removed from the target.  In
9366                  non-stop mode, a race condition is possible where
9367                  we've removed a breakpoint, but stop events for that
9368                  breakpoint are already queued and will arrive later.
9369                  We apply an heuristic to be able to distinguish such
9370                  SIGTRAPs from other random SIGTRAPs: we keep this
9371                  breakpoint location for a bit, and will retire it
9372                  after we see some number of events.  The theory here
9373                  is that reporting of events should, "on the average",
9374                  be fair, so after a while we'll see events from all
9375                  threads that have anything of interest, and no longer
9376                  need to keep this breakpoint location around.  We
9377                  don't hold locations forever so to reduce chances of
9378                  mistaking a non-breakpoint SIGTRAP for a breakpoint
9379                  SIGTRAP.
9380
9381                  The heuristic failing can be disastrous on
9382                  decr_pc_after_break targets.
9383
9384                  On decr_pc_after_break targets, like e.g., x86-linux,
9385                  if we fail to recognize a late breakpoint SIGTRAP,
9386                  because events_till_retirement has reached 0 too
9387                  soon, we'll fail to do the PC adjustment, and report
9388                  a random SIGTRAP to the user.  When the user resumes
9389                  the inferior, it will most likely immediately crash
9390                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
9391                  corrupted, because of being resumed e.g., in the
9392                  middle of a multi-byte instruction, or skipped a
9393                  one-byte instruction.  This was actually seen happen
9394                  on native x86-linux, and should be less rare on
9395                  targets that do not support new thread events, like
9396                  remote, due to the heuristic depending on
9397                  thread_count.
9398
9399                  Mistaking a random SIGTRAP for a breakpoint trap
9400                  causes similar symptoms (PC adjustment applied when
9401                  it shouldn't), but then again, playing with SIGTRAPs
9402                  behind the debugger's back is asking for trouble.
9403
9404                  Since hardware watchpoint traps are always
9405                  distinguishable from other traps, so we don't need to
9406                  apply keep hardware watchpoint moribund locations
9407                  around.  We simply always ignore hardware watchpoint
9408                  traps we can no longer explain.  */
9409
9410               old_loc->events_till_retirement = 3 * (thread_count () + 1);
9411               old_loc->owner = NULL;
9412
9413               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
9414             }
9415           else
9416             free_bp_location (old_loc);
9417         }
9418     }
9419
9420   /* Rescan breakpoints at the same address and section, marking the
9421      first one as "first" and any others as "duplicates".  This is so
9422      that the bpt instruction is only inserted once.  If we have a
9423      permanent breakpoint at the same place as BPT, make that one the
9424      official one, and the rest as duplicates.  Permanent breakpoints
9425      are sorted first for the same address.
9426
9427      Do the same for hardware watchpoints, but also considering the
9428      watchpoint's type (regular/access/read) and length.  */
9429
9430   bp_loc_first = NULL;
9431   wp_loc_first = NULL;
9432   awp_loc_first = NULL;
9433   rwp_loc_first = NULL;
9434   ALL_BP_LOCATIONS (loc, locp)
9435     {
9436       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
9437       struct breakpoint *b = loc->owner;
9438       struct bp_location **loc_first_p;
9439
9440       if (b->enable_state == bp_disabled
9441           || b->enable_state == bp_call_disabled
9442           || b->enable_state == bp_startup_disabled
9443           || !loc->enabled
9444           || loc->shlib_disabled
9445           || !breakpoint_address_is_meaningful (b)
9446           || is_tracepoint (b))
9447         continue;
9448
9449       /* Permanent breakpoint should always be inserted.  */
9450       if (b->enable_state == bp_permanent && ! loc->inserted)
9451         internal_error (__FILE__, __LINE__,
9452                         _("allegedly permanent breakpoint is not "
9453                         "actually inserted"));
9454
9455       if (b->type == bp_hardware_watchpoint)
9456         loc_first_p = &wp_loc_first;
9457       else if (b->type == bp_read_watchpoint)
9458         loc_first_p = &rwp_loc_first;
9459       else if (b->type == bp_access_watchpoint)
9460         loc_first_p = &awp_loc_first;
9461       else
9462         loc_first_p = &bp_loc_first;
9463
9464       if (*loc_first_p == NULL
9465           || (overlay_debugging && loc->section != (*loc_first_p)->section)
9466           || !breakpoint_locations_match (loc, *loc_first_p))
9467         {
9468           *loc_first_p = loc;
9469           loc->duplicate = 0;
9470           continue;
9471         }
9472
9473       loc->duplicate = 1;
9474
9475       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
9476           && b->enable_state != bp_permanent)
9477         internal_error (__FILE__, __LINE__,
9478                         _("another breakpoint was inserted on top of "
9479                         "a permanent breakpoint"));
9480     }
9481
9482   if (breakpoints_always_inserted_mode () && should_insert
9483       && (have_live_inferiors ()
9484           || (gdbarch_has_global_breakpoints (target_gdbarch))))
9485     insert_breakpoint_locations ();
9486
9487   do_cleanups (cleanups);
9488 }
9489
9490 void
9491 breakpoint_retire_moribund (void)
9492 {
9493   struct bp_location *loc;
9494   int ix;
9495
9496   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
9497     if (--(loc->events_till_retirement) == 0)
9498       {
9499         free_bp_location (loc);
9500         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
9501         --ix;
9502       }
9503 }
9504
9505 static void
9506 update_global_location_list_nothrow (int inserting)
9507 {
9508   struct gdb_exception e;
9509
9510   TRY_CATCH (e, RETURN_MASK_ERROR)
9511     update_global_location_list (inserting);
9512 }
9513
9514 /* Clear LOC from a BPS.  */
9515 static void
9516 bpstat_remove_bp_location (bpstat bps, struct bp_location *loc)
9517 {
9518   bpstat bs;
9519
9520   for (bs = bps; bs; bs = bs->next)
9521     if (bs->breakpoint_at == loc)
9522       {
9523         bs->breakpoint_at = NULL;
9524         bs->old_val = NULL;
9525         /* bs->commands will be freed later.  */
9526       }
9527 }
9528
9529 /* Callback for iterate_over_threads.  */
9530 static int
9531 bpstat_remove_bp_location_callback (struct thread_info *th, void *data)
9532 {
9533   struct bp_location *loc = data;
9534
9535   bpstat_remove_bp_location (th->stop_bpstat, loc);
9536   return 0;
9537 }
9538
9539 /* Delete a breakpoint and clean up all traces of it in the data
9540    structures. */
9541
9542 void
9543 delete_breakpoint (struct breakpoint *bpt)
9544 {
9545   struct breakpoint *b;
9546
9547   gdb_assert (bpt != NULL);
9548
9549   /* Has this bp already been deleted?  This can happen because multiple
9550      lists can hold pointers to bp's.  bpstat lists are especial culprits.
9551
9552      One example of this happening is a watchpoint's scope bp.  When the
9553      scope bp triggers, we notice that the watchpoint is out of scope, and
9554      delete it.  We also delete its scope bp.  But the scope bp is marked
9555      "auto-deleting", and is already on a bpstat.  That bpstat is then
9556      checked for auto-deleting bp's, which are deleted.
9557
9558      A real solution to this problem might involve reference counts in bp's,
9559      and/or giving them pointers back to their referencing bpstat's, and
9560      teaching delete_breakpoint to only free a bp's storage when no more
9561      references were extent.  A cheaper bandaid was chosen.  */
9562   if (bpt->type == bp_none)
9563     return;
9564
9565   /* At least avoid this stale reference until the reference counting of
9566      breakpoints gets resolved.  */
9567   if (bpt->related_breakpoint != NULL)
9568     {
9569       gdb_assert (bpt->related_breakpoint->related_breakpoint == bpt);
9570       bpt->related_breakpoint->disposition = disp_del_at_next_stop;
9571       bpt->related_breakpoint->related_breakpoint = NULL;
9572       bpt->related_breakpoint = NULL;
9573     }
9574
9575   observer_notify_breakpoint_deleted (bpt->number);
9576
9577   if (breakpoint_chain == bpt)
9578     breakpoint_chain = bpt->next;
9579
9580   ALL_BREAKPOINTS (b)
9581     if (b->next == bpt)
9582     {
9583       b->next = bpt->next;
9584       break;
9585     }
9586
9587   decref_counted_command_line (&bpt->commands);
9588   xfree (bpt->cond_string);
9589   xfree (bpt->cond_exp);
9590   xfree (bpt->addr_string);
9591   xfree (bpt->exp);
9592   xfree (bpt->exp_string);
9593   value_free (bpt->val);
9594   xfree (bpt->source_file);
9595   xfree (bpt->exec_pathname);
9596   clean_up_filters (&bpt->syscalls_to_be_caught);
9597
9598   /* Now that breakpoint is removed from breakpoint
9599      list, update the global location list.  This
9600      will remove locations that used to belong to
9601      this breakpoint.  Do this before freeing
9602      the breakpoint itself, since remove_breakpoint
9603      looks at location's owner.  It might be better
9604      design to have location completely self-contained,
9605      but it's not the case now.  */
9606   update_global_location_list (0);
9607
9608
9609   /* On the chance that someone will soon try again to delete this same
9610      bp, we mark it as deleted before freeing its storage. */
9611   bpt->type = bp_none;
9612
9613   xfree (bpt);
9614 }
9615
9616 static void
9617 do_delete_breakpoint_cleanup (void *b)
9618 {
9619   delete_breakpoint (b);
9620 }
9621
9622 struct cleanup *
9623 make_cleanup_delete_breakpoint (struct breakpoint *b)
9624 {
9625   return make_cleanup (do_delete_breakpoint_cleanup, b);
9626 }
9627
9628 /* A callback for map_breakpoint_numbers that calls
9629    delete_breakpoint.  */
9630
9631 static void
9632 do_delete_breakpoint (struct breakpoint *b, void *ignore)
9633 {
9634   delete_breakpoint (b);
9635 }
9636
9637 void
9638 delete_command (char *arg, int from_tty)
9639 {
9640   struct breakpoint *b, *temp;
9641
9642   dont_repeat ();
9643
9644   if (arg == 0)
9645     {
9646       int breaks_to_delete = 0;
9647
9648       /* Delete all breakpoints if no argument.
9649          Do not delete internal or call-dummy breakpoints, these
9650          have to be deleted with an explicit breakpoint number argument.  */
9651       ALL_BREAKPOINTS (b)
9652       {
9653         if (b->type != bp_call_dummy
9654             && b->type != bp_std_terminate
9655             && b->type != bp_shlib_event
9656             && b->type != bp_jit_event
9657             && b->type != bp_thread_event
9658             && b->type != bp_overlay_event
9659             && b->type != bp_longjmp_master
9660             && b->type != bp_std_terminate_master
9661             && b->number >= 0)
9662           {
9663             breaks_to_delete = 1;
9664             break;
9665           }
9666       }
9667
9668       /* Ask user only if there are some breakpoints to delete.  */
9669       if (!from_tty
9670           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
9671         {
9672           ALL_BREAKPOINTS_SAFE (b, temp)
9673           {
9674             if (b->type != bp_call_dummy
9675                 && b->type != bp_std_terminate
9676                 && b->type != bp_shlib_event
9677                 && b->type != bp_thread_event
9678                 && b->type != bp_jit_event
9679                 && b->type != bp_overlay_event
9680                 && b->type != bp_longjmp_master
9681                 && b->type != bp_std_terminate_master
9682                 && b->number >= 0)
9683               delete_breakpoint (b);
9684           }
9685         }
9686     }
9687   else
9688     map_breakpoint_numbers (arg, do_delete_breakpoint, NULL);
9689 }
9690
9691 static int
9692 all_locations_are_pending (struct bp_location *loc)
9693 {
9694   for (; loc; loc = loc->next)
9695     if (!loc->shlib_disabled)
9696       return 0;
9697   return 1;
9698 }
9699
9700 /* Subroutine of update_breakpoint_locations to simplify it.
9701    Return non-zero if multiple fns in list LOC have the same name.
9702    Null names are ignored.  */
9703
9704 static int
9705 ambiguous_names_p (struct bp_location *loc)
9706 {
9707   struct bp_location *l;
9708   htab_t htab = htab_create_alloc (13, htab_hash_string,
9709                                    (int (*) (const void *, 
9710                                              const void *)) streq,
9711                                    NULL, xcalloc, xfree);
9712
9713   for (l = loc; l != NULL; l = l->next)
9714     {
9715       const char **slot;
9716       const char *name = l->function_name;
9717
9718       /* Allow for some names to be NULL, ignore them.  */
9719       if (name == NULL)
9720         continue;
9721
9722       slot = (const char **) htab_find_slot (htab, (const void *) name,
9723                                              INSERT);
9724       /* NOTE: We can assume slot != NULL here because xcalloc never returns
9725          NULL.  */
9726       if (*slot != NULL)
9727         {
9728           htab_delete (htab);
9729           return 1;
9730         }
9731       *slot = name;
9732     }
9733
9734   htab_delete (htab);
9735   return 0;
9736 }
9737
9738 /* When symbols change, it probably means the sources changed as well,
9739    and it might mean the static tracepoint markers are no longer at
9740    the same address or line numbers they used to be at last we
9741    checked.  Losing your static tracepoints whenever you rebuild is
9742    undesirable.  This function tries to resync/rematch gdb static
9743    tracepoints with the markers on the target, for static tracepoints
9744    that have not been set by marker id.  Static tracepoint that have
9745    been set by marker id are reset by marker id in breakpoint_re_set.
9746    The heuristic is:
9747
9748    1) For a tracepoint set at a specific address, look for a marker at
9749    the old PC.  If one is found there, assume to be the same marker.
9750    If the name / string id of the marker found is different from the
9751    previous known name, assume that means the user renamed the marker
9752    in the sources, and output a warning.
9753
9754    2) For a tracepoint set at a given line number, look for a marker
9755    at the new address of the old line number.  If one is found there,
9756    assume to be the same marker.  If the name / string id of the
9757    marker found is different from the previous known name, assume that
9758    means the user renamed the marker in the sources, and output a
9759    warning.
9760
9761    3) If a marker is no longer found at the same address or line, it
9762    may mean the marker no longer exists.  But it may also just mean
9763    the code changed a bit.  Maybe the user added a few lines of code
9764    that made the marker move up or down (in line number terms).  Ask
9765    the target for info about the marker with the string id as we knew
9766    it.  If found, update line number and address in the matching
9767    static tracepoint.  This will get confused if there's more than one
9768    marker with the same ID (possible in UST, although unadvised
9769    precisely because it confuses tools).  */
9770
9771 static struct symtab_and_line
9772 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
9773 {
9774   struct static_tracepoint_marker marker;
9775   CORE_ADDR pc;
9776   int i;
9777
9778   pc = sal.pc;
9779   if (sal.line)
9780     find_line_pc (sal.symtab, sal.line, &pc);
9781
9782   if (target_static_tracepoint_marker_at (pc, &marker))
9783     {
9784       if (strcmp (b->static_trace_marker_id, marker.str_id) != 0)
9785         warning (_("static tracepoint %d changed probed marker from %s to %s"),
9786                  b->number,
9787                  b->static_trace_marker_id, marker.str_id);
9788
9789       xfree (b->static_trace_marker_id);
9790       b->static_trace_marker_id = xstrdup (marker.str_id);
9791       release_static_tracepoint_marker (&marker);
9792
9793       return sal;
9794     }
9795
9796   /* Old marker wasn't found on target at lineno.  Try looking it up
9797      by string ID.  */
9798   if (!sal.explicit_pc
9799       && sal.line != 0
9800       && sal.symtab != NULL
9801       && b->static_trace_marker_id != NULL)
9802     {
9803       VEC(static_tracepoint_marker_p) *markers;
9804
9805       markers
9806         = target_static_tracepoint_markers_by_strid (b->static_trace_marker_id);
9807
9808       if (!VEC_empty(static_tracepoint_marker_p, markers))
9809         {
9810           struct symtab_and_line sal;
9811           struct symbol *sym;
9812           struct static_tracepoint_marker *marker;
9813
9814           marker = VEC_index (static_tracepoint_marker_p, markers, 0);
9815
9816           xfree (b->static_trace_marker_id);
9817           b->static_trace_marker_id = xstrdup (marker->str_id);
9818
9819           warning (_("marker for static tracepoint %d (%s) not "
9820                      "found at previous line number"),
9821                    b->number, b->static_trace_marker_id);
9822
9823           init_sal (&sal);
9824
9825           sal.pc = marker->address;
9826
9827           sal = find_pc_line (marker->address, 0);
9828           sym = find_pc_sect_function (marker->address, NULL);
9829           ui_out_text (uiout, "Now in ");
9830           if (sym)
9831             {
9832               ui_out_field_string (uiout, "func",
9833                                    SYMBOL_PRINT_NAME (sym));
9834               ui_out_text (uiout, " at ");
9835             }
9836           ui_out_field_string (uiout, "file", sal.symtab->filename);
9837           ui_out_text (uiout, ":");
9838
9839           if (ui_out_is_mi_like_p (uiout))
9840             {
9841               char *fullname = symtab_to_fullname (sal.symtab);
9842
9843               if (fullname)
9844                 ui_out_field_string (uiout, "fullname", fullname);
9845             }
9846
9847           ui_out_field_int (uiout, "line", sal.line);
9848           ui_out_text (uiout, "\n");
9849
9850           b->line_number = sal.line;
9851
9852           xfree (b->source_file);
9853           if (sym)
9854             b->source_file = xstrdup (sal.symtab->filename);
9855           else
9856             b->source_file = NULL;
9857
9858           xfree (b->addr_string);
9859           b->addr_string = xstrprintf ("%s:%d",
9860                                        sal.symtab->filename, b->line_number);
9861
9862           /* Might be nice to check if function changed, and warn if
9863              so.  */
9864
9865           release_static_tracepoint_marker (marker);
9866         }
9867     }
9868   return sal;
9869 }
9870
9871 static void
9872 update_breakpoint_locations (struct breakpoint *b,
9873                              struct symtabs_and_lines sals)
9874 {
9875   int i;
9876   char *s;
9877   struct bp_location *existing_locations = b->loc;
9878
9879   /* If there's no new locations, and all existing locations
9880      are pending, don't do anything.  This optimizes
9881      the common case where all locations are in the same
9882      shared library, that was unloaded. We'd like to
9883      retain the location, so that when the library
9884      is loaded again, we don't loose the enabled/disabled
9885      status of the individual locations.  */
9886   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
9887     return;
9888
9889   b->loc = NULL;
9890
9891   for (i = 0; i < sals.nelts; ++i)
9892     {
9893       struct bp_location *new_loc = 
9894         add_location_to_breakpoint (b, &(sals.sals[i]));
9895
9896       /* Reparse conditions, they might contain references to the
9897          old symtab.  */
9898       if (b->cond_string != NULL)
9899         {
9900           struct gdb_exception e;
9901
9902           s = b->cond_string;
9903           TRY_CATCH (e, RETURN_MASK_ERROR)
9904             {
9905               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
9906                                            0);
9907             }
9908           if (e.reason < 0)
9909             {
9910               warning (_("failed to reevaluate condition for breakpoint %d: %s"), 
9911                        b->number, e.message);
9912               new_loc->enabled = 0;
9913             }
9914         }
9915
9916       if (b->source_file != NULL)
9917         xfree (b->source_file);
9918       if (sals.sals[i].symtab == NULL)
9919         b->source_file = NULL;
9920       else
9921         b->source_file = xstrdup (sals.sals[i].symtab->filename);
9922
9923       if (b->line_number == 0)
9924         b->line_number = sals.sals[i].line;
9925     }
9926
9927   /* Update locations of permanent breakpoints.  */
9928   if (b->enable_state == bp_permanent)
9929     make_breakpoint_permanent (b);
9930
9931   /* If possible, carry over 'disable' status from existing breakpoints.  */
9932   {
9933     struct bp_location *e = existing_locations;
9934     /* If there are multiple breakpoints with the same function name,
9935        e.g. for inline functions, comparing function names won't work.
9936        Instead compare pc addresses; this is just a heuristic as things
9937        may have moved, but in practice it gives the correct answer
9938        often enough until a better solution is found.  */
9939     int have_ambiguous_names = ambiguous_names_p (b->loc);
9940
9941     for (; e; e = e->next)
9942       {
9943         if (!e->enabled && e->function_name)
9944           {
9945             struct bp_location *l = b->loc;
9946             if (have_ambiguous_names)
9947               {
9948                 for (; l; l = l->next)
9949                   if (breakpoint_address_match (e->pspace->aspace, e->address,
9950                                                 l->pspace->aspace, l->address))
9951                     {
9952                       l->enabled = 0;
9953                       break;
9954                     }
9955               }
9956             else
9957               {
9958                 for (; l; l = l->next)
9959                   if (l->function_name
9960                       && strcmp (e->function_name, l->function_name) == 0)
9961                     {
9962                       l->enabled = 0;
9963                       break;
9964                     }
9965               }
9966           }
9967       }
9968   }
9969
9970   update_global_location_list (1);
9971 }
9972
9973 /* Reset a breakpoint given it's struct breakpoint * BINT.
9974    The value we return ends up being the return value from catch_errors.
9975    Unused in this case.  */
9976
9977 static int
9978 breakpoint_re_set_one (void *bint)
9979 {
9980   /* get past catch_errs */
9981   struct breakpoint *b = (struct breakpoint *) bint;
9982   int not_found = 0;
9983   int *not_found_ptr = &not_found;
9984   struct symtabs_and_lines sals = {0};
9985   struct symtabs_and_lines expanded = {0};
9986   char *s;
9987   struct gdb_exception e;
9988   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
9989   int marker_spec = 0;
9990
9991   switch (b->type)
9992     {
9993     case bp_none:
9994       warning (_("attempted to reset apparently deleted breakpoint #%d?"),
9995                b->number);
9996       return 0;
9997     case bp_breakpoint:
9998     case bp_hardware_breakpoint:
9999     case bp_tracepoint:
10000     case bp_fast_tracepoint:
10001     case bp_static_tracepoint:
10002       /* Do not attempt to re-set breakpoints disabled during startup.  */
10003       if (b->enable_state == bp_startup_disabled)
10004         return 0;
10005
10006       if (b->addr_string == NULL)
10007         {
10008           /* Anything without a string can't be re-set. */
10009           delete_breakpoint (b);
10010           return 0;
10011         }
10012
10013       input_radix = b->input_radix;
10014       s = b->addr_string;
10015
10016       save_current_space_and_thread ();
10017       switch_to_program_space_and_thread (b->pspace);
10018
10019       marker_spec = b->type == bp_static_tracepoint && is_marker_spec (s);
10020
10021       set_language (b->language);
10022       TRY_CATCH (e, RETURN_MASK_ERROR)
10023         {
10024           if (marker_spec)
10025             {
10026               sals = decode_static_tracepoint_spec (&s);
10027               if (sals.nelts > b->static_trace_marker_id_idx)
10028                 {
10029                   sals.sals[0] = sals.sals[b->static_trace_marker_id_idx];
10030                   sals.nelts = 1;
10031                 }
10032               else
10033                 error (_("marker %s not found"), b->static_trace_marker_id);
10034             }
10035           else
10036             sals = decode_line_1 (&s, 1, (struct symtab *) NULL, 0, (char ***) NULL,
10037                                   not_found_ptr);
10038         }
10039       if (e.reason < 0)
10040         {
10041           int not_found_and_ok = 0;
10042           /* For pending breakpoints, it's expected that parsing
10043              will fail until the right shared library is loaded.
10044              User has already told to create pending breakpoints and
10045              don't need extra messages.  If breakpoint is in bp_shlib_disabled
10046              state, then user already saw the message about that breakpoint
10047              being disabled, and don't want to see more errors.  */
10048           if (not_found 
10049               && (b->condition_not_parsed 
10050                   || (b->loc && b->loc->shlib_disabled)
10051                   || b->enable_state == bp_disabled))
10052             not_found_and_ok = 1;
10053
10054           if (!not_found_and_ok)
10055             {
10056               /* We surely don't want to warn about the same breakpoint
10057                  10 times.  One solution, implemented here, is disable
10058                  the breakpoint on error.  Another solution would be to
10059                  have separate 'warning emitted' flag.  Since this
10060                  happens only when a binary has changed, I don't know
10061                  which approach is better.  */
10062               b->enable_state = bp_disabled;
10063               throw_exception (e);
10064             }
10065         }
10066
10067       if (!not_found)
10068         {
10069           gdb_assert (sals.nelts == 1);
10070
10071           resolve_sal_pc (&sals.sals[0]);
10072           if (b->condition_not_parsed && s && s[0])
10073             {
10074               char *cond_string = 0;
10075               int thread = -1;
10076               int task = 0;
10077
10078               find_condition_and_thread (s, sals.sals[0].pc,
10079                                          &cond_string, &thread, &task);
10080               if (cond_string)
10081                 b->cond_string = cond_string;
10082               b->thread = thread;
10083               b->task = task;
10084               b->condition_not_parsed = 0;
10085             }
10086
10087           if (b->type == bp_static_tracepoint && !marker_spec)
10088             sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
10089
10090           expanded = expand_line_sal_maybe (sals.sals[0]);
10091         }
10092
10093       make_cleanup (xfree, sals.sals);
10094       update_breakpoint_locations (b, expanded);
10095       break;
10096
10097     case bp_watchpoint:
10098     case bp_hardware_watchpoint:
10099     case bp_read_watchpoint:
10100     case bp_access_watchpoint:
10101       /* Watchpoint can be either on expression using entirely global variables,
10102          or it can be on local variables.
10103
10104          Watchpoints of the first kind are never auto-deleted, and even persist
10105          across program restarts. Since they can use variables from shared 
10106          libraries, we need to reparse expression as libraries are loaded
10107          and unloaded.
10108
10109          Watchpoints on local variables can also change meaning as result
10110          of solib event. For example, if a watchpoint uses both a local and
10111          a global variables in expression, it's a local watchpoint, but
10112          unloading of a shared library will make the expression invalid.
10113          This is not a very common use case, but we still re-evaluate
10114          expression, to avoid surprises to the user. 
10115
10116          Note that for local watchpoints, we re-evaluate it only if
10117          watchpoints frame id is still valid.  If it's not, it means
10118          the watchpoint is out of scope and will be deleted soon. In fact,
10119          I'm not sure we'll ever be called in this case.  
10120
10121          If a local watchpoint's frame id is still valid, then
10122          b->exp_valid_block is likewise valid, and we can safely use it.  
10123          
10124          Don't do anything about disabled watchpoints, since they will
10125          be reevaluated again when enabled.  */
10126       update_watchpoint (b, 1 /* reparse */);
10127       break;
10128       /* We needn't really do anything to reset these, since the mask
10129          that requests them is unaffected by e.g., new libraries being
10130          loaded. */
10131     case bp_catchpoint:
10132       break;
10133
10134     default:
10135       printf_filtered (_("Deleting unknown breakpoint type %d\n"), b->type);
10136       /* fall through */
10137       /* Delete overlay event and longjmp master breakpoints; they will be
10138          reset later by breakpoint_re_set.  */
10139     case bp_overlay_event:
10140     case bp_longjmp_master:
10141     case bp_std_terminate_master:
10142       delete_breakpoint (b);
10143       break;
10144
10145       /* This breakpoint is special, it's set up when the inferior
10146          starts and we really don't want to touch it.  */
10147     case bp_shlib_event:
10148
10149       /* Like bp_shlib_event, this breakpoint type is special.
10150          Once it is set up, we do not want to touch it.  */
10151     case bp_thread_event:
10152
10153       /* Keep temporary breakpoints, which can be encountered when we step
10154          over a dlopen call and SOLIB_ADD is resetting the breakpoints.
10155          Otherwise these should have been blown away via the cleanup chain
10156          or by breakpoint_init_inferior when we rerun the executable.  */
10157     case bp_until:
10158     case bp_finish:
10159     case bp_watchpoint_scope:
10160     case bp_call_dummy:
10161     case bp_std_terminate:
10162     case bp_step_resume:
10163     case bp_longjmp:
10164     case bp_longjmp_resume:
10165     case bp_jit_event:
10166       break;
10167     }
10168
10169   do_cleanups (cleanups);
10170   return 0;
10171 }
10172
10173 /* Re-set all breakpoints after symbols have been re-loaded.  */
10174 void
10175 breakpoint_re_set (void)
10176 {
10177   struct breakpoint *b, *temp;
10178   enum language save_language;
10179   int save_input_radix;
10180   struct cleanup *old_chain;
10181
10182   save_language = current_language->la_language;
10183   save_input_radix = input_radix;
10184   old_chain = save_current_program_space ();
10185
10186   ALL_BREAKPOINTS_SAFE (b, temp)
10187   {
10188     /* Format possible error msg */
10189     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
10190                                 b->number);
10191     struct cleanup *cleanups = make_cleanup (xfree, message);
10192     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
10193     do_cleanups (cleanups);
10194   }
10195   set_language (save_language);
10196   input_radix = save_input_radix;
10197
10198   jit_breakpoint_re_set ();
10199
10200   do_cleanups (old_chain);
10201
10202   create_overlay_event_breakpoint ("_ovly_debug_event");
10203   create_longjmp_master_breakpoint ("longjmp");
10204   create_longjmp_master_breakpoint ("_longjmp");
10205   create_longjmp_master_breakpoint ("siglongjmp");
10206   create_longjmp_master_breakpoint ("_siglongjmp");
10207   create_std_terminate_master_breakpoint ("std::terminate()");
10208 }
10209 \f
10210 /* Reset the thread number of this breakpoint:
10211
10212    - If the breakpoint is for all threads, leave it as-is.
10213    - Else, reset it to the current thread for inferior_ptid. */
10214 void
10215 breakpoint_re_set_thread (struct breakpoint *b)
10216 {
10217   if (b->thread != -1)
10218     {
10219       if (in_thread_list (inferior_ptid))
10220         b->thread = pid_to_thread_id (inferior_ptid);
10221
10222       /* We're being called after following a fork.  The new fork is
10223          selected as current, and unless this was a vfork will have a
10224          different program space from the original thread.  Reset that
10225          as well.  */
10226       b->loc->pspace = current_program_space;
10227     }
10228 }
10229
10230 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
10231    If from_tty is nonzero, it prints a message to that effect,
10232    which ends with a period (no newline).  */
10233
10234 void
10235 set_ignore_count (int bptnum, int count, int from_tty)
10236 {
10237   struct breakpoint *b;
10238
10239   if (count < 0)
10240     count = 0;
10241
10242   ALL_BREAKPOINTS (b)
10243     if (b->number == bptnum)
10244     {
10245       if (is_tracepoint (b))
10246         {
10247           if (from_tty && count != 0)
10248             printf_filtered (_("Ignore count ignored for tracepoint %d."),
10249                              bptnum);
10250           return;
10251         }
10252       
10253       b->ignore_count = count;
10254       if (from_tty)
10255         {
10256           if (count == 0)
10257             printf_filtered (_("Will stop next time breakpoint %d is reached."),
10258                              bptnum);
10259           else if (count == 1)
10260             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
10261                              bptnum);
10262           else
10263             printf_filtered (_("Will ignore next %d crossings of breakpoint %d."),
10264                              count, bptnum);
10265         }
10266       breakpoints_changed ();
10267       observer_notify_breakpoint_modified (b->number);
10268       return;
10269     }
10270
10271   error (_("No breakpoint number %d."), bptnum);
10272 }
10273
10274 void
10275 make_breakpoint_silent (struct breakpoint *b)
10276 {
10277   /* Silence the breakpoint.  */
10278   b->silent = 1;
10279 }
10280
10281 /* Command to set ignore-count of breakpoint N to COUNT.  */
10282
10283 static void
10284 ignore_command (char *args, int from_tty)
10285 {
10286   char *p = args;
10287   int num;
10288
10289   if (p == 0)
10290     error_no_arg (_("a breakpoint number"));
10291
10292   num = get_number (&p);
10293   if (num == 0)
10294     error (_("bad breakpoint number: '%s'"), args);
10295   if (*p == 0)
10296     error (_("Second argument (specified ignore-count) is missing."));
10297
10298   set_ignore_count (num,
10299                     longest_to_int (value_as_long (parse_and_eval (p))),
10300                     from_tty);
10301   if (from_tty)
10302     printf_filtered ("\n");
10303 }
10304 \f
10305 /* Call FUNCTION on each of the breakpoints
10306    whose numbers are given in ARGS.  */
10307
10308 static void
10309 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
10310                                                       void *),
10311                         void *data)
10312 {
10313   char *p = args;
10314   char *p1;
10315   int num;
10316   struct breakpoint *b, *tmp;
10317   int match;
10318
10319   if (p == 0)
10320     error_no_arg (_("one or more breakpoint numbers"));
10321
10322   while (*p)
10323     {
10324       match = 0;
10325       p1 = p;
10326
10327       num = get_number_or_range (&p1);
10328       if (num == 0)
10329         {
10330           warning (_("bad breakpoint number at or near '%s'"), p);
10331         }
10332       else
10333         {
10334           ALL_BREAKPOINTS_SAFE (b, tmp)
10335             if (b->number == num)
10336               {
10337                 struct breakpoint *related_breakpoint = b->related_breakpoint;
10338                 match = 1;
10339                 function (b, data);
10340                 if (related_breakpoint)
10341                   function (related_breakpoint, data);
10342                 break;
10343               }
10344           if (match == 0)
10345             printf_unfiltered (_("No breakpoint number %d.\n"), num);
10346         }
10347       p = p1;
10348     }
10349 }
10350
10351 static struct bp_location *
10352 find_location_by_number (char *number)
10353 {
10354   char *dot = strchr (number, '.');
10355   char *p1;
10356   int bp_num;
10357   int loc_num;
10358   struct breakpoint *b;
10359   struct bp_location *loc;  
10360
10361   *dot = '\0';
10362
10363   p1 = number;
10364   bp_num = get_number_or_range (&p1);
10365   if (bp_num == 0)
10366     error (_("Bad breakpoint number '%s'"), number);
10367
10368   ALL_BREAKPOINTS (b)
10369     if (b->number == bp_num)
10370       {
10371         break;
10372       }
10373
10374   if (!b || b->number != bp_num)
10375     error (_("Bad breakpoint number '%s'"), number);
10376   
10377   p1 = dot+1;
10378   loc_num = get_number_or_range (&p1);
10379   if (loc_num == 0)
10380     error (_("Bad breakpoint location number '%s'"), number);
10381
10382   --loc_num;
10383   loc = b->loc;
10384   for (;loc_num && loc; --loc_num, loc = loc->next)
10385     ;
10386   if (!loc)
10387     error (_("Bad breakpoint location number '%s'"), dot+1);
10388     
10389   return loc;  
10390 }
10391
10392
10393 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
10394    If from_tty is nonzero, it prints a message to that effect,
10395    which ends with a period (no newline).  */
10396
10397 void
10398 disable_breakpoint (struct breakpoint *bpt)
10399 {
10400   /* Never disable a watchpoint scope breakpoint; we want to
10401      hit them when we leave scope so we can delete both the
10402      watchpoint and its scope breakpoint at that time.  */
10403   if (bpt->type == bp_watchpoint_scope)
10404     return;
10405
10406   /* You can't disable permanent breakpoints.  */
10407   if (bpt->enable_state == bp_permanent)
10408     return;
10409
10410   bpt->enable_state = bp_disabled;
10411
10412   update_global_location_list (0);
10413
10414   observer_notify_breakpoint_modified (bpt->number);
10415 }
10416
10417 /* A callback for map_breakpoint_numbers that calls
10418    disable_breakpoint.  */
10419
10420 static void
10421 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
10422 {
10423   disable_breakpoint (b);
10424 }
10425
10426 static void
10427 disable_command (char *args, int from_tty)
10428 {
10429   struct breakpoint *bpt;
10430
10431   if (args == 0)
10432     ALL_BREAKPOINTS (bpt)
10433       switch (bpt->type)
10434       {
10435       case bp_none:
10436         warning (_("attempted to disable apparently deleted breakpoint #%d?"),
10437                  bpt->number);
10438         continue;
10439       case bp_breakpoint:
10440       case bp_tracepoint:
10441       case bp_fast_tracepoint:
10442       case bp_static_tracepoint:
10443       case bp_catchpoint:
10444       case bp_hardware_breakpoint:
10445       case bp_watchpoint:
10446       case bp_hardware_watchpoint:
10447       case bp_read_watchpoint:
10448       case bp_access_watchpoint:
10449         disable_breakpoint (bpt);
10450       default:
10451         continue;
10452       }
10453   else if (strchr (args, '.'))
10454     {
10455       struct bp_location *loc = find_location_by_number (args);
10456       if (loc)
10457         loc->enabled = 0;
10458       update_global_location_list (0);
10459     }
10460   else
10461     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
10462 }
10463
10464 static void
10465 do_enable_breakpoint (struct breakpoint *bpt, enum bpdisp disposition)
10466 {
10467   int target_resources_ok;
10468
10469   if (bpt->type == bp_hardware_breakpoint)
10470     {
10471       int i;
10472       i = hw_breakpoint_used_count ();
10473       target_resources_ok = 
10474         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
10475                                             i + 1, 0);
10476       if (target_resources_ok == 0)
10477         error (_("No hardware breakpoint support in the target."));
10478       else if (target_resources_ok < 0)
10479         error (_("Hardware breakpoints used exceeds limit."));
10480     }
10481
10482   if (is_watchpoint (bpt))
10483     {
10484       struct gdb_exception e;
10485
10486       TRY_CATCH (e, RETURN_MASK_ALL)
10487         {
10488           update_watchpoint (bpt, 1 /* reparse */);
10489         }
10490       if (e.reason < 0)
10491         {
10492           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
10493                              bpt->number);
10494           return;
10495         }
10496     }
10497
10498   if (bpt->enable_state != bp_permanent)
10499     bpt->enable_state = bp_enabled;
10500   bpt->disposition = disposition;
10501   update_global_location_list (1);
10502   breakpoints_changed ();
10503   
10504   observer_notify_breakpoint_modified (bpt->number);
10505 }
10506
10507
10508 void
10509 enable_breakpoint (struct breakpoint *bpt)
10510 {
10511   do_enable_breakpoint (bpt, bpt->disposition);
10512 }
10513
10514 /* A callback for map_breakpoint_numbers that calls
10515    enable_breakpoint.  */
10516
10517 static void
10518 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
10519 {
10520   enable_breakpoint (b);
10521 }
10522
10523 /* The enable command enables the specified breakpoints (or all defined
10524    breakpoints) so they once again become (or continue to be) effective
10525    in stopping the inferior.  */
10526
10527 static void
10528 enable_command (char *args, int from_tty)
10529 {
10530   struct breakpoint *bpt;
10531
10532   if (args == 0)
10533     ALL_BREAKPOINTS (bpt)
10534       switch (bpt->type)
10535       {
10536       case bp_none:
10537         warning (_("attempted to enable apparently deleted breakpoint #%d?"),
10538                  bpt->number);
10539         continue;
10540       case bp_breakpoint:
10541       case bp_tracepoint:
10542       case bp_fast_tracepoint:
10543       case bp_static_tracepoint:
10544       case bp_catchpoint:
10545       case bp_hardware_breakpoint:
10546       case bp_watchpoint:
10547       case bp_hardware_watchpoint:
10548       case bp_read_watchpoint:
10549       case bp_access_watchpoint:
10550         enable_breakpoint (bpt);
10551       default:
10552         continue;
10553       }
10554   else if (strchr (args, '.'))
10555     {
10556       struct bp_location *loc = find_location_by_number (args);
10557       if (loc)
10558         loc->enabled = 1;
10559       update_global_location_list (1);
10560     }
10561   else
10562     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
10563 }
10564
10565 static void
10566 enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
10567 {
10568   do_enable_breakpoint (bpt, disp_disable);
10569 }
10570
10571 static void
10572 enable_once_command (char *args, int from_tty)
10573 {
10574   map_breakpoint_numbers (args, enable_once_breakpoint, NULL);
10575 }
10576
10577 static void
10578 enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
10579 {
10580   do_enable_breakpoint (bpt, disp_del);
10581 }
10582
10583 static void
10584 enable_delete_command (char *args, int from_tty)
10585 {
10586   map_breakpoint_numbers (args, enable_delete_breakpoint, NULL);
10587 }
10588 \f
10589 static void
10590 set_breakpoint_cmd (char *args, int from_tty)
10591 {
10592 }
10593
10594 static void
10595 show_breakpoint_cmd (char *args, int from_tty)
10596 {
10597 }
10598
10599 /* Invalidate last known value of any hardware watchpoint if
10600    the memory which that value represents has been written to by
10601    GDB itself.  */
10602
10603 static void
10604 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
10605                                       const bfd_byte *data)
10606 {
10607   struct breakpoint *bp;
10608
10609   ALL_BREAKPOINTS (bp)
10610     if (bp->enable_state == bp_enabled
10611         && bp->type == bp_hardware_watchpoint
10612         && bp->val_valid && bp->val)
10613       {
10614         struct bp_location *loc;
10615
10616         for (loc = bp->loc; loc != NULL; loc = loc->next)
10617           if (loc->loc_type == bp_loc_hardware_watchpoint
10618               && loc->address + loc->length > addr
10619               && addr + len > loc->address)
10620             {
10621               value_free (bp->val);
10622               bp->val = NULL;
10623               bp->val_valid = 0;
10624             }
10625       }
10626 }
10627
10628 /* Use default_breakpoint_'s, or nothing if they aren't valid.  */
10629
10630 struct symtabs_and_lines
10631 decode_line_spec_1 (char *string, int funfirstline)
10632 {
10633   struct symtabs_and_lines sals;
10634
10635   if (string == 0)
10636     error (_("Empty line specification."));
10637   if (default_breakpoint_valid)
10638     sals = decode_line_1 (&string, funfirstline,
10639                           default_breakpoint_symtab,
10640                           default_breakpoint_line,
10641                           (char ***) NULL, NULL);
10642   else
10643     sals = decode_line_1 (&string, funfirstline,
10644                           (struct symtab *) NULL, 0, (char ***) NULL, NULL);
10645   if (*string)
10646     error (_("Junk at end of line specification: %s"), string);
10647   return sals;
10648 }
10649
10650 /* Create and insert a raw software breakpoint at PC.  Return an
10651    identifier, which should be used to remove the breakpoint later.
10652    In general, places which call this should be using something on the
10653    breakpoint chain instead; this function should be eliminated
10654    someday.  */
10655
10656 void *
10657 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
10658                                   struct address_space *aspace, CORE_ADDR pc)
10659 {
10660   struct bp_target_info *bp_tgt;
10661
10662   bp_tgt = XZALLOC (struct bp_target_info);
10663
10664   bp_tgt->placed_address_space = aspace;
10665   bp_tgt->placed_address = pc;
10666
10667   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
10668     {
10669       /* Could not insert the breakpoint.  */
10670       xfree (bp_tgt);
10671       return NULL;
10672     }
10673
10674   return bp_tgt;
10675 }
10676
10677 /* Remove a breakpoint BP inserted by deprecated_insert_raw_breakpoint.  */
10678
10679 int
10680 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
10681 {
10682   struct bp_target_info *bp_tgt = bp;
10683   int ret;
10684
10685   ret = target_remove_breakpoint (gdbarch, bp_tgt);
10686   xfree (bp_tgt);
10687
10688   return ret;
10689 }
10690
10691 /* One (or perhaps two) breakpoints used for software single stepping.  */
10692
10693 static void *single_step_breakpoints[2];
10694 static struct gdbarch *single_step_gdbarch[2];
10695
10696 /* Create and insert a breakpoint for software single step.  */
10697
10698 void
10699 insert_single_step_breakpoint (struct gdbarch *gdbarch,
10700                                struct address_space *aspace, CORE_ADDR next_pc)
10701 {
10702   void **bpt_p;
10703
10704   if (single_step_breakpoints[0] == NULL)
10705     {
10706       bpt_p = &single_step_breakpoints[0];
10707       single_step_gdbarch[0] = gdbarch;
10708     }
10709   else
10710     {
10711       gdb_assert (single_step_breakpoints[1] == NULL);
10712       bpt_p = &single_step_breakpoints[1];
10713       single_step_gdbarch[1] = gdbarch;
10714     }
10715
10716   /* NOTE drow/2006-04-11: A future improvement to this function would be
10717      to only create the breakpoints once, and actually put them on the
10718      breakpoint chain.  That would let us use set_raw_breakpoint.  We could
10719      adjust the addresses each time they were needed.  Doing this requires
10720      corresponding changes elsewhere where single step breakpoints are
10721      handled, however.  So, for now, we use this.  */
10722
10723   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
10724   if (*bpt_p == NULL)
10725     error (_("Could not insert single-step breakpoint at %s"),
10726              paddress (gdbarch, next_pc));
10727 }
10728
10729 /* Remove and delete any breakpoints used for software single step.  */
10730
10731 void
10732 remove_single_step_breakpoints (void)
10733 {
10734   gdb_assert (single_step_breakpoints[0] != NULL);
10735
10736   /* See insert_single_step_breakpoint for more about this deprecated
10737      call.  */
10738   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
10739                                     single_step_breakpoints[0]);
10740   single_step_gdbarch[0] = NULL;
10741   single_step_breakpoints[0] = NULL;
10742
10743   if (single_step_breakpoints[1] != NULL)
10744     {
10745       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
10746                                         single_step_breakpoints[1]);
10747       single_step_gdbarch[1] = NULL;
10748       single_step_breakpoints[1] = NULL;
10749     }
10750 }
10751
10752 /* Delete software single step breakpoints without removing them from
10753    the inferior.  This is intended to be used if the inferior's address
10754    space where they were inserted is already gone, e.g. after exit or
10755    exec.  */
10756
10757 void
10758 cancel_single_step_breakpoints (void)
10759 {
10760   int i;
10761
10762   for (i = 0; i < 2; i++)
10763     if (single_step_breakpoints[i])
10764       {
10765         xfree (single_step_breakpoints[i]);
10766         single_step_breakpoints[i] = NULL;
10767         single_step_gdbarch[i] = NULL;
10768       }
10769 }
10770
10771 /* Detach software single-step breakpoints from INFERIOR_PTID without
10772    removing them.  */
10773
10774 static void
10775 detach_single_step_breakpoints (void)
10776 {
10777   int i;
10778
10779   for (i = 0; i < 2; i++)
10780     if (single_step_breakpoints[i])
10781       target_remove_breakpoint (single_step_gdbarch[i],
10782                                 single_step_breakpoints[i]);
10783 }
10784
10785 /* Check whether a software single-step breakpoint is inserted at PC.  */
10786
10787 static int
10788 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
10789                                         CORE_ADDR pc)
10790 {
10791   int i;
10792
10793   for (i = 0; i < 2; i++)
10794     {
10795       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
10796       if (bp_tgt
10797           && breakpoint_address_match (bp_tgt->placed_address_space,
10798                                        bp_tgt->placed_address,
10799                                        aspace, pc))
10800         return 1;
10801     }
10802
10803   return 0;
10804 }
10805
10806 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
10807    non-zero otherwise.  */
10808 static int
10809 is_syscall_catchpoint_enabled (struct breakpoint *bp)
10810 {
10811   if (syscall_catchpoint_p (bp)
10812       && bp->enable_state != bp_disabled
10813       && bp->enable_state != bp_call_disabled)
10814     return 1;
10815   else
10816     return 0;
10817 }
10818
10819 int
10820 catch_syscall_enabled (void)
10821 {
10822   struct inferior *inf = current_inferior ();
10823
10824   return inf->total_syscalls_count != 0;
10825 }
10826
10827 int
10828 catching_syscall_number (int syscall_number)
10829 {
10830   struct breakpoint *bp;
10831
10832   ALL_BREAKPOINTS (bp)
10833     if (is_syscall_catchpoint_enabled (bp))
10834       {
10835         if (bp->syscalls_to_be_caught)
10836           {
10837             int i, iter;
10838             for (i = 0;
10839                  VEC_iterate (int, bp->syscalls_to_be_caught, i, iter);
10840                  i++)
10841               if (syscall_number == iter)
10842                 return 1;
10843           }
10844         else
10845           return 1;
10846       }
10847
10848   return 0;
10849 }
10850
10851 /* Complete syscall names.  Used by "catch syscall".  */
10852 static char **
10853 catch_syscall_completer (struct cmd_list_element *cmd,
10854                          char *text, char *word)
10855 {
10856   const char **list = get_syscall_names ();
10857
10858   return (list == NULL) ? NULL : complete_on_enum (list, text, word);
10859 }
10860
10861 /* Tracepoint-specific operations.  */
10862
10863 /* Set tracepoint count to NUM.  */
10864 static void
10865 set_tracepoint_count (int num)
10866 {
10867   tracepoint_count = num;
10868   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
10869 }
10870
10871 void
10872 trace_command (char *arg, int from_tty)
10873 {
10874   if (create_breakpoint (get_current_arch (),
10875                          arg,
10876                          NULL, 0, 1 /* parse arg */,
10877                          0 /* tempflag */,
10878                          bp_tracepoint /* type_wanted */,
10879                          0 /* Ignore count */,
10880                          pending_break_support,
10881                          NULL,
10882                          from_tty,
10883                          1 /* enabled */))
10884     set_tracepoint_count (breakpoint_count);
10885 }
10886
10887 void
10888 ftrace_command (char *arg, int from_tty)
10889 {
10890   if (create_breakpoint (get_current_arch (),
10891                          arg,
10892                          NULL, 0, 1 /* parse arg */,
10893                          0 /* tempflag */,
10894                          bp_fast_tracepoint /* type_wanted */,
10895                          0 /* Ignore count */,
10896                          pending_break_support,
10897                          NULL,
10898                          from_tty,
10899                          1 /* enabled */))
10900     set_tracepoint_count (breakpoint_count);
10901 }
10902
10903 /* strace command implementation.  Creates a static tracepoint.  */
10904
10905 void
10906 strace_command (char *arg, int from_tty)
10907 {
10908   if (create_breakpoint (get_current_arch (),
10909                          arg,
10910                          NULL, 0, 1 /* parse arg */,
10911                          0 /* tempflag */,
10912                          bp_static_tracepoint /* type_wanted */,
10913                          0 /* Ignore count */,
10914                          pending_break_support,
10915                          NULL,
10916                          from_tty,
10917                          1 /* enabled */))
10918     set_tracepoint_count (breakpoint_count);
10919 }
10920
10921 /* Set up a fake reader function that gets command lines from a linked
10922    list that was acquired during tracepoint uploading.  */
10923
10924 static struct uploaded_tp *this_utp;
10925 static int next_cmd;
10926
10927 static char *
10928 read_uploaded_action (void)
10929 {
10930   char *rslt;
10931
10932   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
10933
10934   next_cmd++;
10935
10936   return rslt;
10937 }
10938
10939 /* Given information about a tracepoint as recorded on a target (which
10940    can be either a live system or a trace file), attempt to create an
10941    equivalent GDB tracepoint.  This is not a reliable process, since
10942    the target does not necessarily have all the information used when
10943    the tracepoint was originally defined.  */
10944   
10945 struct breakpoint *
10946 create_tracepoint_from_upload (struct uploaded_tp *utp)
10947 {
10948   char *addr_str, small_buf[100];
10949   struct breakpoint *tp;
10950
10951   if (utp->at_string)
10952     addr_str = utp->at_string;
10953   else
10954     {
10955       /* In the absence of a source location, fall back to raw
10956          address.  Since there is no way to confirm that the address
10957          means the same thing as when the trace was started, warn the
10958          user.  */
10959       warning (_("Uploaded tracepoint %d has no source location, using raw address"),
10960                utp->number);
10961       sprintf (small_buf, "*%s", hex_string (utp->addr));
10962       addr_str = small_buf;
10963     }
10964
10965   /* There's not much we can do with a sequence of bytecodes.  */
10966   if (utp->cond && !utp->cond_string)
10967     warning (_("Uploaded tracepoint %d condition has no source form, ignoring it"),
10968              utp->number);
10969
10970   if (!create_breakpoint (get_current_arch (),
10971                           addr_str,
10972                           utp->cond_string, -1, 0 /* parse cond/thread */,
10973                           0 /* tempflag */,
10974                           utp->type /* type_wanted */,
10975                           0 /* Ignore count */,
10976                           pending_break_support,
10977                           NULL,
10978                           0 /* from_tty */,
10979                           utp->enabled /* enabled */))
10980     return NULL;
10981
10982   set_tracepoint_count (breakpoint_count);
10983   
10984   /* Get the tracepoint we just created.  */
10985   tp = get_tracepoint (tracepoint_count);
10986   gdb_assert (tp != NULL);
10987
10988   if (utp->pass > 0)
10989     {
10990       sprintf (small_buf, "%d %d", utp->pass, tp->number);
10991
10992       trace_pass_command (small_buf, 0);
10993     }
10994
10995   /* If we have uploaded versions of the original commands, set up a
10996      special-purpose "reader" function and call the usual command line
10997      reader, then pass the result to the breakpoint command-setting
10998      function.  */
10999   if (!VEC_empty (char_ptr, utp->cmd_strings))
11000     {
11001       struct command_line *cmd_list;
11002
11003       this_utp = utp;
11004       next_cmd = 0;
11005
11006       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
11007
11008       breakpoint_set_commands (tp, cmd_list);
11009     }
11010   else if (!VEC_empty (char_ptr, utp->actions)
11011            || !VEC_empty (char_ptr, utp->step_actions))
11012     warning (_("Uploaded tracepoint %d actions have no source form, ignoring them"),
11013              utp->number);
11014
11015   return tp;
11016   }
11017   
11018 /* Print information on tracepoint number TPNUM_EXP, or all if
11019    omitted.  */
11020
11021 static void
11022 tracepoints_info (char *tpnum_exp, int from_tty)
11023 {
11024   int tpnum = -1, num_printed;
11025
11026   if (tpnum_exp)
11027     tpnum = parse_and_eval_long (tpnum_exp);
11028
11029   num_printed = breakpoint_1 (tpnum, 0, is_tracepoint);
11030
11031   if (num_printed == 0)
11032     {
11033       if (tpnum == -1)
11034         ui_out_message (uiout, 0, "No tracepoints.\n");
11035       else
11036         ui_out_message (uiout, 0, "No tracepoint number %d.\n", tpnum);
11037     }
11038
11039   default_collect_info ();
11040 }
11041
11042 /* The 'enable trace' command enables tracepoints.  
11043    Not supported by all targets.  */
11044 static void
11045 enable_trace_command (char *args, int from_tty)
11046 {
11047   enable_command (args, from_tty);
11048 }
11049
11050 /* The 'disable trace' command disables tracepoints.  
11051    Not supported by all targets.  */
11052 static void
11053 disable_trace_command (char *args, int from_tty)
11054 {
11055   disable_command (args, from_tty);
11056 }
11057
11058 /* Remove a tracepoint (or all if no argument) */
11059 static void
11060 delete_trace_command (char *arg, int from_tty)
11061 {
11062   struct breakpoint *b, *temp;
11063
11064   dont_repeat ();
11065
11066   if (arg == 0)
11067     {
11068       int breaks_to_delete = 0;
11069
11070       /* Delete all breakpoints if no argument.
11071          Do not delete internal or call-dummy breakpoints, these
11072          have to be deleted with an explicit breakpoint number argument.  */
11073       ALL_TRACEPOINTS (b)
11074       {
11075         if (b->number >= 0)
11076           {
11077             breaks_to_delete = 1;
11078             break;
11079           }
11080       }
11081
11082       /* Ask user only if there are some breakpoints to delete.  */
11083       if (!from_tty
11084           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
11085         {
11086           ALL_BREAKPOINTS_SAFE (b, temp)
11087           {
11088             if (is_tracepoint (b)
11089                 && b->number >= 0)
11090               delete_breakpoint (b);
11091           }
11092         }
11093     }
11094   else
11095     map_breakpoint_numbers (arg, do_delete_breakpoint, NULL);
11096 }
11097
11098 /* Set passcount for tracepoint.
11099
11100    First command argument is passcount, second is tracepoint number.
11101    If tracepoint number omitted, apply to most recently defined.
11102    Also accepts special argument "all".  */
11103
11104 static void
11105 trace_pass_command (char *args, int from_tty)
11106 {
11107   struct breakpoint *t1 = (struct breakpoint *) -1, *t2;
11108   unsigned int count;
11109   int all = 0;
11110
11111   if (args == 0 || *args == 0)
11112     error (_("passcount command requires an argument (count + optional TP num)"));
11113
11114   count = strtoul (args, &args, 10);    /* Count comes first, then TP num. */
11115
11116   while (*args && isspace ((int) *args))
11117     args++;
11118
11119   if (*args && strncasecmp (args, "all", 3) == 0)
11120     {
11121       args += 3;                        /* Skip special argument "all".  */
11122       all = 1;
11123       if (*args)
11124         error (_("Junk at end of arguments."));
11125     }
11126   else
11127     t1 = get_tracepoint_by_number (&args, 1, 1);
11128
11129   do
11130     {
11131       if (t1)
11132         {
11133           ALL_TRACEPOINTS (t2)
11134             if (t1 == (struct breakpoint *) -1 || t1 == t2)
11135               {
11136                 t2->pass_count = count;
11137                 observer_notify_tracepoint_modified (t2->number);
11138                 if (from_tty)
11139                   printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
11140                                    t2->number, count);
11141               }
11142           if (! all && *args)
11143             t1 = get_tracepoint_by_number (&args, 1, 0);
11144         }
11145     }
11146   while (*args);
11147 }
11148
11149 struct breakpoint *
11150 get_tracepoint (int num)
11151 {
11152   struct breakpoint *t;
11153
11154   ALL_TRACEPOINTS (t)
11155     if (t->number == num)
11156       return t;
11157
11158   return NULL;
11159 }
11160
11161 /* Find the tracepoint with the given target-side number (which may be
11162    different from the tracepoint number after disconnecting and
11163    reconnecting).  */
11164
11165 struct breakpoint *
11166 get_tracepoint_by_number_on_target (int num)
11167 {
11168   struct breakpoint *t;
11169
11170   ALL_TRACEPOINTS (t)
11171     if (t->number_on_target == num)
11172       return t;
11173
11174   return NULL;
11175 }
11176
11177 /* Utility: parse a tracepoint number and look it up in the list.
11178    If MULTI_P is true, there might be a range of tracepoints in ARG.
11179    if OPTIONAL_P is true, then if the argument is missing, the most
11180    recent tracepoint (tracepoint_count) is returned.  */
11181 struct breakpoint *
11182 get_tracepoint_by_number (char **arg, int multi_p, int optional_p)
11183 {
11184   extern int tracepoint_count;
11185   struct breakpoint *t;
11186   int tpnum;
11187   char *instring = arg == NULL ? NULL : *arg;
11188
11189   if (arg == NULL || *arg == NULL || ! **arg)
11190     {
11191       if (optional_p)
11192         tpnum = tracepoint_count;
11193       else
11194         error_no_arg (_("tracepoint number"));
11195     }
11196   else
11197     tpnum = multi_p ? get_number_or_range (arg) : get_number (arg);
11198
11199   if (tpnum <= 0)
11200     {
11201       if (instring && *instring)
11202         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
11203                          instring);
11204       else
11205         printf_filtered (_("Tracepoint argument missing and no previous tracepoint\n"));
11206       return NULL;
11207     }
11208
11209   ALL_TRACEPOINTS (t)
11210     if (t->number == tpnum)
11211     {
11212       return t;
11213     }
11214
11215   /* FIXME: if we are in the middle of a range we don't want to give
11216      a message.  The current interface to get_number_or_range doesn't
11217      allow us to discover this.  */
11218   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
11219   return NULL;
11220 }
11221
11222 /* Save information on user settable breakpoints (watchpoints, etc) to
11223    a new script file named FILENAME.  If FILTER is non-NULL, call it
11224    on each breakpoint and only include the ones for which it returns
11225    non-zero.  */
11226
11227 static void
11228 save_breakpoints (char *filename, int from_tty,
11229                   int (*filter) (const struct breakpoint *))
11230 {
11231   struct breakpoint *tp;
11232   int any = 0;
11233   char *pathname;
11234   struct cleanup *cleanup;
11235   struct ui_file *fp;
11236   int extra_trace_bits = 0;
11237
11238   if (filename == 0 || *filename == 0)
11239     error (_("Argument required (file name in which to save)"));
11240
11241   /* See if we have anything to save.  */
11242   ALL_BREAKPOINTS (tp)
11243   {
11244     /* Skip internal and momentary breakpoints.  */
11245     if (!user_settable_breakpoint (tp))
11246       continue;
11247
11248     /* If we have a filter, only save the breakpoints it accepts.  */
11249     if (filter && !filter (tp))
11250       continue;
11251
11252     any = 1;
11253
11254     if (is_tracepoint (tp))
11255       {
11256         extra_trace_bits = 1;
11257
11258         /* We can stop searching.  */
11259         break;
11260       }
11261   }
11262
11263   if (!any)
11264     {
11265       warning (_("Nothing to save."));
11266       return;
11267     }
11268
11269   pathname = tilde_expand (filename);
11270   cleanup = make_cleanup (xfree, pathname);
11271   fp = gdb_fopen (pathname, "w");
11272   if (!fp)
11273     error (_("Unable to open file '%s' for saving (%s)"),
11274            filename, safe_strerror (errno));
11275   make_cleanup_ui_file_delete (fp);
11276
11277   if (extra_trace_bits)
11278     save_trace_state_variables (fp);
11279
11280   ALL_BREAKPOINTS (tp)
11281   {
11282     /* Skip internal and momentary breakpoints.  */
11283     if (!user_settable_breakpoint (tp))
11284       continue;
11285
11286     /* If we have a filter, only save the breakpoints it accepts.  */
11287     if (filter && !filter (tp))
11288       continue;
11289
11290     if (tp->ops != NULL)
11291       (tp->ops->print_recreate) (tp, fp);
11292     else
11293       {
11294         if (tp->type == bp_fast_tracepoint)
11295           fprintf_unfiltered (fp, "ftrace");
11296         if (tp->type == bp_static_tracepoint)
11297           fprintf_unfiltered (fp, "strace");
11298         else if (tp->type == bp_tracepoint)
11299           fprintf_unfiltered (fp, "trace");
11300         else if (tp->type == bp_breakpoint && tp->disposition == disp_del)
11301           fprintf_unfiltered (fp, "tbreak");
11302         else if (tp->type == bp_breakpoint)
11303           fprintf_unfiltered (fp, "break");
11304         else if (tp->type == bp_hardware_breakpoint
11305                  && tp->disposition == disp_del)
11306           fprintf_unfiltered (fp, "thbreak");
11307         else if (tp->type == bp_hardware_breakpoint)
11308           fprintf_unfiltered (fp, "hbreak");
11309         else if (tp->type == bp_watchpoint)
11310           fprintf_unfiltered (fp, "watch");
11311         else if (tp->type == bp_hardware_watchpoint)
11312           fprintf_unfiltered (fp, "watch");
11313         else if (tp->type == bp_read_watchpoint)
11314           fprintf_unfiltered (fp, "rwatch");
11315         else if (tp->type == bp_access_watchpoint)
11316           fprintf_unfiltered (fp, "awatch");
11317         else
11318           internal_error (__FILE__, __LINE__,
11319                           _("unhandled breakpoint type %d"), (int) tp->type);
11320
11321         if (tp->exp_string)
11322           fprintf_unfiltered (fp, " %s", tp->exp_string);
11323         else if (tp->addr_string)
11324           fprintf_unfiltered (fp, " %s", tp->addr_string);
11325         else
11326           {
11327             char tmp[40];
11328
11329             sprintf_vma (tmp, tp->loc->address);
11330             fprintf_unfiltered (fp, " *0x%s", tmp);
11331           }
11332       }
11333
11334     if (tp->thread != -1)
11335       fprintf_unfiltered (fp, " thread %d", tp->thread);
11336
11337     if (tp->task != 0)
11338       fprintf_unfiltered (fp, " task %d", tp->task);
11339
11340     fprintf_unfiltered (fp, "\n");
11341
11342     /* Note, we can't rely on tp->number for anything, as we can't
11343        assume the recreated breakpoint numbers will match.  Use $bpnum
11344        instead.  */
11345
11346     if (tp->cond_string)
11347       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
11348
11349     if (tp->ignore_count)
11350       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
11351
11352     if (tp->pass_count)
11353       fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
11354
11355     if (tp->commands)
11356       {
11357         volatile struct gdb_exception ex;       
11358
11359         fprintf_unfiltered (fp, "  commands\n");
11360         
11361         ui_out_redirect (uiout, fp);
11362         TRY_CATCH (ex, RETURN_MASK_ERROR)
11363           {
11364             print_command_lines (uiout, tp->commands->commands, 2);
11365           }
11366         ui_out_redirect (uiout, NULL);
11367
11368         if (ex.reason < 0)
11369           throw_exception (ex);
11370
11371         fprintf_unfiltered (fp, "  end\n");
11372       }
11373
11374     if (tp->enable_state == bp_disabled)
11375       fprintf_unfiltered (fp, "disable\n");
11376
11377     /* If this is a multi-location breakpoint, check if the locations
11378        should be individually disabled.  Watchpoint locations are
11379        special, and not user visible.  */
11380     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
11381       {
11382         struct bp_location *loc;
11383         int n = 1;
11384
11385         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
11386           if (!loc->enabled)
11387             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
11388       }
11389   }
11390
11391   if (extra_trace_bits && *default_collect)
11392     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
11393
11394   do_cleanups (cleanup);
11395   if (from_tty)
11396     printf_filtered (_("Saved to file '%s'.\n"), filename);
11397 }
11398
11399 /* The `save breakpoints' command.  */
11400
11401 static void
11402 save_breakpoints_command (char *args, int from_tty)
11403 {
11404   save_breakpoints (args, from_tty, NULL);
11405 }
11406
11407 /* The `save tracepoints' command.  */
11408
11409 static void
11410 save_tracepoints_command (char *args, int from_tty)
11411 {
11412   save_breakpoints (args, from_tty, is_tracepoint);
11413 }
11414
11415 /* Create a vector of all tracepoints.  */
11416
11417 VEC(breakpoint_p) *
11418 all_tracepoints ()
11419 {
11420   VEC(breakpoint_p) *tp_vec = 0;
11421   struct breakpoint *tp;
11422
11423   ALL_TRACEPOINTS (tp)
11424   {
11425     VEC_safe_push (breakpoint_p, tp_vec, tp);
11426   }
11427
11428   return tp_vec;
11429 }
11430
11431 \f
11432 /* This help string is used for the break, hbreak, tbreak and thbreak commands.
11433    It is defined as a macro to prevent duplication.
11434    COMMAND should be a string constant containing the name of the command.  */
11435 #define BREAK_ARGS_HELP(command) \
11436 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
11437 LOCATION may be a line number, function name, or \"*\" and an address.\n\
11438 If a line number is specified, break at start of code for that line.\n\
11439 If a function is specified, break at start of code for that function.\n\
11440 If an address is specified, break at that exact address.\n\
11441 With no LOCATION, uses current execution address of the selected\n\
11442 stack frame.  This is useful for breaking on return to a stack frame.\n\
11443 \n\
11444 THREADNUM is the number from \"info threads\".\n\
11445 CONDITION is a boolean expression.\n\
11446 \n\
11447 Multiple breakpoints at one place are permitted, and useful if their\n\
11448 conditions are different.\n\
11449 \n\
11450 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
11451
11452 /* List of subcommands for "catch".  */
11453 static struct cmd_list_element *catch_cmdlist;
11454
11455 /* List of subcommands for "tcatch".  */
11456 static struct cmd_list_element *tcatch_cmdlist;
11457
11458 /* Like add_cmd, but add the command to both the "catch" and "tcatch"
11459    lists, and pass some additional user data to the command function.  */
11460 static void
11461 add_catch_command (char *name, char *docstring,
11462                    void (*sfunc) (char *args, int from_tty,
11463                                   struct cmd_list_element *command),
11464                    char **(*completer) (struct cmd_list_element *cmd,
11465                                          char *text, char *word),
11466                    void *user_data_catch,
11467                    void *user_data_tcatch)
11468 {
11469   struct cmd_list_element *command;
11470
11471   command = add_cmd (name, class_breakpoint, NULL, docstring,
11472                      &catch_cmdlist);
11473   set_cmd_sfunc (command, sfunc);
11474   set_cmd_context (command, user_data_catch);
11475   set_cmd_completer (command, completer);
11476
11477   command = add_cmd (name, class_breakpoint, NULL, docstring,
11478                      &tcatch_cmdlist);
11479   set_cmd_sfunc (command, sfunc);
11480   set_cmd_context (command, user_data_tcatch);
11481   set_cmd_completer (command, completer);
11482 }
11483
11484 static void
11485 clear_syscall_counts (struct inferior *inf)
11486 {
11487   inf->total_syscalls_count = 0;
11488   inf->any_syscall_count = 0;
11489   VEC_free (int, inf->syscalls_counts);
11490 }
11491
11492 static void
11493 save_command (char *arg, int from_tty)
11494 {
11495   printf_unfiltered (_("\
11496 \"save\" must be followed by the name of a save subcommand.\n"));
11497   help_list (save_cmdlist, "save ", -1, gdb_stdout);
11498 }
11499
11500 void
11501 _initialize_breakpoint (void)
11502 {
11503   struct cmd_list_element *c;
11504
11505   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
11506   observer_attach_inferior_exit (clear_syscall_counts);
11507   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
11508
11509   breakpoint_chain = 0;
11510   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
11511      before a breakpoint is set.  */
11512   breakpoint_count = 0;
11513
11514   tracepoint_count = 0;
11515
11516   add_com ("ignore", class_breakpoint, ignore_command, _("\
11517 Set ignore-count of breakpoint number N to COUNT.\n\
11518 Usage is `ignore N COUNT'."));
11519   if (xdb_commands)
11520     add_com_alias ("bc", "ignore", class_breakpoint, 1);
11521
11522   add_com ("commands", class_breakpoint, commands_command, _("\
11523 Set commands to be executed when a breakpoint is hit.\n\
11524 Give breakpoint number as argument after \"commands\".\n\
11525 With no argument, the targeted breakpoint is the last one set.\n\
11526 The commands themselves follow starting on the next line.\n\
11527 Type a line containing \"end\" to indicate the end of them.\n\
11528 Give \"silent\" as the first line to make the breakpoint silent;\n\
11529 then no output is printed when it is hit, except what the commands print."));
11530
11531   add_com ("condition", class_breakpoint, condition_command, _("\
11532 Specify breakpoint number N to break only if COND is true.\n\
11533 Usage is `condition N COND', where N is an integer and COND is an\n\
11534 expression to be evaluated whenever breakpoint N is reached."));
11535
11536   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
11537 Set a temporary breakpoint.\n\
11538 Like \"break\" except the breakpoint is only temporary,\n\
11539 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
11540 by using \"enable delete\" on the breakpoint number.\n\
11541 \n"
11542 BREAK_ARGS_HELP ("tbreak")));
11543   set_cmd_completer (c, location_completer);
11544
11545   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
11546 Set a hardware assisted  breakpoint.\n\
11547 Like \"break\" except the breakpoint requires hardware support,\n\
11548 some target hardware may not have this support.\n\
11549 \n"
11550 BREAK_ARGS_HELP ("hbreak")));
11551   set_cmd_completer (c, location_completer);
11552
11553   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
11554 Set a temporary hardware assisted breakpoint.\n\
11555 Like \"hbreak\" except the breakpoint is only temporary,\n\
11556 so it will be deleted when hit.\n\
11557 \n"
11558 BREAK_ARGS_HELP ("thbreak")));
11559   set_cmd_completer (c, location_completer);
11560
11561   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
11562 Enable some breakpoints.\n\
11563 Give breakpoint numbers (separated by spaces) as arguments.\n\
11564 With no subcommand, breakpoints are enabled until you command otherwise.\n\
11565 This is used to cancel the effect of the \"disable\" command.\n\
11566 With a subcommand you can enable temporarily."),
11567                   &enablelist, "enable ", 1, &cmdlist);
11568   if (xdb_commands)
11569     add_com ("ab", class_breakpoint, enable_command, _("\
11570 Enable some breakpoints.\n\
11571 Give breakpoint numbers (separated by spaces) as arguments.\n\
11572 With no subcommand, breakpoints are enabled until you command otherwise.\n\
11573 This is used to cancel the effect of the \"disable\" command.\n\
11574 With a subcommand you can enable temporarily."));
11575
11576   add_com_alias ("en", "enable", class_breakpoint, 1);
11577
11578   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
11579 Enable some breakpoints.\n\
11580 Give breakpoint numbers (separated by spaces) as arguments.\n\
11581 This is used to cancel the effect of the \"disable\" command.\n\
11582 May be abbreviated to simply \"enable\".\n"),
11583                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
11584
11585   add_cmd ("once", no_class, enable_once_command, _("\
11586 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
11587 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
11588            &enablebreaklist);
11589
11590   add_cmd ("delete", no_class, enable_delete_command, _("\
11591 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
11592 If a breakpoint is hit while enabled in this fashion, it is deleted."),
11593            &enablebreaklist);
11594
11595   add_cmd ("delete", no_class, enable_delete_command, _("\
11596 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
11597 If a breakpoint is hit while enabled in this fashion, it is deleted."),
11598            &enablelist);
11599
11600   add_cmd ("once", no_class, enable_once_command, _("\
11601 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
11602 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
11603            &enablelist);
11604
11605   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
11606 Disable some breakpoints.\n\
11607 Arguments are breakpoint numbers with spaces in between.\n\
11608 To disable all breakpoints, give no argument.\n\
11609 A disabled breakpoint is not forgotten, but has no effect until reenabled."),
11610                   &disablelist, "disable ", 1, &cmdlist);
11611   add_com_alias ("dis", "disable", class_breakpoint, 1);
11612   add_com_alias ("disa", "disable", class_breakpoint, 1);
11613   if (xdb_commands)
11614     add_com ("sb", class_breakpoint, disable_command, _("\
11615 Disable some breakpoints.\n\
11616 Arguments are breakpoint numbers with spaces in between.\n\
11617 To disable all breakpoints, give no argument.\n\
11618 A disabled breakpoint is not forgotten, but has no effect until reenabled."));
11619
11620   add_cmd ("breakpoints", class_alias, disable_command, _("\
11621 Disable some breakpoints.\n\
11622 Arguments are breakpoint numbers with spaces in between.\n\
11623 To disable all breakpoints, give no argument.\n\
11624 A disabled breakpoint is not forgotten, but has no effect until reenabled.\n\
11625 This command may be abbreviated \"disable\"."),
11626            &disablelist);
11627
11628   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
11629 Delete some breakpoints or auto-display expressions.\n\
11630 Arguments are breakpoint numbers with spaces in between.\n\
11631 To delete all breakpoints, give no argument.\n\
11632 \n\
11633 Also a prefix command for deletion of other GDB objects.\n\
11634 The \"unset\" command is also an alias for \"delete\"."),
11635                   &deletelist, "delete ", 1, &cmdlist);
11636   add_com_alias ("d", "delete", class_breakpoint, 1);
11637   add_com_alias ("del", "delete", class_breakpoint, 1);
11638   if (xdb_commands)
11639     add_com ("db", class_breakpoint, delete_command, _("\
11640 Delete some breakpoints.\n\
11641 Arguments are breakpoint numbers with spaces in between.\n\
11642 To delete all breakpoints, give no argument.\n"));
11643
11644   add_cmd ("breakpoints", class_alias, delete_command, _("\
11645 Delete some breakpoints or auto-display expressions.\n\
11646 Arguments are breakpoint numbers with spaces in between.\n\
11647 To delete all breakpoints, give no argument.\n\
11648 This command may be abbreviated \"delete\"."),
11649            &deletelist);
11650
11651   add_com ("clear", class_breakpoint, clear_command, _("\
11652 Clear breakpoint at specified line or function.\n\
11653 Argument may be line number, function name, or \"*\" and an address.\n\
11654 If line number is specified, all breakpoints in that line are cleared.\n\
11655 If function is specified, breakpoints at beginning of function are cleared.\n\
11656 If an address is specified, breakpoints at that address are cleared.\n\
11657 \n\
11658 With no argument, clears all breakpoints in the line that the selected frame\n\
11659 is executing in.\n\
11660 \n\
11661 See also the \"delete\" command which clears breakpoints by number."));
11662   add_com_alias ("cl", "clear", class_breakpoint, 1);
11663
11664   c = add_com ("break", class_breakpoint, break_command, _("\
11665 Set breakpoint at specified line or function.\n"
11666 BREAK_ARGS_HELP ("break")));
11667   set_cmd_completer (c, location_completer);
11668
11669   add_com_alias ("b", "break", class_run, 1);
11670   add_com_alias ("br", "break", class_run, 1);
11671   add_com_alias ("bre", "break", class_run, 1);
11672   add_com_alias ("brea", "break", class_run, 1);
11673
11674   if (xdb_commands)
11675    add_com_alias ("ba", "break", class_breakpoint, 1);
11676
11677   if (dbx_commands)
11678     {
11679       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
11680 Break in function/address or break at a line in the current file."),
11681                              &stoplist, "stop ", 1, &cmdlist);
11682       add_cmd ("in", class_breakpoint, stopin_command,
11683                _("Break in function or address."), &stoplist);
11684       add_cmd ("at", class_breakpoint, stopat_command,
11685                _("Break at a line in the current file."), &stoplist);
11686       add_com ("status", class_info, breakpoints_info, _("\
11687 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
11688 The \"Type\" column indicates one of:\n\
11689 \tbreakpoint     - normal breakpoint\n\
11690 \twatchpoint     - watchpoint\n\
11691 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
11692 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
11693 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
11694 address and file/line number respectively.\n\
11695 \n\
11696 Convenience variable \"$_\" and default examine address for \"x\"\n\
11697 are set to the address of the last breakpoint listed unless the command\n\
11698 is prefixed with \"server \".\n\n\
11699 Convenience variable \"$bpnum\" contains the number of the last\n\
11700 breakpoint set."));
11701     }
11702
11703   add_info ("breakpoints", breakpoints_info, _("\
11704 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
11705 The \"Type\" column indicates one of:\n\
11706 \tbreakpoint     - normal breakpoint\n\
11707 \twatchpoint     - watchpoint\n\
11708 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
11709 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
11710 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
11711 address and file/line number respectively.\n\
11712 \n\
11713 Convenience variable \"$_\" and default examine address for \"x\"\n\
11714 are set to the address of the last breakpoint listed unless the command\n\
11715 is prefixed with \"server \".\n\n\
11716 Convenience variable \"$bpnum\" contains the number of the last\n\
11717 breakpoint set."));
11718
11719   add_info_alias ("b", "breakpoints", 1);
11720
11721   if (xdb_commands)
11722     add_com ("lb", class_breakpoint, breakpoints_info, _("\
11723 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
11724 The \"Type\" column indicates one of:\n\
11725 \tbreakpoint     - normal breakpoint\n\
11726 \twatchpoint     - watchpoint\n\
11727 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
11728 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
11729 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
11730 address and file/line number respectively.\n\
11731 \n\
11732 Convenience variable \"$_\" and default examine address for \"x\"\n\
11733 are set to the address of the last breakpoint listed unless the command\n\
11734 is prefixed with \"server \".\n\n\
11735 Convenience variable \"$bpnum\" contains the number of the last\n\
11736 breakpoint set."));
11737
11738   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
11739 Status of all breakpoints, or breakpoint number NUMBER.\n\
11740 The \"Type\" column indicates one of:\n\
11741 \tbreakpoint     - normal breakpoint\n\
11742 \twatchpoint     - watchpoint\n\
11743 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
11744 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
11745 \tuntil          - internal breakpoint used by the \"until\" command\n\
11746 \tfinish         - internal breakpoint used by the \"finish\" command\n\
11747 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
11748 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
11749 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
11750 address and file/line number respectively.\n\
11751 \n\
11752 Convenience variable \"$_\" and default examine address for \"x\"\n\
11753 are set to the address of the last breakpoint listed unless the command\n\
11754 is prefixed with \"server \".\n\n\
11755 Convenience variable \"$bpnum\" contains the number of the last\n\
11756 breakpoint set."),
11757            &maintenanceinfolist);
11758
11759   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
11760 Set catchpoints to catch events."),
11761                   &catch_cmdlist, "catch ",
11762                   0/*allow-unknown*/, &cmdlist);
11763
11764   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
11765 Set temporary catchpoints to catch events."),
11766                   &tcatch_cmdlist, "tcatch ",
11767                   0/*allow-unknown*/, &cmdlist);
11768
11769   /* Add catch and tcatch sub-commands.  */
11770   add_catch_command ("catch", _("\
11771 Catch an exception, when caught.\n\
11772 With an argument, catch only exceptions with the given name."),
11773                      catch_catch_command,
11774                      NULL,
11775                      CATCH_PERMANENT,
11776                      CATCH_TEMPORARY);
11777   add_catch_command ("throw", _("\
11778 Catch an exception, when thrown.\n\
11779 With an argument, catch only exceptions with the given name."),
11780                      catch_throw_command,
11781                      NULL,
11782                      CATCH_PERMANENT,
11783                      CATCH_TEMPORARY);
11784   add_catch_command ("fork", _("Catch calls to fork."),
11785                      catch_fork_command_1,
11786                      NULL,
11787                      (void *) (uintptr_t) catch_fork_permanent,
11788                      (void *) (uintptr_t) catch_fork_temporary);
11789   add_catch_command ("vfork", _("Catch calls to vfork."),
11790                      catch_fork_command_1,
11791                      NULL,
11792                      (void *) (uintptr_t) catch_vfork_permanent,
11793                      (void *) (uintptr_t) catch_vfork_temporary);
11794   add_catch_command ("exec", _("Catch calls to exec."),
11795                      catch_exec_command_1,
11796                      NULL,
11797                      CATCH_PERMANENT,
11798                      CATCH_TEMPORARY);
11799   add_catch_command ("syscall", _("\
11800 Catch system calls by their names and/or numbers.\n\
11801 Arguments say which system calls to catch.  If no arguments\n\
11802 are given, every system call will be caught.\n\
11803 Arguments, if given, should be one or more system call names\n\
11804 (if your system supports that), or system call numbers."),
11805                      catch_syscall_command_1,
11806                      catch_syscall_completer,
11807                      CATCH_PERMANENT,
11808                      CATCH_TEMPORARY);
11809   add_catch_command ("exception", _("\
11810 Catch Ada exceptions, when raised.\n\
11811 With an argument, catch only exceptions with the given name."),
11812                      catch_ada_exception_command,
11813                      NULL,
11814                      CATCH_PERMANENT,
11815                      CATCH_TEMPORARY);
11816   add_catch_command ("assert", _("\
11817 Catch failed Ada assertions, when raised.\n\
11818 With an argument, catch only exceptions with the given name."),
11819                      catch_assert_command,
11820                      NULL,
11821                      CATCH_PERMANENT,
11822                      CATCH_TEMPORARY);
11823
11824   c = add_com ("watch", class_breakpoint, watch_command, _("\
11825 Set a watchpoint for an expression.\n\
11826 A watchpoint stops execution of your program whenever the value of\n\
11827 an expression changes."));
11828   set_cmd_completer (c, expression_completer);
11829
11830   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
11831 Set a read watchpoint for an expression.\n\
11832 A watchpoint stops execution of your program whenever the value of\n\
11833 an expression is read."));
11834   set_cmd_completer (c, expression_completer);
11835
11836   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
11837 Set a watchpoint for an expression.\n\
11838 A watchpoint stops execution of your program whenever the value of\n\
11839 an expression is either read or written."));
11840   set_cmd_completer (c, expression_completer);
11841
11842   add_info ("watchpoints", watchpoints_info, _("\
11843 Status of watchpoints, or watchpoint number NUMBER."));
11844
11845
11846
11847   /* XXX: cagney/2005-02-23: This should be a boolean, and should
11848      respond to changes - contrary to the description.  */
11849   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
11850                             &can_use_hw_watchpoints, _("\
11851 Set debugger's willingness to use watchpoint hardware."), _("\
11852 Show debugger's willingness to use watchpoint hardware."), _("\
11853 If zero, gdb will not use hardware for new watchpoints, even if\n\
11854 such is available.  (However, any hardware watchpoints that were\n\
11855 created before setting this to nonzero, will continue to use watchpoint\n\
11856 hardware.)"),
11857                             NULL,
11858                             show_can_use_hw_watchpoints,
11859                             &setlist, &showlist);
11860
11861   can_use_hw_watchpoints = 1;
11862
11863   /* Tracepoint manipulation commands.  */
11864
11865   c = add_com ("trace", class_breakpoint, trace_command, _("\
11866 Set a tracepoint at specified line or function.\n\
11867 \n"
11868 BREAK_ARGS_HELP ("trace") "\n\
11869 Do \"help tracepoints\" for info on other tracepoint commands."));
11870   set_cmd_completer (c, location_completer);
11871
11872   add_com_alias ("tp", "trace", class_alias, 0);
11873   add_com_alias ("tr", "trace", class_alias, 1);
11874   add_com_alias ("tra", "trace", class_alias, 1);
11875   add_com_alias ("trac", "trace", class_alias, 1);
11876
11877   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
11878 Set a fast tracepoint at specified line or function.\n\
11879 \n"
11880 BREAK_ARGS_HELP ("ftrace") "\n\
11881 Do \"help tracepoints\" for info on other tracepoint commands."));
11882   set_cmd_completer (c, location_completer);
11883
11884   c = add_com ("strace", class_breakpoint, strace_command, _("\
11885 Set a static tracepoint at specified line, function or marker.\n\
11886 \n\
11887 strace [LOCATION] [if CONDITION]\n\
11888 LOCATION may be a line number, function name, \"*\" and an address,\n\
11889 or -m MARKER_ID.\n\
11890 If a line number is specified, probe the marker at start of code\n\
11891 for that line.  If a function is specified, probe the marker at start\n\
11892 of code for that function.  If an address is specified, probe the marker\n\
11893 at that exact address.  If a marker id is specified, probe the marker\n\
11894 with that name.  With no LOCATION, uses current execution address of\n\
11895 the selected stack frame.\n\
11896 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
11897 This collects arbitrary user data passed in the probe point call to the\n\
11898 tracing library.  You can inspect it when analyzing the trace buffer,\n\
11899 by printing the $_sdata variable like any other convenience variable.\n\
11900 \n\
11901 CONDITION is a boolean expression.\n\
11902 \n\
11903 Multiple tracepoints at one place are permitted, and useful if their\n\
11904 conditions are different.\n\
11905 \n\
11906 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
11907 Do \"help tracepoints\" for info on other tracepoint commands."));
11908   set_cmd_completer (c, location_completer);
11909
11910   add_info ("tracepoints", tracepoints_info, _("\
11911 Status of tracepoints, or tracepoint number NUMBER.\n\
11912 Convenience variable \"$tpnum\" contains the number of the\n\
11913 last tracepoint set."));
11914
11915   add_info_alias ("tp", "tracepoints", 1);
11916
11917   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
11918 Delete specified tracepoints.\n\
11919 Arguments are tracepoint numbers, separated by spaces.\n\
11920 No argument means delete all tracepoints."),
11921            &deletelist);
11922
11923   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
11924 Disable specified tracepoints.\n\
11925 Arguments are tracepoint numbers, separated by spaces.\n\
11926 No argument means disable all tracepoints."),
11927            &disablelist);
11928   deprecate_cmd (c, "disable");
11929
11930   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
11931 Enable specified tracepoints.\n\
11932 Arguments are tracepoint numbers, separated by spaces.\n\
11933 No argument means enable all tracepoints."),
11934            &enablelist);
11935   deprecate_cmd (c, "enable");
11936
11937   add_com ("passcount", class_trace, trace_pass_command, _("\
11938 Set the passcount for a tracepoint.\n\
11939 The trace will end when the tracepoint has been passed 'count' times.\n\
11940 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
11941 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
11942
11943   add_prefix_cmd ("save", class_breakpoint, save_command,
11944                   _("Save breakpoint definitions as a script."),
11945                   &save_cmdlist, "save ",
11946                   0/*allow-unknown*/, &cmdlist);
11947
11948   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
11949 Save current breakpoint definitions as a script.\n\
11950 This includes all types of breakpoints (breakpoints, watchpoints,\n\
11951 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
11952 session to restore them."),
11953                &save_cmdlist);
11954   set_cmd_completer (c, filename_completer);
11955
11956   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
11957 Save current tracepoint definitions as a script.\n\
11958 Use the 'source' command in another debug session to restore them."),
11959                &save_cmdlist);
11960   set_cmd_completer (c, filename_completer);
11961
11962   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
11963   deprecate_cmd (c, "save tracepoints");
11964
11965   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
11966 Breakpoint specific settings\n\
11967 Configure various breakpoint-specific variables such as\n\
11968 pending breakpoint behavior"),
11969                   &breakpoint_set_cmdlist, "set breakpoint ",
11970                   0/*allow-unknown*/, &setlist);
11971   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
11972 Breakpoint specific settings\n\
11973 Configure various breakpoint-specific variables such as\n\
11974 pending breakpoint behavior"),
11975                   &breakpoint_show_cmdlist, "show breakpoint ",
11976                   0/*allow-unknown*/, &showlist);
11977
11978   add_setshow_auto_boolean_cmd ("pending", no_class,
11979                                 &pending_break_support, _("\
11980 Set debugger's behavior regarding pending breakpoints."), _("\
11981 Show debugger's behavior regarding pending breakpoints."), _("\
11982 If on, an unrecognized breakpoint location will cause gdb to create a\n\
11983 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
11984 an error.  If auto, an unrecognized breakpoint location results in a\n\
11985 user-query to see if a pending breakpoint should be created."),
11986                                 NULL,
11987                                 show_pending_break_support,
11988                                 &breakpoint_set_cmdlist,
11989                                 &breakpoint_show_cmdlist);
11990
11991   pending_break_support = AUTO_BOOLEAN_AUTO;
11992
11993   add_setshow_boolean_cmd ("auto-hw", no_class,
11994                            &automatic_hardware_breakpoints, _("\
11995 Set automatic usage of hardware breakpoints."), _("\
11996 Show automatic usage of hardware breakpoints."), _("\
11997 If set, the debugger will automatically use hardware breakpoints for\n\
11998 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
11999 a warning will be emitted for such breakpoints."),
12000                            NULL,
12001                            show_automatic_hardware_breakpoints,
12002                            &breakpoint_set_cmdlist,
12003                            &breakpoint_show_cmdlist);
12004
12005   add_setshow_enum_cmd ("always-inserted", class_support,
12006                         always_inserted_enums, &always_inserted_mode, _("\
12007 Set mode for inserting breakpoints."), _("\
12008 Show mode for inserting breakpoints."), _("\
12009 When this mode is off, breakpoints are inserted in inferior when it is\n\
12010 resumed, and removed when execution stops.  When this mode is on,\n\
12011 breakpoints are inserted immediately and removed only when the user\n\
12012 deletes the breakpoint.  When this mode is auto (which is the default),\n\
12013 the behaviour depends on the non-stop setting (see help set non-stop).\n\
12014 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
12015 behaves as if always-inserted mode is on; if gdb is controlling the\n\
12016 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
12017                            NULL,
12018                            &show_always_inserted_mode,
12019                            &breakpoint_set_cmdlist,
12020                            &breakpoint_show_cmdlist);
12021   
12022   automatic_hardware_breakpoints = 1;
12023
12024   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
12025 }