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