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