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