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