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