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