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