2012-01-24 Pedro Alves <palves@redhat.com>
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "cli/cli-utils.h"
64 #include "continuations.h"
65 #include "stack.h"
66 #include "skip.h"
67 #include "record.h"
68
69 /* readline include files */
70 #include "readline/readline.h"
71 #include "readline/history.h"
72
73 /* readline defines this.  */
74 #undef savestring
75
76 #include "mi/mi-common.h"
77 #include "python/python.h"
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 breakpoint_re_set_default (struct breakpoint *);
98
99 static void create_sals_from_address_default (char **,
100                                               struct linespec_result *,
101                                               enum bptype, char *,
102                                               char **);
103
104 static void create_breakpoints_sal_default (struct gdbarch *,
105                                             struct linespec_result *,
106                                             struct linespec_sals *,
107                                             char *, enum bptype,
108                                             enum bpdisp, int, int,
109                                             int,
110                                             const struct breakpoint_ops *,
111                                             int, int, int);
112
113 static void decode_linespec_default (struct breakpoint *, char **,
114                                      struct symtabs_and_lines *);
115
116 static void clear_command (char *, int);
117
118 static void catch_command (char *, int);
119
120 static int can_use_hardware_watchpoint (struct value *);
121
122 static void break_command_1 (char *, int, int);
123
124 static void mention (struct breakpoint *);
125
126 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
127                                                                enum bptype,
128                                                                const struct breakpoint_ops *);
129 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
130                                                        const struct symtab_and_line *);
131
132 /* This function is used in gdbtk sources and thus can not be made
133    static.  */
134 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
135                                        struct symtab_and_line,
136                                        enum bptype,
137                                        const struct breakpoint_ops *);
138
139 static struct breakpoint *
140   momentary_breakpoint_from_master (struct breakpoint *orig,
141                                     enum bptype type,
142                                     const struct breakpoint_ops *ops);
143
144 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
145
146 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
147                                             CORE_ADDR bpaddr,
148                                             enum bptype bptype);
149
150 static void describe_other_breakpoints (struct gdbarch *,
151                                         struct program_space *, CORE_ADDR,
152                                         struct obj_section *, int);
153
154 static int breakpoint_address_match (struct address_space *aspace1,
155                                      CORE_ADDR addr1,
156                                      struct address_space *aspace2,
157                                      CORE_ADDR addr2);
158
159 static int watchpoint_locations_match (struct bp_location *loc1,
160                                        struct bp_location *loc2);
161
162 static int breakpoint_location_address_match (struct bp_location *bl,
163                                               struct address_space *aspace,
164                                               CORE_ADDR addr);
165
166 static void breakpoints_info (char *, int);
167
168 static void watchpoints_info (char *, int);
169
170 static int breakpoint_1 (char *, int, 
171                          int (*) (const struct breakpoint *));
172
173 static int breakpoint_cond_eval (void *);
174
175 static void cleanup_executing_breakpoints (void *);
176
177 static void commands_command (char *, int);
178
179 static void condition_command (char *, int);
180
181 typedef enum
182   {
183     mark_inserted,
184     mark_uninserted
185   }
186 insertion_state_t;
187
188 static int remove_breakpoint (struct bp_location *, insertion_state_t);
189 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
190
191 static enum print_stop_action print_bp_stop_message (bpstat bs);
192
193 static int watchpoint_check (void *);
194
195 static void maintenance_info_breakpoints (char *, int);
196
197 static int hw_breakpoint_used_count (void);
198
199 static int hw_watchpoint_use_count (struct breakpoint *);
200
201 static int hw_watchpoint_used_count_others (struct breakpoint *except,
202                                             enum bptype type,
203                                             int *other_type_used);
204
205 static void hbreak_command (char *, int);
206
207 static void thbreak_command (char *, int);
208
209 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp);
210
211 static void stop_command (char *arg, int from_tty);
212
213 static void stopin_command (char *arg, int from_tty);
214
215 static void stopat_command (char *arg, int from_tty);
216
217 static char *ep_parse_optional_if_clause (char **arg);
218
219 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
220                                        char *arg, int tempflag, int from_tty);
221
222 static void tcatch_command (char *arg, int from_tty);
223
224 static void detach_single_step_breakpoints (void);
225
226 static int single_step_breakpoint_inserted_here_p (struct address_space *,
227                                                    CORE_ADDR pc);
228
229 static void free_bp_location (struct bp_location *loc);
230 static void incref_bp_location (struct bp_location *loc);
231 static void decref_bp_location (struct bp_location **loc);
232
233 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
234
235 static void update_global_location_list (int);
236
237 static void update_global_location_list_nothrow (int);
238
239 static int is_hardware_watchpoint (const struct breakpoint *bpt);
240
241 static void insert_breakpoint_locations (void);
242
243 static int syscall_catchpoint_p (struct breakpoint *b);
244
245 static void tracepoints_info (char *, int);
246
247 static void delete_trace_command (char *, int);
248
249 static void enable_trace_command (char *, int);
250
251 static void disable_trace_command (char *, int);
252
253 static void trace_pass_command (char *, int);
254
255 static int is_masked_watchpoint (const struct breakpoint *b);
256
257 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
258    otherwise.  */
259
260 static int strace_marker_p (struct breakpoint *b);
261
262 /* The abstract base class all breakpoint_ops structures inherit
263    from.  */
264 static struct breakpoint_ops base_breakpoint_ops;
265
266 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
267    that are implemented on top of software or hardware breakpoints
268    (user breakpoints, internal and momentary breakpoints, etc.).  */
269 static struct breakpoint_ops bkpt_base_breakpoint_ops;
270
271 /* Internal breakpoints class type.  */
272 static struct breakpoint_ops internal_breakpoint_ops;
273
274 /* Momentary breakpoints class type.  */
275 static struct breakpoint_ops momentary_breakpoint_ops;
276
277 /* The breakpoint_ops structure to be used in regular user created
278    breakpoints.  */
279 struct breakpoint_ops bkpt_breakpoint_ops;
280
281 /* A reference-counted struct command_line.  This lets multiple
282    breakpoints share a single command list.  */
283 struct counted_command_line
284 {
285   /* The reference count.  */
286   int refc;
287
288   /* The command list.  */
289   struct command_line *commands;
290 };
291
292 struct command_line *
293 breakpoint_commands (struct breakpoint *b)
294 {
295   return b->commands ? b->commands->commands : NULL;
296 }
297
298 /* Flag indicating that a command has proceeded the inferior past the
299    current breakpoint.  */
300
301 static int breakpoint_proceeded;
302
303 const char *
304 bpdisp_text (enum bpdisp disp)
305 {
306   /* NOTE: the following values are a part of MI protocol and
307      represent values of 'disp' field returned when inferior stops at
308      a breakpoint.  */
309   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
310
311   return bpdisps[(int) disp];
312 }
313
314 /* Prototypes for exported functions.  */
315 /* If FALSE, gdb will not use hardware support for watchpoints, even
316    if such is available.  */
317 static int can_use_hw_watchpoints;
318
319 static void
320 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
321                              struct cmd_list_element *c,
322                              const char *value)
323 {
324   fprintf_filtered (file,
325                     _("Debugger's willingness to use "
326                       "watchpoint hardware is %s.\n"),
327                     value);
328 }
329
330 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
331    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
332    for unrecognized breakpoint locations.
333    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
334 static enum auto_boolean pending_break_support;
335 static void
336 show_pending_break_support (struct ui_file *file, int from_tty,
337                             struct cmd_list_element *c,
338                             const char *value)
339 {
340   fprintf_filtered (file,
341                     _("Debugger's behavior regarding "
342                       "pending breakpoints is %s.\n"),
343                     value);
344 }
345
346 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
347    set with "break" but falling in read-only memory.
348    If 0, gdb will warn about such breakpoints, but won't automatically
349    use hardware breakpoints.  */
350 static int automatic_hardware_breakpoints;
351 static void
352 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
353                                      struct cmd_list_element *c,
354                                      const char *value)
355 {
356   fprintf_filtered (file,
357                     _("Automatic usage of hardware breakpoints is %s.\n"),
358                     value);
359 }
360
361 /* If on, gdb will keep breakpoints inserted even as inferior is
362    stopped, and immediately insert any new breakpoints.  If off, gdb
363    will insert breakpoints into inferior only when resuming it, and
364    will remove breakpoints upon stop.  If auto, GDB will behave as ON
365    if in non-stop mode, and as OFF if all-stop mode.*/
366
367 static const char always_inserted_auto[] = "auto";
368 static const char always_inserted_on[] = "on";
369 static const char always_inserted_off[] = "off";
370 static const char *always_inserted_enums[] = {
371   always_inserted_auto,
372   always_inserted_off,
373   always_inserted_on,
374   NULL
375 };
376 static const char *always_inserted_mode = always_inserted_auto;
377 static void
378 show_always_inserted_mode (struct ui_file *file, int from_tty,
379                      struct cmd_list_element *c, const char *value)
380 {
381   if (always_inserted_mode == always_inserted_auto)
382     fprintf_filtered (file,
383                       _("Always inserted breakpoint "
384                         "mode is %s (currently %s).\n"),
385                       value,
386                       breakpoints_always_inserted_mode () ? "on" : "off");
387   else
388     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
389                       value);
390 }
391
392 int
393 breakpoints_always_inserted_mode (void)
394 {
395   return ((always_inserted_mode == always_inserted_on
396            || (always_inserted_mode == always_inserted_auto && non_stop))
397           && !RECORD_IS_USED);
398 }
399
400 void _initialize_breakpoint (void);
401
402 /* Are we executing breakpoint commands?  */
403 static int executing_breakpoint_commands;
404
405 /* Are overlay event breakpoints enabled? */
406 static int overlay_events_enabled;
407
408 /* See description in breakpoint.h. */
409 int target_exact_watchpoints = 0;
410
411 /* Walk the following statement or block through all breakpoints.
412    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
413    current breakpoint.  */
414
415 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
416
417 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
418         for (B = breakpoint_chain;      \
419              B ? (TMP=B->next, 1): 0;   \
420              B = TMP)
421
422 /* Similar iterator for the low-level breakpoints.  SAFE variant is
423    not provided so update_global_location_list must not be called
424    while executing the block of ALL_BP_LOCATIONS.  */
425
426 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
427         for (BP_TMP = bp_location;                                      \
428              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
429              BP_TMP++)
430
431 /* Iterator for tracepoints only.  */
432
433 #define ALL_TRACEPOINTS(B)  \
434   for (B = breakpoint_chain; B; B = B->next)  \
435     if (is_tracepoint (B))
436
437 /* Chains of all breakpoints defined.  */
438
439 struct breakpoint *breakpoint_chain;
440
441 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
442
443 static struct bp_location **bp_location;
444
445 /* Number of elements of BP_LOCATION.  */
446
447 static unsigned bp_location_count;
448
449 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
450    ADDRESS for the current elements of BP_LOCATION which get a valid
451    result from bp_location_has_shadow.  You can use it for roughly
452    limiting the subrange of BP_LOCATION to scan for shadow bytes for
453    an address you need to read.  */
454
455 static CORE_ADDR bp_location_placed_address_before_address_max;
456
457 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
458    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
459    BP_LOCATION which get a valid result from bp_location_has_shadow.
460    You can use it for roughly limiting the subrange of BP_LOCATION to
461    scan for shadow bytes for an address you need to read.  */
462
463 static CORE_ADDR bp_location_shadow_len_after_address_max;
464
465 /* The locations that no longer correspond to any breakpoint, unlinked
466    from bp_location array, but for which a hit may still be reported
467    by a target.  */
468 VEC(bp_location_p) *moribund_locations = NULL;
469
470 /* Number of last breakpoint made.  */
471
472 static int breakpoint_count;
473
474 /* The value of `breakpoint_count' before the last command that
475    created breakpoints.  If the last (break-like) command created more
476    than one breakpoint, then the difference between BREAKPOINT_COUNT
477    and PREV_BREAKPOINT_COUNT is more than one.  */
478 static int prev_breakpoint_count;
479
480 /* Number of last tracepoint made.  */
481
482 static int tracepoint_count;
483
484 static struct cmd_list_element *breakpoint_set_cmdlist;
485 static struct cmd_list_element *breakpoint_show_cmdlist;
486 struct cmd_list_element *save_cmdlist;
487
488 /* Return whether a breakpoint is an active enabled breakpoint.  */
489 static int
490 breakpoint_enabled (struct breakpoint *b)
491 {
492   return (b->enable_state == bp_enabled);
493 }
494
495 /* Set breakpoint count to NUM.  */
496
497 static void
498 set_breakpoint_count (int num)
499 {
500   prev_breakpoint_count = breakpoint_count;
501   breakpoint_count = num;
502   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
503 }
504
505 /* Used by `start_rbreak_breakpoints' below, to record the current
506    breakpoint count before "rbreak" creates any breakpoint.  */
507 static int rbreak_start_breakpoint_count;
508
509 /* Called at the start an "rbreak" command to record the first
510    breakpoint made.  */
511
512 void
513 start_rbreak_breakpoints (void)
514 {
515   rbreak_start_breakpoint_count = breakpoint_count;
516 }
517
518 /* Called at the end of an "rbreak" command to record the last
519    breakpoint made.  */
520
521 void
522 end_rbreak_breakpoints (void)
523 {
524   prev_breakpoint_count = rbreak_start_breakpoint_count;
525 }
526
527 /* Used in run_command to zero the hit count when a new run starts.  */
528
529 void
530 clear_breakpoint_hit_counts (void)
531 {
532   struct breakpoint *b;
533
534   ALL_BREAKPOINTS (b)
535     b->hit_count = 0;
536 }
537
538 /* Allocate a new counted_command_line with reference count of 1.
539    The new structure owns COMMANDS.  */
540
541 static struct counted_command_line *
542 alloc_counted_command_line (struct command_line *commands)
543 {
544   struct counted_command_line *result
545     = xmalloc (sizeof (struct counted_command_line));
546
547   result->refc = 1;
548   result->commands = commands;
549   return result;
550 }
551
552 /* Increment reference count.  This does nothing if CMD is NULL.  */
553
554 static void
555 incref_counted_command_line (struct counted_command_line *cmd)
556 {
557   if (cmd)
558     ++cmd->refc;
559 }
560
561 /* Decrement reference count.  If the reference count reaches 0,
562    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
563    nothing if *CMDP is NULL.  */
564
565 static void
566 decref_counted_command_line (struct counted_command_line **cmdp)
567 {
568   if (*cmdp)
569     {
570       if (--(*cmdp)->refc == 0)
571         {
572           free_command_lines (&(*cmdp)->commands);
573           xfree (*cmdp);
574         }
575       *cmdp = NULL;
576     }
577 }
578
579 /* A cleanup function that calls decref_counted_command_line.  */
580
581 static void
582 do_cleanup_counted_command_line (void *arg)
583 {
584   decref_counted_command_line (arg);
585 }
586
587 /* Create a cleanup that calls decref_counted_command_line on the
588    argument.  */
589
590 static struct cleanup *
591 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
592 {
593   return make_cleanup (do_cleanup_counted_command_line, cmdp);
594 }
595
596 \f
597 /* Return the breakpoint with the specified number, or NULL
598    if the number does not refer to an existing breakpoint.  */
599
600 struct breakpoint *
601 get_breakpoint (int num)
602 {
603   struct breakpoint *b;
604
605   ALL_BREAKPOINTS (b)
606     if (b->number == num)
607       return b;
608   
609   return NULL;
610 }
611
612 \f
613
614 void
615 set_breakpoint_condition (struct breakpoint *b, char *exp,
616                           int from_tty)
617 {
618   xfree (b->cond_string);
619   b->cond_string = NULL;
620
621   if (is_watchpoint (b))
622     {
623       struct watchpoint *w = (struct watchpoint *) b;
624
625       xfree (w->cond_exp);
626       w->cond_exp = NULL;
627     }
628   else
629     {
630       struct bp_location *loc;
631
632       for (loc = b->loc; loc; loc = loc->next)
633         {
634           xfree (loc->cond);
635           loc->cond = NULL;
636         }
637     }
638
639   if (*exp == 0)
640     {
641       if (from_tty)
642         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
643     }
644   else
645     {
646       char *arg = exp;
647
648       /* I don't know if it matters whether this is the string the user
649          typed in or the decompiled expression.  */
650       b->cond_string = xstrdup (arg);
651       b->condition_not_parsed = 0;
652
653       if (is_watchpoint (b))
654         {
655           struct watchpoint *w = (struct watchpoint *) b;
656
657           innermost_block = NULL;
658           arg = exp;
659           w->cond_exp = parse_exp_1 (&arg, 0, 0);
660           if (*arg)
661             error (_("Junk at end of expression"));
662           w->cond_exp_valid_block = innermost_block;
663         }
664       else
665         {
666           struct bp_location *loc;
667
668           for (loc = b->loc; loc; loc = loc->next)
669             {
670               arg = exp;
671               loc->cond =
672                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
673               if (*arg)
674                 error (_("Junk at end of expression"));
675             }
676         }
677     }
678   breakpoints_changed ();
679   observer_notify_breakpoint_modified (b);
680 }
681
682 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
683
684 static void
685 condition_command (char *arg, int from_tty)
686 {
687   struct breakpoint *b;
688   char *p;
689   int bnum;
690
691   if (arg == 0)
692     error_no_arg (_("breakpoint number"));
693
694   p = arg;
695   bnum = get_number (&p);
696   if (bnum == 0)
697     error (_("Bad breakpoint argument: '%s'"), arg);
698
699   ALL_BREAKPOINTS (b)
700     if (b->number == bnum)
701       {
702         /* Check if this breakpoint has a Python object assigned to
703            it, and if it has a definition of the "stop"
704            method.  This method and conditions entered into GDB from
705            the CLI are mutually exclusive.  */
706         if (b->py_bp_object
707             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
708           error (_("Cannot set a condition where a Python 'stop' "
709                    "method has been defined in the breakpoint."));
710         set_breakpoint_condition (b, p, from_tty);
711         return;
712       }
713
714   error (_("No breakpoint number %d."), bnum);
715 }
716
717 /* Check that COMMAND do not contain commands that are suitable
718    only for tracepoints and not suitable for ordinary breakpoints.
719    Throw if any such commands is found.  */
720
721 static void
722 check_no_tracepoint_commands (struct command_line *commands)
723 {
724   struct command_line *c;
725
726   for (c = commands; c; c = c->next)
727     {
728       int i;
729
730       if (c->control_type == while_stepping_control)
731         error (_("The 'while-stepping' command can "
732                  "only be used for tracepoints"));
733
734       for (i = 0; i < c->body_count; ++i)
735         check_no_tracepoint_commands ((c->body_list)[i]);
736
737       /* Not that command parsing removes leading whitespace and comment
738          lines and also empty lines.  So, we only need to check for
739          command directly.  */
740       if (strstr (c->line, "collect ") == c->line)
741         error (_("The 'collect' command can only be used for tracepoints"));
742
743       if (strstr (c->line, "teval ") == c->line)
744         error (_("The 'teval' command can only be used for tracepoints"));
745     }
746 }
747
748 /* Encapsulate tests for different types of tracepoints.  */
749
750 static int
751 is_tracepoint_type (enum bptype type)
752 {
753   return (type == bp_tracepoint
754           || type == bp_fast_tracepoint
755           || type == bp_static_tracepoint);
756 }
757
758 int
759 is_tracepoint (const struct breakpoint *b)
760 {
761   return is_tracepoint_type (b->type);
762 }
763
764 /* A helper function that validates that COMMANDS are valid for a
765    breakpoint.  This function will throw an exception if a problem is
766    found.  */
767
768 static void
769 validate_commands_for_breakpoint (struct breakpoint *b,
770                                   struct command_line *commands)
771 {
772   if (is_tracepoint (b))
773     {
774       /* We need to verify that each top-level element of commands is
775          valid for tracepoints, that there's at most one
776          while-stepping element, and that while-stepping's body has
777          valid tracing commands excluding nested while-stepping.  */
778       struct command_line *c;
779       struct command_line *while_stepping = 0;
780       for (c = commands; c; c = c->next)
781         {
782           if (c->control_type == while_stepping_control)
783             {
784               if (b->type == bp_fast_tracepoint)
785                 error (_("The 'while-stepping' command "
786                          "cannot be used for fast tracepoint"));
787               else if (b->type == bp_static_tracepoint)
788                 error (_("The 'while-stepping' command "
789                          "cannot be used for static tracepoint"));
790
791               if (while_stepping)
792                 error (_("The 'while-stepping' command "
793                          "can be used only once"));
794               else
795                 while_stepping = c;
796             }
797         }
798       if (while_stepping)
799         {
800           struct command_line *c2;
801
802           gdb_assert (while_stepping->body_count == 1);
803           c2 = while_stepping->body_list[0];
804           for (; c2; c2 = c2->next)
805             {
806               if (c2->control_type == while_stepping_control)
807                 error (_("The 'while-stepping' command cannot be nested"));
808             }
809         }
810     }
811   else
812     {
813       check_no_tracepoint_commands (commands);
814     }
815 }
816
817 /* Return a vector of all the static tracepoints set at ADDR.  The
818    caller is responsible for releasing the vector.  */
819
820 VEC(breakpoint_p) *
821 static_tracepoints_here (CORE_ADDR addr)
822 {
823   struct breakpoint *b;
824   VEC(breakpoint_p) *found = 0;
825   struct bp_location *loc;
826
827   ALL_BREAKPOINTS (b)
828     if (b->type == bp_static_tracepoint)
829       {
830         for (loc = b->loc; loc; loc = loc->next)
831           if (loc->address == addr)
832             VEC_safe_push(breakpoint_p, found, b);
833       }
834
835   return found;
836 }
837
838 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
839    validate that only allowed commands are included.  */
840
841 void
842 breakpoint_set_commands (struct breakpoint *b, 
843                          struct command_line *commands)
844 {
845   validate_commands_for_breakpoint (b, commands);
846
847   decref_counted_command_line (&b->commands);
848   b->commands = alloc_counted_command_line (commands);
849   breakpoints_changed ();
850   observer_notify_breakpoint_modified (b);
851 }
852
853 /* Set the internal `silent' flag on the breakpoint.  Note that this
854    is not the same as the "silent" that may appear in the breakpoint's
855    commands.  */
856
857 void
858 breakpoint_set_silent (struct breakpoint *b, int silent)
859 {
860   int old_silent = b->silent;
861
862   b->silent = silent;
863   if (old_silent != silent)
864     observer_notify_breakpoint_modified (b);
865 }
866
867 /* Set the thread for this breakpoint.  If THREAD is -1, make the
868    breakpoint work for any thread.  */
869
870 void
871 breakpoint_set_thread (struct breakpoint *b, int thread)
872 {
873   int old_thread = b->thread;
874
875   b->thread = thread;
876   if (old_thread != thread)
877     observer_notify_breakpoint_modified (b);
878 }
879
880 /* Set the task for this breakpoint.  If TASK is 0, make the
881    breakpoint work for any task.  */
882
883 void
884 breakpoint_set_task (struct breakpoint *b, int task)
885 {
886   int old_task = b->task;
887
888   b->task = task;
889   if (old_task != task)
890     observer_notify_breakpoint_modified (b);
891 }
892
893 void
894 check_tracepoint_command (char *line, void *closure)
895 {
896   struct breakpoint *b = closure;
897
898   validate_actionline (&line, b);
899 }
900
901 /* A structure used to pass information through
902    map_breakpoint_numbers.  */
903
904 struct commands_info
905 {
906   /* True if the command was typed at a tty.  */
907   int from_tty;
908
909   /* The breakpoint range spec.  */
910   char *arg;
911
912   /* Non-NULL if the body of the commands are being read from this
913      already-parsed command.  */
914   struct command_line *control;
915
916   /* The command lines read from the user, or NULL if they have not
917      yet been read.  */
918   struct counted_command_line *cmd;
919 };
920
921 /* A callback for map_breakpoint_numbers that sets the commands for
922    commands_command.  */
923
924 static void
925 do_map_commands_command (struct breakpoint *b, void *data)
926 {
927   struct commands_info *info = data;
928
929   if (info->cmd == NULL)
930     {
931       struct command_line *l;
932
933       if (info->control != NULL)
934         l = copy_command_lines (info->control->body_list[0]);
935       else
936         {
937           struct cleanup *old_chain;
938           char *str;
939
940           str = xstrprintf (_("Type commands for breakpoint(s) "
941                               "%s, one per line."),
942                             info->arg);
943
944           old_chain = make_cleanup (xfree, str);
945
946           l = read_command_lines (str,
947                                   info->from_tty, 1,
948                                   (is_tracepoint (b)
949                                    ? check_tracepoint_command : 0),
950                                   b);
951
952           do_cleanups (old_chain);
953         }
954
955       info->cmd = alloc_counted_command_line (l);
956     }
957
958   /* If a breakpoint was on the list more than once, we don't need to
959      do anything.  */
960   if (b->commands != info->cmd)
961     {
962       validate_commands_for_breakpoint (b, info->cmd->commands);
963       incref_counted_command_line (info->cmd);
964       decref_counted_command_line (&b->commands);
965       b->commands = info->cmd;
966       breakpoints_changed ();
967       observer_notify_breakpoint_modified (b);
968     }
969 }
970
971 static void
972 commands_command_1 (char *arg, int from_tty, 
973                     struct command_line *control)
974 {
975   struct cleanup *cleanups;
976   struct commands_info info;
977
978   info.from_tty = from_tty;
979   info.control = control;
980   info.cmd = NULL;
981   /* If we read command lines from the user, then `info' will hold an
982      extra reference to the commands that we must clean up.  */
983   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
984
985   if (arg == NULL || !*arg)
986     {
987       if (breakpoint_count - prev_breakpoint_count > 1)
988         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
989                           breakpoint_count);
990       else if (breakpoint_count > 0)
991         arg = xstrprintf ("%d", breakpoint_count);
992       else
993         {
994           /* So that we don't try to free the incoming non-NULL
995              argument in the cleanup below.  Mapping breakpoint
996              numbers will fail in this case.  */
997           arg = NULL;
998         }
999     }
1000   else
1001     /* The command loop has some static state, so we need to preserve
1002        our argument.  */
1003     arg = xstrdup (arg);
1004
1005   if (arg != NULL)
1006     make_cleanup (xfree, arg);
1007
1008   info.arg = arg;
1009
1010   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1011
1012   if (info.cmd == NULL)
1013     error (_("No breakpoints specified."));
1014
1015   do_cleanups (cleanups);
1016 }
1017
1018 static void
1019 commands_command (char *arg, int from_tty)
1020 {
1021   commands_command_1 (arg, from_tty, NULL);
1022 }
1023
1024 /* Like commands_command, but instead of reading the commands from
1025    input stream, takes them from an already parsed command structure.
1026
1027    This is used by cli-script.c to DTRT with breakpoint commands
1028    that are part of if and while bodies.  */
1029 enum command_control_type
1030 commands_from_control_command (char *arg, struct command_line *cmd)
1031 {
1032   commands_command_1 (arg, 0, cmd);
1033   return simple_control;
1034 }
1035
1036 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1037
1038 static int
1039 bp_location_has_shadow (struct bp_location *bl)
1040 {
1041   if (bl->loc_type != bp_loc_software_breakpoint)
1042     return 0;
1043   if (!bl->inserted)
1044     return 0;
1045   if (bl->target_info.shadow_len == 0)
1046     /* BL isn't valid, or doesn't shadow memory.  */
1047     return 0;
1048   return 1;
1049 }
1050
1051 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1052    by replacing any memory breakpoints with their shadowed contents.
1053
1054    The range of shadowed area by each bp_location is:
1055      bl->address - bp_location_placed_address_before_address_max
1056      up to bl->address + bp_location_shadow_len_after_address_max
1057    The range we were requested to resolve shadows for is:
1058      memaddr ... memaddr + len
1059    Thus the safe cutoff boundaries for performance optimization are
1060      memaddr + len <= (bl->address
1061                        - bp_location_placed_address_before_address_max)
1062    and:
1063      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1064
1065 void
1066 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1067                         const gdb_byte *writebuf_org,
1068                         ULONGEST memaddr, LONGEST len)
1069 {
1070   /* Left boundary, right boundary and median element of our binary
1071      search.  */
1072   unsigned bc_l, bc_r, bc;
1073
1074   /* Find BC_L which is a leftmost element which may affect BUF
1075      content.  It is safe to report lower value but a failure to
1076      report higher one.  */
1077
1078   bc_l = 0;
1079   bc_r = bp_location_count;
1080   while (bc_l + 1 < bc_r)
1081     {
1082       struct bp_location *bl;
1083
1084       bc = (bc_l + bc_r) / 2;
1085       bl = bp_location[bc];
1086
1087       /* Check first BL->ADDRESS will not overflow due to the added
1088          constant.  Then advance the left boundary only if we are sure
1089          the BC element can in no way affect the BUF content (MEMADDR
1090          to MEMADDR + LEN range).
1091
1092          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1093          offset so that we cannot miss a breakpoint with its shadow
1094          range tail still reaching MEMADDR.  */
1095
1096       if ((bl->address + bp_location_shadow_len_after_address_max
1097            >= bl->address)
1098           && (bl->address + bp_location_shadow_len_after_address_max
1099               <= memaddr))
1100         bc_l = bc;
1101       else
1102         bc_r = bc;
1103     }
1104
1105   /* Due to the binary search above, we need to make sure we pick the
1106      first location that's at BC_L's address.  E.g., if there are
1107      multiple locations at the same address, BC_L may end up pointing
1108      at a duplicate location, and miss the "master"/"inserted"
1109      location.  Say, given locations L1, L2 and L3 at addresses A and
1110      B:
1111
1112       L1@A, L2@A, L3@B, ...
1113
1114      BC_L could end up pointing at location L2, while the "master"
1115      location could be L1.  Since the `loc->inserted' flag is only set
1116      on "master" locations, we'd forget to restore the shadow of L1
1117      and L2.  */
1118   while (bc_l > 0
1119          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1120     bc_l--;
1121
1122   /* Now do full processing of the found relevant range of elements.  */
1123
1124   for (bc = bc_l; bc < bp_location_count; bc++)
1125   {
1126     struct bp_location *bl = bp_location[bc];
1127     CORE_ADDR bp_addr = 0;
1128     int bp_size = 0;
1129     int bptoffset = 0;
1130
1131     /* bp_location array has BL->OWNER always non-NULL.  */
1132     if (bl->owner->type == bp_none)
1133       warning (_("reading through apparently deleted breakpoint #%d?"),
1134                bl->owner->number);
1135
1136     /* Performance optimization: any further element can no longer affect BUF
1137        content.  */
1138
1139     if (bl->address >= bp_location_placed_address_before_address_max
1140         && memaddr + len <= (bl->address
1141                              - bp_location_placed_address_before_address_max))
1142       break;
1143
1144     if (!bp_location_has_shadow (bl))
1145       continue;
1146     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1147                                    current_program_space->aspace, 0))
1148       continue;
1149
1150     /* Addresses and length of the part of the breakpoint that
1151        we need to copy.  */
1152     bp_addr = bl->target_info.placed_address;
1153     bp_size = bl->target_info.shadow_len;
1154
1155     if (bp_addr + bp_size <= memaddr)
1156       /* The breakpoint is entirely before the chunk of memory we
1157          are reading.  */
1158       continue;
1159
1160     if (bp_addr >= memaddr + len)
1161       /* The breakpoint is entirely after the chunk of memory we are
1162          reading.  */
1163       continue;
1164
1165     /* Offset within shadow_contents.  */
1166     if (bp_addr < memaddr)
1167       {
1168         /* Only copy the second part of the breakpoint.  */
1169         bp_size -= memaddr - bp_addr;
1170         bptoffset = memaddr - bp_addr;
1171         bp_addr = memaddr;
1172       }
1173
1174     if (bp_addr + bp_size > memaddr + len)
1175       {
1176         /* Only copy the first part of the breakpoint.  */
1177         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1178       }
1179
1180     if (readbuf != NULL)
1181       {
1182         /* Update the read buffer with this inserted breakpoint's
1183            shadow.  */
1184         memcpy (readbuf + bp_addr - memaddr,
1185                 bl->target_info.shadow_contents + bptoffset, bp_size);
1186       }
1187     else
1188       {
1189         struct gdbarch *gdbarch = bl->gdbarch;
1190         const unsigned char *bp;
1191         CORE_ADDR placed_address = bl->target_info.placed_address;
1192         unsigned placed_size = bl->target_info.placed_size;
1193
1194         /* Update the shadow with what we want to write to memory.  */
1195         memcpy (bl->target_info.shadow_contents + bptoffset,
1196                 writebuf_org + bp_addr - memaddr, bp_size);
1197
1198         /* Determine appropriate breakpoint contents and size for this
1199            address.  */
1200         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1201
1202         /* Update the final write buffer with this inserted
1203            breakpoint's INSN.  */
1204         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1205       }
1206   }
1207 }
1208 \f
1209
1210 /* Return true if BPT is of any hardware watchpoint kind.  */
1211
1212 static int
1213 is_hardware_watchpoint (const struct breakpoint *bpt)
1214 {
1215   return (bpt->type == bp_hardware_watchpoint
1216           || bpt->type == bp_read_watchpoint
1217           || bpt->type == bp_access_watchpoint);
1218 }
1219
1220 /* Return true if BPT is of any watchpoint kind, hardware or
1221    software.  */
1222
1223 int
1224 is_watchpoint (const struct breakpoint *bpt)
1225 {
1226   return (is_hardware_watchpoint (bpt)
1227           || bpt->type == bp_watchpoint);
1228 }
1229
1230 /* Returns true if the current thread and its running state are safe
1231    to evaluate or update watchpoint B.  Watchpoints on local
1232    expressions need to be evaluated in the context of the thread that
1233    was current when the watchpoint was created, and, that thread needs
1234    to be stopped to be able to select the correct frame context.
1235    Watchpoints on global expressions can be evaluated on any thread,
1236    and in any state.  It is presently left to the target allowing
1237    memory accesses when threads are running.  */
1238
1239 static int
1240 watchpoint_in_thread_scope (struct watchpoint *b)
1241 {
1242   return (b->base.pspace == current_program_space
1243           && (ptid_equal (b->watchpoint_thread, null_ptid)
1244               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1245                   && !is_executing (inferior_ptid))));
1246 }
1247
1248 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1249    associated bp_watchpoint_scope breakpoint.  */
1250
1251 static void
1252 watchpoint_del_at_next_stop (struct watchpoint *w)
1253 {
1254   struct breakpoint *b = &w->base;
1255
1256   if (b->related_breakpoint != b)
1257     {
1258       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1259       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1260       b->related_breakpoint->disposition = disp_del_at_next_stop;
1261       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1262       b->related_breakpoint = b;
1263     }
1264   b->disposition = disp_del_at_next_stop;
1265 }
1266
1267 /* Assuming that B is a watchpoint:
1268    - Reparse watchpoint expression, if REPARSE is non-zero
1269    - Evaluate expression and store the result in B->val
1270    - Evaluate the condition if there is one, and store the result
1271      in b->loc->cond.
1272    - Update the list of values that must be watched in B->loc.
1273
1274    If the watchpoint disposition is disp_del_at_next_stop, then do
1275    nothing.  If this is local watchpoint that is out of scope, delete
1276    it.
1277
1278    Even with `set breakpoint always-inserted on' the watchpoints are
1279    removed + inserted on each stop here.  Normal breakpoints must
1280    never be removed because they might be missed by a running thread
1281    when debugging in non-stop mode.  On the other hand, hardware
1282    watchpoints (is_hardware_watchpoint; processed here) are specific
1283    to each LWP since they are stored in each LWP's hardware debug
1284    registers.  Therefore, such LWP must be stopped first in order to
1285    be able to modify its hardware watchpoints.
1286
1287    Hardware watchpoints must be reset exactly once after being
1288    presented to the user.  It cannot be done sooner, because it would
1289    reset the data used to present the watchpoint hit to the user.  And
1290    it must not be done later because it could display the same single
1291    watchpoint hit during multiple GDB stops.  Note that the latter is
1292    relevant only to the hardware watchpoint types bp_read_watchpoint
1293    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1294    not user-visible - its hit is suppressed if the memory content has
1295    not changed.
1296
1297    The following constraints influence the location where we can reset
1298    hardware watchpoints:
1299
1300    * target_stopped_by_watchpoint and target_stopped_data_address are
1301      called several times when GDB stops.
1302
1303    [linux] 
1304    * Multiple hardware watchpoints can be hit at the same time,
1305      causing GDB to stop.  GDB only presents one hardware watchpoint
1306      hit at a time as the reason for stopping, and all the other hits
1307      are presented later, one after the other, each time the user
1308      requests the execution to be resumed.  Execution is not resumed
1309      for the threads still having pending hit event stored in
1310      LWP_INFO->STATUS.  While the watchpoint is already removed from
1311      the inferior on the first stop the thread hit event is kept being
1312      reported from its cached value by linux_nat_stopped_data_address
1313      until the real thread resume happens after the watchpoint gets
1314      presented and thus its LWP_INFO->STATUS gets reset.
1315
1316    Therefore the hardware watchpoint hit can get safely reset on the
1317    watchpoint removal from inferior.  */
1318
1319 static void
1320 update_watchpoint (struct watchpoint *b, int reparse)
1321 {
1322   int within_current_scope;
1323   struct frame_id saved_frame_id;
1324   int frame_saved;
1325
1326   /* If this is a local watchpoint, we only want to check if the
1327      watchpoint frame is in scope if the current thread is the thread
1328      that was used to create the watchpoint.  */
1329   if (!watchpoint_in_thread_scope (b))
1330     return;
1331
1332   if (b->base.disposition == disp_del_at_next_stop)
1333     return;
1334  
1335   frame_saved = 0;
1336
1337   /* Determine if the watchpoint is within scope.  */
1338   if (b->exp_valid_block == NULL)
1339     within_current_scope = 1;
1340   else
1341     {
1342       struct frame_info *fi = get_current_frame ();
1343       struct gdbarch *frame_arch = get_frame_arch (fi);
1344       CORE_ADDR frame_pc = get_frame_pc (fi);
1345
1346       /* If we're in a function epilogue, unwinding may not work
1347          properly, so do not attempt to recreate locations at this
1348          point.  See similar comments in watchpoint_check.  */
1349       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1350         return;
1351
1352       /* Save the current frame's ID so we can restore it after
1353          evaluating the watchpoint expression on its own frame.  */
1354       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1355          took a frame parameter, so that we didn't have to change the
1356          selected frame.  */
1357       frame_saved = 1;
1358       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1359
1360       fi = frame_find_by_id (b->watchpoint_frame);
1361       within_current_scope = (fi != NULL);
1362       if (within_current_scope)
1363         select_frame (fi);
1364     }
1365
1366   /* We don't free locations.  They are stored in the bp_location array
1367      and update_global_location_list will eventually delete them and
1368      remove breakpoints if needed.  */
1369   b->base.loc = NULL;
1370
1371   if (within_current_scope && reparse)
1372     {
1373       char *s;
1374
1375       if (b->exp)
1376         {
1377           xfree (b->exp);
1378           b->exp = NULL;
1379         }
1380       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1381       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1382       /* If the meaning of expression itself changed, the old value is
1383          no longer relevant.  We don't want to report a watchpoint hit
1384          to the user when the old value and the new value may actually
1385          be completely different objects.  */
1386       value_free (b->val);
1387       b->val = NULL;
1388       b->val_valid = 0;
1389
1390       /* Note that unlike with breakpoints, the watchpoint's condition
1391          expression is stored in the breakpoint object, not in the
1392          locations (re)created below.  */
1393       if (b->base.cond_string != NULL)
1394         {
1395           if (b->cond_exp != NULL)
1396             {
1397               xfree (b->cond_exp);
1398               b->cond_exp = NULL;
1399             }
1400
1401           s = b->base.cond_string;
1402           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1403         }
1404     }
1405
1406   /* If we failed to parse the expression, for example because
1407      it refers to a global variable in a not-yet-loaded shared library,
1408      don't try to insert watchpoint.  We don't automatically delete
1409      such watchpoint, though, since failure to parse expression
1410      is different from out-of-scope watchpoint.  */
1411   if ( !target_has_execution)
1412     {
1413       /* Without execution, memory can't change.  No use to try and
1414          set watchpoint locations.  The watchpoint will be reset when
1415          the target gains execution, through breakpoint_re_set.  */
1416     }
1417   else if (within_current_scope && b->exp)
1418     {
1419       int pc = 0;
1420       struct value *val_chain, *v, *result, *next;
1421       struct program_space *frame_pspace;
1422
1423       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1424
1425       /* Avoid setting b->val if it's already set.  The meaning of
1426          b->val is 'the last value' user saw, and we should update
1427          it only if we reported that last value to user.  As it
1428          happens, the code that reports it updates b->val directly.
1429          We don't keep track of the memory value for masked
1430          watchpoints.  */
1431       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1432         {
1433           b->val = v;
1434           b->val_valid = 1;
1435         }
1436
1437       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1438
1439       /* Look at each value on the value chain.  */
1440       for (v = val_chain; v; v = value_next (v))
1441         {
1442           /* If it's a memory location, and GDB actually needed
1443              its contents to evaluate the expression, then we
1444              must watch it.  If the first value returned is
1445              still lazy, that means an error occurred reading it;
1446              watch it anyway in case it becomes readable.  */
1447           if (VALUE_LVAL (v) == lval_memory
1448               && (v == val_chain || ! value_lazy (v)))
1449             {
1450               struct type *vtype = check_typedef (value_type (v));
1451
1452               /* We only watch structs and arrays if user asked
1453                  for it explicitly, never if they just happen to
1454                  appear in the middle of some value chain.  */
1455               if (v == result
1456                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1457                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1458                 {
1459                   CORE_ADDR addr;
1460                   int len, type;
1461                   struct bp_location *loc, **tmp;
1462
1463                   addr = value_address (v);
1464                   len = TYPE_LENGTH (value_type (v));
1465                   type = hw_write;
1466                   if (b->base.type == bp_read_watchpoint)
1467                     type = hw_read;
1468                   else if (b->base.type == bp_access_watchpoint)
1469                     type = hw_access;
1470
1471                   loc = allocate_bp_location (&b->base);
1472                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1473                     ;
1474                   *tmp = loc;
1475                   loc->gdbarch = get_type_arch (value_type (v));
1476
1477                   loc->pspace = frame_pspace;
1478                   loc->address = addr;
1479                   loc->length = len;
1480                   loc->watchpoint_type = type;
1481                 }
1482             }
1483         }
1484
1485       /* Change the type of breakpoint between hardware assisted or
1486          an ordinary watchpoint depending on the hardware support
1487          and free hardware slots.  REPARSE is set when the inferior
1488          is started.  */
1489       if (reparse)
1490         {
1491           int reg_cnt;
1492           enum bp_loc_type loc_type;
1493           struct bp_location *bl;
1494
1495           reg_cnt = can_use_hardware_watchpoint (val_chain);
1496
1497           if (reg_cnt)
1498             {
1499               int i, target_resources_ok, other_type_used;
1500               enum bptype type;
1501
1502               /* Use an exact watchpoint when there's only one memory region to be
1503                  watched, and only one debug register is needed to watch it.  */
1504               b->exact = target_exact_watchpoints && reg_cnt == 1;
1505
1506               /* We need to determine how many resources are already
1507                  used for all other hardware watchpoints plus this one
1508                  to see if we still have enough resources to also fit
1509                  this watchpoint in as well.  */
1510
1511               /* If this is a software watchpoint, we try to turn it
1512                  to a hardware one -- count resources as if B was of
1513                  hardware watchpoint type.  */
1514               type = b->base.type;
1515               if (type == bp_watchpoint)
1516                 type = bp_hardware_watchpoint;
1517
1518               /* This watchpoint may or may not have been placed on
1519                  the list yet at this point (it won't be in the list
1520                  if we're trying to create it for the first time,
1521                  through watch_command), so always account for it
1522                  manually.  */
1523
1524               /* Count resources used by all watchpoints except B.  */
1525               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1526
1527               /* Add in the resources needed for B.  */
1528               i += hw_watchpoint_use_count (&b->base);
1529
1530               target_resources_ok
1531                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1532               if (target_resources_ok <= 0)
1533                 {
1534                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1535
1536                   if (target_resources_ok == 0 && !sw_mode)
1537                     error (_("Target does not support this type of "
1538                              "hardware watchpoint."));
1539                   else if (target_resources_ok < 0 && !sw_mode)
1540                     error (_("There are not enough available hardware "
1541                              "resources for this watchpoint."));
1542
1543                   /* Downgrade to software watchpoint.  */
1544                   b->base.type = bp_watchpoint;
1545                 }
1546               else
1547                 {
1548                   /* If this was a software watchpoint, we've just
1549                      found we have enough resources to turn it to a
1550                      hardware watchpoint.  Otherwise, this is a
1551                      nop.  */
1552                   b->base.type = type;
1553                 }
1554             }
1555           else if (!b->base.ops->works_in_software_mode (&b->base))
1556             error (_("Expression cannot be implemented with "
1557                      "read/access watchpoint."));
1558           else
1559             b->base.type = bp_watchpoint;
1560
1561           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1562                       : bp_loc_hardware_watchpoint);
1563           for (bl = b->base.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->base.type == bp_watchpoint && b->base.loc == NULL)
1579         {
1580           struct breakpoint *base = &b->base;
1581           base->loc = allocate_bp_location (base);
1582           base->loc->pspace = frame_pspace;
1583           base->loc->address = -1;
1584           base->loc->length = -1;
1585           base->loc->watchpoint_type = -1;
1586         }
1587     }
1588   else if (!within_current_scope)
1589     {
1590       printf_filtered (_("\
1591 Watchpoint %d deleted because the program has left the block\n\
1592 in which its expression is valid.\n"),
1593                        b->base.number);
1594       watchpoint_del_at_next_stop (b);
1595     }
1596
1597   /* Restore the selected frame.  */
1598   if (frame_saved)
1599     select_frame (frame_find_by_id (saved_frame_id));
1600 }
1601
1602
1603 /* Returns 1 iff breakpoint location should be
1604    inserted in the inferior.  We don't differentiate the type of BL's owner
1605    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1606    breakpoint_ops is not defined, because in insert_bp_location,
1607    tracepoint's insert_location will not be called.  */
1608 static int
1609 should_be_inserted (struct bp_location *bl)
1610 {
1611   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1612     return 0;
1613
1614   if (bl->owner->disposition == disp_del_at_next_stop)
1615     return 0;
1616
1617   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1618     return 0;
1619
1620   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1621     return 0;
1622
1623   /* This is set for example, when we're attached to the parent of a
1624      vfork, and have detached from the child.  The child is running
1625      free, and we expect it to do an exec or exit, at which point the
1626      OS makes the parent schedulable again (and the target reports
1627      that the vfork is done).  Until the child is done with the shared
1628      memory region, do not insert breakpoints in the parent, otherwise
1629      the child could still trip on the parent's breakpoints.  Since
1630      the parent is blocked anyway, it won't miss any breakpoint.  */
1631   if (bl->pspace->breakpoints_not_allowed)
1632     return 0;
1633
1634   return 1;
1635 }
1636
1637 /* Same as should_be_inserted but does the check assuming
1638    that the location is not duplicated.  */
1639
1640 static int
1641 unduplicated_should_be_inserted (struct bp_location *bl)
1642 {
1643   int result;
1644   const int save_duplicate = bl->duplicate;
1645
1646   bl->duplicate = 0;
1647   result = should_be_inserted (bl);
1648   bl->duplicate = save_duplicate;
1649   return result;
1650 }
1651
1652 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
1653    location.  Any error messages are printed to TMP_ERROR_STREAM; and
1654    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
1655    Returns 0 for success, 1 if the bp_location type is not supported or
1656    -1 for failure.
1657
1658    NOTE drow/2003-09-09: This routine could be broken down to an
1659    object-style method for each breakpoint or catchpoint type.  */
1660 static int
1661 insert_bp_location (struct bp_location *bl,
1662                     struct ui_file *tmp_error_stream,
1663                     int *disabled_breaks,
1664                     int *hw_breakpoint_error)
1665 {
1666   int val = 0;
1667
1668   if (!should_be_inserted (bl) || bl->inserted)
1669     return 0;
1670
1671   /* Initialize the target-specific information.  */
1672   memset (&bl->target_info, 0, sizeof (bl->target_info));
1673   bl->target_info.placed_address = bl->address;
1674   bl->target_info.placed_address_space = bl->pspace->aspace;
1675   bl->target_info.length = bl->length;
1676
1677   if (bl->loc_type == bp_loc_software_breakpoint
1678       || bl->loc_type == bp_loc_hardware_breakpoint)
1679     {
1680       if (bl->owner->type != bp_hardware_breakpoint)
1681         {
1682           /* If the explicitly specified breakpoint type
1683              is not hardware breakpoint, check the memory map to see
1684              if the breakpoint address is in read only memory or not.
1685
1686              Two important cases are:
1687              - location type is not hardware breakpoint, memory
1688              is readonly.  We change the type of the location to
1689              hardware breakpoint.
1690              - location type is hardware breakpoint, memory is
1691              read-write.  This means we've previously made the
1692              location hardware one, but then the memory map changed,
1693              so we undo.
1694              
1695              When breakpoints are removed, remove_breakpoints will use
1696              location types we've just set here, the only possible
1697              problem is that memory map has changed during running
1698              program, but it's not going to work anyway with current
1699              gdb.  */
1700           struct mem_region *mr 
1701             = lookup_mem_region (bl->target_info.placed_address);
1702           
1703           if (mr)
1704             {
1705               if (automatic_hardware_breakpoints)
1706                 {
1707                   enum bp_loc_type new_type;
1708                   
1709                   if (mr->attrib.mode != MEM_RW)
1710                     new_type = bp_loc_hardware_breakpoint;
1711                   else 
1712                     new_type = bp_loc_software_breakpoint;
1713                   
1714                   if (new_type != bl->loc_type)
1715                     {
1716                       static int said = 0;
1717
1718                       bl->loc_type = new_type;
1719                       if (!said)
1720                         {
1721                           fprintf_filtered (gdb_stdout,
1722                                             _("Note: automatically using "
1723                                               "hardware breakpoints for "
1724                                               "read-only addresses.\n"));
1725                           said = 1;
1726                         }
1727                     }
1728                 }
1729               else if (bl->loc_type == bp_loc_software_breakpoint
1730                        && mr->attrib.mode != MEM_RW)        
1731                 warning (_("cannot set software breakpoint "
1732                            "at readonly address %s"),
1733                          paddress (bl->gdbarch, bl->address));
1734             }
1735         }
1736         
1737       /* First check to see if we have to handle an overlay.  */
1738       if (overlay_debugging == ovly_off
1739           || bl->section == NULL
1740           || !(section_is_overlay (bl->section)))
1741         {
1742           /* No overlay handling: just set the breakpoint.  */
1743
1744           val = bl->owner->ops->insert_location (bl);
1745         }
1746       else
1747         {
1748           /* This breakpoint is in an overlay section.
1749              Shall we set a breakpoint at the LMA?  */
1750           if (!overlay_events_enabled)
1751             {
1752               /* Yes -- overlay event support is not active, 
1753                  so we must try to set a breakpoint at the LMA.
1754                  This will not work for a hardware breakpoint.  */
1755               if (bl->loc_type == bp_loc_hardware_breakpoint)
1756                 warning (_("hardware breakpoint %d not supported in overlay!"),
1757                          bl->owner->number);
1758               else
1759                 {
1760                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
1761                                                              bl->section);
1762                   /* Set a software (trap) breakpoint at the LMA.  */
1763                   bl->overlay_target_info = bl->target_info;
1764                   bl->overlay_target_info.placed_address = addr;
1765                   val = target_insert_breakpoint (bl->gdbarch,
1766                                                   &bl->overlay_target_info);
1767                   if (val != 0)
1768                     fprintf_unfiltered (tmp_error_stream,
1769                                         "Overlay breakpoint %d "
1770                                         "failed: in ROM?\n",
1771                                         bl->owner->number);
1772                 }
1773             }
1774           /* Shall we set a breakpoint at the VMA? */
1775           if (section_is_mapped (bl->section))
1776             {
1777               /* Yes.  This overlay section is mapped into memory.  */
1778               val = bl->owner->ops->insert_location (bl);
1779             }
1780           else
1781             {
1782               /* No.  This breakpoint will not be inserted.  
1783                  No error, but do not mark the bp as 'inserted'.  */
1784               return 0;
1785             }
1786         }
1787
1788       if (val)
1789         {
1790           /* Can't set the breakpoint.  */
1791           if (solib_name_from_address (bl->pspace, bl->address))
1792             {
1793               /* See also: disable_breakpoints_in_shlibs.  */
1794               val = 0;
1795               bl->shlib_disabled = 1;
1796               observer_notify_breakpoint_modified (bl->owner);
1797               if (!*disabled_breaks)
1798                 {
1799                   fprintf_unfiltered (tmp_error_stream, 
1800                                       "Cannot insert breakpoint %d.\n", 
1801                                       bl->owner->number);
1802                   fprintf_unfiltered (tmp_error_stream, 
1803                                       "Temporarily disabling shared "
1804                                       "library breakpoints:\n");
1805                 }
1806               *disabled_breaks = 1;
1807               fprintf_unfiltered (tmp_error_stream,
1808                                   "breakpoint #%d\n", bl->owner->number);
1809             }
1810           else
1811             {
1812               if (bl->loc_type == bp_loc_hardware_breakpoint)
1813                 {
1814                   *hw_breakpoint_error = 1;
1815                   fprintf_unfiltered (tmp_error_stream,
1816                                       "Cannot insert hardware "
1817                                       "breakpoint %d.\n",
1818                                       bl->owner->number);
1819                 }
1820               else
1821                 {
1822                   fprintf_unfiltered (tmp_error_stream, 
1823                                       "Cannot insert breakpoint %d.\n", 
1824                                       bl->owner->number);
1825                   fprintf_filtered (tmp_error_stream, 
1826                                     "Error accessing memory address ");
1827                   fputs_filtered (paddress (bl->gdbarch, bl->address),
1828                                   tmp_error_stream);
1829                   fprintf_filtered (tmp_error_stream, ": %s.\n",
1830                                     safe_strerror (val));
1831                 }
1832
1833             }
1834         }
1835       else
1836         bl->inserted = 1;
1837
1838       return val;
1839     }
1840
1841   else if (bl->loc_type == bp_loc_hardware_watchpoint
1842            /* NOTE drow/2003-09-08: This state only exists for removing
1843               watchpoints.  It's not clear that it's necessary...  */
1844            && bl->owner->disposition != disp_del_at_next_stop)
1845     {
1846       gdb_assert (bl->owner->ops != NULL
1847                   && bl->owner->ops->insert_location != NULL);
1848
1849       val = bl->owner->ops->insert_location (bl);
1850
1851       /* If trying to set a read-watchpoint, and it turns out it's not
1852          supported, try emulating one with an access watchpoint.  */
1853       if (val == 1 && bl->watchpoint_type == hw_read)
1854         {
1855           struct bp_location *loc, **loc_temp;
1856
1857           /* But don't try to insert it, if there's already another
1858              hw_access location that would be considered a duplicate
1859              of this one.  */
1860           ALL_BP_LOCATIONS (loc, loc_temp)
1861             if (loc != bl
1862                 && loc->watchpoint_type == hw_access
1863                 && watchpoint_locations_match (bl, loc))
1864               {
1865                 bl->duplicate = 1;
1866                 bl->inserted = 1;
1867                 bl->target_info = loc->target_info;
1868                 bl->watchpoint_type = hw_access;
1869                 val = 0;
1870                 break;
1871               }
1872
1873           if (val == 1)
1874             {
1875               bl->watchpoint_type = hw_access;
1876               val = bl->owner->ops->insert_location (bl);
1877
1878               if (val)
1879                 /* Back to the original value.  */
1880                 bl->watchpoint_type = hw_read;
1881             }
1882         }
1883
1884       bl->inserted = (val == 0);
1885     }
1886
1887   else if (bl->owner->type == bp_catchpoint)
1888     {
1889       gdb_assert (bl->owner->ops != NULL
1890                   && bl->owner->ops->insert_location != NULL);
1891
1892       val = bl->owner->ops->insert_location (bl);
1893       if (val)
1894         {
1895           bl->owner->enable_state = bp_disabled;
1896
1897           if (val == 1)
1898             warning (_("\
1899 Error inserting catchpoint %d: Your system does not support this type\n\
1900 of catchpoint."), bl->owner->number);
1901           else
1902             warning (_("Error inserting catchpoint %d."), bl->owner->number);
1903         }
1904
1905       bl->inserted = (val == 0);
1906
1907       /* We've already printed an error message if there was a problem
1908          inserting this catchpoint, and we've disabled the catchpoint,
1909          so just return success.  */
1910       return 0;
1911     }
1912
1913   return 0;
1914 }
1915
1916 /* This function is called when program space PSPACE is about to be
1917    deleted.  It takes care of updating breakpoints to not reference
1918    PSPACE anymore.  */
1919
1920 void
1921 breakpoint_program_space_exit (struct program_space *pspace)
1922 {
1923   struct breakpoint *b, *b_temp;
1924   struct bp_location *loc, **loc_temp;
1925
1926   /* Remove any breakpoint that was set through this program space.  */
1927   ALL_BREAKPOINTS_SAFE (b, b_temp)
1928     {
1929       if (b->pspace == pspace)
1930         delete_breakpoint (b);
1931     }
1932
1933   /* Breakpoints set through other program spaces could have locations
1934      bound to PSPACE as well.  Remove those.  */
1935   ALL_BP_LOCATIONS (loc, loc_temp)
1936     {
1937       struct bp_location *tmp;
1938
1939       if (loc->pspace == pspace)
1940         {
1941           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
1942           if (loc->owner->loc == loc)
1943             loc->owner->loc = loc->next;
1944           else
1945             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
1946               if (tmp->next == loc)
1947                 {
1948                   tmp->next = loc->next;
1949                   break;
1950                 }
1951         }
1952     }
1953
1954   /* Now update the global location list to permanently delete the
1955      removed locations above.  */
1956   update_global_location_list (0);
1957 }
1958
1959 /* Make sure all breakpoints are inserted in inferior.
1960    Throws exception on any error.
1961    A breakpoint that is already inserted won't be inserted
1962    again, so calling this function twice is safe.  */
1963 void
1964 insert_breakpoints (void)
1965 {
1966   struct breakpoint *bpt;
1967
1968   ALL_BREAKPOINTS (bpt)
1969     if (is_hardware_watchpoint (bpt))
1970       {
1971         struct watchpoint *w = (struct watchpoint *) bpt;
1972
1973         update_watchpoint (w, 0 /* don't reparse.  */);
1974       }
1975
1976   update_global_location_list (1);
1977
1978   /* update_global_location_list does not insert breakpoints when
1979      always_inserted_mode is not enabled.  Explicitly insert them
1980      now.  */
1981   if (!breakpoints_always_inserted_mode ())
1982     insert_breakpoint_locations ();
1983 }
1984
1985 /* Used when starting or continuing the program.  */
1986
1987 static void
1988 insert_breakpoint_locations (void)
1989 {
1990   struct breakpoint *bpt;
1991   struct bp_location *bl, **blp_tmp;
1992   int error_flag = 0;
1993   int val = 0;
1994   int disabled_breaks = 0;
1995   int hw_breakpoint_error = 0;
1996
1997   struct ui_file *tmp_error_stream = mem_fileopen ();
1998   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
1999   
2000   /* Explicitly mark the warning -- this will only be printed if
2001      there was an error.  */
2002   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2003
2004   save_current_space_and_thread ();
2005
2006   ALL_BP_LOCATIONS (bl, blp_tmp)
2007     {
2008       if (!should_be_inserted (bl) || bl->inserted)
2009         continue;
2010
2011       /* There is no point inserting thread-specific breakpoints if
2012          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2013          has BL->OWNER always non-NULL.  */
2014       if (bl->owner->thread != -1
2015           && !valid_thread_id (bl->owner->thread))
2016         continue;
2017
2018       switch_to_program_space_and_thread (bl->pspace);
2019
2020       /* For targets that support global breakpoints, there's no need
2021          to select an inferior to insert breakpoint to.  In fact, even
2022          if we aren't attached to any process yet, we should still
2023          insert breakpoints.  */
2024       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2025           && ptid_equal (inferior_ptid, null_ptid))
2026         continue;
2027
2028       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2029                                     &hw_breakpoint_error);
2030       if (val)
2031         error_flag = val;
2032     }
2033
2034   /* If we failed to insert all locations of a watchpoint, remove
2035      them, as half-inserted watchpoint is of limited use.  */
2036   ALL_BREAKPOINTS (bpt)  
2037     {
2038       int some_failed = 0;
2039       struct bp_location *loc;
2040
2041       if (!is_hardware_watchpoint (bpt))
2042         continue;
2043
2044       if (!breakpoint_enabled (bpt))
2045         continue;
2046
2047       if (bpt->disposition == disp_del_at_next_stop)
2048         continue;
2049       
2050       for (loc = bpt->loc; loc; loc = loc->next)
2051         if (!loc->inserted && should_be_inserted (loc))
2052           {
2053             some_failed = 1;
2054             break;
2055           }
2056       if (some_failed)
2057         {
2058           for (loc = bpt->loc; loc; loc = loc->next)
2059             if (loc->inserted)
2060               remove_breakpoint (loc, mark_uninserted);
2061
2062           hw_breakpoint_error = 1;
2063           fprintf_unfiltered (tmp_error_stream,
2064                               "Could not insert hardware watchpoint %d.\n", 
2065                               bpt->number);
2066           error_flag = -1;
2067         }
2068     }
2069
2070   if (error_flag)
2071     {
2072       /* If a hardware breakpoint or watchpoint was inserted, add a
2073          message about possibly exhausted resources.  */
2074       if (hw_breakpoint_error)
2075         {
2076           fprintf_unfiltered (tmp_error_stream, 
2077                               "Could not insert hardware breakpoints:\n\
2078 You may have requested too many hardware breakpoints/watchpoints.\n");
2079         }
2080       target_terminal_ours_for_output ();
2081       error_stream (tmp_error_stream);
2082     }
2083
2084   do_cleanups (cleanups);
2085 }
2086
2087 /* Used when the program stops.
2088    Returns zero if successful, or non-zero if there was a problem
2089    removing a breakpoint location.  */
2090
2091 int
2092 remove_breakpoints (void)
2093 {
2094   struct bp_location *bl, **blp_tmp;
2095   int val = 0;
2096
2097   ALL_BP_LOCATIONS (bl, blp_tmp)
2098   {
2099     if (bl->inserted && !is_tracepoint (bl->owner))
2100       val |= remove_breakpoint (bl, mark_uninserted);
2101   }
2102   return val;
2103 }
2104
2105 /* Remove breakpoints of process PID.  */
2106
2107 int
2108 remove_breakpoints_pid (int pid)
2109 {
2110   struct bp_location *bl, **blp_tmp;
2111   int val;
2112   struct inferior *inf = find_inferior_pid (pid);
2113
2114   ALL_BP_LOCATIONS (bl, blp_tmp)
2115   {
2116     if (bl->pspace != inf->pspace)
2117       continue;
2118
2119     if (bl->inserted)
2120       {
2121         val = remove_breakpoint (bl, mark_uninserted);
2122         if (val != 0)
2123           return val;
2124       }
2125   }
2126   return 0;
2127 }
2128
2129 int
2130 reattach_breakpoints (int pid)
2131 {
2132   struct cleanup *old_chain;
2133   struct bp_location *bl, **blp_tmp;
2134   int val;
2135   struct ui_file *tmp_error_stream;
2136   int dummy1 = 0, dummy2 = 0;
2137   struct inferior *inf;
2138   struct thread_info *tp;
2139
2140   tp = any_live_thread_of_process (pid);
2141   if (tp == NULL)
2142     return 1;
2143
2144   inf = find_inferior_pid (pid);
2145   old_chain = save_inferior_ptid ();
2146
2147   inferior_ptid = tp->ptid;
2148
2149   tmp_error_stream = mem_fileopen ();
2150   make_cleanup_ui_file_delete (tmp_error_stream);
2151
2152   ALL_BP_LOCATIONS (bl, blp_tmp)
2153   {
2154     if (bl->pspace != inf->pspace)
2155       continue;
2156
2157     if (bl->inserted)
2158       {
2159         bl->inserted = 0;
2160         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2161         if (val != 0)
2162           {
2163             do_cleanups (old_chain);
2164             return val;
2165           }
2166       }
2167   }
2168   do_cleanups (old_chain);
2169   return 0;
2170 }
2171
2172 static int internal_breakpoint_number = -1;
2173
2174 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2175    If INTERNAL is non-zero, the breakpoint number will be populated
2176    from internal_breakpoint_number and that variable decremented.
2177    Otherwise the breakpoint number will be populated from
2178    breakpoint_count and that value incremented.  Internal breakpoints
2179    do not set the internal var bpnum.  */
2180 static void
2181 set_breakpoint_number (int internal, struct breakpoint *b)
2182 {
2183   if (internal)
2184     b->number = internal_breakpoint_number--;
2185   else
2186     {
2187       set_breakpoint_count (breakpoint_count + 1);
2188       b->number = breakpoint_count;
2189     }
2190 }
2191
2192 static struct breakpoint *
2193 create_internal_breakpoint (struct gdbarch *gdbarch,
2194                             CORE_ADDR address, enum bptype type,
2195                             const struct breakpoint_ops *ops)
2196 {
2197   struct symtab_and_line sal;
2198   struct breakpoint *b;
2199
2200   init_sal (&sal);              /* Initialize to zeroes.  */
2201
2202   sal.pc = address;
2203   sal.section = find_pc_overlay (sal.pc);
2204   sal.pspace = current_program_space;
2205
2206   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2207   b->number = internal_breakpoint_number--;
2208   b->disposition = disp_donttouch;
2209
2210   return b;
2211 }
2212
2213 static const char *const longjmp_names[] =
2214   {
2215     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2216   };
2217 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2218
2219 /* Per-objfile data private to breakpoint.c.  */
2220 struct breakpoint_objfile_data
2221 {
2222   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2223   struct minimal_symbol *overlay_msym;
2224
2225   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2226   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2227
2228   /* Minimal symbol for "std::terminate()" (if any).  */
2229   struct minimal_symbol *terminate_msym;
2230
2231   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2232   struct minimal_symbol *exception_msym;
2233 };
2234
2235 static const struct objfile_data *breakpoint_objfile_key;
2236
2237 /* Minimal symbol not found sentinel.  */
2238 static struct minimal_symbol msym_not_found;
2239
2240 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2241
2242 static int
2243 msym_not_found_p (const struct minimal_symbol *msym)
2244 {
2245   return msym == &msym_not_found;
2246 }
2247
2248 /* Return per-objfile data needed by breakpoint.c.
2249    Allocate the data if necessary.  */
2250
2251 static struct breakpoint_objfile_data *
2252 get_breakpoint_objfile_data (struct objfile *objfile)
2253 {
2254   struct breakpoint_objfile_data *bp_objfile_data;
2255
2256   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2257   if (bp_objfile_data == NULL)
2258     {
2259       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2260                                        sizeof (*bp_objfile_data));
2261
2262       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2263       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2264     }
2265   return bp_objfile_data;
2266 }
2267
2268 static void
2269 create_overlay_event_breakpoint (void)
2270 {
2271   struct objfile *objfile;
2272   const char *const func_name = "_ovly_debug_event";
2273
2274   ALL_OBJFILES (objfile)
2275     {
2276       struct breakpoint *b;
2277       struct breakpoint_objfile_data *bp_objfile_data;
2278       CORE_ADDR addr;
2279
2280       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2281
2282       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2283         continue;
2284
2285       if (bp_objfile_data->overlay_msym == NULL)
2286         {
2287           struct minimal_symbol *m;
2288
2289           m = lookup_minimal_symbol_text (func_name, objfile);
2290           if (m == NULL)
2291             {
2292               /* Avoid future lookups in this objfile.  */
2293               bp_objfile_data->overlay_msym = &msym_not_found;
2294               continue;
2295             }
2296           bp_objfile_data->overlay_msym = m;
2297         }
2298
2299       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2300       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2301                                       bp_overlay_event,
2302                                       &internal_breakpoint_ops);
2303       b->addr_string = xstrdup (func_name);
2304
2305       if (overlay_debugging == ovly_auto)
2306         {
2307           b->enable_state = bp_enabled;
2308           overlay_events_enabled = 1;
2309         }
2310       else
2311        {
2312          b->enable_state = bp_disabled;
2313          overlay_events_enabled = 0;
2314        }
2315     }
2316   update_global_location_list (1);
2317 }
2318
2319 static void
2320 create_longjmp_master_breakpoint (void)
2321 {
2322   struct program_space *pspace;
2323   struct cleanup *old_chain;
2324
2325   old_chain = save_current_program_space ();
2326
2327   ALL_PSPACES (pspace)
2328   {
2329     struct objfile *objfile;
2330
2331     set_current_program_space (pspace);
2332
2333     ALL_OBJFILES (objfile)
2334     {
2335       int i;
2336       struct gdbarch *gdbarch;
2337       struct breakpoint_objfile_data *bp_objfile_data;
2338
2339       gdbarch = get_objfile_arch (objfile);
2340       if (!gdbarch_get_longjmp_target_p (gdbarch))
2341         continue;
2342
2343       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2344
2345       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2346         {
2347           struct breakpoint *b;
2348           const char *func_name;
2349           CORE_ADDR addr;
2350
2351           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2352             continue;
2353
2354           func_name = longjmp_names[i];
2355           if (bp_objfile_data->longjmp_msym[i] == NULL)
2356             {
2357               struct minimal_symbol *m;
2358
2359               m = lookup_minimal_symbol_text (func_name, objfile);
2360               if (m == NULL)
2361                 {
2362                   /* Prevent future lookups in this objfile.  */
2363                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2364                   continue;
2365                 }
2366               bp_objfile_data->longjmp_msym[i] = m;
2367             }
2368
2369           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2370           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2371                                           &internal_breakpoint_ops);
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                                       &internal_breakpoint_ops);
2428       b->addr_string = xstrdup (func_name);
2429       b->enable_state = bp_disabled;
2430     }
2431   }
2432
2433   update_global_location_list (1);
2434
2435   do_cleanups (old_chain);
2436 }
2437
2438 /* Install a master breakpoint on the unwinder's debug hook.  */
2439
2440 void
2441 create_exception_master_breakpoint (void)
2442 {
2443   struct objfile *objfile;
2444   const char *const func_name = "_Unwind_DebugHook";
2445
2446   ALL_OBJFILES (objfile)
2447     {
2448       struct breakpoint *b;
2449       struct gdbarch *gdbarch;
2450       struct breakpoint_objfile_data *bp_objfile_data;
2451       CORE_ADDR addr;
2452
2453       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2454
2455       if (msym_not_found_p (bp_objfile_data->exception_msym))
2456         continue;
2457
2458       gdbarch = get_objfile_arch (objfile);
2459
2460       if (bp_objfile_data->exception_msym == NULL)
2461         {
2462           struct minimal_symbol *debug_hook;
2463
2464           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
2465           if (debug_hook == NULL)
2466             {
2467               bp_objfile_data->exception_msym = &msym_not_found;
2468               continue;
2469             }
2470
2471           bp_objfile_data->exception_msym = debug_hook;
2472         }
2473
2474       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
2475       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2476                                                  &current_target);
2477       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
2478                                       &internal_breakpoint_ops);
2479       b->addr_string = xstrdup (func_name);
2480       b->enable_state = bp_disabled;
2481     }
2482
2483   update_global_location_list (1);
2484 }
2485
2486 void
2487 update_breakpoints_after_exec (void)
2488 {
2489   struct breakpoint *b, *b_tmp;
2490   struct bp_location *bploc, **bplocp_tmp;
2491
2492   /* We're about to delete breakpoints from GDB's lists.  If the
2493      INSERTED flag is true, GDB will try to lift the breakpoints by
2494      writing the breakpoints' "shadow contents" back into memory.  The
2495      "shadow contents" are NOT valid after an exec, so GDB should not
2496      do that.  Instead, the target is responsible from marking
2497      breakpoints out as soon as it detects an exec.  We don't do that
2498      here instead, because there may be other attempts to delete
2499      breakpoints after detecting an exec and before reaching here.  */
2500   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
2501     if (bploc->pspace == current_program_space)
2502       gdb_assert (!bploc->inserted);
2503
2504   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2505   {
2506     if (b->pspace != current_program_space)
2507       continue;
2508
2509     /* Solib breakpoints must be explicitly reset after an exec().  */
2510     if (b->type == bp_shlib_event)
2511       {
2512         delete_breakpoint (b);
2513         continue;
2514       }
2515
2516     /* JIT breakpoints must be explicitly reset after an exec().  */
2517     if (b->type == bp_jit_event)
2518       {
2519         delete_breakpoint (b);
2520         continue;
2521       }
2522
2523     /* Thread event breakpoints must be set anew after an exec(),
2524        as must overlay event and longjmp master breakpoints.  */
2525     if (b->type == bp_thread_event || b->type == bp_overlay_event
2526         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
2527         || b->type == bp_exception_master)
2528       {
2529         delete_breakpoint (b);
2530         continue;
2531       }
2532
2533     /* Step-resume breakpoints are meaningless after an exec().  */
2534     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
2535       {
2536         delete_breakpoint (b);
2537         continue;
2538       }
2539
2540     /* Longjmp and longjmp-resume breakpoints are also meaningless
2541        after an exec.  */
2542     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
2543         || b->type == bp_exception || b->type == bp_exception_resume)
2544       {
2545         delete_breakpoint (b);
2546         continue;
2547       }
2548
2549     if (b->type == bp_catchpoint)
2550       {
2551         /* For now, none of the bp_catchpoint breakpoints need to
2552            do anything at this point.  In the future, if some of
2553            the catchpoints need to something, we will need to add
2554            a new method, and call this method from here.  */
2555         continue;
2556       }
2557
2558     /* bp_finish is a special case.  The only way we ought to be able
2559        to see one of these when an exec() has happened, is if the user
2560        caught a vfork, and then said "finish".  Ordinarily a finish just
2561        carries them to the call-site of the current callee, by setting
2562        a temporary bp there and resuming.  But in this case, the finish
2563        will carry them entirely through the vfork & exec.
2564
2565        We don't want to allow a bp_finish to remain inserted now.  But
2566        we can't safely delete it, 'cause finish_command has a handle to
2567        the bp on a bpstat, and will later want to delete it.  There's a
2568        chance (and I've seen it happen) that if we delete the bp_finish
2569        here, that its storage will get reused by the time finish_command
2570        gets 'round to deleting the "use to be a bp_finish" breakpoint.
2571        We really must allow finish_command to delete a bp_finish.
2572
2573        In the absence of a general solution for the "how do we know
2574        it's safe to delete something others may have handles to?"
2575        problem, what we'll do here is just uninsert the bp_finish, and
2576        let finish_command delete it.
2577
2578        (We know the bp_finish is "doomed" in the sense that it's
2579        momentary, and will be deleted as soon as finish_command sees
2580        the inferior stopped.  So it doesn't matter that the bp's
2581        address is probably bogus in the new a.out, unlike e.g., the
2582        solib breakpoints.)  */
2583
2584     if (b->type == bp_finish)
2585       {
2586         continue;
2587       }
2588
2589     /* Without a symbolic address, we have little hope of the
2590        pre-exec() address meaning the same thing in the post-exec()
2591        a.out.  */
2592     if (b->addr_string == NULL)
2593       {
2594         delete_breakpoint (b);
2595         continue;
2596       }
2597   }
2598   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
2599   create_overlay_event_breakpoint ();
2600   create_longjmp_master_breakpoint ();
2601   create_std_terminate_master_breakpoint ();
2602   create_exception_master_breakpoint ();
2603 }
2604
2605 int
2606 detach_breakpoints (int pid)
2607 {
2608   struct bp_location *bl, **blp_tmp;
2609   int val = 0;
2610   struct cleanup *old_chain = save_inferior_ptid ();
2611   struct inferior *inf = current_inferior ();
2612
2613   if (pid == PIDGET (inferior_ptid))
2614     error (_("Cannot detach breakpoints of inferior_ptid"));
2615
2616   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
2617   inferior_ptid = pid_to_ptid (pid);
2618   ALL_BP_LOCATIONS (bl, blp_tmp)
2619   {
2620     if (bl->pspace != inf->pspace)
2621       continue;
2622
2623     if (bl->inserted)
2624       val |= remove_breakpoint_1 (bl, mark_inserted);
2625   }
2626
2627   /* Detach single-step breakpoints as well.  */
2628   detach_single_step_breakpoints ();
2629
2630   do_cleanups (old_chain);
2631   return val;
2632 }
2633
2634 /* Remove the breakpoint location BL from the current address space.
2635    Note that this is used to detach breakpoints from a child fork.
2636    When we get here, the child isn't in the inferior list, and neither
2637    do we have objects to represent its address space --- we should
2638    *not* look at bl->pspace->aspace here.  */
2639
2640 static int
2641 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
2642 {
2643   int val;
2644
2645   /* BL is never in moribund_locations by our callers.  */
2646   gdb_assert (bl->owner != NULL);
2647
2648   if (bl->owner->enable_state == bp_permanent)
2649     /* Permanent breakpoints cannot be inserted or removed.  */
2650     return 0;
2651
2652   /* The type of none suggests that owner is actually deleted.
2653      This should not ever happen.  */
2654   gdb_assert (bl->owner->type != bp_none);
2655
2656   if (bl->loc_type == bp_loc_software_breakpoint
2657       || bl->loc_type == bp_loc_hardware_breakpoint)
2658     {
2659       /* "Normal" instruction breakpoint: either the standard
2660          trap-instruction bp (bp_breakpoint), or a
2661          bp_hardware_breakpoint.  */
2662
2663       /* First check to see if we have to handle an overlay.  */
2664       if (overlay_debugging == ovly_off
2665           || bl->section == NULL
2666           || !(section_is_overlay (bl->section)))
2667         {
2668           /* No overlay handling: just remove the breakpoint.  */
2669           val = bl->owner->ops->remove_location (bl);
2670         }
2671       else
2672         {
2673           /* This breakpoint is in an overlay section.
2674              Did we set a breakpoint at the LMA?  */
2675           if (!overlay_events_enabled)
2676               {
2677                 /* Yes -- overlay event support is not active, so we
2678                    should have set a breakpoint at the LMA.  Remove it.  
2679                 */
2680                 /* Ignore any failures: if the LMA is in ROM, we will
2681                    have already warned when we failed to insert it.  */
2682                 if (bl->loc_type == bp_loc_hardware_breakpoint)
2683                   target_remove_hw_breakpoint (bl->gdbarch,
2684                                                &bl->overlay_target_info);
2685                 else
2686                   target_remove_breakpoint (bl->gdbarch,
2687                                             &bl->overlay_target_info);
2688               }
2689           /* Did we set a breakpoint at the VMA? 
2690              If so, we will have marked the breakpoint 'inserted'.  */
2691           if (bl->inserted)
2692             {
2693               /* Yes -- remove it.  Previously we did not bother to
2694                  remove the breakpoint if the section had been
2695                  unmapped, but let's not rely on that being safe.  We
2696                  don't know what the overlay manager might do.  */
2697
2698               /* However, we should remove *software* breakpoints only
2699                  if the section is still mapped, or else we overwrite
2700                  wrong code with the saved shadow contents.  */
2701               if (bl->loc_type == bp_loc_hardware_breakpoint
2702                   || section_is_mapped (bl->section))
2703                 val = bl->owner->ops->remove_location (bl);
2704               else
2705                 val = 0;
2706             }
2707           else
2708             {
2709               /* No -- not inserted, so no need to remove.  No error.  */
2710               val = 0;
2711             }
2712         }
2713
2714       /* In some cases, we might not be able to remove a breakpoint
2715          in a shared library that has already been removed, but we
2716          have not yet processed the shlib unload event.  */
2717       if (val && solib_name_from_address (bl->pspace, bl->address))
2718         val = 0;
2719
2720       if (val)
2721         return val;
2722       bl->inserted = (is == mark_inserted);
2723     }
2724   else if (bl->loc_type == bp_loc_hardware_watchpoint)
2725     {
2726       gdb_assert (bl->owner->ops != NULL
2727                   && bl->owner->ops->remove_location != NULL);
2728
2729       bl->inserted = (is == mark_inserted);
2730       bl->owner->ops->remove_location (bl);
2731
2732       /* Failure to remove any of the hardware watchpoints comes here.  */
2733       if ((is == mark_uninserted) && (bl->inserted))
2734         warning (_("Could not remove hardware watchpoint %d."),
2735                  bl->owner->number);
2736     }
2737   else if (bl->owner->type == bp_catchpoint
2738            && breakpoint_enabled (bl->owner)
2739            && !bl->duplicate)
2740     {
2741       gdb_assert (bl->owner->ops != NULL
2742                   && bl->owner->ops->remove_location != NULL);
2743
2744       val = bl->owner->ops->remove_location (bl);
2745       if (val)
2746         return val;
2747
2748       bl->inserted = (is == mark_inserted);
2749     }
2750
2751   return 0;
2752 }
2753
2754 static int
2755 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
2756 {
2757   int ret;
2758   struct cleanup *old_chain;
2759
2760   /* BL is never in moribund_locations by our callers.  */
2761   gdb_assert (bl->owner != NULL);
2762
2763   if (bl->owner->enable_state == bp_permanent)
2764     /* Permanent breakpoints cannot be inserted or removed.  */
2765     return 0;
2766
2767   /* The type of none suggests that owner is actually deleted.
2768      This should not ever happen.  */
2769   gdb_assert (bl->owner->type != bp_none);
2770
2771   old_chain = save_current_space_and_thread ();
2772
2773   switch_to_program_space_and_thread (bl->pspace);
2774
2775   ret = remove_breakpoint_1 (bl, is);
2776
2777   do_cleanups (old_chain);
2778   return ret;
2779 }
2780
2781 /* Clear the "inserted" flag in all breakpoints.  */
2782
2783 void
2784 mark_breakpoints_out (void)
2785 {
2786   struct bp_location *bl, **blp_tmp;
2787
2788   ALL_BP_LOCATIONS (bl, blp_tmp)
2789     if (bl->pspace == current_program_space)
2790       bl->inserted = 0;
2791 }
2792
2793 /* Clear the "inserted" flag in all breakpoints and delete any
2794    breakpoints which should go away between runs of the program.
2795
2796    Plus other such housekeeping that has to be done for breakpoints
2797    between runs.
2798
2799    Note: this function gets called at the end of a run (by
2800    generic_mourn_inferior) and when a run begins (by
2801    init_wait_for_inferior).  */
2802
2803
2804
2805 void
2806 breakpoint_init_inferior (enum inf_context context)
2807 {
2808   struct breakpoint *b, *b_tmp;
2809   struct bp_location *bl, **blp_tmp;
2810   int ix;
2811   struct program_space *pspace = current_program_space;
2812
2813   /* If breakpoint locations are shared across processes, then there's
2814      nothing to do.  */
2815   if (gdbarch_has_global_breakpoints (target_gdbarch))
2816     return;
2817
2818   ALL_BP_LOCATIONS (bl, blp_tmp)
2819   {
2820     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
2821     if (bl->pspace == pspace
2822         && bl->owner->enable_state != bp_permanent)
2823       bl->inserted = 0;
2824   }
2825
2826   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2827   {
2828     if (b->loc && b->loc->pspace != pspace)
2829       continue;
2830
2831     switch (b->type)
2832       {
2833       case bp_call_dummy:
2834
2835         /* If the call dummy breakpoint is at the entry point it will
2836            cause problems when the inferior is rerun, so we better get
2837            rid of it.  */
2838
2839       case bp_watchpoint_scope:
2840
2841         /* Also get rid of scope breakpoints.  */
2842
2843       case bp_shlib_event:
2844
2845         /* Also remove solib event breakpoints.  Their addresses may
2846            have changed since the last time we ran the program.
2847            Actually we may now be debugging against different target;
2848            and so the solib backend that installed this breakpoint may
2849            not be used in by the target.  E.g.,
2850
2851            (gdb) file prog-linux
2852            (gdb) run               # native linux target
2853            ...
2854            (gdb) kill
2855            (gdb) file prog-win.exe
2856            (gdb) tar rem :9999     # remote Windows gdbserver.
2857         */
2858
2859         delete_breakpoint (b);
2860         break;
2861
2862       case bp_watchpoint:
2863       case bp_hardware_watchpoint:
2864       case bp_read_watchpoint:
2865       case bp_access_watchpoint:
2866         {
2867           struct watchpoint *w = (struct watchpoint *) b;
2868
2869           /* Likewise for watchpoints on local expressions.  */
2870           if (w->exp_valid_block != NULL)
2871             delete_breakpoint (b);
2872           else if (context == inf_starting)
2873             {
2874               /* Reset val field to force reread of starting value in
2875                  insert_breakpoints.  */
2876               if (w->val)
2877                 value_free (w->val);
2878               w->val = NULL;
2879               w->val_valid = 0;
2880           }
2881         }
2882         break;
2883       default:
2884         break;
2885       }
2886   }
2887
2888   /* Get rid of the moribund locations.  */
2889   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
2890     decref_bp_location (&bl);
2891   VEC_free (bp_location_p, moribund_locations);
2892 }
2893
2894 /* These functions concern about actual breakpoints inserted in the
2895    target --- to e.g. check if we need to do decr_pc adjustment or if
2896    we need to hop over the bkpt --- so we check for address space
2897    match, not program space.  */
2898
2899 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
2900    exists at PC.  It returns ordinary_breakpoint_here if it's an
2901    ordinary breakpoint, or permanent_breakpoint_here if it's a
2902    permanent breakpoint.
2903    - When continuing from a location with an ordinary breakpoint, we
2904      actually single step once before calling insert_breakpoints.
2905    - When continuing from a location with a permanent breakpoint, we
2906      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
2907      the target, to advance the PC past the breakpoint.  */
2908
2909 enum breakpoint_here
2910 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
2911 {
2912   struct bp_location *bl, **blp_tmp;
2913   int any_breakpoint_here = 0;
2914
2915   ALL_BP_LOCATIONS (bl, blp_tmp)
2916     {
2917       if (bl->loc_type != bp_loc_software_breakpoint
2918           && bl->loc_type != bp_loc_hardware_breakpoint)
2919         continue;
2920
2921       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
2922       if ((breakpoint_enabled (bl->owner)
2923            || bl->owner->enable_state == bp_permanent)
2924           && breakpoint_location_address_match (bl, aspace, pc))
2925         {
2926           if (overlay_debugging 
2927               && section_is_overlay (bl->section)
2928               && !section_is_mapped (bl->section))
2929             continue;           /* unmapped overlay -- can't be a match */
2930           else if (bl->owner->enable_state == bp_permanent)
2931             return permanent_breakpoint_here;
2932           else
2933             any_breakpoint_here = 1;
2934         }
2935     }
2936
2937   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
2938 }
2939
2940 /* Return true if there's a moribund breakpoint at PC.  */
2941
2942 int
2943 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
2944 {
2945   struct bp_location *loc;
2946   int ix;
2947
2948   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
2949     if (breakpoint_location_address_match (loc, aspace, pc))
2950       return 1;
2951
2952   return 0;
2953 }
2954
2955 /* Returns non-zero if there's a breakpoint inserted at PC, which is
2956    inserted using regular breakpoint_chain / bp_location array
2957    mechanism.  This does not check for single-step breakpoints, which
2958    are inserted and removed using direct target manipulation.  */
2959
2960 int
2961 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
2962                                     CORE_ADDR pc)
2963 {
2964   struct bp_location *bl, **blp_tmp;
2965
2966   ALL_BP_LOCATIONS (bl, blp_tmp)
2967     {
2968       if (bl->loc_type != bp_loc_software_breakpoint
2969           && bl->loc_type != bp_loc_hardware_breakpoint)
2970         continue;
2971
2972       if (bl->inserted
2973           && breakpoint_location_address_match (bl, aspace, pc))
2974         {
2975           if (overlay_debugging 
2976               && section_is_overlay (bl->section)
2977               && !section_is_mapped (bl->section))
2978             continue;           /* unmapped overlay -- can't be a match */
2979           else
2980             return 1;
2981         }
2982     }
2983   return 0;
2984 }
2985
2986 /* Returns non-zero iff there's either regular breakpoint
2987    or a single step breakpoint inserted at PC.  */
2988
2989 int
2990 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
2991 {
2992   if (regular_breakpoint_inserted_here_p (aspace, pc))
2993     return 1;
2994
2995   if (single_step_breakpoint_inserted_here_p (aspace, pc))
2996     return 1;
2997
2998   return 0;
2999 }
3000
3001 /* This function returns non-zero iff there is a software breakpoint
3002    inserted at PC.  */
3003
3004 int
3005 software_breakpoint_inserted_here_p (struct address_space *aspace,
3006                                      CORE_ADDR pc)
3007 {
3008   struct bp_location *bl, **blp_tmp;
3009
3010   ALL_BP_LOCATIONS (bl, blp_tmp)
3011     {
3012       if (bl->loc_type != bp_loc_software_breakpoint)
3013         continue;
3014
3015       if (bl->inserted
3016           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3017                                        aspace, pc))
3018         {
3019           if (overlay_debugging 
3020               && section_is_overlay (bl->section)
3021               && !section_is_mapped (bl->section))
3022             continue;           /* unmapped overlay -- can't be a match */
3023           else
3024             return 1;
3025         }
3026     }
3027
3028   /* Also check for software single-step breakpoints.  */
3029   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3030     return 1;
3031
3032   return 0;
3033 }
3034
3035 int
3036 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3037                                        CORE_ADDR addr, ULONGEST len)
3038 {
3039   struct breakpoint *bpt;
3040
3041   ALL_BREAKPOINTS (bpt)
3042     {
3043       struct bp_location *loc;
3044
3045       if (bpt->type != bp_hardware_watchpoint
3046           && bpt->type != bp_access_watchpoint)
3047         continue;
3048
3049       if (!breakpoint_enabled (bpt))
3050         continue;
3051
3052       for (loc = bpt->loc; loc; loc = loc->next)
3053         if (loc->pspace->aspace == aspace && loc->inserted)
3054           {
3055             CORE_ADDR l, h;
3056
3057             /* Check for intersection.  */
3058             l = max (loc->address, addr);
3059             h = min (loc->address + loc->length, addr + len);
3060             if (l < h)
3061               return 1;
3062           }
3063     }
3064   return 0;
3065 }
3066
3067 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3068    PC is valid for process/thread PTID.  */
3069
3070 int
3071 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3072                          ptid_t ptid)
3073 {
3074   struct bp_location *bl, **blp_tmp;
3075   /* The thread and task IDs associated to PTID, computed lazily.  */
3076   int thread = -1;
3077   int task = 0;
3078   
3079   ALL_BP_LOCATIONS (bl, blp_tmp)
3080     {
3081       if (bl->loc_type != bp_loc_software_breakpoint
3082           && bl->loc_type != bp_loc_hardware_breakpoint)
3083         continue;
3084
3085       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3086       if (!breakpoint_enabled (bl->owner)
3087           && bl->owner->enable_state != bp_permanent)
3088         continue;
3089
3090       if (!breakpoint_location_address_match (bl, aspace, pc))
3091         continue;
3092
3093       if (bl->owner->thread != -1)
3094         {
3095           /* This is a thread-specific breakpoint.  Check that ptid
3096              matches that thread.  If thread hasn't been computed yet,
3097              it is now time to do so.  */
3098           if (thread == -1)
3099             thread = pid_to_thread_id (ptid);
3100           if (bl->owner->thread != thread)
3101             continue;
3102         }
3103
3104       if (bl->owner->task != 0)
3105         {
3106           /* This is a task-specific breakpoint.  Check that ptid
3107              matches that task.  If task hasn't been computed yet,
3108              it is now time to do so.  */
3109           if (task == 0)
3110             task = ada_get_task_number (ptid);
3111           if (bl->owner->task != task)
3112             continue;
3113         }
3114
3115       if (overlay_debugging 
3116           && section_is_overlay (bl->section)
3117           && !section_is_mapped (bl->section))
3118         continue;           /* unmapped overlay -- can't be a match */
3119
3120       return 1;
3121     }
3122
3123   return 0;
3124 }
3125 \f
3126
3127 /* bpstat stuff.  External routines' interfaces are documented
3128    in breakpoint.h.  */
3129
3130 int
3131 ep_is_catchpoint (struct breakpoint *ep)
3132 {
3133   return (ep->type == bp_catchpoint);
3134 }
3135
3136 /* Frees any storage that is part of a bpstat.  Does not walk the
3137    'next' chain.  */
3138
3139 static void
3140 bpstat_free (bpstat bs)
3141 {
3142   if (bs->old_val != NULL)
3143     value_free (bs->old_val);
3144   decref_counted_command_line (&bs->commands);
3145   decref_bp_location (&bs->bp_location_at);
3146   xfree (bs);
3147 }
3148
3149 /* Clear a bpstat so that it says we are not at any breakpoint.
3150    Also free any storage that is part of a bpstat.  */
3151
3152 void
3153 bpstat_clear (bpstat *bsp)
3154 {
3155   bpstat p;
3156   bpstat q;
3157
3158   if (bsp == 0)
3159     return;
3160   p = *bsp;
3161   while (p != NULL)
3162     {
3163       q = p->next;
3164       bpstat_free (p);
3165       p = q;
3166     }
3167   *bsp = NULL;
3168 }
3169
3170 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3171    is part of the bpstat is copied as well.  */
3172
3173 bpstat
3174 bpstat_copy (bpstat bs)
3175 {
3176   bpstat p = NULL;
3177   bpstat tmp;
3178   bpstat retval = NULL;
3179
3180   if (bs == NULL)
3181     return bs;
3182
3183   for (; bs != NULL; bs = bs->next)
3184     {
3185       tmp = (bpstat) xmalloc (sizeof (*tmp));
3186       memcpy (tmp, bs, sizeof (*tmp));
3187       incref_counted_command_line (tmp->commands);
3188       incref_bp_location (tmp->bp_location_at);
3189       if (bs->old_val != NULL)
3190         {
3191           tmp->old_val = value_copy (bs->old_val);
3192           release_value (tmp->old_val);
3193         }
3194
3195       if (p == NULL)
3196         /* This is the first thing in the chain.  */
3197         retval = tmp;
3198       else
3199         p->next = tmp;
3200       p = tmp;
3201     }
3202   p->next = NULL;
3203   return retval;
3204 }
3205
3206 /* Find the bpstat associated with this breakpoint.  */
3207
3208 bpstat
3209 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3210 {
3211   if (bsp == NULL)
3212     return NULL;
3213
3214   for (; bsp != NULL; bsp = bsp->next)
3215     {
3216       if (bsp->breakpoint_at == breakpoint)
3217         return bsp;
3218     }
3219   return NULL;
3220 }
3221
3222 /* Put in *NUM the breakpoint number of the first breakpoint we are
3223    stopped at.  *BSP upon return is a bpstat which points to the
3224    remaining breakpoints stopped at (but which is not guaranteed to be
3225    good for anything but further calls to bpstat_num).
3226
3227    Return 0 if passed a bpstat which does not indicate any breakpoints.
3228    Return -1 if stopped at a breakpoint that has been deleted since
3229    we set it.
3230    Return 1 otherwise.  */
3231
3232 int
3233 bpstat_num (bpstat *bsp, int *num)
3234 {
3235   struct breakpoint *b;
3236
3237   if ((*bsp) == NULL)
3238     return 0;                   /* No more breakpoint values */
3239
3240   /* We assume we'll never have several bpstats that correspond to a
3241      single breakpoint -- otherwise, this function might return the
3242      same number more than once and this will look ugly.  */
3243   b = (*bsp)->breakpoint_at;
3244   *bsp = (*bsp)->next;
3245   if (b == NULL)
3246     return -1;                  /* breakpoint that's been deleted since */
3247
3248   *num = b->number;             /* We have its number */
3249   return 1;
3250 }
3251
3252 /* See breakpoint.h.  */
3253
3254 void
3255 bpstat_clear_actions (void)
3256 {
3257   struct thread_info *tp;
3258   bpstat bs;
3259
3260   if (ptid_equal (inferior_ptid, null_ptid))
3261     return;
3262
3263   tp = find_thread_ptid (inferior_ptid);
3264   if (tp == NULL)
3265     return;
3266
3267   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3268     {
3269       decref_counted_command_line (&bs->commands);
3270
3271       if (bs->old_val != NULL)
3272         {
3273           value_free (bs->old_val);
3274           bs->old_val = NULL;
3275         }
3276     }
3277 }
3278
3279 /* Called when a command is about to proceed the inferior.  */
3280
3281 static void
3282 breakpoint_about_to_proceed (void)
3283 {
3284   if (!ptid_equal (inferior_ptid, null_ptid))
3285     {
3286       struct thread_info *tp = inferior_thread ();
3287
3288       /* Allow inferior function calls in breakpoint commands to not
3289          interrupt the command list.  When the call finishes
3290          successfully, the inferior will be standing at the same
3291          breakpoint as if nothing happened.  */
3292       if (tp->control.in_infcall)
3293         return;
3294     }
3295
3296   breakpoint_proceeded = 1;
3297 }
3298
3299 /* Stub for cleaning up our state if we error-out of a breakpoint
3300    command.  */
3301 static void
3302 cleanup_executing_breakpoints (void *ignore)
3303 {
3304   executing_breakpoint_commands = 0;
3305 }
3306
3307 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3308    or its equivalent.  */
3309
3310 static int
3311 command_line_is_silent (struct command_line *cmd)
3312 {
3313   return cmd && (strcmp ("silent", cmd->line) == 0
3314                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3315 }
3316
3317 /* Execute all the commands associated with all the breakpoints at
3318    this location.  Any of these commands could cause the process to
3319    proceed beyond this point, etc.  We look out for such changes by
3320    checking the global "breakpoint_proceeded" after each command.
3321
3322    Returns true if a breakpoint command resumed the inferior.  In that
3323    case, it is the caller's responsibility to recall it again with the
3324    bpstat of the current thread.  */
3325
3326 static int
3327 bpstat_do_actions_1 (bpstat *bsp)
3328 {
3329   bpstat bs;
3330   struct cleanup *old_chain;
3331   int again = 0;
3332
3333   /* Avoid endless recursion if a `source' command is contained
3334      in bs->commands.  */
3335   if (executing_breakpoint_commands)
3336     return 0;
3337
3338   executing_breakpoint_commands = 1;
3339   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3340
3341   prevent_dont_repeat ();
3342
3343   /* This pointer will iterate over the list of bpstat's.  */
3344   bs = *bsp;
3345
3346   breakpoint_proceeded = 0;
3347   for (; bs != NULL; bs = bs->next)
3348     {
3349       struct counted_command_line *ccmd;
3350       struct command_line *cmd;
3351       struct cleanup *this_cmd_tree_chain;
3352
3353       /* Take ownership of the BSP's command tree, if it has one.
3354
3355          The command tree could legitimately contain commands like
3356          'step' and 'next', which call clear_proceed_status, which
3357          frees stop_bpstat's command tree.  To make sure this doesn't
3358          free the tree we're executing out from under us, we need to
3359          take ownership of the tree ourselves.  Since a given bpstat's
3360          commands are only executed once, we don't need to copy it; we
3361          can clear the pointer in the bpstat, and make sure we free
3362          the tree when we're done.  */
3363       ccmd = bs->commands;
3364       bs->commands = NULL;
3365       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3366       cmd = ccmd ? ccmd->commands : NULL;
3367       if (command_line_is_silent (cmd))
3368         {
3369           /* The action has been already done by bpstat_stop_status.  */
3370           cmd = cmd->next;
3371         }
3372
3373       while (cmd != NULL)
3374         {
3375           execute_control_command (cmd);
3376
3377           if (breakpoint_proceeded)
3378             break;
3379           else
3380             cmd = cmd->next;
3381         }
3382
3383       /* We can free this command tree now.  */
3384       do_cleanups (this_cmd_tree_chain);
3385
3386       if (breakpoint_proceeded)
3387         {
3388           if (target_can_async_p ())
3389             /* If we are in async mode, then the target might be still
3390                running, not stopped at any breakpoint, so nothing for
3391                us to do here -- just return to the event loop.  */
3392             ;
3393           else
3394             /* In sync mode, when execute_control_command returns
3395                we're already standing on the next breakpoint.
3396                Breakpoint commands for that stop were not run, since
3397                execute_command does not run breakpoint commands --
3398                only command_line_handler does, but that one is not
3399                involved in execution of breakpoint commands.  So, we
3400                can now execute breakpoint commands.  It should be
3401                noted that making execute_command do bpstat actions is
3402                not an option -- in this case we'll have recursive
3403                invocation of bpstat for each breakpoint with a
3404                command, and can easily blow up GDB stack.  Instead, we
3405                return true, which will trigger the caller to recall us
3406                with the new stop_bpstat.  */
3407             again = 1;
3408           break;
3409         }
3410     }
3411   do_cleanups (old_chain);
3412   return again;
3413 }
3414
3415 void
3416 bpstat_do_actions (void)
3417 {
3418   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
3419
3420   /* Do any commands attached to breakpoint we are stopped at.  */
3421   while (!ptid_equal (inferior_ptid, null_ptid)
3422          && target_has_execution
3423          && !is_exited (inferior_ptid)
3424          && !is_executing (inferior_ptid))
3425     /* Since in sync mode, bpstat_do_actions may resume the inferior,
3426        and only return when it is stopped at the next breakpoint, we
3427        keep doing breakpoint actions until it returns false to
3428        indicate the inferior was not resumed.  */
3429     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
3430       break;
3431
3432   discard_cleanups (cleanup_if_error);
3433 }
3434
3435 /* Print out the (old or new) value associated with a watchpoint.  */
3436
3437 static void
3438 watchpoint_value_print (struct value *val, struct ui_file *stream)
3439 {
3440   if (val == NULL)
3441     fprintf_unfiltered (stream, _("<unreadable>"));
3442   else
3443     {
3444       struct value_print_options opts;
3445       get_user_print_options (&opts);
3446       value_print (val, stream, &opts);
3447     }
3448 }
3449
3450 /* Generic routine for printing messages indicating why we
3451    stopped.  The behavior of this function depends on the value
3452    'print_it' in the bpstat structure.  Under some circumstances we
3453    may decide not to print anything here and delegate the task to
3454    normal_stop().  */
3455
3456 static enum print_stop_action
3457 print_bp_stop_message (bpstat bs)
3458 {
3459   switch (bs->print_it)
3460     {
3461     case print_it_noop:
3462       /* Nothing should be printed for this bpstat entry.  */
3463       return PRINT_UNKNOWN;
3464       break;
3465
3466     case print_it_done:
3467       /* We still want to print the frame, but we already printed the
3468          relevant messages.  */
3469       return PRINT_SRC_AND_LOC;
3470       break;
3471
3472     case print_it_normal:
3473       {
3474         struct breakpoint *b = bs->breakpoint_at;
3475
3476         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
3477            which has since been deleted.  */
3478         if (b == NULL)
3479           return PRINT_UNKNOWN;
3480
3481         /* Normal case.  Call the breakpoint's print_it method.  */
3482         return b->ops->print_it (bs);
3483       }
3484       break;
3485
3486     default:
3487       internal_error (__FILE__, __LINE__,
3488                       _("print_bp_stop_message: unrecognized enum value"));
3489       break;
3490     }
3491 }
3492
3493 /* Print a message indicating what happened.  This is called from
3494    normal_stop().  The input to this routine is the head of the bpstat
3495    list - a list of the eventpoints that caused this stop.  KIND is
3496    the target_waitkind for the stopping event.  This
3497    routine calls the generic print routine for printing a message
3498    about reasons for stopping.  This will print (for example) the
3499    "Breakpoint n," part of the output.  The return value of this
3500    routine is one of:
3501
3502    PRINT_UNKNOWN: Means we printed nothing.
3503    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
3504    code to print the location.  An example is 
3505    "Breakpoint 1, " which should be followed by
3506    the location.
3507    PRINT_SRC_ONLY: Means we printed something, but there is no need
3508    to also print the location part of the message.
3509    An example is the catch/throw messages, which
3510    don't require a location appended to the end.
3511    PRINT_NOTHING: We have done some printing and we don't need any 
3512    further info to be printed.  */
3513
3514 enum print_stop_action
3515 bpstat_print (bpstat bs, int kind)
3516 {
3517   int val;
3518
3519   /* Maybe another breakpoint in the chain caused us to stop.
3520      (Currently all watchpoints go on the bpstat whether hit or not.
3521      That probably could (should) be changed, provided care is taken
3522      with respect to bpstat_explains_signal).  */
3523   for (; bs; bs = bs->next)
3524     {
3525       val = print_bp_stop_message (bs);
3526       if (val == PRINT_SRC_ONLY 
3527           || val == PRINT_SRC_AND_LOC 
3528           || val == PRINT_NOTHING)
3529         return val;
3530     }
3531
3532   /* If we had hit a shared library event breakpoint,
3533      print_bp_stop_message would print out this message.  If we hit an
3534      OS-level shared library event, do the same thing.  */
3535   if (kind == TARGET_WAITKIND_LOADED)
3536     {
3537       ui_out_text (current_uiout, _("Stopped due to shared library event\n"));
3538       if (ui_out_is_mi_like_p (current_uiout))
3539         ui_out_field_string (current_uiout, "reason",
3540                              async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
3541       return PRINT_NOTHING;
3542     }
3543
3544   /* We reached the end of the chain, or we got a null BS to start
3545      with and nothing was printed.  */
3546   return PRINT_UNKNOWN;
3547 }
3548
3549 /* Evaluate the expression EXP and return 1 if value is zero.  This is
3550    used inside a catch_errors to evaluate the breakpoint condition.
3551    The argument is a "struct expression *" that has been cast to a
3552    "char *" to make it pass through catch_errors.  */
3553
3554 static int
3555 breakpoint_cond_eval (void *exp)
3556 {
3557   struct value *mark = value_mark ();
3558   int i = !value_true (evaluate_expression ((struct expression *) exp));
3559
3560   value_free_to_mark (mark);
3561   return i;
3562 }
3563
3564 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
3565
3566 static bpstat
3567 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
3568 {
3569   bpstat bs;
3570
3571   bs = (bpstat) xmalloc (sizeof (*bs));
3572   bs->next = NULL;
3573   **bs_link_pointer = bs;
3574   *bs_link_pointer = &bs->next;
3575   bs->breakpoint_at = bl->owner;
3576   bs->bp_location_at = bl;
3577   incref_bp_location (bl);
3578   /* If the condition is false, etc., don't do the commands.  */
3579   bs->commands = NULL;
3580   bs->old_val = NULL;
3581   bs->print_it = print_it_normal;
3582   return bs;
3583 }
3584 \f
3585 /* The target has stopped with waitstatus WS.  Check if any hardware
3586    watchpoints have triggered, according to the target.  */
3587
3588 int
3589 watchpoints_triggered (struct target_waitstatus *ws)
3590 {
3591   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
3592   CORE_ADDR addr;
3593   struct breakpoint *b;
3594
3595   if (!stopped_by_watchpoint)
3596     {
3597       /* We were not stopped by a watchpoint.  Mark all watchpoints
3598          as not triggered.  */
3599       ALL_BREAKPOINTS (b)
3600         if (is_hardware_watchpoint (b))
3601           {
3602             struct watchpoint *w = (struct watchpoint *) b;
3603
3604             w->watchpoint_triggered = watch_triggered_no;
3605           }
3606
3607       return 0;
3608     }
3609
3610   if (!target_stopped_data_address (&current_target, &addr))
3611     {
3612       /* We were stopped by a watchpoint, but we don't know where.
3613          Mark all watchpoints as unknown.  */
3614       ALL_BREAKPOINTS (b)
3615         if (is_hardware_watchpoint (b))
3616           {
3617             struct watchpoint *w = (struct watchpoint *) b;
3618
3619             w->watchpoint_triggered = watch_triggered_unknown;
3620           }
3621
3622       return stopped_by_watchpoint;
3623     }
3624
3625   /* The target could report the data address.  Mark watchpoints
3626      affected by this data address as triggered, and all others as not
3627      triggered.  */
3628
3629   ALL_BREAKPOINTS (b)
3630     if (is_hardware_watchpoint (b))
3631       {
3632         struct watchpoint *w = (struct watchpoint *) b;
3633         struct bp_location *loc;
3634
3635         w->watchpoint_triggered = watch_triggered_no;
3636         for (loc = b->loc; loc; loc = loc->next)
3637           {
3638             if (is_masked_watchpoint (b))
3639               {
3640                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
3641                 CORE_ADDR start = loc->address & w->hw_wp_mask;
3642
3643                 if (newaddr == start)
3644                   {
3645                     w->watchpoint_triggered = watch_triggered_yes;
3646                     break;
3647                   }
3648               }
3649             /* Exact match not required.  Within range is sufficient.  */
3650             else if (target_watchpoint_addr_within_range (&current_target,
3651                                                          addr, loc->address,
3652                                                          loc->length))
3653               {
3654                 w->watchpoint_triggered = watch_triggered_yes;
3655                 break;
3656               }
3657           }
3658       }
3659
3660   return 1;
3661 }
3662
3663 /* Possible return values for watchpoint_check (this can't be an enum
3664    because of check_errors).  */
3665 /* The watchpoint has been deleted.  */
3666 #define WP_DELETED 1
3667 /* The value has changed.  */
3668 #define WP_VALUE_CHANGED 2
3669 /* The value has not changed.  */
3670 #define WP_VALUE_NOT_CHANGED 3
3671 /* Ignore this watchpoint, no matter if the value changed or not.  */
3672 #define WP_IGNORE 4
3673
3674 #define BP_TEMPFLAG 1
3675 #define BP_HARDWAREFLAG 2
3676
3677 /* Evaluate watchpoint condition expression and check if its value
3678    changed.
3679
3680    P should be a pointer to struct bpstat, but is defined as a void *
3681    in order for this function to be usable with catch_errors.  */
3682
3683 static int
3684 watchpoint_check (void *p)
3685 {
3686   bpstat bs = (bpstat) p;
3687   struct watchpoint *b;
3688   struct frame_info *fr;
3689   int within_current_scope;
3690
3691   /* BS is built from an existing struct breakpoint.  */
3692   gdb_assert (bs->breakpoint_at != NULL);
3693   b = (struct watchpoint *) bs->breakpoint_at;
3694
3695   /* If this is a local watchpoint, we only want to check if the
3696      watchpoint frame is in scope if the current thread is the thread
3697      that was used to create the watchpoint.  */
3698   if (!watchpoint_in_thread_scope (b))
3699     return WP_IGNORE;
3700
3701   if (b->exp_valid_block == NULL)
3702     within_current_scope = 1;
3703   else
3704     {
3705       struct frame_info *frame = get_current_frame ();
3706       struct gdbarch *frame_arch = get_frame_arch (frame);
3707       CORE_ADDR frame_pc = get_frame_pc (frame);
3708
3709       /* in_function_epilogue_p() returns a non-zero value if we're
3710          still in the function but the stack frame has already been
3711          invalidated.  Since we can't rely on the values of local
3712          variables after the stack has been destroyed, we are treating
3713          the watchpoint in that state as `not changed' without further
3714          checking.  Don't mark watchpoints as changed if the current
3715          frame is in an epilogue - even if they are in some other
3716          frame, our view of the stack is likely to be wrong and
3717          frame_find_by_id could error out.  */
3718       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
3719         return WP_IGNORE;
3720
3721       fr = frame_find_by_id (b->watchpoint_frame);
3722       within_current_scope = (fr != NULL);
3723
3724       /* If we've gotten confused in the unwinder, we might have
3725          returned a frame that can't describe this variable.  */
3726       if (within_current_scope)
3727         {
3728           struct symbol *function;
3729
3730           function = get_frame_function (fr);
3731           if (function == NULL
3732               || !contained_in (b->exp_valid_block,
3733                                 SYMBOL_BLOCK_VALUE (function)))
3734             within_current_scope = 0;
3735         }
3736
3737       if (within_current_scope)
3738         /* If we end up stopping, the current frame will get selected
3739            in normal_stop.  So this call to select_frame won't affect
3740            the user.  */
3741         select_frame (fr);
3742     }
3743
3744   if (within_current_scope)
3745     {
3746       /* We use value_{,free_to_}mark because it could be a *long*
3747          time before we return to the command level and call
3748          free_all_values.  We can't call free_all_values because we
3749          might be in the middle of evaluating a function call.  */
3750
3751       int pc = 0;
3752       struct value *mark;
3753       struct value *new_val;
3754
3755       if (is_masked_watchpoint (&b->base))
3756         /* Since we don't know the exact trigger address (from
3757            stopped_data_address), just tell the user we've triggered
3758            a mask watchpoint.  */
3759         return WP_VALUE_CHANGED;
3760
3761       mark = value_mark ();
3762       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
3763
3764       /* We use value_equal_contents instead of value_equal because
3765          the latter coerces an array to a pointer, thus comparing just
3766          the address of the array instead of its contents.  This is
3767          not what we want.  */
3768       if ((b->val != NULL) != (new_val != NULL)
3769           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
3770         {
3771           if (new_val != NULL)
3772             {
3773               release_value (new_val);
3774               value_free_to_mark (mark);
3775             }
3776           bs->old_val = b->val;
3777           b->val = new_val;
3778           b->val_valid = 1;
3779           return WP_VALUE_CHANGED;
3780         }
3781       else
3782         {
3783           /* Nothing changed.  */
3784           value_free_to_mark (mark);
3785           return WP_VALUE_NOT_CHANGED;
3786         }
3787     }
3788   else
3789     {
3790       struct ui_out *uiout = current_uiout;
3791
3792       /* This seems like the only logical thing to do because
3793          if we temporarily ignored the watchpoint, then when
3794          we reenter the block in which it is valid it contains
3795          garbage (in the case of a function, it may have two
3796          garbage values, one before and one after the prologue).
3797          So we can't even detect the first assignment to it and
3798          watch after that (since the garbage may or may not equal
3799          the first value assigned).  */
3800       /* We print all the stop information in
3801          breakpoint_ops->print_it, but in this case, by the time we
3802          call breakpoint_ops->print_it this bp will be deleted
3803          already.  So we have no choice but print the information
3804          here.  */
3805       if (ui_out_is_mi_like_p (uiout))
3806         ui_out_field_string
3807           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
3808       ui_out_text (uiout, "\nWatchpoint ");
3809       ui_out_field_int (uiout, "wpnum", b->base.number);
3810       ui_out_text (uiout,
3811                    " deleted because the program has left the block in\n\
3812 which its expression is valid.\n");     
3813
3814       /* Make sure the watchpoint's commands aren't executed.  */
3815       decref_counted_command_line (&b->base.commands);
3816       watchpoint_del_at_next_stop (b);
3817
3818       return WP_DELETED;
3819     }
3820 }
3821
3822 /* Return true if it looks like target has stopped due to hitting
3823    breakpoint location BL.  This function does not check if we should
3824    stop, only if BL explains the stop.  */
3825
3826 static int
3827 bpstat_check_location (const struct bp_location *bl,
3828                        struct address_space *aspace, CORE_ADDR bp_addr)
3829 {
3830   struct breakpoint *b = bl->owner;
3831
3832   /* BL is from an existing breakpoint.  */
3833   gdb_assert (b != NULL);
3834
3835   return b->ops->breakpoint_hit (bl, aspace, bp_addr);
3836 }
3837
3838 /* Determine if the watched values have actually changed, and we
3839    should stop.  If not, set BS->stop to 0.  */
3840
3841 static void
3842 bpstat_check_watchpoint (bpstat bs)
3843 {
3844   const struct bp_location *bl;
3845   struct watchpoint *b;
3846
3847   /* BS is built for existing struct breakpoint.  */
3848   bl = bs->bp_location_at;
3849   gdb_assert (bl != NULL);
3850   b = (struct watchpoint *) bs->breakpoint_at;
3851   gdb_assert (b != NULL);
3852
3853     {
3854       int must_check_value = 0;
3855       
3856       if (b->base.type == bp_watchpoint)
3857         /* For a software watchpoint, we must always check the
3858            watched value.  */
3859         must_check_value = 1;
3860       else if (b->watchpoint_triggered == watch_triggered_yes)
3861         /* We have a hardware watchpoint (read, write, or access)
3862            and the target earlier reported an address watched by
3863            this watchpoint.  */
3864         must_check_value = 1;
3865       else if (b->watchpoint_triggered == watch_triggered_unknown
3866                && b->base.type == bp_hardware_watchpoint)
3867         /* We were stopped by a hardware watchpoint, but the target could
3868            not report the data address.  We must check the watchpoint's
3869            value.  Access and read watchpoints are out of luck; without
3870            a data address, we can't figure it out.  */
3871         must_check_value = 1;
3872
3873       if (must_check_value)
3874         {
3875           char *message
3876             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
3877                           b->base.number);
3878           struct cleanup *cleanups = make_cleanup (xfree, message);
3879           int e = catch_errors (watchpoint_check, bs, message,
3880                                 RETURN_MASK_ALL);
3881           do_cleanups (cleanups);
3882           switch (e)
3883             {
3884             case WP_DELETED:
3885               /* We've already printed what needs to be printed.  */
3886               bs->print_it = print_it_done;
3887               /* Stop.  */
3888               break;
3889             case WP_IGNORE:
3890               bs->print_it = print_it_noop;
3891               bs->stop = 0;
3892               break;
3893             case WP_VALUE_CHANGED:
3894               if (b->base.type == bp_read_watchpoint)
3895                 {
3896                   /* There are two cases to consider here:
3897
3898                      1. We're watching the triggered memory for reads.
3899                      In that case, trust the target, and always report
3900                      the watchpoint hit to the user.  Even though
3901                      reads don't cause value changes, the value may
3902                      have changed since the last time it was read, and
3903                      since we're not trapping writes, we will not see
3904                      those, and as such we should ignore our notion of
3905                      old value.
3906
3907                      2. We're watching the triggered memory for both
3908                      reads and writes.  There are two ways this may
3909                      happen:
3910
3911                      2.1. This is a target that can't break on data
3912                      reads only, but can break on accesses (reads or
3913                      writes), such as e.g., x86.  We detect this case
3914                      at the time we try to insert read watchpoints.
3915
3916                      2.2. Otherwise, the target supports read
3917                      watchpoints, but, the user set an access or write
3918                      watchpoint watching the same memory as this read
3919                      watchpoint.
3920
3921                      If we're watching memory writes as well as reads,
3922                      ignore watchpoint hits when we find that the
3923                      value hasn't changed, as reads don't cause
3924                      changes.  This still gives false positives when
3925                      the program writes the same value to memory as
3926                      what there was already in memory (we will confuse
3927                      it for a read), but it's much better than
3928                      nothing.  */
3929
3930                   int other_write_watchpoint = 0;
3931
3932                   if (bl->watchpoint_type == hw_read)
3933                     {
3934                       struct breakpoint *other_b;
3935
3936                       ALL_BREAKPOINTS (other_b)
3937                         if (other_b->type == bp_hardware_watchpoint
3938                             || other_b->type == bp_access_watchpoint)
3939                           {
3940                             struct watchpoint *other_w =
3941                               (struct watchpoint *) other_b;
3942
3943                             if (other_w->watchpoint_triggered
3944                                 == watch_triggered_yes)
3945                               {
3946                                 other_write_watchpoint = 1;
3947                                 break;
3948                               }
3949                           }
3950                     }
3951
3952                   if (other_write_watchpoint
3953                       || bl->watchpoint_type == hw_access)
3954                     {
3955                       /* We're watching the same memory for writes,
3956                          and the value changed since the last time we
3957                          updated it, so this trap must be for a write.
3958                          Ignore it.  */
3959                       bs->print_it = print_it_noop;
3960                       bs->stop = 0;
3961                     }
3962                 }
3963               break;
3964             case WP_VALUE_NOT_CHANGED:
3965               if (b->base.type == bp_hardware_watchpoint
3966                   || b->base.type == bp_watchpoint)
3967                 {
3968                   /* Don't stop: write watchpoints shouldn't fire if
3969                      the value hasn't changed.  */
3970                   bs->print_it = print_it_noop;
3971                   bs->stop = 0;
3972                 }
3973               /* Stop.  */
3974               break;
3975             default:
3976               /* Can't happen.  */
3977             case 0:
3978               /* Error from catch_errors.  */
3979               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
3980               watchpoint_del_at_next_stop (b);
3981               /* We've already printed what needs to be printed.  */
3982               bs->print_it = print_it_done;
3983               break;
3984             }
3985         }
3986       else      /* must_check_value == 0 */
3987         {
3988           /* This is a case where some watchpoint(s) triggered, but
3989              not at the address of this watchpoint, or else no
3990              watchpoint triggered after all.  So don't print
3991              anything for this watchpoint.  */
3992           bs->print_it = print_it_noop;
3993           bs->stop = 0;
3994         }
3995     }
3996 }
3997
3998
3999 /* Check conditions (condition proper, frame, thread and ignore count)
4000    of breakpoint referred to by BS.  If we should not stop for this
4001    breakpoint, set BS->stop to 0.  */
4002
4003 static void
4004 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4005 {
4006   int thread_id = pid_to_thread_id (ptid);
4007   const struct bp_location *bl;
4008   struct breakpoint *b;
4009
4010   /* BS is built for existing struct breakpoint.  */
4011   bl = bs->bp_location_at;
4012   gdb_assert (bl != NULL);
4013   b = bs->breakpoint_at;
4014   gdb_assert (b != NULL);
4015
4016   if (frame_id_p (b->frame_id)
4017       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4018     bs->stop = 0;
4019   else if (bs->stop)
4020     {
4021       int value_is_zero = 0;
4022       struct expression *cond;
4023
4024       /* Evaluate Python breakpoints that have a "stop"
4025          method implemented.  */
4026       if (b->py_bp_object)
4027         bs->stop = gdbpy_should_stop (b->py_bp_object);
4028
4029       if (is_watchpoint (b))
4030         {
4031           struct watchpoint *w = (struct watchpoint *) b;
4032
4033           cond = w->cond_exp;
4034         }
4035       else
4036         cond = bl->cond;
4037
4038       if (cond && b->disposition != disp_del_at_next_stop)
4039         {
4040           int within_current_scope = 1;
4041           struct watchpoint * w;
4042
4043           /* We use value_mark and value_free_to_mark because it could
4044              be a long time before we return to the command level and
4045              call free_all_values.  We can't call free_all_values
4046              because we might be in the middle of evaluating a
4047              function call.  */
4048           struct value *mark = value_mark ();
4049
4050           if (is_watchpoint (b))
4051             w = (struct watchpoint *) b;
4052           else
4053             w = NULL;
4054
4055           /* Need to select the frame, with all that implies so that
4056              the conditions will have the right context.  Because we
4057              use the frame, we will not see an inlined function's
4058              variables when we arrive at a breakpoint at the start
4059              of the inlined function; the current frame will be the
4060              call site.  */
4061           if (w == NULL || w->cond_exp_valid_block == NULL)
4062             select_frame (get_current_frame ());
4063           else
4064             {
4065               struct frame_info *frame;
4066
4067               /* For local watchpoint expressions, which particular
4068                  instance of a local is being watched matters, so we
4069                  keep track of the frame to evaluate the expression
4070                  in.  To evaluate the condition however, it doesn't
4071                  really matter which instantiation of the function
4072                  where the condition makes sense triggers the
4073                  watchpoint.  This allows an expression like "watch
4074                  global if q > 10" set in `func', catch writes to
4075                  global on all threads that call `func', or catch
4076                  writes on all recursive calls of `func' by a single
4077                  thread.  We simply always evaluate the condition in
4078                  the innermost frame that's executing where it makes
4079                  sense to evaluate the condition.  It seems
4080                  intuitive.  */
4081               frame = block_innermost_frame (w->cond_exp_valid_block);
4082               if (frame != NULL)
4083                 select_frame (frame);
4084               else
4085                 within_current_scope = 0;
4086             }
4087           if (within_current_scope)
4088             value_is_zero
4089               = catch_errors (breakpoint_cond_eval, cond,
4090                               "Error in testing breakpoint condition:\n",
4091                               RETURN_MASK_ALL);
4092           else
4093             {
4094               warning (_("Watchpoint condition cannot be tested "
4095                          "in the current scope"));
4096               /* If we failed to set the right context for this
4097                  watchpoint, unconditionally report it.  */
4098               value_is_zero = 0;
4099             }
4100           /* FIXME-someday, should give breakpoint #.  */
4101           value_free_to_mark (mark);
4102         }
4103
4104       if (cond && value_is_zero)
4105         {
4106           bs->stop = 0;
4107         }
4108       else if (b->thread != -1 && b->thread != thread_id)
4109         {
4110           bs->stop = 0;
4111         }
4112       else if (b->ignore_count > 0)
4113         {
4114           b->ignore_count--;
4115           annotate_ignore_count_change ();
4116           bs->stop = 0;
4117           /* Increase the hit count even though we don't stop.  */
4118           ++(b->hit_count);
4119           observer_notify_breakpoint_modified (b);
4120         }       
4121     }
4122 }
4123
4124
4125 /* Get a bpstat associated with having just stopped at address
4126    BP_ADDR in thread PTID.
4127
4128    Determine whether we stopped at a breakpoint, etc, or whether we
4129    don't understand this stop.  Result is a chain of bpstat's such
4130    that:
4131
4132    if we don't understand the stop, the result is a null pointer.
4133
4134    if we understand why we stopped, the result is not null.
4135
4136    Each element of the chain refers to a particular breakpoint or
4137    watchpoint at which we have stopped.  (We may have stopped for
4138    several reasons concurrently.)
4139
4140    Each element of the chain has valid next, breakpoint_at,
4141    commands, FIXME??? fields.  */
4142
4143 bpstat
4144 bpstat_stop_status (struct address_space *aspace,
4145                     CORE_ADDR bp_addr, ptid_t ptid)
4146 {
4147   struct breakpoint *b = NULL;
4148   struct bp_location *bl;
4149   struct bp_location *loc;
4150   /* First item of allocated bpstat's.  */
4151   bpstat bs_head = NULL, *bs_link = &bs_head;
4152   /* Pointer to the last thing in the chain currently.  */
4153   bpstat bs;
4154   int ix;
4155   int need_remove_insert;
4156   int removed_any;
4157
4158   /* First, build the bpstat chain with locations that explain a
4159      target stop, while being careful to not set the target running,
4160      as that may invalidate locations (in particular watchpoint
4161      locations are recreated).  Resuming will happen here with
4162      breakpoint conditions or watchpoint expressions that include
4163      inferior function calls.  */
4164
4165   ALL_BREAKPOINTS (b)
4166     {
4167       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4168         continue;
4169
4170       for (bl = b->loc; bl != NULL; bl = bl->next)
4171         {
4172           /* For hardware watchpoints, we look only at the first
4173              location.  The watchpoint_check function will work on the
4174              entire expression, not the individual locations.  For
4175              read watchpoints, the watchpoints_triggered function has
4176              checked all locations already.  */
4177           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4178             break;
4179
4180           if (bl->shlib_disabled)
4181             continue;
4182
4183           if (!bpstat_check_location (bl, aspace, bp_addr))
4184             continue;
4185
4186           /* Come here if it's a watchpoint, or if the break address
4187              matches.  */
4188
4189           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4190                                                    explain stop.  */
4191
4192           /* Assume we stop.  Should we find a watchpoint that is not
4193              actually triggered, or if the condition of the breakpoint
4194              evaluates as false, we'll reset 'stop' to 0.  */
4195           bs->stop = 1;
4196           bs->print = 1;
4197
4198           /* If this is a scope breakpoint, mark the associated
4199              watchpoint as triggered so that we will handle the
4200              out-of-scope event.  We'll get to the watchpoint next
4201              iteration.  */
4202           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4203             {
4204               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4205
4206               w->watchpoint_triggered = watch_triggered_yes;
4207             }
4208         }
4209     }
4210
4211   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4212     {
4213       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4214         {
4215           bs = bpstat_alloc (loc, &bs_link);
4216           /* For hits of moribund locations, we should just proceed.  */
4217           bs->stop = 0;
4218           bs->print = 0;
4219           bs->print_it = print_it_noop;
4220         }
4221     }
4222
4223   /* Now go through the locations that caused the target to stop, and
4224      check whether we're interested in reporting this stop to higher
4225      layers, or whether we should resume the target transparently.  */
4226
4227   removed_any = 0;
4228
4229   for (bs = bs_head; bs != NULL; bs = bs->next)
4230     {
4231       if (!bs->stop)
4232         continue;
4233
4234       b = bs->breakpoint_at;
4235       b->ops->check_status (bs);
4236       if (bs->stop)
4237         {
4238           bpstat_check_breakpoint_conditions (bs, ptid);
4239
4240           if (bs->stop)
4241             {
4242               ++(b->hit_count);
4243               observer_notify_breakpoint_modified (b);
4244
4245               /* We will stop here.  */
4246               if (b->disposition == disp_disable)
4247                 {
4248                   if (b->enable_state != bp_permanent)
4249                     b->enable_state = bp_disabled;
4250                   removed_any = 1;
4251                 }
4252               if (b->silent)
4253                 bs->print = 0;
4254               bs->commands = b->commands;
4255               incref_counted_command_line (bs->commands);
4256               if (command_line_is_silent (bs->commands
4257                                           ? bs->commands->commands : NULL))
4258                 bs->print = 0;
4259             }
4260
4261         }
4262
4263       /* Print nothing for this entry if we don't stop or don't
4264          print.  */
4265       if (!bs->stop || !bs->print)
4266         bs->print_it = print_it_noop;
4267     }
4268
4269   /* If we aren't stopping, the value of some hardware watchpoint may
4270      not have changed, but the intermediate memory locations we are
4271      watching may have.  Don't bother if we're stopping; this will get
4272      done later.  */
4273   need_remove_insert = 0;
4274   if (! bpstat_causes_stop (bs_head))
4275     for (bs = bs_head; bs != NULL; bs = bs->next)
4276       if (!bs->stop
4277           && bs->breakpoint_at
4278           && is_hardware_watchpoint (bs->breakpoint_at))
4279         {
4280           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4281
4282           update_watchpoint (w, 0 /* don't reparse.  */);
4283           need_remove_insert = 1;
4284         }
4285
4286   if (need_remove_insert)
4287     update_global_location_list (1);
4288   else if (removed_any)
4289     update_global_location_list (0);
4290
4291   return bs_head;
4292 }
4293
4294 static void
4295 handle_jit_event (void)
4296 {
4297   struct frame_info *frame;
4298   struct gdbarch *gdbarch;
4299
4300   /* Switch terminal for any messages produced by
4301      breakpoint_re_set.  */
4302   target_terminal_ours_for_output ();
4303
4304   frame = get_current_frame ();
4305   gdbarch = get_frame_arch (frame);
4306
4307   jit_event_handler (gdbarch);
4308
4309   target_terminal_inferior ();
4310 }
4311
4312 /* Prepare WHAT final decision for infrun.  */
4313
4314 /* Decide what infrun needs to do with this bpstat.  */
4315
4316 struct bpstat_what
4317 bpstat_what (bpstat bs_head)
4318 {
4319   struct bpstat_what retval;
4320   /* We need to defer calling `solib_add', as adding new symbols
4321      resets breakpoints, which in turn deletes breakpoint locations,
4322      and hence may clear unprocessed entries in the BS chain.  */
4323   int shlib_event = 0;
4324   int jit_event = 0;
4325   bpstat bs;
4326
4327   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
4328   retval.call_dummy = STOP_NONE;
4329   retval.is_longjmp = 0;
4330
4331   for (bs = bs_head; bs != NULL; bs = bs->next)
4332     {
4333       /* Extract this BS's action.  After processing each BS, we check
4334          if its action overrides all we've seem so far.  */
4335       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
4336       enum bptype bptype;
4337
4338       if (bs->breakpoint_at == NULL)
4339         {
4340           /* I suspect this can happen if it was a momentary
4341              breakpoint which has since been deleted.  */
4342           bptype = bp_none;
4343         }
4344       else
4345         bptype = bs->breakpoint_at->type;
4346
4347       if (bptype == bp_shlib_event)
4348         shlib_event = 1;
4349
4350       switch (bptype)
4351         {
4352         case bp_none:
4353           break;
4354         case bp_breakpoint:
4355         case bp_hardware_breakpoint:
4356         case bp_until:
4357         case bp_finish:
4358         case bp_shlib_event:
4359           if (bs->stop)
4360             {
4361               if (bs->print)
4362                 this_action = BPSTAT_WHAT_STOP_NOISY;
4363               else
4364                 this_action = BPSTAT_WHAT_STOP_SILENT;
4365             }
4366           else
4367             this_action = BPSTAT_WHAT_SINGLE;
4368           break;
4369         case bp_watchpoint:
4370         case bp_hardware_watchpoint:
4371         case bp_read_watchpoint:
4372         case bp_access_watchpoint:
4373           if (bs->stop)
4374             {
4375               if (bs->print)
4376                 this_action = BPSTAT_WHAT_STOP_NOISY;
4377               else
4378                 this_action = BPSTAT_WHAT_STOP_SILENT;
4379             }
4380           else
4381             {
4382               /* There was a watchpoint, but we're not stopping.
4383                  This requires no further action.  */
4384             }
4385           break;
4386         case bp_longjmp:
4387         case bp_exception:
4388           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
4389           retval.is_longjmp = bptype == bp_longjmp;
4390           break;
4391         case bp_longjmp_resume:
4392         case bp_exception_resume:
4393           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
4394           retval.is_longjmp = bptype == bp_longjmp_resume;
4395           break;
4396         case bp_step_resume:
4397           if (bs->stop)
4398             this_action = BPSTAT_WHAT_STEP_RESUME;
4399           else
4400             {
4401               /* It is for the wrong frame.  */
4402               this_action = BPSTAT_WHAT_SINGLE;
4403             }
4404           break;
4405         case bp_hp_step_resume:
4406           if (bs->stop)
4407             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
4408           else
4409             {
4410               /* It is for the wrong frame.  */
4411               this_action = BPSTAT_WHAT_SINGLE;
4412             }
4413           break;
4414         case bp_watchpoint_scope:
4415         case bp_thread_event:
4416         case bp_overlay_event:
4417         case bp_longjmp_master:
4418         case bp_std_terminate_master:
4419         case bp_exception_master:
4420           this_action = BPSTAT_WHAT_SINGLE;
4421           break;
4422         case bp_catchpoint:
4423           if (bs->stop)
4424             {
4425               if (bs->print)
4426                 this_action = BPSTAT_WHAT_STOP_NOISY;
4427               else
4428                 this_action = BPSTAT_WHAT_STOP_SILENT;
4429             }
4430           else
4431             {
4432               /* There was a catchpoint, but we're not stopping.
4433                  This requires no further action.  */
4434             }
4435           break;
4436         case bp_jit_event:
4437           jit_event = 1;
4438           this_action = BPSTAT_WHAT_SINGLE;
4439           break;
4440         case bp_call_dummy:
4441           /* Make sure the action is stop (silent or noisy),
4442              so infrun.c pops the dummy frame.  */
4443           retval.call_dummy = STOP_STACK_DUMMY;
4444           this_action = BPSTAT_WHAT_STOP_SILENT;
4445           break;
4446         case bp_std_terminate:
4447           /* Make sure the action is stop (silent or noisy),
4448              so infrun.c pops the dummy frame.  */
4449           retval.call_dummy = STOP_STD_TERMINATE;
4450           this_action = BPSTAT_WHAT_STOP_SILENT;
4451           break;
4452         case bp_tracepoint:
4453         case bp_fast_tracepoint:
4454         case bp_static_tracepoint:
4455           /* Tracepoint hits should not be reported back to GDB, and
4456              if one got through somehow, it should have been filtered
4457              out already.  */
4458           internal_error (__FILE__, __LINE__,
4459                           _("bpstat_what: tracepoint encountered"));
4460           break;
4461         case bp_gnu_ifunc_resolver:
4462           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
4463           this_action = BPSTAT_WHAT_SINGLE;
4464           break;
4465         case bp_gnu_ifunc_resolver_return:
4466           /* The breakpoint will be removed, execution will restart from the
4467              PC of the former breakpoint.  */
4468           this_action = BPSTAT_WHAT_KEEP_CHECKING;
4469           break;
4470         default:
4471           internal_error (__FILE__, __LINE__,
4472                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
4473         }
4474
4475       retval.main_action = max (retval.main_action, this_action);
4476     }
4477
4478   /* These operations may affect the bs->breakpoint_at state so they are
4479      delayed after MAIN_ACTION is decided above.  */
4480
4481   if (shlib_event)
4482     {
4483       if (debug_infrun)
4484         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_shlib_event\n");
4485
4486       /* Check for any newly added shared libraries if we're supposed
4487          to be adding them automatically.  */
4488
4489       /* Switch terminal for any messages produced by
4490          breakpoint_re_set.  */
4491       target_terminal_ours_for_output ();
4492
4493 #ifdef SOLIB_ADD
4494       SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
4495 #else
4496       solib_add (NULL, 0, &current_target, auto_solib_add);
4497 #endif
4498
4499       target_terminal_inferior ();
4500     }
4501
4502   if (jit_event)
4503     {
4504       if (debug_infrun)
4505         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
4506
4507       handle_jit_event ();
4508     }
4509
4510   for (bs = bs_head; bs != NULL; bs = bs->next)
4511     {
4512       struct breakpoint *b = bs->breakpoint_at;
4513
4514       if (b == NULL)
4515         continue;
4516       switch (b->type)
4517         {
4518         case bp_gnu_ifunc_resolver:
4519           gnu_ifunc_resolver_stop (b);
4520           break;
4521         case bp_gnu_ifunc_resolver_return:
4522           gnu_ifunc_resolver_return_stop (b);
4523           break;
4524         }
4525     }
4526
4527   return retval;
4528 }
4529
4530 /* Nonzero if we should step constantly (e.g. watchpoints on machines
4531    without hardware support).  This isn't related to a specific bpstat,
4532    just to things like whether watchpoints are set.  */
4533
4534 int
4535 bpstat_should_step (void)
4536 {
4537   struct breakpoint *b;
4538
4539   ALL_BREAKPOINTS (b)
4540     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
4541       return 1;
4542   return 0;
4543 }
4544
4545 int
4546 bpstat_causes_stop (bpstat bs)
4547 {
4548   for (; bs != NULL; bs = bs->next)
4549     if (bs->stop)
4550       return 1;
4551
4552   return 0;
4553 }
4554
4555 \f
4556
4557 /* Compute a string of spaces suitable to indent the next line
4558    so it starts at the position corresponding to the table column
4559    named COL_NAME in the currently active table of UIOUT.  */
4560
4561 static char *
4562 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
4563 {
4564   static char wrap_indent[80];
4565   int i, total_width, width, align;
4566   char *text;
4567
4568   total_width = 0;
4569   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
4570     {
4571       if (strcmp (text, col_name) == 0)
4572         {
4573           gdb_assert (total_width < sizeof wrap_indent);
4574           memset (wrap_indent, ' ', total_width);
4575           wrap_indent[total_width] = 0;
4576
4577           return wrap_indent;
4578         }
4579
4580       total_width += width + 1;
4581     }
4582
4583   return NULL;
4584 }
4585
4586 /* Print the LOC location out of the list of B->LOC locations.  */
4587
4588 static void
4589 print_breakpoint_location (struct breakpoint *b,
4590                            struct bp_location *loc)
4591 {
4592   struct ui_out *uiout = current_uiout;
4593   struct cleanup *old_chain = save_current_program_space ();
4594
4595   if (loc != NULL && loc->shlib_disabled)
4596     loc = NULL;
4597
4598   if (loc != NULL)
4599     set_current_program_space (loc->pspace);
4600
4601   if (b->display_canonical)
4602     ui_out_field_string (uiout, "what", b->addr_string);
4603   else if (loc && loc->source_file)
4604     {
4605       struct symbol *sym 
4606         = find_pc_sect_function (loc->address, loc->section);
4607       if (sym)
4608         {
4609           ui_out_text (uiout, "in ");
4610           ui_out_field_string (uiout, "func",
4611                                SYMBOL_PRINT_NAME (sym));
4612           ui_out_text (uiout, " ");
4613           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
4614           ui_out_text (uiout, "at ");
4615         }
4616       ui_out_field_string (uiout, "file", loc->source_file);
4617       ui_out_text (uiout, ":");
4618       
4619       if (ui_out_is_mi_like_p (uiout))
4620         {
4621           struct symtab_and_line sal = find_pc_line (loc->address, 0);
4622           char *fullname = symtab_to_fullname (sal.symtab);
4623           
4624           if (fullname)
4625             ui_out_field_string (uiout, "fullname", fullname);
4626         }
4627       
4628       ui_out_field_int (uiout, "line", loc->line_number);
4629     }
4630   else if (loc)
4631     {
4632       struct ui_stream *stb = ui_out_stream_new (uiout);
4633       struct cleanup *stb_chain = make_cleanup_ui_out_stream_delete (stb);
4634
4635       print_address_symbolic (loc->gdbarch, loc->address, stb->stream,
4636                               demangle, "");
4637       ui_out_field_stream (uiout, "at", stb);
4638
4639       do_cleanups (stb_chain);
4640     }
4641   else
4642     ui_out_field_string (uiout, "pending", b->addr_string);
4643
4644   do_cleanups (old_chain);
4645 }
4646
4647 static const char *
4648 bptype_string (enum bptype type)
4649 {
4650   struct ep_type_description
4651     {
4652       enum bptype type;
4653       char *description;
4654     };
4655   static struct ep_type_description bptypes[] =
4656   {
4657     {bp_none, "?deleted?"},
4658     {bp_breakpoint, "breakpoint"},
4659     {bp_hardware_breakpoint, "hw breakpoint"},
4660     {bp_until, "until"},
4661     {bp_finish, "finish"},
4662     {bp_watchpoint, "watchpoint"},
4663     {bp_hardware_watchpoint, "hw watchpoint"},
4664     {bp_read_watchpoint, "read watchpoint"},
4665     {bp_access_watchpoint, "acc watchpoint"},
4666     {bp_longjmp, "longjmp"},
4667     {bp_longjmp_resume, "longjmp resume"},
4668     {bp_exception, "exception"},
4669     {bp_exception_resume, "exception resume"},
4670     {bp_step_resume, "step resume"},
4671     {bp_hp_step_resume, "high-priority step resume"},
4672     {bp_watchpoint_scope, "watchpoint scope"},
4673     {bp_call_dummy, "call dummy"},
4674     {bp_std_terminate, "std::terminate"},
4675     {bp_shlib_event, "shlib events"},
4676     {bp_thread_event, "thread events"},
4677     {bp_overlay_event, "overlay events"},
4678     {bp_longjmp_master, "longjmp master"},
4679     {bp_std_terminate_master, "std::terminate master"},
4680     {bp_exception_master, "exception master"},
4681     {bp_catchpoint, "catchpoint"},
4682     {bp_tracepoint, "tracepoint"},
4683     {bp_fast_tracepoint, "fast tracepoint"},
4684     {bp_static_tracepoint, "static tracepoint"},
4685     {bp_jit_event, "jit events"},
4686     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
4687     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
4688   };
4689
4690   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
4691       || ((int) type != bptypes[(int) type].type))
4692     internal_error (__FILE__, __LINE__,
4693                     _("bptypes table does not describe type #%d."),
4694                     (int) type);
4695
4696   return bptypes[(int) type].description;
4697 }
4698
4699 /* Print B to gdb_stdout.  */
4700
4701 static void
4702 print_one_breakpoint_location (struct breakpoint *b,
4703                                struct bp_location *loc,
4704                                int loc_number,
4705                                struct bp_location **last_loc,
4706                                int allflag)
4707 {
4708   struct command_line *l;
4709   static char bpenables[] = "nynny";
4710
4711   struct ui_out *uiout = current_uiout;
4712   int header_of_multiple = 0;
4713   int part_of_multiple = (loc != NULL);
4714   struct value_print_options opts;
4715
4716   get_user_print_options (&opts);
4717
4718   gdb_assert (!loc || loc_number != 0);
4719   /* See comment in print_one_breakpoint concerning treatment of
4720      breakpoints with single disabled location.  */
4721   if (loc == NULL 
4722       && (b->loc != NULL 
4723           && (b->loc->next != NULL || !b->loc->enabled)))
4724     header_of_multiple = 1;
4725   if (loc == NULL)
4726     loc = b->loc;
4727
4728   annotate_record ();
4729
4730   /* 1 */
4731   annotate_field (0);
4732   if (part_of_multiple)
4733     {
4734       char *formatted;
4735       formatted = xstrprintf ("%d.%d", b->number, loc_number);
4736       ui_out_field_string (uiout, "number", formatted);
4737       xfree (formatted);
4738     }
4739   else
4740     {
4741       ui_out_field_int (uiout, "number", b->number);
4742     }
4743
4744   /* 2 */
4745   annotate_field (1);
4746   if (part_of_multiple)
4747     ui_out_field_skip (uiout, "type");
4748   else
4749     ui_out_field_string (uiout, "type", bptype_string (b->type));
4750
4751   /* 3 */
4752   annotate_field (2);
4753   if (part_of_multiple)
4754     ui_out_field_skip (uiout, "disp");
4755   else
4756     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
4757
4758
4759   /* 4 */
4760   annotate_field (3);
4761   if (part_of_multiple)
4762     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
4763   else
4764     ui_out_field_fmt (uiout, "enabled", "%c", 
4765                       bpenables[(int) b->enable_state]);
4766   ui_out_spaces (uiout, 2);
4767
4768   
4769   /* 5 and 6 */
4770   if (b->ops != NULL && b->ops->print_one != NULL)
4771     {
4772       /* Although the print_one can possibly print all locations,
4773          calling it here is not likely to get any nice result.  So,
4774          make sure there's just one location.  */
4775       gdb_assert (b->loc == NULL || b->loc->next == NULL);
4776       b->ops->print_one (b, last_loc);
4777     }
4778   else
4779     switch (b->type)
4780       {
4781       case bp_none:
4782         internal_error (__FILE__, __LINE__,
4783                         _("print_one_breakpoint: bp_none encountered\n"));
4784         break;
4785
4786       case bp_watchpoint:
4787       case bp_hardware_watchpoint:
4788       case bp_read_watchpoint:
4789       case bp_access_watchpoint:
4790         {
4791           struct watchpoint *w = (struct watchpoint *) b;
4792
4793           /* Field 4, the address, is omitted (which makes the columns
4794              not line up too nicely with the headers, but the effect
4795              is relatively readable).  */
4796           if (opts.addressprint)
4797             ui_out_field_skip (uiout, "addr");
4798           annotate_field (5);
4799           ui_out_field_string (uiout, "what", w->exp_string);
4800         }
4801         break;
4802
4803       case bp_breakpoint:
4804       case bp_hardware_breakpoint:
4805       case bp_until:
4806       case bp_finish:
4807       case bp_longjmp:
4808       case bp_longjmp_resume:
4809       case bp_exception:
4810       case bp_exception_resume:
4811       case bp_step_resume:
4812       case bp_hp_step_resume:
4813       case bp_watchpoint_scope:
4814       case bp_call_dummy:
4815       case bp_std_terminate:
4816       case bp_shlib_event:
4817       case bp_thread_event:
4818       case bp_overlay_event:
4819       case bp_longjmp_master:
4820       case bp_std_terminate_master:
4821       case bp_exception_master:
4822       case bp_tracepoint:
4823       case bp_fast_tracepoint:
4824       case bp_static_tracepoint:
4825       case bp_jit_event:
4826       case bp_gnu_ifunc_resolver:
4827       case bp_gnu_ifunc_resolver_return:
4828         if (opts.addressprint)
4829           {
4830             annotate_field (4);
4831             if (header_of_multiple)
4832               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
4833             else if (b->loc == NULL || loc->shlib_disabled)
4834               ui_out_field_string (uiout, "addr", "<PENDING>");
4835             else
4836               ui_out_field_core_addr (uiout, "addr",
4837                                       loc->gdbarch, loc->address);
4838           }
4839         annotate_field (5);
4840         if (!header_of_multiple)
4841           print_breakpoint_location (b, loc);
4842         if (b->loc)
4843           *last_loc = b->loc;
4844         break;
4845       }
4846
4847
4848   /* For backward compatibility, don't display inferiors unless there
4849      are several.  */
4850   if (loc != NULL
4851       && !header_of_multiple
4852       && (allflag
4853           || (!gdbarch_has_global_breakpoints (target_gdbarch)
4854               && (number_of_program_spaces () > 1
4855                   || number_of_inferiors () > 1)
4856               /* LOC is for existing B, it cannot be in
4857                  moribund_locations and thus having NULL OWNER.  */
4858               && loc->owner->type != bp_catchpoint)))
4859     {
4860       struct inferior *inf;
4861       int first = 1;
4862
4863       for (inf = inferior_list; inf != NULL; inf = inf->next)
4864         {
4865           if (inf->pspace == loc->pspace)
4866             {
4867               if (first)
4868                 {
4869                   first = 0;
4870                   ui_out_text (uiout, " inf ");
4871                 }
4872               else
4873                 ui_out_text (uiout, ", ");
4874               ui_out_text (uiout, plongest (inf->num));
4875             }
4876         }
4877     }
4878
4879   if (!part_of_multiple)
4880     {
4881       if (b->thread != -1)
4882         {
4883           /* FIXME: This seems to be redundant and lost here; see the
4884              "stop only in" line a little further down.  */
4885           ui_out_text (uiout, " thread ");
4886           ui_out_field_int (uiout, "thread", b->thread);
4887         }
4888       else if (b->task != 0)
4889         {
4890           ui_out_text (uiout, " task ");
4891           ui_out_field_int (uiout, "task", b->task);
4892         }
4893     }
4894
4895   ui_out_text (uiout, "\n");
4896
4897   if (!part_of_multiple)
4898     b->ops->print_one_detail (b, uiout);
4899
4900   if (part_of_multiple && frame_id_p (b->frame_id))
4901     {
4902       annotate_field (6);
4903       ui_out_text (uiout, "\tstop only in stack frame at ");
4904       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
4905          the frame ID.  */
4906       ui_out_field_core_addr (uiout, "frame",
4907                               b->gdbarch, b->frame_id.stack_addr);
4908       ui_out_text (uiout, "\n");
4909     }
4910   
4911   if (!part_of_multiple && b->cond_string)
4912     {
4913       annotate_field (7);
4914       if (is_tracepoint (b))
4915         ui_out_text (uiout, "\ttrace only if ");
4916       else
4917         ui_out_text (uiout, "\tstop only if ");
4918       ui_out_field_string (uiout, "cond", b->cond_string);
4919       ui_out_text (uiout, "\n");
4920     }
4921
4922   if (!part_of_multiple && b->thread != -1)
4923     {
4924       /* FIXME should make an annotation for this.  */
4925       ui_out_text (uiout, "\tstop only in thread ");
4926       ui_out_field_int (uiout, "thread", b->thread);
4927       ui_out_text (uiout, "\n");
4928     }
4929   
4930   if (!part_of_multiple && b->hit_count)
4931     {
4932       /* FIXME should make an annotation for this.  */
4933       if (ep_is_catchpoint (b))
4934         ui_out_text (uiout, "\tcatchpoint");
4935       else if (is_tracepoint (b))
4936         ui_out_text (uiout, "\ttracepoint");
4937       else
4938         ui_out_text (uiout, "\tbreakpoint");
4939       ui_out_text (uiout, " already hit ");
4940       ui_out_field_int (uiout, "times", b->hit_count);
4941       if (b->hit_count == 1)
4942         ui_out_text (uiout, " time\n");
4943       else
4944         ui_out_text (uiout, " times\n");
4945     }
4946   
4947   /* Output the count also if it is zero, but only if this is mi.
4948      FIXME: Should have a better test for this.  */
4949   if (ui_out_is_mi_like_p (uiout))
4950     if (!part_of_multiple && b->hit_count == 0)
4951       ui_out_field_int (uiout, "times", b->hit_count);
4952
4953   if (!part_of_multiple && b->ignore_count)
4954     {
4955       annotate_field (8);
4956       ui_out_text (uiout, "\tignore next ");
4957       ui_out_field_int (uiout, "ignore", b->ignore_count);
4958       ui_out_text (uiout, " hits\n");
4959     }
4960
4961   if (!part_of_multiple && is_tracepoint (b))
4962     {
4963       struct tracepoint *tp = (struct tracepoint *) b;
4964
4965       if (tp->traceframe_usage)
4966         {
4967           ui_out_text (uiout, "\ttrace buffer usage ");
4968           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
4969           ui_out_text (uiout, " bytes\n");
4970         }
4971     }
4972   
4973   l = b->commands ? b->commands->commands : NULL;
4974   if (!part_of_multiple && l)
4975     {
4976       struct cleanup *script_chain;
4977
4978       annotate_field (9);
4979       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
4980       print_command_lines (uiout, l, 4);
4981       do_cleanups (script_chain);
4982     }
4983
4984   if (is_tracepoint (b))
4985     {
4986       struct tracepoint *t = (struct tracepoint *) b;
4987
4988       if (!part_of_multiple && t->pass_count)
4989         {
4990           annotate_field (10);
4991           ui_out_text (uiout, "\tpass count ");
4992           ui_out_field_int (uiout, "pass", t->pass_count);
4993           ui_out_text (uiout, " \n");
4994         }
4995     }
4996
4997   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
4998     {
4999       if (is_watchpoint (b))
5000         {
5001           struct watchpoint *w = (struct watchpoint *) b;
5002
5003           ui_out_field_string (uiout, "original-location", w->exp_string);
5004         }
5005       else if (b->addr_string)
5006         ui_out_field_string (uiout, "original-location", b->addr_string);
5007     }
5008 }
5009
5010 static void
5011 print_one_breakpoint (struct breakpoint *b,
5012                       struct bp_location **last_loc, 
5013                       int allflag)
5014 {
5015   struct cleanup *bkpt_chain;
5016   struct ui_out *uiout = current_uiout;
5017
5018   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5019
5020   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5021   do_cleanups (bkpt_chain);
5022
5023   /* If this breakpoint has custom print function,
5024      it's already printed.  Otherwise, print individual
5025      locations, if any.  */
5026   if (b->ops == NULL || b->ops->print_one == NULL)
5027     {
5028       /* If breakpoint has a single location that is disabled, we
5029          print it as if it had several locations, since otherwise it's
5030          hard to represent "breakpoint enabled, location disabled"
5031          situation.
5032
5033          Note that while hardware watchpoints have several locations
5034          internally, that's not a property exposed to user.  */
5035       if (b->loc 
5036           && !is_hardware_watchpoint (b)
5037           && (b->loc->next || !b->loc->enabled))
5038         {
5039           struct bp_location *loc;
5040           int n = 1;
5041
5042           for (loc = b->loc; loc; loc = loc->next, ++n)
5043             {
5044               struct cleanup *inner2 =
5045                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5046               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5047               do_cleanups (inner2);
5048             }
5049         }
5050     }
5051 }
5052
5053 static int
5054 breakpoint_address_bits (struct breakpoint *b)
5055 {
5056   int print_address_bits = 0;
5057   struct bp_location *loc;
5058
5059   for (loc = b->loc; loc; loc = loc->next)
5060     {
5061       int addr_bit;
5062
5063       /* Software watchpoints that aren't watching memory don't have
5064          an address to print.  */
5065       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5066         continue;
5067
5068       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5069       if (addr_bit > print_address_bits)
5070         print_address_bits = addr_bit;
5071     }
5072
5073   return print_address_bits;
5074 }
5075
5076 struct captured_breakpoint_query_args
5077   {
5078     int bnum;
5079   };
5080
5081 static int
5082 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5083 {
5084   struct captured_breakpoint_query_args *args = data;
5085   struct breakpoint *b;
5086   struct bp_location *dummy_loc = NULL;
5087
5088   ALL_BREAKPOINTS (b)
5089     {
5090       if (args->bnum == b->number)
5091         {
5092           print_one_breakpoint (b, &dummy_loc, 0);
5093           return GDB_RC_OK;
5094         }
5095     }
5096   return GDB_RC_NONE;
5097 }
5098
5099 enum gdb_rc
5100 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5101                       char **error_message)
5102 {
5103   struct captured_breakpoint_query_args args;
5104
5105   args.bnum = bnum;
5106   /* For the moment we don't trust print_one_breakpoint() to not throw
5107      an error.  */
5108   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5109                                  error_message, RETURN_MASK_ALL) < 0)
5110     return GDB_RC_FAIL;
5111   else
5112     return GDB_RC_OK;
5113 }
5114
5115 /* Return true if this breakpoint was set by the user, false if it is
5116    internal or momentary.  */
5117
5118 int
5119 user_breakpoint_p (struct breakpoint *b)
5120 {
5121   return b->number > 0;
5122 }
5123
5124 /* Print information on user settable breakpoint (watchpoint, etc)
5125    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5126    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5127    FILTER is non-NULL, call it on each breakpoint and only include the
5128    ones for which it returns non-zero.  Return the total number of
5129    breakpoints listed.  */
5130
5131 static int
5132 breakpoint_1 (char *args, int allflag, 
5133               int (*filter) (const struct breakpoint *))
5134 {
5135   struct breakpoint *b;
5136   struct bp_location *last_loc = NULL;
5137   int nr_printable_breakpoints;
5138   struct cleanup *bkpttbl_chain;
5139   struct value_print_options opts;
5140   int print_address_bits = 0;
5141   int print_type_col_width = 14;
5142   struct ui_out *uiout = current_uiout;
5143
5144   get_user_print_options (&opts);
5145
5146   /* Compute the number of rows in the table, as well as the size
5147      required for address fields.  */
5148   nr_printable_breakpoints = 0;
5149   ALL_BREAKPOINTS (b)
5150     {
5151       /* If we have a filter, only list the breakpoints it accepts.  */
5152       if (filter && !filter (b))
5153         continue;
5154
5155       /* If we have an "args" string, it is a list of breakpoints to 
5156          accept.  Skip the others.  */
5157       if (args != NULL && *args != '\0')
5158         {
5159           if (allflag && parse_and_eval_long (args) != b->number)
5160             continue;
5161           if (!allflag && !number_is_in_list (args, b->number))
5162             continue;
5163         }
5164
5165       if (allflag || user_breakpoint_p (b))
5166         {
5167           int addr_bit, type_len;
5168
5169           addr_bit = breakpoint_address_bits (b);
5170           if (addr_bit > print_address_bits)
5171             print_address_bits = addr_bit;
5172
5173           type_len = strlen (bptype_string (b->type));
5174           if (type_len > print_type_col_width)
5175             print_type_col_width = type_len;
5176
5177           nr_printable_breakpoints++;
5178         }
5179     }
5180
5181   if (opts.addressprint)
5182     bkpttbl_chain 
5183       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5184                                              nr_printable_breakpoints,
5185                                              "BreakpointTable");
5186   else
5187     bkpttbl_chain 
5188       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5189                                              nr_printable_breakpoints,
5190                                              "BreakpointTable");
5191
5192   if (nr_printable_breakpoints > 0)
5193     annotate_breakpoints_headers ();
5194   if (nr_printable_breakpoints > 0)
5195     annotate_field (0);
5196   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5197   if (nr_printable_breakpoints > 0)
5198     annotate_field (1);
5199   ui_out_table_header (uiout, print_type_col_width, ui_left,
5200                        "type", "Type");                         /* 2 */
5201   if (nr_printable_breakpoints > 0)
5202     annotate_field (2);
5203   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
5204   if (nr_printable_breakpoints > 0)
5205     annotate_field (3);
5206   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
5207   if (opts.addressprint)
5208     {
5209       if (nr_printable_breakpoints > 0)
5210         annotate_field (4);
5211       if (print_address_bits <= 32)
5212         ui_out_table_header (uiout, 10, ui_left, 
5213                              "addr", "Address");                /* 5 */
5214       else
5215         ui_out_table_header (uiout, 18, ui_left, 
5216                              "addr", "Address");                /* 5 */
5217     }
5218   if (nr_printable_breakpoints > 0)
5219     annotate_field (5);
5220   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
5221   ui_out_table_body (uiout);
5222   if (nr_printable_breakpoints > 0)
5223     annotate_breakpoints_table ();
5224
5225   ALL_BREAKPOINTS (b)
5226     {
5227       QUIT;
5228       /* If we have a filter, only list the breakpoints it accepts.  */
5229       if (filter && !filter (b))
5230         continue;
5231
5232       /* If we have an "args" string, it is a list of breakpoints to 
5233          accept.  Skip the others.  */
5234
5235       if (args != NULL && *args != '\0')
5236         {
5237           if (allflag)  /* maintenance info breakpoint */
5238             {
5239               if (parse_and_eval_long (args) != b->number)
5240                 continue;
5241             }
5242           else          /* all others */
5243             {
5244               if (!number_is_in_list (args, b->number))
5245                 continue;
5246             }
5247         }
5248       /* We only print out user settable breakpoints unless the
5249          allflag is set.  */
5250       if (allflag || user_breakpoint_p (b))
5251         print_one_breakpoint (b, &last_loc, allflag);
5252     }
5253
5254   do_cleanups (bkpttbl_chain);
5255
5256   if (nr_printable_breakpoints == 0)
5257     {
5258       /* If there's a filter, let the caller decide how to report
5259          empty list.  */
5260       if (!filter)
5261         {
5262           if (args == NULL || *args == '\0')
5263             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
5264           else
5265             ui_out_message (uiout, 0, 
5266                             "No breakpoint or watchpoint matching '%s'.\n",
5267                             args);
5268         }
5269     }
5270   else
5271     {
5272       if (last_loc && !server_command)
5273         set_next_address (last_loc->gdbarch, last_loc->address);
5274     }
5275
5276   /* FIXME?  Should this be moved up so that it is only called when
5277      there have been breakpoints? */
5278   annotate_breakpoints_table_end ();
5279
5280   return nr_printable_breakpoints;
5281 }
5282
5283 /* Display the value of default-collect in a way that is generally
5284    compatible with the breakpoint list.  */
5285
5286 static void
5287 default_collect_info (void)
5288 {
5289   struct ui_out *uiout = current_uiout;
5290
5291   /* If it has no value (which is frequently the case), say nothing; a
5292      message like "No default-collect." gets in user's face when it's
5293      not wanted.  */
5294   if (!*default_collect)
5295     return;
5296
5297   /* The following phrase lines up nicely with per-tracepoint collect
5298      actions.  */
5299   ui_out_text (uiout, "default collect ");
5300   ui_out_field_string (uiout, "default-collect", default_collect);
5301   ui_out_text (uiout, " \n");
5302 }
5303   
5304 static void
5305 breakpoints_info (char *args, int from_tty)
5306 {
5307   breakpoint_1 (args, 0, NULL);
5308
5309   default_collect_info ();
5310 }
5311
5312 static void
5313 watchpoints_info (char *args, int from_tty)
5314 {
5315   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
5316   struct ui_out *uiout = current_uiout;
5317
5318   if (num_printed == 0)
5319     {
5320       if (args == NULL || *args == '\0')
5321         ui_out_message (uiout, 0, "No watchpoints.\n");
5322       else
5323         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
5324     }
5325 }
5326
5327 static void
5328 maintenance_info_breakpoints (char *args, int from_tty)
5329 {
5330   breakpoint_1 (args, 1, NULL);
5331
5332   default_collect_info ();
5333 }
5334
5335 static int
5336 breakpoint_has_pc (struct breakpoint *b,
5337                    struct program_space *pspace,
5338                    CORE_ADDR pc, struct obj_section *section)
5339 {
5340   struct bp_location *bl = b->loc;
5341
5342   for (; bl; bl = bl->next)
5343     {
5344       if (bl->pspace == pspace
5345           && bl->address == pc
5346           && (!overlay_debugging || bl->section == section))
5347         return 1;         
5348     }
5349   return 0;
5350 }
5351
5352 /* Print a message describing any user-breakpoints set at PC.  This
5353    concerns with logical breakpoints, so we match program spaces, not
5354    address spaces.  */
5355
5356 static void
5357 describe_other_breakpoints (struct gdbarch *gdbarch,
5358                             struct program_space *pspace, CORE_ADDR pc,
5359                             struct obj_section *section, int thread)
5360 {
5361   int others = 0;
5362   struct breakpoint *b;
5363
5364   ALL_BREAKPOINTS (b)
5365     others += (user_breakpoint_p (b)
5366                && breakpoint_has_pc (b, pspace, pc, section));
5367   if (others > 0)
5368     {
5369       if (others == 1)
5370         printf_filtered (_("Note: breakpoint "));
5371       else /* if (others == ???) */
5372         printf_filtered (_("Note: breakpoints "));
5373       ALL_BREAKPOINTS (b)
5374         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
5375           {
5376             others--;
5377             printf_filtered ("%d", b->number);
5378             if (b->thread == -1 && thread != -1)
5379               printf_filtered (" (all threads)");
5380             else if (b->thread != -1)
5381               printf_filtered (" (thread %d)", b->thread);
5382             printf_filtered ("%s%s ",
5383                              ((b->enable_state == bp_disabled
5384                                || b->enable_state == bp_call_disabled)
5385                               ? " (disabled)"
5386                               : b->enable_state == bp_permanent 
5387                               ? " (permanent)"
5388                               : ""),
5389                              (others > 1) ? "," 
5390                              : ((others == 1) ? " and" : ""));
5391           }
5392       printf_filtered (_("also set at pc "));
5393       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
5394       printf_filtered (".\n");
5395     }
5396 }
5397 \f
5398
5399 /* Return true iff it is meaningful to use the address member of
5400    BPT.  For some breakpoint types, the address member is irrelevant
5401    and it makes no sense to attempt to compare it to other addresses
5402    (or use it for any other purpose either).
5403
5404    More specifically, each of the following breakpoint types will
5405    always have a zero valued address and we don't want to mark
5406    breakpoints of any of these types to be a duplicate of an actual
5407    breakpoint at address zero:
5408
5409       bp_watchpoint
5410       bp_catchpoint
5411
5412 */
5413
5414 static int
5415 breakpoint_address_is_meaningful (struct breakpoint *bpt)
5416 {
5417   enum bptype type = bpt->type;
5418
5419   return (type != bp_watchpoint && type != bp_catchpoint);
5420 }
5421
5422 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
5423    true if LOC1 and LOC2 represent the same watchpoint location.  */
5424
5425 static int
5426 watchpoint_locations_match (struct bp_location *loc1, 
5427                             struct bp_location *loc2)
5428 {
5429   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
5430   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
5431
5432   /* Both of them must exist.  */
5433   gdb_assert (w1 != NULL);
5434   gdb_assert (w2 != NULL);
5435
5436   /* If the target can evaluate the condition expression in hardware,
5437      then we we need to insert both watchpoints even if they are at
5438      the same place.  Otherwise the watchpoint will only trigger when
5439      the condition of whichever watchpoint was inserted evaluates to
5440      true, not giving a chance for GDB to check the condition of the
5441      other watchpoint.  */
5442   if ((w1->cond_exp
5443        && target_can_accel_watchpoint_condition (loc1->address, 
5444                                                  loc1->length,
5445                                                  loc1->watchpoint_type,
5446                                                  w1->cond_exp))
5447       || (w2->cond_exp
5448           && target_can_accel_watchpoint_condition (loc2->address, 
5449                                                     loc2->length,
5450                                                     loc2->watchpoint_type,
5451                                                     w2->cond_exp)))
5452     return 0;
5453
5454   /* Note that this checks the owner's type, not the location's.  In
5455      case the target does not support read watchpoints, but does
5456      support access watchpoints, we'll have bp_read_watchpoint
5457      watchpoints with hw_access locations.  Those should be considered
5458      duplicates of hw_read locations.  The hw_read locations will
5459      become hw_access locations later.  */
5460   return (loc1->owner->type == loc2->owner->type
5461           && loc1->pspace->aspace == loc2->pspace->aspace
5462           && loc1->address == loc2->address
5463           && loc1->length == loc2->length);
5464 }
5465
5466 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
5467    same breakpoint location.  In most targets, this can only be true
5468    if ASPACE1 matches ASPACE2.  On targets that have global
5469    breakpoints, the address space doesn't really matter.  */
5470
5471 static int
5472 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
5473                           struct address_space *aspace2, CORE_ADDR addr2)
5474 {
5475   return ((gdbarch_has_global_breakpoints (target_gdbarch)
5476            || aspace1 == aspace2)
5477           && addr1 == addr2);
5478 }
5479
5480 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
5481    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
5482    matches ASPACE2.  On targets that have global breakpoints, the address
5483    space doesn't really matter.  */
5484
5485 static int
5486 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
5487                                 int len1, struct address_space *aspace2,
5488                                 CORE_ADDR addr2)
5489 {
5490   return ((gdbarch_has_global_breakpoints (target_gdbarch)
5491            || aspace1 == aspace2)
5492           && addr2 >= addr1 && addr2 < addr1 + len1);
5493 }
5494
5495 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
5496    a ranged breakpoint.  In most targets, a match happens only if ASPACE
5497    matches the breakpoint's address space.  On targets that have global
5498    breakpoints, the address space doesn't really matter.  */
5499
5500 static int
5501 breakpoint_location_address_match (struct bp_location *bl,
5502                                    struct address_space *aspace,
5503                                    CORE_ADDR addr)
5504 {
5505   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
5506                                     aspace, addr)
5507           || (bl->length
5508               && breakpoint_address_match_range (bl->pspace->aspace,
5509                                                  bl->address, bl->length,
5510                                                  aspace, addr)));
5511 }
5512
5513 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
5514    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
5515    true, otherwise returns false.  */
5516
5517 static int
5518 tracepoint_locations_match (struct bp_location *loc1,
5519                             struct bp_location *loc2)
5520 {
5521   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
5522     /* Since tracepoint locations are never duplicated with others', tracepoint
5523        locations at the same address of different tracepoints are regarded as
5524        different locations.  */
5525     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
5526   else
5527     return 0;
5528 }
5529
5530 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
5531    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
5532    represent the same location.  */
5533
5534 static int
5535 breakpoint_locations_match (struct bp_location *loc1, 
5536                             struct bp_location *loc2)
5537 {
5538   int hw_point1, hw_point2;
5539
5540   /* Both of them must not be in moribund_locations.  */
5541   gdb_assert (loc1->owner != NULL);
5542   gdb_assert (loc2->owner != NULL);
5543
5544   hw_point1 = is_hardware_watchpoint (loc1->owner);
5545   hw_point2 = is_hardware_watchpoint (loc2->owner);
5546
5547   if (hw_point1 != hw_point2)
5548     return 0;
5549   else if (hw_point1)
5550     return watchpoint_locations_match (loc1, loc2);
5551   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
5552     return tracepoint_locations_match (loc1, loc2);
5553   else
5554     /* We compare bp_location.length in order to cover ranged breakpoints.  */
5555     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
5556                                      loc2->pspace->aspace, loc2->address)
5557             && loc1->length == loc2->length);
5558 }
5559
5560 static void
5561 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
5562                                int bnum, int have_bnum)
5563 {
5564   /* The longest string possibly returned by hex_string_custom
5565      is 50 chars.  These must be at least that big for safety.  */
5566   char astr1[64];
5567   char astr2[64];
5568
5569   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
5570   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
5571   if (have_bnum)
5572     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
5573              bnum, astr1, astr2);
5574   else
5575     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
5576 }
5577
5578 /* Adjust a breakpoint's address to account for architectural
5579    constraints on breakpoint placement.  Return the adjusted address.
5580    Note: Very few targets require this kind of adjustment.  For most
5581    targets, this function is simply the identity function.  */
5582
5583 static CORE_ADDR
5584 adjust_breakpoint_address (struct gdbarch *gdbarch,
5585                            CORE_ADDR bpaddr, enum bptype bptype)
5586 {
5587   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
5588     {
5589       /* Very few targets need any kind of breakpoint adjustment.  */
5590       return bpaddr;
5591     }
5592   else if (bptype == bp_watchpoint
5593            || bptype == bp_hardware_watchpoint
5594            || bptype == bp_read_watchpoint
5595            || bptype == bp_access_watchpoint
5596            || bptype == bp_catchpoint)
5597     {
5598       /* Watchpoints and the various bp_catch_* eventpoints should not
5599          have their addresses modified.  */
5600       return bpaddr;
5601     }
5602   else
5603     {
5604       CORE_ADDR adjusted_bpaddr;
5605
5606       /* Some targets have architectural constraints on the placement
5607          of breakpoint instructions.  Obtain the adjusted address.  */
5608       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
5609
5610       /* An adjusted breakpoint address can significantly alter
5611          a user's expectations.  Print a warning if an adjustment
5612          is required.  */
5613       if (adjusted_bpaddr != bpaddr)
5614         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
5615
5616       return adjusted_bpaddr;
5617     }
5618 }
5619
5620 void
5621 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
5622                   struct breakpoint *owner)
5623 {
5624   memset (loc, 0, sizeof (*loc));
5625
5626   gdb_assert (ops != NULL);
5627
5628   loc->ops = ops;
5629   loc->owner = owner;
5630   loc->cond = NULL;
5631   loc->shlib_disabled = 0;
5632   loc->enabled = 1;
5633
5634   switch (owner->type)
5635     {
5636     case bp_breakpoint:
5637     case bp_until:
5638     case bp_finish:
5639     case bp_longjmp:
5640     case bp_longjmp_resume:
5641     case bp_exception:
5642     case bp_exception_resume:
5643     case bp_step_resume:
5644     case bp_hp_step_resume:
5645     case bp_watchpoint_scope:
5646     case bp_call_dummy:
5647     case bp_std_terminate:
5648     case bp_shlib_event:
5649     case bp_thread_event:
5650     case bp_overlay_event:
5651     case bp_jit_event:
5652     case bp_longjmp_master:
5653     case bp_std_terminate_master:
5654     case bp_exception_master:
5655     case bp_gnu_ifunc_resolver:
5656     case bp_gnu_ifunc_resolver_return:
5657       loc->loc_type = bp_loc_software_breakpoint;
5658       break;
5659     case bp_hardware_breakpoint:
5660       loc->loc_type = bp_loc_hardware_breakpoint;
5661       break;
5662     case bp_hardware_watchpoint:
5663     case bp_read_watchpoint:
5664     case bp_access_watchpoint:
5665       loc->loc_type = bp_loc_hardware_watchpoint;
5666       break;
5667     case bp_watchpoint:
5668     case bp_catchpoint:
5669     case bp_tracepoint:
5670     case bp_fast_tracepoint:
5671     case bp_static_tracepoint:
5672       loc->loc_type = bp_loc_other;
5673       break;
5674     default:
5675       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
5676     }
5677
5678   loc->refc = 1;
5679 }
5680
5681 /* Allocate a struct bp_location.  */
5682
5683 static struct bp_location *
5684 allocate_bp_location (struct breakpoint *bpt)
5685 {
5686   return bpt->ops->allocate_location (bpt);
5687 }
5688
5689 static void
5690 free_bp_location (struct bp_location *loc)
5691 {
5692   loc->ops->dtor (loc);
5693   xfree (loc);
5694 }
5695
5696 /* Increment reference count.  */
5697
5698 static void
5699 incref_bp_location (struct bp_location *bl)
5700 {
5701   ++bl->refc;
5702 }
5703
5704 /* Decrement reference count.  If the reference count reaches 0,
5705    destroy the bp_location.  Sets *BLP to NULL.  */
5706
5707 static void
5708 decref_bp_location (struct bp_location **blp)
5709 {
5710   gdb_assert ((*blp)->refc > 0);
5711
5712   if (--(*blp)->refc == 0)
5713     free_bp_location (*blp);
5714   *blp = NULL;
5715 }
5716
5717 /* Add breakpoint B at the end of the global breakpoint chain.  */
5718
5719 static void
5720 add_to_breakpoint_chain (struct breakpoint *b)
5721 {
5722   struct breakpoint *b1;
5723
5724   /* Add this breakpoint to the end of the chain so that a list of
5725      breakpoints will come out in order of increasing numbers.  */
5726
5727   b1 = breakpoint_chain;
5728   if (b1 == 0)
5729     breakpoint_chain = b;
5730   else
5731     {
5732       while (b1->next)
5733         b1 = b1->next;
5734       b1->next = b;
5735     }
5736 }
5737
5738 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
5739
5740 static void
5741 init_raw_breakpoint_without_location (struct breakpoint *b,
5742                                       struct gdbarch *gdbarch,
5743                                       enum bptype bptype,
5744                                       const struct breakpoint_ops *ops)
5745 {
5746   memset (b, 0, sizeof (*b));
5747
5748   gdb_assert (ops != NULL);
5749
5750   b->ops = ops;
5751   b->type = bptype;
5752   b->gdbarch = gdbarch;
5753   b->language = current_language->la_language;
5754   b->input_radix = input_radix;
5755   b->thread = -1;
5756   b->enable_state = bp_enabled;
5757   b->next = 0;
5758   b->silent = 0;
5759   b->ignore_count = 0;
5760   b->commands = NULL;
5761   b->frame_id = null_frame_id;
5762   b->condition_not_parsed = 0;
5763   b->py_bp_object = NULL;
5764   b->related_breakpoint = b;
5765 }
5766
5767 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
5768    that has type BPTYPE and has no locations as yet.  */
5769
5770 static struct breakpoint *
5771 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
5772                                      enum bptype bptype,
5773                                      const struct breakpoint_ops *ops)
5774 {
5775   struct breakpoint *b = XNEW (struct breakpoint);
5776
5777   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
5778   add_to_breakpoint_chain (b);
5779   return b;
5780 }
5781
5782 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
5783    resolutions should be made as the user specified the location explicitly
5784    enough.  */
5785
5786 static void
5787 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
5788 {
5789   gdb_assert (loc->owner != NULL);
5790
5791   if (loc->owner->type == bp_breakpoint
5792       || loc->owner->type == bp_hardware_breakpoint
5793       || is_tracepoint (loc->owner))
5794     {
5795       int is_gnu_ifunc;
5796
5797       find_pc_partial_function_gnu_ifunc (loc->address, &loc->function_name,
5798                                           NULL, NULL, &is_gnu_ifunc);
5799
5800       if (is_gnu_ifunc && !explicit_loc)
5801         {
5802           struct breakpoint *b = loc->owner;
5803
5804           gdb_assert (loc->pspace == current_program_space);
5805           if (gnu_ifunc_resolve_name (loc->function_name,
5806                                       &loc->requested_address))
5807             {
5808               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
5809               loc->address = adjust_breakpoint_address (loc->gdbarch,
5810                                                         loc->requested_address,
5811                                                         b->type);
5812             }
5813           else if (b->type == bp_breakpoint && b->loc == loc
5814                    && loc->next == NULL && b->related_breakpoint == b)
5815             {
5816               /* Create only the whole new breakpoint of this type but do not
5817                  mess more complicated breakpoints with multiple locations.  */
5818               b->type = bp_gnu_ifunc_resolver;
5819             }
5820         }
5821
5822       if (loc->function_name)
5823         loc->function_name = xstrdup (loc->function_name);
5824     }
5825 }
5826
5827 /* Attempt to determine architecture of location identified by SAL.  */
5828 struct gdbarch *
5829 get_sal_arch (struct symtab_and_line sal)
5830 {
5831   if (sal.section)
5832     return get_objfile_arch (sal.section->objfile);
5833   if (sal.symtab)
5834     return get_objfile_arch (sal.symtab->objfile);
5835
5836   return NULL;
5837 }
5838
5839 /* Low level routine for partially initializing a breakpoint of type
5840    BPTYPE.  The newly created breakpoint's address, section, source
5841    file name, and line number are provided by SAL.
5842
5843    It is expected that the caller will complete the initialization of
5844    the newly created breakpoint struct as well as output any status
5845    information regarding the creation of a new breakpoint.  */
5846
5847 static void
5848 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
5849                      struct symtab_and_line sal, enum bptype bptype,
5850                      const struct breakpoint_ops *ops)
5851 {
5852   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
5853
5854   add_location_to_breakpoint (b, &sal);
5855
5856   if (bptype != bp_catchpoint)
5857     gdb_assert (sal.pspace != NULL);
5858
5859   /* Store the program space that was used to set the breakpoint,
5860      except for ordinary breakpoints, which are independent of the
5861      program space.  */
5862   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
5863     b->pspace = sal.pspace;
5864
5865   breakpoints_changed ();
5866 }
5867
5868 /* set_raw_breakpoint is a low level routine for allocating and
5869    partially initializing a breakpoint of type BPTYPE.  The newly
5870    created breakpoint's address, section, source file name, and line
5871    number are provided by SAL.  The newly created and partially
5872    initialized breakpoint is added to the breakpoint chain and
5873    is also returned as the value of this function.
5874
5875    It is expected that the caller will complete the initialization of
5876    the newly created breakpoint struct as well as output any status
5877    information regarding the creation of a new breakpoint.  In
5878    particular, set_raw_breakpoint does NOT set the breakpoint
5879    number!  Care should be taken to not allow an error to occur
5880    prior to completing the initialization of the breakpoint.  If this
5881    should happen, a bogus breakpoint will be left on the chain.  */
5882
5883 struct breakpoint *
5884 set_raw_breakpoint (struct gdbarch *gdbarch,
5885                     struct symtab_and_line sal, enum bptype bptype,
5886                     const struct breakpoint_ops *ops)
5887 {
5888   struct breakpoint *b = XNEW (struct breakpoint);
5889
5890   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
5891   add_to_breakpoint_chain (b);
5892   return b;
5893 }
5894
5895
5896 /* Note that the breakpoint object B describes a permanent breakpoint
5897    instruction, hard-wired into the inferior's code.  */
5898 void
5899 make_breakpoint_permanent (struct breakpoint *b)
5900 {
5901   struct bp_location *bl;
5902
5903   b->enable_state = bp_permanent;
5904
5905   /* By definition, permanent breakpoints are already present in the
5906      code.  Mark all locations as inserted.  For now,
5907      make_breakpoint_permanent is called in just one place, so it's
5908      hard to say if it's reasonable to have permanent breakpoint with
5909      multiple locations or not, but it's easy to implement.  */
5910   for (bl = b->loc; bl; bl = bl->next)
5911     bl->inserted = 1;
5912 }
5913
5914 /* Call this routine when stepping and nexting to enable a breakpoint
5915    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
5916    initiated the operation.  */
5917
5918 void
5919 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
5920 {
5921   struct breakpoint *b, *b_tmp;
5922   int thread = tp->num;
5923
5924   /* To avoid having to rescan all objfile symbols at every step,
5925      we maintain a list of continually-inserted but always disabled
5926      longjmp "master" breakpoints.  Here, we simply create momentary
5927      clones of those and enable them for the requested thread.  */
5928   ALL_BREAKPOINTS_SAFE (b, b_tmp)
5929     if (b->pspace == current_program_space
5930         && (b->type == bp_longjmp_master
5931             || b->type == bp_exception_master))
5932       {
5933         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
5934         struct breakpoint *clone;
5935
5936         clone = momentary_breakpoint_from_master (b, type,
5937                                                   &momentary_breakpoint_ops);
5938         clone->thread = thread;
5939       }
5940
5941   tp->initiating_frame = frame;
5942 }
5943
5944 /* Delete all longjmp breakpoints from THREAD.  */
5945 void
5946 delete_longjmp_breakpoint (int thread)
5947 {
5948   struct breakpoint *b, *b_tmp;
5949
5950   ALL_BREAKPOINTS_SAFE (b, b_tmp)
5951     if (b->type == bp_longjmp || b->type == bp_exception)
5952       {
5953         if (b->thread == thread)
5954           delete_breakpoint (b);
5955       }
5956 }
5957
5958 void
5959 enable_overlay_breakpoints (void)
5960 {
5961   struct breakpoint *b;
5962
5963   ALL_BREAKPOINTS (b)
5964     if (b->type == bp_overlay_event)
5965     {
5966       b->enable_state = bp_enabled;
5967       update_global_location_list (1);
5968       overlay_events_enabled = 1;
5969     }
5970 }
5971
5972 void
5973 disable_overlay_breakpoints (void)
5974 {
5975   struct breakpoint *b;
5976
5977   ALL_BREAKPOINTS (b)
5978     if (b->type == bp_overlay_event)
5979     {
5980       b->enable_state = bp_disabled;
5981       update_global_location_list (0);
5982       overlay_events_enabled = 0;
5983     }
5984 }
5985
5986 /* Set an active std::terminate breakpoint for each std::terminate
5987    master breakpoint.  */
5988 void
5989 set_std_terminate_breakpoint (void)
5990 {
5991   struct breakpoint *b, *b_tmp;
5992
5993   ALL_BREAKPOINTS_SAFE (b, b_tmp)
5994     if (b->pspace == current_program_space
5995         && b->type == bp_std_terminate_master)
5996       {
5997         momentary_breakpoint_from_master (b, bp_std_terminate,
5998                                           &momentary_breakpoint_ops);
5999       }
6000 }
6001
6002 /* Delete all the std::terminate breakpoints.  */
6003 void
6004 delete_std_terminate_breakpoint (void)
6005 {
6006   struct breakpoint *b, *b_tmp;
6007
6008   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6009     if (b->type == bp_std_terminate)
6010       delete_breakpoint (b);
6011 }
6012
6013 struct breakpoint *
6014 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6015 {
6016   struct breakpoint *b;
6017
6018   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6019                                   &internal_breakpoint_ops);
6020
6021   b->enable_state = bp_enabled;
6022   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6023   b->addr_string
6024     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6025
6026   update_global_location_list_nothrow (1);
6027
6028   return b;
6029 }
6030
6031 void
6032 remove_thread_event_breakpoints (void)
6033 {
6034   struct breakpoint *b, *b_tmp;
6035
6036   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6037     if (b->type == bp_thread_event
6038         && b->loc->pspace == current_program_space)
6039       delete_breakpoint (b);
6040 }
6041
6042 struct lang_and_radix
6043   {
6044     enum language lang;
6045     int radix;
6046   };
6047
6048 /* Create a breakpoint for JIT code registration and unregistration.  */
6049
6050 struct breakpoint *
6051 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6052 {
6053   struct breakpoint *b;
6054
6055   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6056                                   &internal_breakpoint_ops);
6057   update_global_location_list_nothrow (1);
6058   return b;
6059 }
6060
6061 /* Remove JIT code registration and unregistration breakpoint(s).  */
6062
6063 void
6064 remove_jit_event_breakpoints (void)
6065 {
6066   struct breakpoint *b, *b_tmp;
6067
6068   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6069     if (b->type == bp_jit_event
6070         && b->loc->pspace == current_program_space)
6071       delete_breakpoint (b);
6072 }
6073
6074 void
6075 remove_solib_event_breakpoints (void)
6076 {
6077   struct breakpoint *b, *b_tmp;
6078
6079   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6080     if (b->type == bp_shlib_event
6081         && b->loc->pspace == current_program_space)
6082       delete_breakpoint (b);
6083 }
6084
6085 struct breakpoint *
6086 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6087 {
6088   struct breakpoint *b;
6089
6090   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6091                                   &internal_breakpoint_ops);
6092   update_global_location_list_nothrow (1);
6093   return b;
6094 }
6095
6096 /* Disable any breakpoints that are on code in shared libraries.  Only
6097    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6098
6099 void
6100 disable_breakpoints_in_shlibs (void)
6101 {
6102   struct bp_location *loc, **locp_tmp;
6103
6104   ALL_BP_LOCATIONS (loc, locp_tmp)
6105   {
6106     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6107     struct breakpoint *b = loc->owner;
6108
6109     /* We apply the check to all breakpoints, including disabled for
6110        those with loc->duplicate set.  This is so that when breakpoint
6111        becomes enabled, or the duplicate is removed, gdb will try to
6112        insert all breakpoints.  If we don't set shlib_disabled here,
6113        we'll try to insert those breakpoints and fail.  */
6114     if (((b->type == bp_breakpoint)
6115          || (b->type == bp_jit_event)
6116          || (b->type == bp_hardware_breakpoint)
6117          || (is_tracepoint (b)))
6118         && loc->pspace == current_program_space
6119         && !loc->shlib_disabled
6120 #ifdef PC_SOLIB
6121         && PC_SOLIB (loc->address)
6122 #else
6123         && solib_name_from_address (loc->pspace, loc->address)
6124 #endif
6125         )
6126       {
6127         loc->shlib_disabled = 1;
6128       }
6129   }
6130 }
6131
6132 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6133    library.  Only apply to enabled breakpoints, disabled ones can just stay
6134    disabled.  */
6135
6136 static void
6137 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6138 {
6139   struct bp_location *loc, **locp_tmp;
6140   int disabled_shlib_breaks = 0;
6141
6142   /* SunOS a.out shared libraries are always mapped, so do not
6143      disable breakpoints; they will only be reported as unloaded
6144      through clear_solib when GDB discards its shared library
6145      list.  See clear_solib for more information.  */
6146   if (exec_bfd != NULL
6147       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6148     return;
6149
6150   ALL_BP_LOCATIONS (loc, locp_tmp)
6151   {
6152     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6153     struct breakpoint *b = loc->owner;
6154
6155     if (solib->pspace == loc->pspace
6156         && !loc->shlib_disabled
6157         && (((b->type == bp_breakpoint
6158               || b->type == bp_jit_event
6159               || b->type == bp_hardware_breakpoint)
6160              && (loc->loc_type == bp_loc_hardware_breakpoint
6161                  || loc->loc_type == bp_loc_software_breakpoint))
6162             || is_tracepoint (b))
6163         && solib_contains_address_p (solib, loc->address))
6164       {
6165         loc->shlib_disabled = 1;
6166         /* At this point, we cannot rely on remove_breakpoint
6167            succeeding so we must mark the breakpoint as not inserted
6168            to prevent future errors occurring in remove_breakpoints.  */
6169         loc->inserted = 0;
6170
6171         /* This may cause duplicate notifications for the same breakpoint.  */
6172         observer_notify_breakpoint_modified (b);
6173
6174         if (!disabled_shlib_breaks)
6175           {
6176             target_terminal_ours_for_output ();
6177             warning (_("Temporarily disabling breakpoints "
6178                        "for unloaded shared library \"%s\""),
6179                      solib->so_name);
6180           }
6181         disabled_shlib_breaks = 1;
6182       }
6183   }
6184 }
6185
6186 /* FORK & VFORK catchpoints.  */
6187
6188 /* An instance of this type is used to represent a fork or vfork
6189    catchpoint.  It includes a "struct breakpoint" as a kind of base
6190    class; users downcast to "struct breakpoint *" when needed.  A
6191    breakpoint is really of this type iff its ops pointer points to
6192    CATCH_FORK_BREAKPOINT_OPS.  */
6193
6194 struct fork_catchpoint
6195 {
6196   /* The base class.  */
6197   struct breakpoint base;
6198
6199   /* Process id of a child process whose forking triggered this
6200      catchpoint.  This field is only valid immediately after this
6201      catchpoint has triggered.  */
6202   ptid_t forked_inferior_pid;
6203 };
6204
6205 /* Implement the "insert" breakpoint_ops method for fork
6206    catchpoints.  */
6207
6208 static int
6209 insert_catch_fork (struct bp_location *bl)
6210 {
6211   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
6212 }
6213
6214 /* Implement the "remove" breakpoint_ops method for fork
6215    catchpoints.  */
6216
6217 static int
6218 remove_catch_fork (struct bp_location *bl)
6219 {
6220   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
6221 }
6222
6223 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
6224    catchpoints.  */
6225
6226 static int
6227 breakpoint_hit_catch_fork (const struct bp_location *bl,
6228                            struct address_space *aspace, CORE_ADDR bp_addr)
6229 {
6230   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6231
6232   return inferior_has_forked (inferior_ptid, &c->forked_inferior_pid);
6233 }
6234
6235 /* Implement the "print_it" breakpoint_ops method for fork
6236    catchpoints.  */
6237
6238 static enum print_stop_action
6239 print_it_catch_fork (bpstat bs)
6240 {
6241   struct ui_out *uiout = current_uiout;
6242   struct breakpoint *b = bs->breakpoint_at;
6243   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
6244
6245   annotate_catchpoint (b->number);
6246   if (b->disposition == disp_del)
6247     ui_out_text (uiout, "\nTemporary catchpoint ");
6248   else
6249     ui_out_text (uiout, "\nCatchpoint ");
6250   if (ui_out_is_mi_like_p (uiout))
6251     {
6252       ui_out_field_string (uiout, "reason",
6253                            async_reason_lookup (EXEC_ASYNC_FORK));
6254       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6255     }
6256   ui_out_field_int (uiout, "bkptno", b->number);
6257   ui_out_text (uiout, " (forked process ");
6258   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6259   ui_out_text (uiout, "), ");
6260   return PRINT_SRC_AND_LOC;
6261 }
6262
6263 /* Implement the "print_one" breakpoint_ops method for fork
6264    catchpoints.  */
6265
6266 static void
6267 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
6268 {
6269   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6270   struct value_print_options opts;
6271   struct ui_out *uiout = current_uiout;
6272
6273   get_user_print_options (&opts);
6274
6275   /* Field 4, the address, is omitted (which makes the columns not
6276      line up too nicely with the headers, but the effect is relatively
6277      readable).  */
6278   if (opts.addressprint)
6279     ui_out_field_skip (uiout, "addr");
6280   annotate_field (5);
6281   ui_out_text (uiout, "fork");
6282   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6283     {
6284       ui_out_text (uiout, ", process ");
6285       ui_out_field_int (uiout, "what",
6286                         ptid_get_pid (c->forked_inferior_pid));
6287       ui_out_spaces (uiout, 1);
6288     }
6289 }
6290
6291 /* Implement the "print_mention" breakpoint_ops method for fork
6292    catchpoints.  */
6293
6294 static void
6295 print_mention_catch_fork (struct breakpoint *b)
6296 {
6297   printf_filtered (_("Catchpoint %d (fork)"), b->number);
6298 }
6299
6300 /* Implement the "print_recreate" breakpoint_ops method for fork
6301    catchpoints.  */
6302
6303 static void
6304 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
6305 {
6306   fprintf_unfiltered (fp, "catch fork");
6307   print_recreate_thread (b, fp);
6308 }
6309
6310 /* The breakpoint_ops structure to be used in fork catchpoints.  */
6311
6312 static struct breakpoint_ops catch_fork_breakpoint_ops;
6313
6314 /* Implement the "insert" breakpoint_ops method for vfork
6315    catchpoints.  */
6316
6317 static int
6318 insert_catch_vfork (struct bp_location *bl)
6319 {
6320   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
6321 }
6322
6323 /* Implement the "remove" breakpoint_ops method for vfork
6324    catchpoints.  */
6325
6326 static int
6327 remove_catch_vfork (struct bp_location *bl)
6328 {
6329   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
6330 }
6331
6332 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
6333    catchpoints.  */
6334
6335 static int
6336 breakpoint_hit_catch_vfork (const struct bp_location *bl,
6337                             struct address_space *aspace, CORE_ADDR bp_addr)
6338 {
6339   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6340
6341   return inferior_has_vforked (inferior_ptid, &c->forked_inferior_pid);
6342 }
6343
6344 /* Implement the "print_it" breakpoint_ops method for vfork
6345    catchpoints.  */
6346
6347 static enum print_stop_action
6348 print_it_catch_vfork (bpstat bs)
6349 {
6350   struct ui_out *uiout = current_uiout;
6351   struct breakpoint *b = bs->breakpoint_at;
6352   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6353
6354   annotate_catchpoint (b->number);
6355   if (b->disposition == disp_del)
6356     ui_out_text (uiout, "\nTemporary catchpoint ");
6357   else
6358     ui_out_text (uiout, "\nCatchpoint ");
6359   if (ui_out_is_mi_like_p (uiout))
6360     {
6361       ui_out_field_string (uiout, "reason",
6362                            async_reason_lookup (EXEC_ASYNC_VFORK));
6363       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6364     }
6365   ui_out_field_int (uiout, "bkptno", b->number);
6366   ui_out_text (uiout, " (vforked process ");
6367   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6368   ui_out_text (uiout, "), ");
6369   return PRINT_SRC_AND_LOC;
6370 }
6371
6372 /* Implement the "print_one" breakpoint_ops method for vfork
6373    catchpoints.  */
6374
6375 static void
6376 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
6377 {
6378   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6379   struct value_print_options opts;
6380   struct ui_out *uiout = current_uiout;
6381
6382   get_user_print_options (&opts);
6383   /* Field 4, the address, is omitted (which makes the columns not
6384      line up too nicely with the headers, but the effect is relatively
6385      readable).  */
6386   if (opts.addressprint)
6387     ui_out_field_skip (uiout, "addr");
6388   annotate_field (5);
6389   ui_out_text (uiout, "vfork");
6390   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6391     {
6392       ui_out_text (uiout, ", process ");
6393       ui_out_field_int (uiout, "what",
6394                         ptid_get_pid (c->forked_inferior_pid));
6395       ui_out_spaces (uiout, 1);
6396     }
6397 }
6398
6399 /* Implement the "print_mention" breakpoint_ops method for vfork
6400    catchpoints.  */
6401
6402 static void
6403 print_mention_catch_vfork (struct breakpoint *b)
6404 {
6405   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
6406 }
6407
6408 /* Implement the "print_recreate" breakpoint_ops method for vfork
6409    catchpoints.  */
6410
6411 static void
6412 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
6413 {
6414   fprintf_unfiltered (fp, "catch vfork");
6415   print_recreate_thread (b, fp);
6416 }
6417
6418 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
6419
6420 static struct breakpoint_ops catch_vfork_breakpoint_ops;
6421
6422 /* An instance of this type is used to represent a syscall catchpoint.
6423    It includes a "struct breakpoint" as a kind of base class; users
6424    downcast to "struct breakpoint *" when needed.  A breakpoint is
6425    really of this type iff its ops pointer points to
6426    CATCH_SYSCALL_BREAKPOINT_OPS.  */
6427
6428 struct syscall_catchpoint
6429 {
6430   /* The base class.  */
6431   struct breakpoint base;
6432
6433   /* Syscall numbers used for the 'catch syscall' feature.  If no
6434      syscall has been specified for filtering, its value is NULL.
6435      Otherwise, it holds a list of all syscalls to be caught.  The
6436      list elements are allocated with xmalloc.  */
6437   VEC(int) *syscalls_to_be_caught;
6438 };
6439
6440 /* Implement the "dtor" breakpoint_ops method for syscall
6441    catchpoints.  */
6442
6443 static void
6444 dtor_catch_syscall (struct breakpoint *b)
6445 {
6446   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6447
6448   VEC_free (int, c->syscalls_to_be_caught);
6449
6450   base_breakpoint_ops.dtor (b);
6451 }
6452
6453 /* Implement the "insert" breakpoint_ops method for syscall
6454    catchpoints.  */
6455
6456 static int
6457 insert_catch_syscall (struct bp_location *bl)
6458 {
6459   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
6460   struct inferior *inf = current_inferior ();
6461
6462   ++inf->total_syscalls_count;
6463   if (!c->syscalls_to_be_caught)
6464     ++inf->any_syscall_count;
6465   else
6466     {
6467       int i, iter;
6468
6469       for (i = 0;
6470            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6471            i++)
6472         {
6473           int elem;
6474
6475           if (iter >= VEC_length (int, inf->syscalls_counts))
6476             {
6477               int old_size = VEC_length (int, inf->syscalls_counts);
6478               uintptr_t vec_addr_offset
6479                 = old_size * ((uintptr_t) sizeof (int));
6480               uintptr_t vec_addr;
6481               VEC_safe_grow (int, inf->syscalls_counts, iter + 1);
6482               vec_addr = (uintptr_t) VEC_address (int, inf->syscalls_counts) +
6483                 vec_addr_offset;
6484               memset ((void *) vec_addr, 0,
6485                       (iter + 1 - old_size) * sizeof (int));
6486             }
6487           elem = VEC_index (int, inf->syscalls_counts, iter);
6488           VEC_replace (int, inf->syscalls_counts, iter, ++elem);
6489         }
6490     }
6491
6492   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
6493                                         inf->total_syscalls_count != 0,
6494                                         inf->any_syscall_count,
6495                                         VEC_length (int, inf->syscalls_counts),
6496                                         VEC_address (int, inf->syscalls_counts));
6497 }
6498
6499 /* Implement the "remove" breakpoint_ops method for syscall
6500    catchpoints.  */
6501
6502 static int
6503 remove_catch_syscall (struct bp_location *bl)
6504 {
6505   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
6506   struct inferior *inf = current_inferior ();
6507
6508   --inf->total_syscalls_count;
6509   if (!c->syscalls_to_be_caught)
6510     --inf->any_syscall_count;
6511   else
6512     {
6513       int i, iter;
6514
6515       for (i = 0;
6516            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6517            i++)
6518         {
6519           int elem;
6520           if (iter >= VEC_length (int, inf->syscalls_counts))
6521             /* Shouldn't happen.  */
6522             continue;
6523           elem = VEC_index (int, inf->syscalls_counts, iter);
6524           VEC_replace (int, inf->syscalls_counts, iter, --elem);
6525         }
6526     }
6527
6528   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
6529                                         inf->total_syscalls_count != 0,
6530                                         inf->any_syscall_count,
6531                                         VEC_length (int, inf->syscalls_counts),
6532                                         VEC_address (int,
6533                                                      inf->syscalls_counts));
6534 }
6535
6536 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
6537    catchpoints.  */
6538
6539 static int
6540 breakpoint_hit_catch_syscall (const struct bp_location *bl,
6541                               struct address_space *aspace, CORE_ADDR bp_addr)
6542 {
6543   /* We must check if we are catching specific syscalls in this
6544      breakpoint.  If we are, then we must guarantee that the called
6545      syscall is the same syscall we are catching.  */
6546   int syscall_number = 0;
6547   const struct syscall_catchpoint *c
6548     = (const struct syscall_catchpoint *) bl->owner;
6549
6550   if (!inferior_has_called_syscall (inferior_ptid, &syscall_number))
6551     return 0;
6552
6553   /* Now, checking if the syscall is the same.  */
6554   if (c->syscalls_to_be_caught)
6555     {
6556       int i, iter;
6557
6558       for (i = 0;
6559            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6560            i++)
6561         if (syscall_number == iter)
6562           break;
6563       /* Not the same.  */
6564       if (!iter)
6565         return 0;
6566     }
6567
6568   return 1;
6569 }
6570
6571 /* Implement the "print_it" breakpoint_ops method for syscall
6572    catchpoints.  */
6573
6574 static enum print_stop_action
6575 print_it_catch_syscall (bpstat bs)
6576 {
6577   struct ui_out *uiout = current_uiout;
6578   struct breakpoint *b = bs->breakpoint_at;
6579   /* These are needed because we want to know in which state a
6580      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
6581      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
6582      must print "called syscall" or "returned from syscall".  */
6583   ptid_t ptid;
6584   struct target_waitstatus last;
6585   struct syscall s;
6586   char *syscall_id;
6587
6588   get_last_target_status (&ptid, &last);
6589
6590   get_syscall_by_number (last.value.syscall_number, &s);
6591
6592   annotate_catchpoint (b->number);
6593
6594   if (b->disposition == disp_del)
6595     ui_out_text (uiout, "\nTemporary catchpoint ");
6596   else
6597     ui_out_text (uiout, "\nCatchpoint ");
6598   if (ui_out_is_mi_like_p (uiout))
6599     {
6600       ui_out_field_string (uiout, "reason",
6601                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
6602                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
6603                                                 : EXEC_ASYNC_SYSCALL_RETURN));
6604       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6605     }
6606   ui_out_field_int (uiout, "bkptno", b->number);
6607
6608   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
6609     ui_out_text (uiout, " (call to syscall ");
6610   else
6611     ui_out_text (uiout, " (returned from syscall ");
6612
6613   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
6614     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
6615   if (s.name != NULL)
6616     ui_out_field_string (uiout, "syscall-name", s.name);
6617
6618   ui_out_text (uiout, "), ");
6619
6620   return PRINT_SRC_AND_LOC;
6621 }
6622
6623 /* Implement the "print_one" breakpoint_ops method for syscall
6624    catchpoints.  */
6625
6626 static void
6627 print_one_catch_syscall (struct breakpoint *b,
6628                          struct bp_location **last_loc)
6629 {
6630   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6631   struct value_print_options opts;
6632   struct ui_out *uiout = current_uiout;
6633
6634   get_user_print_options (&opts);
6635   /* Field 4, the address, is omitted (which makes the columns not
6636      line up too nicely with the headers, but the effect is relatively
6637      readable).  */
6638   if (opts.addressprint)
6639     ui_out_field_skip (uiout, "addr");
6640   annotate_field (5);
6641
6642   if (c->syscalls_to_be_caught
6643       && VEC_length (int, c->syscalls_to_be_caught) > 1)
6644     ui_out_text (uiout, "syscalls \"");
6645   else
6646     ui_out_text (uiout, "syscall \"");
6647
6648   if (c->syscalls_to_be_caught)
6649     {
6650       int i, iter;
6651       char *text = xstrprintf ("%s", "");
6652
6653       for (i = 0;
6654            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6655            i++)
6656         {
6657           char *x = text;
6658           struct syscall s;
6659           get_syscall_by_number (iter, &s);
6660
6661           if (s.name != NULL)
6662             text = xstrprintf ("%s%s, ", text, s.name);
6663           else
6664             text = xstrprintf ("%s%d, ", text, iter);
6665
6666           /* We have to xfree the last 'text' (now stored at 'x')
6667              because xstrprintf dynamically allocates new space for it
6668              on every call.  */
6669           xfree (x);
6670         }
6671       /* Remove the last comma.  */
6672       text[strlen (text) - 2] = '\0';
6673       ui_out_field_string (uiout, "what", text);
6674     }
6675   else
6676     ui_out_field_string (uiout, "what", "<any syscall>");
6677   ui_out_text (uiout, "\" ");
6678 }
6679
6680 /* Implement the "print_mention" breakpoint_ops method for syscall
6681    catchpoints.  */
6682
6683 static void
6684 print_mention_catch_syscall (struct breakpoint *b)
6685 {
6686   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6687
6688   if (c->syscalls_to_be_caught)
6689     {
6690       int i, iter;
6691
6692       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
6693         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
6694       else
6695         printf_filtered (_("Catchpoint %d (syscall"), b->number);
6696
6697       for (i = 0;
6698            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6699            i++)
6700         {
6701           struct syscall s;
6702           get_syscall_by_number (iter, &s);
6703
6704           if (s.name)
6705             printf_filtered (" '%s' [%d]", s.name, s.number);
6706           else
6707             printf_filtered (" %d", s.number);
6708         }
6709       printf_filtered (")");
6710     }
6711   else
6712     printf_filtered (_("Catchpoint %d (any syscall)"),
6713                      b->number);
6714 }
6715
6716 /* Implement the "print_recreate" breakpoint_ops method for syscall
6717    catchpoints.  */
6718
6719 static void
6720 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
6721 {
6722   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6723
6724   fprintf_unfiltered (fp, "catch syscall");
6725
6726   if (c->syscalls_to_be_caught)
6727     {
6728       int i, iter;
6729
6730       for (i = 0;
6731            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6732            i++)
6733         {
6734           struct syscall s;
6735
6736           get_syscall_by_number (iter, &s);
6737           if (s.name)
6738             fprintf_unfiltered (fp, " %s", s.name);
6739           else
6740             fprintf_unfiltered (fp, " %d", s.number);
6741         }
6742     }
6743   print_recreate_thread (b, fp);
6744 }
6745
6746 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
6747
6748 static struct breakpoint_ops catch_syscall_breakpoint_ops;
6749
6750 /* Returns non-zero if 'b' is a syscall catchpoint.  */
6751
6752 static int
6753 syscall_catchpoint_p (struct breakpoint *b)
6754 {
6755   return (b->ops == &catch_syscall_breakpoint_ops);
6756 }
6757
6758 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
6759    is non-zero, then make the breakpoint temporary.  If COND_STRING is
6760    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
6761    the breakpoint_ops structure associated to the catchpoint.  */
6762
6763 static void
6764 init_catchpoint (struct breakpoint *b,
6765                  struct gdbarch *gdbarch, int tempflag,
6766                  char *cond_string,
6767                  const struct breakpoint_ops *ops)
6768 {
6769   struct symtab_and_line sal;
6770
6771   init_sal (&sal);
6772   sal.pspace = current_program_space;
6773
6774   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
6775
6776   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
6777   b->disposition = tempflag ? disp_del : disp_donttouch;
6778 }
6779
6780 void
6781 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
6782 {
6783   add_to_breakpoint_chain (b);
6784   set_breakpoint_number (internal, b);
6785   if (!internal)
6786     mention (b);
6787   observer_notify_breakpoint_created (b);
6788
6789   if (update_gll)
6790     update_global_location_list (1);
6791 }
6792
6793 static void
6794 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
6795                                     int tempflag, char *cond_string,
6796                                     const struct breakpoint_ops *ops)
6797 {
6798   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
6799
6800   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
6801
6802   c->forked_inferior_pid = null_ptid;
6803
6804   install_breakpoint (0, &c->base, 1);
6805 }
6806
6807 /* Exec catchpoints.  */
6808
6809 /* An instance of this type is used to represent an exec catchpoint.
6810    It includes a "struct breakpoint" as a kind of base class; users
6811    downcast to "struct breakpoint *" when needed.  A breakpoint is
6812    really of this type iff its ops pointer points to
6813    CATCH_EXEC_BREAKPOINT_OPS.  */
6814
6815 struct exec_catchpoint
6816 {
6817   /* The base class.  */
6818   struct breakpoint base;
6819
6820   /* Filename of a program whose exec triggered this catchpoint.
6821      This field is only valid immediately after this catchpoint has
6822      triggered.  */
6823   char *exec_pathname;
6824 };
6825
6826 /* Implement the "dtor" breakpoint_ops method for exec
6827    catchpoints.  */
6828
6829 static void
6830 dtor_catch_exec (struct breakpoint *b)
6831 {
6832   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
6833
6834   xfree (c->exec_pathname);
6835
6836   base_breakpoint_ops.dtor (b);
6837 }
6838
6839 static int
6840 insert_catch_exec (struct bp_location *bl)
6841 {
6842   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
6843 }
6844
6845 static int
6846 remove_catch_exec (struct bp_location *bl)
6847 {
6848   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
6849 }
6850
6851 static int
6852 breakpoint_hit_catch_exec (const struct bp_location *bl,
6853                            struct address_space *aspace, CORE_ADDR bp_addr)
6854 {
6855   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
6856
6857   return inferior_has_execd (inferior_ptid, &c->exec_pathname);
6858 }
6859
6860 static enum print_stop_action
6861 print_it_catch_exec (bpstat bs)
6862 {
6863   struct ui_out *uiout = current_uiout;
6864   struct breakpoint *b = bs->breakpoint_at;
6865   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
6866
6867   annotate_catchpoint (b->number);
6868   if (b->disposition == disp_del)
6869     ui_out_text (uiout, "\nTemporary catchpoint ");
6870   else
6871     ui_out_text (uiout, "\nCatchpoint ");
6872   if (ui_out_is_mi_like_p (uiout))
6873     {
6874       ui_out_field_string (uiout, "reason",
6875                            async_reason_lookup (EXEC_ASYNC_EXEC));
6876       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6877     }
6878   ui_out_field_int (uiout, "bkptno", b->number);
6879   ui_out_text (uiout, " (exec'd ");
6880   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
6881   ui_out_text (uiout, "), ");
6882
6883   return PRINT_SRC_AND_LOC;
6884 }
6885
6886 static void
6887 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
6888 {
6889   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
6890   struct value_print_options opts;
6891   struct ui_out *uiout = current_uiout;
6892
6893   get_user_print_options (&opts);
6894
6895   /* Field 4, the address, is omitted (which makes the columns
6896      not line up too nicely with the headers, but the effect
6897      is relatively readable).  */
6898   if (opts.addressprint)
6899     ui_out_field_skip (uiout, "addr");
6900   annotate_field (5);
6901   ui_out_text (uiout, "exec");
6902   if (c->exec_pathname != NULL)
6903     {
6904       ui_out_text (uiout, ", program \"");
6905       ui_out_field_string (uiout, "what", c->exec_pathname);
6906       ui_out_text (uiout, "\" ");
6907     }
6908 }
6909
6910 static void
6911 print_mention_catch_exec (struct breakpoint *b)
6912 {
6913   printf_filtered (_("Catchpoint %d (exec)"), b->number);
6914 }
6915
6916 /* Implement the "print_recreate" breakpoint_ops method for exec
6917    catchpoints.  */
6918
6919 static void
6920 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
6921 {
6922   fprintf_unfiltered (fp, "catch exec");
6923   print_recreate_thread (b, fp);
6924 }
6925
6926 static struct breakpoint_ops catch_exec_breakpoint_ops;
6927
6928 static void
6929 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
6930                                  const struct breakpoint_ops *ops)
6931 {
6932   struct syscall_catchpoint *c;
6933   struct gdbarch *gdbarch = get_current_arch ();
6934
6935   c = XNEW (struct syscall_catchpoint);
6936   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
6937   c->syscalls_to_be_caught = filter;
6938
6939   install_breakpoint (0, &c->base, 1);
6940 }
6941
6942 static int
6943 hw_breakpoint_used_count (void)
6944 {
6945   int i = 0;
6946   struct breakpoint *b;
6947   struct bp_location *bl;
6948
6949   ALL_BREAKPOINTS (b)
6950   {
6951     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
6952       for (bl = b->loc; bl; bl = bl->next)
6953         {
6954           /* Special types of hardware breakpoints may use more than
6955              one register.  */
6956           i += b->ops->resources_needed (bl);
6957         }
6958   }
6959
6960   return i;
6961 }
6962
6963 /* Returns the resources B would use if it were a hardware
6964    watchpoint.  */
6965
6966 static int
6967 hw_watchpoint_use_count (struct breakpoint *b)
6968 {
6969   int i = 0;
6970   struct bp_location *bl;
6971
6972   if (!breakpoint_enabled (b))
6973     return 0;
6974
6975   for (bl = b->loc; bl; bl = bl->next)
6976     {
6977       /* Special types of hardware watchpoints may use more than
6978          one register.  */
6979       i += b->ops->resources_needed (bl);
6980     }
6981
6982   return i;
6983 }
6984
6985 /* Returns the sum the used resources of all hardware watchpoints of
6986    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
6987    the sum of the used resources of all hardware watchpoints of other
6988    types _not_ TYPE.  */
6989
6990 static int
6991 hw_watchpoint_used_count_others (struct breakpoint *except,
6992                                  enum bptype type, int *other_type_used)
6993 {
6994   int i = 0;
6995   struct breakpoint *b;
6996
6997   *other_type_used = 0;
6998   ALL_BREAKPOINTS (b)
6999     {
7000       if (b == except)
7001         continue;
7002       if (!breakpoint_enabled (b))
7003         continue;
7004
7005       if (b->type == type)
7006         i += hw_watchpoint_use_count (b);
7007       else if (is_hardware_watchpoint (b))
7008         *other_type_used = 1;
7009     }
7010
7011   return i;
7012 }
7013
7014 void
7015 disable_watchpoints_before_interactive_call_start (void)
7016 {
7017   struct breakpoint *b;
7018
7019   ALL_BREAKPOINTS (b)
7020   {
7021     if (is_watchpoint (b) && breakpoint_enabled (b))
7022       {
7023         b->enable_state = bp_call_disabled;
7024         update_global_location_list (0);
7025       }
7026   }
7027 }
7028
7029 void
7030 enable_watchpoints_after_interactive_call_stop (void)
7031 {
7032   struct breakpoint *b;
7033
7034   ALL_BREAKPOINTS (b)
7035   {
7036     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
7037       {
7038         b->enable_state = bp_enabled;
7039         update_global_location_list (1);
7040       }
7041   }
7042 }
7043
7044 void
7045 disable_breakpoints_before_startup (void)
7046 {
7047   current_program_space->executing_startup = 1;
7048   update_global_location_list (0);
7049 }
7050
7051 void
7052 enable_breakpoints_after_startup (void)
7053 {
7054   current_program_space->executing_startup = 0;
7055   breakpoint_re_set ();
7056 }
7057
7058
7059 /* Set a breakpoint that will evaporate an end of command
7060    at address specified by SAL.
7061    Restrict it to frame FRAME if FRAME is nonzero.  */
7062
7063 struct breakpoint *
7064 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
7065                           struct frame_id frame_id, enum bptype type)
7066 {
7067   struct breakpoint *b;
7068
7069   /* If FRAME_ID is valid, it should be a real frame, not an inlined
7070      one.  */
7071   gdb_assert (!frame_id_inlined_p (frame_id));
7072
7073   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
7074   b->enable_state = bp_enabled;
7075   b->disposition = disp_donttouch;
7076   b->frame_id = frame_id;
7077
7078   /* If we're debugging a multi-threaded program, then we want
7079      momentary breakpoints to be active in only a single thread of
7080      control.  */
7081   if (in_thread_list (inferior_ptid))
7082     b->thread = pid_to_thread_id (inferior_ptid);
7083
7084   update_global_location_list_nothrow (1);
7085
7086   return b;
7087 }
7088
7089 /* Make a momentary breakpoint based on the master breakpoint ORIG.
7090    The new breakpoint will have type TYPE, and use OPS as it
7091    breakpoint_ops.  */
7092
7093 static struct breakpoint *
7094 momentary_breakpoint_from_master (struct breakpoint *orig,
7095                                   enum bptype type,
7096                                   const struct breakpoint_ops *ops)
7097 {
7098   struct breakpoint *copy;
7099
7100   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
7101   copy->loc = allocate_bp_location (copy);
7102   set_breakpoint_location_function (copy->loc, 1);
7103
7104   copy->loc->gdbarch = orig->loc->gdbarch;
7105   copy->loc->requested_address = orig->loc->requested_address;
7106   copy->loc->address = orig->loc->address;
7107   copy->loc->section = orig->loc->section;
7108   copy->loc->pspace = orig->loc->pspace;
7109
7110   if (orig->loc->source_file != NULL)
7111     copy->loc->source_file = xstrdup (orig->loc->source_file);
7112
7113   copy->loc->line_number = orig->loc->line_number;
7114   copy->frame_id = orig->frame_id;
7115   copy->thread = orig->thread;
7116   copy->pspace = orig->pspace;
7117
7118   copy->enable_state = bp_enabled;
7119   copy->disposition = disp_donttouch;
7120   copy->number = internal_breakpoint_number--;
7121
7122   update_global_location_list_nothrow (0);
7123   return copy;
7124 }
7125
7126 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
7127    ORIG is NULL.  */
7128
7129 struct breakpoint *
7130 clone_momentary_breakpoint (struct breakpoint *orig)
7131 {
7132   /* If there's nothing to clone, then return nothing.  */
7133   if (orig == NULL)
7134     return NULL;
7135
7136   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
7137 }
7138
7139 struct breakpoint *
7140 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
7141                                 enum bptype type)
7142 {
7143   struct symtab_and_line sal;
7144
7145   sal = find_pc_line (pc, 0);
7146   sal.pc = pc;
7147   sal.section = find_pc_overlay (pc);
7148   sal.explicit_pc = 1;
7149
7150   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
7151 }
7152 \f
7153
7154 /* Tell the user we have just set a breakpoint B.  */
7155
7156 static void
7157 mention (struct breakpoint *b)
7158 {
7159   b->ops->print_mention (b);
7160   if (ui_out_is_mi_like_p (current_uiout))
7161     return;
7162   printf_filtered ("\n");
7163 }
7164 \f
7165
7166 static struct bp_location *
7167 add_location_to_breakpoint (struct breakpoint *b,
7168                             const struct symtab_and_line *sal)
7169 {
7170   struct bp_location *loc, **tmp;
7171   CORE_ADDR adjusted_address;
7172   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
7173
7174   if (loc_gdbarch == NULL)
7175     loc_gdbarch = b->gdbarch;
7176
7177   /* Adjust the breakpoint's address prior to allocating a location.
7178      Once we call allocate_bp_location(), that mostly uninitialized
7179      location will be placed on the location chain.  Adjustment of the
7180      breakpoint may cause target_read_memory() to be called and we do
7181      not want its scan of the location chain to find a breakpoint and
7182      location that's only been partially initialized.  */
7183   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
7184                                                 sal->pc, b->type);
7185
7186   loc = allocate_bp_location (b);
7187   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
7188     ;
7189   *tmp = loc;
7190
7191   loc->requested_address = sal->pc;
7192   loc->address = adjusted_address;
7193   loc->pspace = sal->pspace;
7194   gdb_assert (loc->pspace != NULL);
7195   loc->section = sal->section;
7196   loc->gdbarch = loc_gdbarch;
7197
7198   if (sal->symtab != NULL)
7199     loc->source_file = xstrdup (sal->symtab->filename);
7200   loc->line_number = sal->line;
7201
7202   set_breakpoint_location_function (loc,
7203                                     sal->explicit_pc || sal->explicit_line);
7204   return loc;
7205 }
7206 \f
7207
7208 /* Return 1 if LOC is pointing to a permanent breakpoint, 
7209    return 0 otherwise.  */
7210
7211 static int
7212 bp_loc_is_permanent (struct bp_location *loc)
7213 {
7214   int len;
7215   CORE_ADDR addr;
7216   const gdb_byte *bpoint;
7217   gdb_byte *target_mem;
7218   struct cleanup *cleanup;
7219   int retval = 0;
7220
7221   gdb_assert (loc != NULL);
7222
7223   addr = loc->address;
7224   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
7225
7226   /* Software breakpoints unsupported?  */
7227   if (bpoint == NULL)
7228     return 0;
7229
7230   target_mem = alloca (len);
7231
7232   /* Enable the automatic memory restoration from breakpoints while
7233      we read the memory.  Otherwise we could say about our temporary
7234      breakpoints they are permanent.  */
7235   cleanup = save_current_space_and_thread ();
7236
7237   switch_to_program_space_and_thread (loc->pspace);
7238   make_show_memory_breakpoints_cleanup (0);
7239
7240   if (target_read_memory (loc->address, target_mem, len) == 0
7241       && memcmp (target_mem, bpoint, len) == 0)
7242     retval = 1;
7243
7244   do_cleanups (cleanup);
7245
7246   return retval;
7247 }
7248
7249
7250
7251 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
7252    as textual description of the location, and COND_STRING
7253    as condition expression.  */
7254
7255 static void
7256 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
7257                      struct symtabs_and_lines sals, char *addr_string,
7258                      char *filter, char *cond_string,
7259                      enum bptype type, enum bpdisp disposition,
7260                      int thread, int task, int ignore_count,
7261                      const struct breakpoint_ops *ops, int from_tty,
7262                      int enabled, int internal, int display_canonical)
7263 {
7264   int i;
7265
7266   if (type == bp_hardware_breakpoint)
7267     {
7268       int target_resources_ok;
7269
7270       i = hw_breakpoint_used_count ();
7271       target_resources_ok =
7272         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
7273                                             i + 1, 0);
7274       if (target_resources_ok == 0)
7275         error (_("No hardware breakpoint support in the target."));
7276       else if (target_resources_ok < 0)
7277         error (_("Hardware breakpoints used exceeds limit."));
7278     }
7279
7280   gdb_assert (sals.nelts > 0);
7281
7282   for (i = 0; i < sals.nelts; ++i)
7283     {
7284       struct symtab_and_line sal = sals.sals[i];
7285       struct bp_location *loc;
7286
7287       if (from_tty)
7288         {
7289           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
7290           if (!loc_gdbarch)
7291             loc_gdbarch = gdbarch;
7292
7293           describe_other_breakpoints (loc_gdbarch,
7294                                       sal.pspace, sal.pc, sal.section, thread);
7295         }
7296
7297       if (i == 0)
7298         {
7299           init_raw_breakpoint (b, gdbarch, sal, type, ops);
7300           b->thread = thread;
7301           b->task = task;
7302   
7303           b->cond_string = cond_string;
7304           b->ignore_count = ignore_count;
7305           b->enable_state = enabled ? bp_enabled : bp_disabled;
7306           b->disposition = disposition;
7307
7308           if (type == bp_static_tracepoint)
7309             {
7310               struct tracepoint *t = (struct tracepoint *) b;
7311               struct static_tracepoint_marker marker;
7312
7313               if (strace_marker_p (b))
7314                 {
7315                   /* We already know the marker exists, otherwise, we
7316                      wouldn't see a sal for it.  */
7317                   char *p = &addr_string[3];
7318                   char *endp;
7319                   char *marker_str;
7320
7321                   p = skip_spaces (p);
7322
7323                   endp = skip_to_space (p);
7324
7325                   marker_str = savestring (p, endp - p);
7326                   t->static_trace_marker_id = marker_str;
7327
7328                   printf_filtered (_("Probed static tracepoint "
7329                                      "marker \"%s\"\n"),
7330                                    t->static_trace_marker_id);
7331                 }
7332               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
7333                 {
7334                   t->static_trace_marker_id = xstrdup (marker.str_id);
7335                   release_static_tracepoint_marker (&marker);
7336
7337                   printf_filtered (_("Probed static tracepoint "
7338                                      "marker \"%s\"\n"),
7339                                    t->static_trace_marker_id);
7340                 }
7341               else
7342                 warning (_("Couldn't determine the static "
7343                            "tracepoint marker to probe"));
7344             }
7345
7346           loc = b->loc;
7347         }
7348       else
7349         {
7350           loc = add_location_to_breakpoint (b, &sal);
7351         }
7352
7353       if (bp_loc_is_permanent (loc))
7354         make_breakpoint_permanent (b);
7355
7356       if (b->cond_string)
7357         {
7358           char *arg = b->cond_string;
7359           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
7360           if (*arg)
7361               error (_("Garbage %s follows condition"), arg);
7362         }
7363     }   
7364
7365   b->display_canonical = display_canonical;
7366   if (addr_string)
7367     b->addr_string = addr_string;
7368   else
7369     /* addr_string has to be used or breakpoint_re_set will delete
7370        me.  */
7371     b->addr_string
7372       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7373   b->filter = filter;
7374 }
7375
7376 static void
7377 create_breakpoint_sal (struct gdbarch *gdbarch,
7378                        struct symtabs_and_lines sals, char *addr_string,
7379                        char *filter, char *cond_string,
7380                        enum bptype type, enum bpdisp disposition,
7381                        int thread, int task, int ignore_count,
7382                        const struct breakpoint_ops *ops, int from_tty,
7383                        int enabled, int internal, int display_canonical)
7384 {
7385   struct breakpoint *b;
7386   struct cleanup *old_chain;
7387
7388   if (is_tracepoint_type (type))
7389     {
7390       struct tracepoint *t;
7391
7392       t = XCNEW (struct tracepoint);
7393       b = &t->base;
7394     }
7395   else
7396     b = XNEW (struct breakpoint);
7397
7398   old_chain = make_cleanup (xfree, b);
7399
7400   init_breakpoint_sal (b, gdbarch,
7401                        sals, addr_string,
7402                        filter, cond_string,
7403                        type, disposition,
7404                        thread, task, ignore_count,
7405                        ops, from_tty,
7406                        enabled, internal, display_canonical);
7407   discard_cleanups (old_chain);
7408
7409   install_breakpoint (internal, b, 0);
7410 }
7411
7412 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
7413    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
7414    value.  COND_STRING, if not NULL, specified the condition to be
7415    used for all breakpoints.  Essentially the only case where
7416    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
7417    function.  In that case, it's still not possible to specify
7418    separate conditions for different overloaded functions, so
7419    we take just a single condition string.
7420    
7421    NOTE: If the function succeeds, the caller is expected to cleanup
7422    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
7423    array contents).  If the function fails (error() is called), the
7424    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
7425    COND and SALS arrays and each of those arrays contents.  */
7426
7427 static void
7428 create_breakpoints_sal (struct gdbarch *gdbarch,
7429                         struct linespec_result *canonical,
7430                         char *cond_string,
7431                         enum bptype type, enum bpdisp disposition,
7432                         int thread, int task, int ignore_count,
7433                         const struct breakpoint_ops *ops, int from_tty,
7434                         int enabled, int internal)
7435 {
7436   int i;
7437   struct linespec_sals *lsal;
7438
7439   if (canonical->pre_expanded)
7440     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
7441
7442   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
7443     {
7444       /* Note that 'addr_string' can be NULL in the case of a plain
7445          'break', without arguments.  */
7446       char *addr_string = (canonical->addr_string
7447                            ? xstrdup (canonical->addr_string)
7448                            : NULL);
7449       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
7450       struct cleanup *inner = make_cleanup (xfree, addr_string);
7451
7452       make_cleanup (xfree, filter_string);
7453       create_breakpoint_sal (gdbarch, lsal->sals,
7454                              addr_string,
7455                              filter_string,
7456                              cond_string, type, disposition,
7457                              thread, task, ignore_count, ops,
7458                              from_tty, enabled, internal,
7459                              canonical->special_display);
7460       discard_cleanups (inner);
7461     }
7462 }
7463
7464 /* Parse ADDRESS which is assumed to be a SAL specification possibly
7465    followed by conditionals.  On return, SALS contains an array of SAL
7466    addresses found.  ADDR_STRING contains a vector of (canonical)
7467    address strings.  ADDRESS points to the end of the SAL.
7468
7469    The array and the line spec strings are allocated on the heap, it is
7470    the caller's responsibility to free them.  */
7471
7472 static void
7473 parse_breakpoint_sals (char **address,
7474                        struct linespec_result *canonical)
7475 {
7476   char *addr_start = *address;
7477
7478   /* If no arg given, or if first arg is 'if ', use the default
7479      breakpoint.  */
7480   if ((*address) == NULL
7481       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
7482     {
7483       /* The last displayed codepoint, if it's valid, is our default breakpoint
7484          address.  */
7485       if (last_displayed_sal_is_valid ())
7486         {
7487           struct linespec_sals lsal;
7488           struct symtab_and_line sal;
7489
7490           init_sal (&sal);              /* Initialize to zeroes.  */
7491           lsal.sals.sals = (struct symtab_and_line *)
7492             xmalloc (sizeof (struct symtab_and_line));
7493
7494           /* Set sal's pspace, pc, symtab, and line to the values
7495              corresponding to the last call to print_frame_info.  */
7496           get_last_displayed_sal (&sal);
7497           sal.section = find_pc_overlay (sal.pc);
7498
7499           /* "break" without arguments is equivalent to "break *PC"
7500              where PC is the last displayed codepoint's address.  So
7501              make sure to set sal.explicit_pc to prevent GDB from
7502              trying to expand the list of sals to include all other
7503              instances with the same symtab and line.  */
7504           sal.explicit_pc = 1;
7505
7506           lsal.sals.sals[0] = sal;
7507           lsal.sals.nelts = 1;
7508           lsal.canonical = NULL;
7509
7510           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
7511         }
7512       else
7513         error (_("No default breakpoint address now."));
7514     }
7515   else
7516     {
7517       /* Force almost all breakpoints to be in terms of the
7518          current_source_symtab (which is decode_line_1's default).
7519          This should produce the results we want almost all of the
7520          time while leaving default_breakpoint_* alone.  */
7521       if (last_displayed_sal_is_valid ())
7522         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
7523                           get_last_displayed_symtab (),
7524                           get_last_displayed_line (),
7525                           canonical, NULL, NULL);
7526       else
7527         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
7528                           (struct symtab *) NULL, 0,
7529                           canonical, NULL, NULL);
7530     }
7531 }
7532
7533
7534 /* Convert each SAL into a real PC.  Verify that the PC can be
7535    inserted as a breakpoint.  If it can't throw an error.  */
7536
7537 static void
7538 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
7539 {    
7540   int i;
7541
7542   for (i = 0; i < sals->nelts; i++)
7543     resolve_sal_pc (&sals->sals[i]);
7544 }
7545
7546 /* Fast tracepoints may have restrictions on valid locations.  For
7547    instance, a fast tracepoint using a jump instead of a trap will
7548    likely have to overwrite more bytes than a trap would, and so can
7549    only be placed where the instruction is longer than the jump, or a
7550    multi-instruction sequence does not have a jump into the middle of
7551    it, etc.  */
7552
7553 static void
7554 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
7555                             struct symtabs_and_lines *sals)
7556 {
7557   int i, rslt;
7558   struct symtab_and_line *sal;
7559   char *msg;
7560   struct cleanup *old_chain;
7561
7562   for (i = 0; i < sals->nelts; i++)
7563     {
7564       struct gdbarch *sarch;
7565
7566       sal = &sals->sals[i];
7567
7568       sarch = get_sal_arch (*sal);
7569       /* We fall back to GDBARCH if there is no architecture
7570          associated with SAL.  */
7571       if (sarch == NULL)
7572         sarch = gdbarch;
7573       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
7574                                                NULL, &msg);
7575       old_chain = make_cleanup (xfree, msg);
7576
7577       if (!rslt)
7578         error (_("May not have a fast tracepoint at 0x%s%s"),
7579                paddress (sarch, sal->pc), (msg ? msg : ""));
7580
7581       do_cleanups (old_chain);
7582     }
7583 }
7584
7585 /* Given TOK, a string specification of condition and thread, as
7586    accepted by the 'break' command, extract the condition
7587    string and thread number and set *COND_STRING and *THREAD.
7588    PC identifies the context at which the condition should be parsed.
7589    If no condition is found, *COND_STRING is set to NULL.
7590    If no thread is found, *THREAD is set to -1.  */
7591 static void 
7592 find_condition_and_thread (char *tok, CORE_ADDR pc, 
7593                            char **cond_string, int *thread, int *task)
7594 {
7595   *cond_string = NULL;
7596   *thread = -1;
7597   while (tok && *tok)
7598     {
7599       char *end_tok;
7600       int toklen;
7601       char *cond_start = NULL;
7602       char *cond_end = NULL;
7603
7604       tok = skip_spaces (tok);
7605       
7606       end_tok = skip_to_space (tok);
7607       
7608       toklen = end_tok - tok;
7609       
7610       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
7611         {
7612           struct expression *expr;
7613
7614           tok = cond_start = end_tok + 1;
7615           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
7616           xfree (expr);
7617           cond_end = tok;
7618           *cond_string = savestring (cond_start, 
7619                                      cond_end - cond_start);
7620         }
7621       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
7622         {
7623           char *tmptok;
7624           
7625           tok = end_tok + 1;
7626           tmptok = tok;
7627           *thread = strtol (tok, &tok, 0);
7628           if (tok == tmptok)
7629             error (_("Junk after thread keyword."));
7630           if (!valid_thread_id (*thread))
7631             error (_("Unknown thread %d."), *thread);
7632         }
7633       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
7634         {
7635           char *tmptok;
7636
7637           tok = end_tok + 1;
7638           tmptok = tok;
7639           *task = strtol (tok, &tok, 0);
7640           if (tok == tmptok)
7641             error (_("Junk after task keyword."));
7642           if (!valid_task_id (*task))
7643             error (_("Unknown task %d."), *task);
7644         }
7645       else
7646         error (_("Junk at end of arguments."));
7647     }
7648 }
7649
7650 /* Decode a static tracepoint marker spec.  */
7651
7652 static struct symtabs_and_lines
7653 decode_static_tracepoint_spec (char **arg_p)
7654 {
7655   VEC(static_tracepoint_marker_p) *markers = NULL;
7656   struct symtabs_and_lines sals;
7657   struct symtab_and_line sal;
7658   struct symbol *sym;
7659   struct cleanup *old_chain;
7660   char *p = &(*arg_p)[3];
7661   char *endp;
7662   char *marker_str;
7663   int i;
7664
7665   p = skip_spaces (p);
7666
7667   endp = skip_to_space (p);
7668
7669   marker_str = savestring (p, endp - p);
7670   old_chain = make_cleanup (xfree, marker_str);
7671
7672   markers = target_static_tracepoint_markers_by_strid (marker_str);
7673   if (VEC_empty(static_tracepoint_marker_p, markers))
7674     error (_("No known static tracepoint marker named %s"), marker_str);
7675
7676   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
7677   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
7678
7679   for (i = 0; i < sals.nelts; i++)
7680     {
7681       struct static_tracepoint_marker *marker;
7682
7683       marker = VEC_index (static_tracepoint_marker_p, markers, i);
7684
7685       init_sal (&sals.sals[i]);
7686
7687       sals.sals[i] = find_pc_line (marker->address, 0);
7688       sals.sals[i].pc = marker->address;
7689
7690       release_static_tracepoint_marker (marker);
7691     }
7692
7693   do_cleanups (old_chain);
7694
7695   *arg_p = endp;
7696   return sals;
7697 }
7698
7699 /* Set a breakpoint.  This function is shared between CLI and MI
7700    functions for setting a breakpoint.  This function has two major
7701    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
7702    parameter.  If non-zero, the function will parse arg, extracting
7703    breakpoint location, address and thread.  Otherwise, ARG is just
7704    the location of breakpoint, with condition and thread specified by
7705    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
7706    the breakpoint number will be allocated from the internal
7707    breakpoint count.  Returns true if any breakpoint was created;
7708    false otherwise.  */
7709
7710 int
7711 create_breakpoint (struct gdbarch *gdbarch,
7712                    char *arg, char *cond_string, int thread,
7713                    int parse_condition_and_thread,
7714                    int tempflag, enum bptype type_wanted,
7715                    int ignore_count,
7716                    enum auto_boolean pending_break_support,
7717                    const struct breakpoint_ops *ops,
7718                    int from_tty, int enabled, int internal)
7719 {
7720   volatile struct gdb_exception e;
7721   char *copy_arg = NULL;
7722   char *addr_start = arg;
7723   struct linespec_result canonical;
7724   struct cleanup *old_chain;
7725   struct cleanup *bkpt_chain = NULL;
7726   int i;
7727   int pending = 0;
7728   int task = 0;
7729   int prev_bkpt_count = breakpoint_count;
7730
7731   gdb_assert (ops != NULL);
7732
7733   init_linespec_result (&canonical);
7734
7735   TRY_CATCH (e, RETURN_MASK_ALL)
7736     {
7737       ops->create_sals_from_address (&arg, &canonical, type_wanted,
7738                                      addr_start, &copy_arg);
7739     }
7740
7741   /* If caller is interested in rc value from parse, set value.  */
7742   switch (e.reason)
7743     {
7744     case GDB_NO_ERROR:
7745       if (VEC_empty (linespec_sals, canonical.sals))
7746         return 0;
7747       break;
7748     case RETURN_ERROR:
7749       switch (e.error)
7750         {
7751         case NOT_FOUND_ERROR:
7752
7753           /* If pending breakpoint support is turned off, throw
7754              error.  */
7755
7756           if (pending_break_support == AUTO_BOOLEAN_FALSE)
7757             throw_exception (e);
7758
7759           exception_print (gdb_stderr, e);
7760
7761           /* If pending breakpoint support is auto query and the user
7762              selects no, then simply return the error code.  */
7763           if (pending_break_support == AUTO_BOOLEAN_AUTO
7764               && !nquery (_("Make %s pending on future shared library load? "),
7765                           bptype_string (type_wanted)))
7766             return 0;
7767
7768           /* At this point, either the user was queried about setting
7769              a pending breakpoint and selected yes, or pending
7770              breakpoint behavior is on and thus a pending breakpoint
7771              is defaulted on behalf of the user.  */
7772           {
7773             struct linespec_sals lsal;
7774
7775             copy_arg = xstrdup (addr_start);
7776             lsal.canonical = xstrdup (copy_arg);
7777             lsal.sals.nelts = 1;
7778             lsal.sals.sals = XNEW (struct symtab_and_line);
7779             init_sal (&lsal.sals.sals[0]);
7780             pending = 1;
7781             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
7782           }
7783           break;
7784         default:
7785           throw_exception (e);
7786         }
7787       break;
7788     default:
7789       throw_exception (e);
7790     }
7791
7792   /* Create a chain of things that always need to be cleaned up.  */
7793   old_chain = make_cleanup_destroy_linespec_result (&canonical);
7794
7795   /* ----------------------------- SNIP -----------------------------
7796      Anything added to the cleanup chain beyond this point is assumed
7797      to be part of a breakpoint.  If the breakpoint create succeeds
7798      then the memory is not reclaimed.  */
7799   bkpt_chain = make_cleanup (null_cleanup, 0);
7800
7801   /* Resolve all line numbers to PC's and verify that the addresses
7802      are ok for the target.  */
7803   if (!pending)
7804     {
7805       int ix;
7806       struct linespec_sals *iter;
7807
7808       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
7809         breakpoint_sals_to_pc (&iter->sals);
7810     }
7811
7812   /* Fast tracepoints may have additional restrictions on location.  */
7813   if (!pending && type_wanted == bp_fast_tracepoint)
7814     {
7815       int ix;
7816       struct linespec_sals *iter;
7817
7818       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
7819         check_fast_tracepoint_sals (gdbarch, &iter->sals);
7820     }
7821
7822   /* Verify that condition can be parsed, before setting any
7823      breakpoints.  Allocate a separate condition expression for each
7824      breakpoint.  */
7825   if (!pending)
7826     {
7827       struct linespec_sals *lsal;
7828
7829       lsal = VEC_index (linespec_sals, canonical.sals, 0);
7830
7831       if (parse_condition_and_thread)
7832         {
7833             /* Here we only parse 'arg' to separate condition
7834                from thread number, so parsing in context of first
7835                sal is OK.  When setting the breakpoint we'll 
7836                re-parse it in context of each sal.  */
7837             cond_string = NULL;
7838             thread = -1;
7839             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
7840                                        &thread, &task);
7841             if (cond_string)
7842                 make_cleanup (xfree, cond_string);
7843         }
7844       else
7845         {
7846             /* Create a private copy of condition string.  */
7847             if (cond_string)
7848             {
7849                 cond_string = xstrdup (cond_string);
7850                 make_cleanup (xfree, cond_string);
7851             }
7852         }
7853
7854       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
7855                                    cond_string, type_wanted,
7856                                    tempflag ? disp_del : disp_donttouch,
7857                                    thread, task, ignore_count, ops,
7858                                    from_tty, enabled, internal);
7859     }
7860   else
7861     {
7862       struct breakpoint *b;
7863
7864       make_cleanup (xfree, copy_arg);
7865
7866       if (is_tracepoint_type (type_wanted))
7867         {
7868           struct tracepoint *t;
7869
7870           t = XCNEW (struct tracepoint);
7871           b = &t->base;
7872         }
7873       else
7874         b = XNEW (struct breakpoint);
7875
7876       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
7877
7878       b->addr_string = copy_arg;
7879       b->cond_string = NULL;
7880       b->ignore_count = ignore_count;
7881       b->disposition = tempflag ? disp_del : disp_donttouch;
7882       b->condition_not_parsed = 1;
7883       b->enable_state = enabled ? bp_enabled : bp_disabled;
7884       if ((type_wanted != bp_breakpoint
7885            && type_wanted != bp_hardware_breakpoint) || thread != -1)
7886         b->pspace = current_program_space;
7887
7888       install_breakpoint (internal, b, 0);
7889     }
7890   
7891   if (VEC_length (linespec_sals, canonical.sals) > 1)
7892     {
7893       warning (_("Multiple breakpoints were set.\nUse the "
7894                  "\"delete\" command to delete unwanted breakpoints."));
7895       prev_breakpoint_count = prev_bkpt_count;
7896     }
7897
7898   /* That's it.  Discard the cleanups for data inserted into the
7899      breakpoint.  */
7900   discard_cleanups (bkpt_chain);
7901   /* But cleanup everything else.  */
7902   do_cleanups (old_chain);
7903
7904   /* error call may happen here - have BKPT_CHAIN already discarded.  */
7905   update_global_location_list (1);
7906
7907   return 1;
7908 }
7909
7910 /* Set a breakpoint.
7911    ARG is a string describing breakpoint address,
7912    condition, and thread.
7913    FLAG specifies if a breakpoint is hardware on,
7914    and if breakpoint is temporary, using BP_HARDWARE_FLAG
7915    and BP_TEMPFLAG.  */
7916
7917 static void
7918 break_command_1 (char *arg, int flag, int from_tty)
7919 {
7920   int tempflag = flag & BP_TEMPFLAG;
7921   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
7922                              ? bp_hardware_breakpoint
7923                              : bp_breakpoint);
7924
7925   create_breakpoint (get_current_arch (),
7926                      arg,
7927                      NULL, 0, 1 /* parse arg */,
7928                      tempflag, type_wanted,
7929                      0 /* Ignore count */,
7930                      pending_break_support,
7931                      &bkpt_breakpoint_ops,
7932                      from_tty,
7933                      1 /* enabled */,
7934                      0 /* internal */);
7935 }
7936
7937 /* Helper function for break_command_1 and disassemble_command.  */
7938
7939 void
7940 resolve_sal_pc (struct symtab_and_line *sal)
7941 {
7942   CORE_ADDR pc;
7943
7944   if (sal->pc == 0 && sal->symtab != NULL)
7945     {
7946       if (!find_line_pc (sal->symtab, sal->line, &pc))
7947         error (_("No line %d in file \"%s\"."),
7948                sal->line, sal->symtab->filename);
7949       sal->pc = pc;
7950
7951       /* If this SAL corresponds to a breakpoint inserted using a line
7952          number, then skip the function prologue if necessary.  */
7953       if (sal->explicit_line)
7954         skip_prologue_sal (sal);
7955     }
7956
7957   if (sal->section == 0 && sal->symtab != NULL)
7958     {
7959       struct blockvector *bv;
7960       struct block *b;
7961       struct symbol *sym;
7962
7963       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
7964       if (bv != NULL)
7965         {
7966           sym = block_linkage_function (b);
7967           if (sym != NULL)
7968             {
7969               fixup_symbol_section (sym, sal->symtab->objfile);
7970               sal->section = SYMBOL_OBJ_SECTION (sym);
7971             }
7972           else
7973             {
7974               /* It really is worthwhile to have the section, so we'll
7975                  just have to look harder. This case can be executed
7976                  if we have line numbers but no functions (as can
7977                  happen in assembly source).  */
7978
7979               struct minimal_symbol *msym;
7980               struct cleanup *old_chain = save_current_space_and_thread ();
7981
7982               switch_to_program_space_and_thread (sal->pspace);
7983
7984               msym = lookup_minimal_symbol_by_pc (sal->pc);
7985               if (msym)
7986                 sal->section = SYMBOL_OBJ_SECTION (msym);
7987
7988               do_cleanups (old_chain);
7989             }
7990         }
7991     }
7992 }
7993
7994 void
7995 break_command (char *arg, int from_tty)
7996 {
7997   break_command_1 (arg, 0, from_tty);
7998 }
7999
8000 void
8001 tbreak_command (char *arg, int from_tty)
8002 {
8003   break_command_1 (arg, BP_TEMPFLAG, from_tty);
8004 }
8005
8006 static void
8007 hbreak_command (char *arg, int from_tty)
8008 {
8009   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
8010 }
8011
8012 static void
8013 thbreak_command (char *arg, int from_tty)
8014 {
8015   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
8016 }
8017
8018 static void
8019 stop_command (char *arg, int from_tty)
8020 {
8021   printf_filtered (_("Specify the type of breakpoint to set.\n\
8022 Usage: stop in <function | address>\n\
8023        stop at <line>\n"));
8024 }
8025
8026 static void
8027 stopin_command (char *arg, int from_tty)
8028 {
8029   int badInput = 0;
8030
8031   if (arg == (char *) NULL)
8032     badInput = 1;
8033   else if (*arg != '*')
8034     {
8035       char *argptr = arg;
8036       int hasColon = 0;
8037
8038       /* Look for a ':'.  If this is a line number specification, then
8039          say it is bad, otherwise, it should be an address or
8040          function/method name.  */
8041       while (*argptr && !hasColon)
8042         {
8043           hasColon = (*argptr == ':');
8044           argptr++;
8045         }
8046
8047       if (hasColon)
8048         badInput = (*argptr != ':');    /* Not a class::method */
8049       else
8050         badInput = isdigit (*arg);      /* a simple line number */
8051     }
8052
8053   if (badInput)
8054     printf_filtered (_("Usage: stop in <function | address>\n"));
8055   else
8056     break_command_1 (arg, 0, from_tty);
8057 }
8058
8059 static void
8060 stopat_command (char *arg, int from_tty)
8061 {
8062   int badInput = 0;
8063
8064   if (arg == (char *) NULL || *arg == '*')      /* no line number */
8065     badInput = 1;
8066   else
8067     {
8068       char *argptr = arg;
8069       int hasColon = 0;
8070
8071       /* Look for a ':'.  If there is a '::' then get out, otherwise
8072          it is probably a line number.  */
8073       while (*argptr && !hasColon)
8074         {
8075           hasColon = (*argptr == ':');
8076           argptr++;
8077         }
8078
8079       if (hasColon)
8080         badInput = (*argptr == ':');    /* we have class::method */
8081       else
8082         badInput = !isdigit (*arg);     /* not a line number */
8083     }
8084
8085   if (badInput)
8086     printf_filtered (_("Usage: stop at <line>\n"));
8087   else
8088     break_command_1 (arg, 0, from_tty);
8089 }
8090
8091 /* Implement the "breakpoint_hit" breakpoint_ops method for
8092    ranged breakpoints.  */
8093
8094 static int
8095 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
8096                                   struct address_space *aspace,
8097                                   CORE_ADDR bp_addr)
8098 {
8099   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
8100                                          bl->length, aspace, bp_addr);
8101 }
8102
8103 /* Implement the "resources_needed" breakpoint_ops method for
8104    ranged breakpoints.  */
8105
8106 static int
8107 resources_needed_ranged_breakpoint (const struct bp_location *bl)
8108 {
8109   return target_ranged_break_num_registers ();
8110 }
8111
8112 /* Implement the "print_it" breakpoint_ops method for
8113    ranged breakpoints.  */
8114
8115 static enum print_stop_action
8116 print_it_ranged_breakpoint (bpstat bs)
8117 {
8118   struct breakpoint *b = bs->breakpoint_at;
8119   struct bp_location *bl = b->loc;
8120   struct ui_out *uiout = current_uiout;
8121
8122   gdb_assert (b->type == bp_hardware_breakpoint);
8123
8124   /* Ranged breakpoints have only one location.  */
8125   gdb_assert (bl && bl->next == NULL);
8126
8127   annotate_breakpoint (b->number);
8128   if (b->disposition == disp_del)
8129     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
8130   else
8131     ui_out_text (uiout, "\nRanged breakpoint ");
8132   if (ui_out_is_mi_like_p (uiout))
8133     {
8134       ui_out_field_string (uiout, "reason",
8135                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
8136       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8137     }
8138   ui_out_field_int (uiout, "bkptno", b->number);
8139   ui_out_text (uiout, ", ");
8140
8141   return PRINT_SRC_AND_LOC;
8142 }
8143
8144 /* Implement the "print_one" breakpoint_ops method for
8145    ranged breakpoints.  */
8146
8147 static void
8148 print_one_ranged_breakpoint (struct breakpoint *b,
8149                              struct bp_location **last_loc)
8150 {
8151   struct bp_location *bl = b->loc;
8152   struct value_print_options opts;
8153   struct ui_out *uiout = current_uiout;
8154
8155   /* Ranged breakpoints have only one location.  */
8156   gdb_assert (bl && bl->next == NULL);
8157
8158   get_user_print_options (&opts);
8159
8160   if (opts.addressprint)
8161     /* We don't print the address range here, it will be printed later
8162        by print_one_detail_ranged_breakpoint.  */
8163     ui_out_field_skip (uiout, "addr");
8164   annotate_field (5);
8165   print_breakpoint_location (b, bl);
8166   *last_loc = bl;
8167 }
8168
8169 /* Implement the "print_one_detail" breakpoint_ops method for
8170    ranged breakpoints.  */
8171
8172 static void
8173 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
8174                                     struct ui_out *uiout)
8175 {
8176   CORE_ADDR address_start, address_end;
8177   struct bp_location *bl = b->loc;
8178   struct ui_stream *stb = ui_out_stream_new (uiout);
8179   struct cleanup *cleanup = make_cleanup_ui_out_stream_delete (stb);
8180
8181   gdb_assert (bl);
8182
8183   address_start = bl->address;
8184   address_end = address_start + bl->length - 1;
8185
8186   ui_out_text (uiout, "\taddress range: ");
8187   fprintf_unfiltered (stb->stream, "[%s, %s]",
8188                       print_core_address (bl->gdbarch, address_start),
8189                       print_core_address (bl->gdbarch, address_end));
8190   ui_out_field_stream (uiout, "addr", stb);
8191   ui_out_text (uiout, "\n");
8192
8193   do_cleanups (cleanup);
8194 }
8195
8196 /* Implement the "print_mention" breakpoint_ops method for
8197    ranged breakpoints.  */
8198
8199 static void
8200 print_mention_ranged_breakpoint (struct breakpoint *b)
8201 {
8202   struct bp_location *bl = b->loc;
8203   struct ui_out *uiout = current_uiout;
8204
8205   gdb_assert (bl);
8206   gdb_assert (b->type == bp_hardware_breakpoint);
8207
8208   if (ui_out_is_mi_like_p (uiout))
8209     return;
8210
8211   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
8212                    b->number, paddress (bl->gdbarch, bl->address),
8213                    paddress (bl->gdbarch, bl->address + bl->length - 1));
8214 }
8215
8216 /* Implement the "print_recreate" breakpoint_ops method for
8217    ranged breakpoints.  */
8218
8219 static void
8220 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
8221 {
8222   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
8223                       b->addr_string_range_end);
8224   print_recreate_thread (b, fp);
8225 }
8226
8227 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
8228
8229 static struct breakpoint_ops ranged_breakpoint_ops;
8230
8231 /* Find the address where the end of the breakpoint range should be
8232    placed, given the SAL of the end of the range.  This is so that if
8233    the user provides a line number, the end of the range is set to the
8234    last instruction of the given line.  */
8235
8236 static CORE_ADDR
8237 find_breakpoint_range_end (struct symtab_and_line sal)
8238 {
8239   CORE_ADDR end;
8240
8241   /* If the user provided a PC value, use it.  Otherwise,
8242      find the address of the end of the given location.  */
8243   if (sal.explicit_pc)
8244     end = sal.pc;
8245   else
8246     {
8247       int ret;
8248       CORE_ADDR start;
8249
8250       ret = find_line_pc_range (sal, &start, &end);
8251       if (!ret)
8252         error (_("Could not find location of the end of the range."));
8253
8254       /* find_line_pc_range returns the start of the next line.  */
8255       end--;
8256     }
8257
8258   return end;
8259 }
8260
8261 /* Implement the "break-range" CLI command.  */
8262
8263 static void
8264 break_range_command (char *arg, int from_tty)
8265 {
8266   char *arg_start, *addr_string_start, *addr_string_end;
8267   struct linespec_result canonical_start, canonical_end;
8268   int bp_count, can_use_bp, length;
8269   CORE_ADDR end;
8270   struct breakpoint *b;
8271   struct symtab_and_line sal_start, sal_end;
8272   struct cleanup *cleanup_bkpt;
8273   struct linespec_sals *lsal_start, *lsal_end;
8274
8275   /* We don't support software ranged breakpoints.  */
8276   if (target_ranged_break_num_registers () < 0)
8277     error (_("This target does not support hardware ranged breakpoints."));
8278
8279   bp_count = hw_breakpoint_used_count ();
8280   bp_count += target_ranged_break_num_registers ();
8281   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8282                                                    bp_count, 0);
8283   if (can_use_bp < 0)
8284     error (_("Hardware breakpoints used exceeds limit."));
8285
8286   arg = skip_spaces (arg);
8287   if (arg == NULL || arg[0] == '\0')
8288     error(_("No address range specified."));
8289
8290   init_linespec_result (&canonical_start);
8291
8292   arg_start = arg;
8293   parse_breakpoint_sals (&arg, &canonical_start);
8294
8295   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
8296
8297   if (arg[0] != ',')
8298     error (_("Too few arguments."));
8299   else if (VEC_empty (linespec_sals, canonical_start.sals))
8300     error (_("Could not find location of the beginning of the range."));
8301
8302   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
8303
8304   if (VEC_length (linespec_sals, canonical_start.sals) > 1
8305       || lsal_start->sals.nelts != 1)
8306     error (_("Cannot create a ranged breakpoint with multiple locations."));
8307
8308   sal_start = lsal_start->sals.sals[0];
8309   addr_string_start = savestring (arg_start, arg - arg_start);
8310   make_cleanup (xfree, addr_string_start);
8311
8312   arg++;        /* Skip the comma.  */
8313   arg = skip_spaces (arg);
8314
8315   /* Parse the end location.  */
8316
8317   init_linespec_result (&canonical_end);
8318   arg_start = arg;
8319
8320   /* We call decode_line_full directly here instead of using
8321      parse_breakpoint_sals because we need to specify the start location's
8322      symtab and line as the default symtab and line for the end of the
8323      range.  This makes it possible to have ranges like "foo.c:27, +14",
8324      where +14 means 14 lines from the start location.  */
8325   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
8326                     sal_start.symtab, sal_start.line,
8327                     &canonical_end, NULL, NULL);
8328
8329   make_cleanup_destroy_linespec_result (&canonical_end);
8330
8331   if (VEC_empty (linespec_sals, canonical_end.sals))
8332     error (_("Could not find location of the end of the range."));
8333
8334   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
8335   if (VEC_length (linespec_sals, canonical_end.sals) > 1
8336       || lsal_end->sals.nelts != 1)
8337     error (_("Cannot create a ranged breakpoint with multiple locations."));
8338
8339   sal_end = lsal_end->sals.sals[0];
8340   addr_string_end = savestring (arg_start, arg - arg_start);
8341   make_cleanup (xfree, addr_string_end);
8342
8343   end = find_breakpoint_range_end (sal_end);
8344   if (sal_start.pc > end)
8345     error (_("Invalid address range, end precedes start."));
8346
8347   length = end - sal_start.pc + 1;
8348   if (length < 0)
8349     /* Length overflowed.  */
8350     error (_("Address range too large."));
8351   else if (length == 1)
8352     {
8353       /* This range is simple enough to be handled by
8354          the `hbreak' command.  */
8355       hbreak_command (addr_string_start, 1);
8356
8357       do_cleanups (cleanup_bkpt);
8358
8359       return;
8360     }
8361
8362   /* Now set up the breakpoint.  */
8363   b = set_raw_breakpoint (get_current_arch (), sal_start,
8364                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
8365   set_breakpoint_count (breakpoint_count + 1);
8366   b->number = breakpoint_count;
8367   b->disposition = disp_donttouch;
8368   b->addr_string = xstrdup (addr_string_start);
8369   b->addr_string_range_end = xstrdup (addr_string_end);
8370   b->loc->length = length;
8371
8372   do_cleanups (cleanup_bkpt);
8373
8374   mention (b);
8375   observer_notify_breakpoint_created (b);
8376   update_global_location_list (1);
8377 }
8378
8379 /*  Return non-zero if EXP is verified as constant.  Returned zero
8380     means EXP is variable.  Also the constant detection may fail for
8381     some constant expressions and in such case still falsely return
8382     zero.  */
8383 static int
8384 watchpoint_exp_is_const (const struct expression *exp)
8385 {
8386   int i = exp->nelts;
8387
8388   while (i > 0)
8389     {
8390       int oplenp, argsp;
8391
8392       /* We are only interested in the descriptor of each element.  */
8393       operator_length (exp, i, &oplenp, &argsp);
8394       i -= oplenp;
8395
8396       switch (exp->elts[i].opcode)
8397         {
8398         case BINOP_ADD:
8399         case BINOP_SUB:
8400         case BINOP_MUL:
8401         case BINOP_DIV:
8402         case BINOP_REM:
8403         case BINOP_MOD:
8404         case BINOP_LSH:
8405         case BINOP_RSH:
8406         case BINOP_LOGICAL_AND:
8407         case BINOP_LOGICAL_OR:
8408         case BINOP_BITWISE_AND:
8409         case BINOP_BITWISE_IOR:
8410         case BINOP_BITWISE_XOR:
8411         case BINOP_EQUAL:
8412         case BINOP_NOTEQUAL:
8413         case BINOP_LESS:
8414         case BINOP_GTR:
8415         case BINOP_LEQ:
8416         case BINOP_GEQ:
8417         case BINOP_REPEAT:
8418         case BINOP_COMMA:
8419         case BINOP_EXP:
8420         case BINOP_MIN:
8421         case BINOP_MAX:
8422         case BINOP_INTDIV:
8423         case BINOP_CONCAT:
8424         case BINOP_IN:
8425         case BINOP_RANGE:
8426         case TERNOP_COND:
8427         case TERNOP_SLICE:
8428         case TERNOP_SLICE_COUNT:
8429
8430         case OP_LONG:
8431         case OP_DOUBLE:
8432         case OP_DECFLOAT:
8433         case OP_LAST:
8434         case OP_COMPLEX:
8435         case OP_STRING:
8436         case OP_BITSTRING:
8437         case OP_ARRAY:
8438         case OP_TYPE:
8439         case OP_NAME:
8440         case OP_OBJC_NSSTRING:
8441
8442         case UNOP_NEG:
8443         case UNOP_LOGICAL_NOT:
8444         case UNOP_COMPLEMENT:
8445         case UNOP_ADDR:
8446         case UNOP_HIGH:
8447           /* Unary, binary and ternary operators: We have to check
8448              their operands.  If they are constant, then so is the
8449              result of that operation.  For instance, if A and B are
8450              determined to be constants, then so is "A + B".
8451
8452              UNOP_IND is one exception to the rule above, because the
8453              value of *ADDR is not necessarily a constant, even when
8454              ADDR is.  */
8455           break;
8456
8457         case OP_VAR_VALUE:
8458           /* Check whether the associated symbol is a constant.
8459
8460              We use SYMBOL_CLASS rather than TYPE_CONST because it's
8461              possible that a buggy compiler could mark a variable as
8462              constant even when it is not, and TYPE_CONST would return
8463              true in this case, while SYMBOL_CLASS wouldn't.
8464
8465              We also have to check for function symbols because they
8466              are always constant.  */
8467           {
8468             struct symbol *s = exp->elts[i + 2].symbol;
8469
8470             if (SYMBOL_CLASS (s) != LOC_BLOCK
8471                 && SYMBOL_CLASS (s) != LOC_CONST
8472                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
8473               return 0;
8474             break;
8475           }
8476
8477         /* The default action is to return 0 because we are using
8478            the optimistic approach here: If we don't know something,
8479            then it is not a constant.  */
8480         default:
8481           return 0;
8482         }
8483     }
8484
8485   return 1;
8486 }
8487
8488 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
8489
8490 static void
8491 dtor_watchpoint (struct breakpoint *self)
8492 {
8493   struct watchpoint *w = (struct watchpoint *) self;
8494
8495   xfree (w->cond_exp);
8496   xfree (w->exp);
8497   xfree (w->exp_string);
8498   xfree (w->exp_string_reparse);
8499   value_free (w->val);
8500
8501   base_breakpoint_ops.dtor (self);
8502 }
8503
8504 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
8505
8506 static void
8507 re_set_watchpoint (struct breakpoint *b)
8508 {
8509   struct watchpoint *w = (struct watchpoint *) b;
8510
8511   /* Watchpoint can be either on expression using entirely global
8512      variables, or it can be on local variables.
8513
8514      Watchpoints of the first kind are never auto-deleted, and even
8515      persist across program restarts.  Since they can use variables
8516      from shared libraries, we need to reparse expression as libraries
8517      are loaded and unloaded.
8518
8519      Watchpoints on local variables can also change meaning as result
8520      of solib event.  For example, if a watchpoint uses both a local
8521      and a global variables in expression, it's a local watchpoint,
8522      but unloading of a shared library will make the expression
8523      invalid.  This is not a very common use case, but we still
8524      re-evaluate expression, to avoid surprises to the user.
8525
8526      Note that for local watchpoints, we re-evaluate it only if
8527      watchpoints frame id is still valid.  If it's not, it means the
8528      watchpoint is out of scope and will be deleted soon.  In fact,
8529      I'm not sure we'll ever be called in this case.
8530
8531      If a local watchpoint's frame id is still valid, then
8532      w->exp_valid_block is likewise valid, and we can safely use it.
8533
8534      Don't do anything about disabled watchpoints, since they will be
8535      reevaluated again when enabled.  */
8536   update_watchpoint (w, 1 /* reparse */);
8537 }
8538
8539 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
8540
8541 static int
8542 insert_watchpoint (struct bp_location *bl)
8543 {
8544   struct watchpoint *w = (struct watchpoint *) bl->owner;
8545   int length = w->exact ? 1 : bl->length;
8546
8547   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
8548                                    w->cond_exp);
8549 }
8550
8551 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
8552
8553 static int
8554 remove_watchpoint (struct bp_location *bl)
8555 {
8556   struct watchpoint *w = (struct watchpoint *) bl->owner;
8557   int length = w->exact ? 1 : bl->length;
8558
8559   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
8560                                    w->cond_exp);
8561 }
8562
8563 static int
8564 breakpoint_hit_watchpoint (const struct bp_location *bl,
8565                            struct address_space *aspace, CORE_ADDR bp_addr)
8566 {
8567   struct breakpoint *b = bl->owner;
8568   struct watchpoint *w = (struct watchpoint *) b;
8569
8570   /* Continuable hardware watchpoints are treated as non-existent if the
8571      reason we stopped wasn't a hardware watchpoint (we didn't stop on
8572      some data address).  Otherwise gdb won't stop on a break instruction
8573      in the code (not from a breakpoint) when a hardware watchpoint has
8574      been defined.  Also skip watchpoints which we know did not trigger
8575      (did not match the data address).  */
8576   if (is_hardware_watchpoint (b)
8577       && w->watchpoint_triggered == watch_triggered_no)
8578     return 0;
8579
8580   return 1;
8581 }
8582
8583 static void
8584 check_status_watchpoint (bpstat bs)
8585 {
8586   gdb_assert (is_watchpoint (bs->breakpoint_at));
8587
8588   bpstat_check_watchpoint (bs);
8589 }
8590
8591 /* Implement the "resources_needed" breakpoint_ops method for
8592    hardware watchpoints.  */
8593
8594 static int
8595 resources_needed_watchpoint (const struct bp_location *bl)
8596 {
8597   struct watchpoint *w = (struct watchpoint *) bl->owner;
8598   int length = w->exact? 1 : bl->length;
8599
8600   return target_region_ok_for_hw_watchpoint (bl->address, length);
8601 }
8602
8603 /* Implement the "works_in_software_mode" breakpoint_ops method for
8604    hardware watchpoints.  */
8605
8606 static int
8607 works_in_software_mode_watchpoint (const struct breakpoint *b)
8608 {
8609   /* Read and access watchpoints only work with hardware support.  */
8610   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
8611 }
8612
8613 static enum print_stop_action
8614 print_it_watchpoint (bpstat bs)
8615 {
8616   struct cleanup *old_chain;
8617   struct breakpoint *b;
8618   const struct bp_location *bl;
8619   struct ui_stream *stb;
8620   enum print_stop_action result;
8621   struct watchpoint *w;
8622   struct ui_out *uiout = current_uiout;
8623
8624   gdb_assert (bs->bp_location_at != NULL);
8625
8626   bl = bs->bp_location_at;
8627   b = bs->breakpoint_at;
8628   w = (struct watchpoint *) b;
8629
8630   stb = ui_out_stream_new (uiout);
8631   old_chain = make_cleanup_ui_out_stream_delete (stb);
8632
8633   switch (b->type)
8634     {
8635     case bp_watchpoint:
8636     case bp_hardware_watchpoint:
8637       annotate_watchpoint (b->number);
8638       if (ui_out_is_mi_like_p (uiout))
8639         ui_out_field_string
8640           (uiout, "reason",
8641            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
8642       mention (b);
8643       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
8644       ui_out_text (uiout, "\nOld value = ");
8645       watchpoint_value_print (bs->old_val, stb->stream);
8646       ui_out_field_stream (uiout, "old", stb);
8647       ui_out_text (uiout, "\nNew value = ");
8648       watchpoint_value_print (w->val, stb->stream);
8649       ui_out_field_stream (uiout, "new", stb);
8650       ui_out_text (uiout, "\n");
8651       /* More than one watchpoint may have been triggered.  */
8652       result = PRINT_UNKNOWN;
8653       break;
8654
8655     case bp_read_watchpoint:
8656       if (ui_out_is_mi_like_p (uiout))
8657         ui_out_field_string
8658           (uiout, "reason",
8659            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
8660       mention (b);
8661       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
8662       ui_out_text (uiout, "\nValue = ");
8663       watchpoint_value_print (w->val, stb->stream);
8664       ui_out_field_stream (uiout, "value", stb);
8665       ui_out_text (uiout, "\n");
8666       result = PRINT_UNKNOWN;
8667       break;
8668
8669     case bp_access_watchpoint:
8670       if (bs->old_val != NULL)
8671         {
8672           annotate_watchpoint (b->number);
8673           if (ui_out_is_mi_like_p (uiout))
8674             ui_out_field_string
8675               (uiout, "reason",
8676                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
8677           mention (b);
8678           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
8679           ui_out_text (uiout, "\nOld value = ");
8680           watchpoint_value_print (bs->old_val, stb->stream);
8681           ui_out_field_stream (uiout, "old", stb);
8682           ui_out_text (uiout, "\nNew value = ");
8683         }
8684       else
8685         {
8686           mention (b);
8687           if (ui_out_is_mi_like_p (uiout))
8688             ui_out_field_string
8689               (uiout, "reason",
8690                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
8691           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
8692           ui_out_text (uiout, "\nValue = ");
8693         }
8694       watchpoint_value_print (w->val, stb->stream);
8695       ui_out_field_stream (uiout, "new", stb);
8696       ui_out_text (uiout, "\n");
8697       result = PRINT_UNKNOWN;
8698       break;
8699     default:
8700       result = PRINT_UNKNOWN;
8701     }
8702
8703   do_cleanups (old_chain);
8704   return result;
8705 }
8706
8707 /* Implement the "print_mention" breakpoint_ops method for hardware
8708    watchpoints.  */
8709
8710 static void
8711 print_mention_watchpoint (struct breakpoint *b)
8712 {
8713   struct cleanup *ui_out_chain;
8714   struct watchpoint *w = (struct watchpoint *) b;
8715   struct ui_out *uiout = current_uiout;
8716
8717   switch (b->type)
8718     {
8719     case bp_watchpoint:
8720       ui_out_text (uiout, "Watchpoint ");
8721       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
8722       break;
8723     case bp_hardware_watchpoint:
8724       ui_out_text (uiout, "Hardware watchpoint ");
8725       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
8726       break;
8727     case bp_read_watchpoint:
8728       ui_out_text (uiout, "Hardware read watchpoint ");
8729       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
8730       break;
8731     case bp_access_watchpoint:
8732       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
8733       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
8734       break;
8735     default:
8736       internal_error (__FILE__, __LINE__,
8737                       _("Invalid hardware watchpoint type."));
8738     }
8739
8740   ui_out_field_int (uiout, "number", b->number);
8741   ui_out_text (uiout, ": ");
8742   ui_out_field_string (uiout, "exp", w->exp_string);
8743   do_cleanups (ui_out_chain);
8744 }
8745
8746 /* Implement the "print_recreate" breakpoint_ops method for
8747    watchpoints.  */
8748
8749 static void
8750 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
8751 {
8752   struct watchpoint *w = (struct watchpoint *) b;
8753
8754   switch (b->type)
8755     {
8756     case bp_watchpoint:
8757     case bp_hardware_watchpoint:
8758       fprintf_unfiltered (fp, "watch");
8759       break;
8760     case bp_read_watchpoint:
8761       fprintf_unfiltered (fp, "rwatch");
8762       break;
8763     case bp_access_watchpoint:
8764       fprintf_unfiltered (fp, "awatch");
8765       break;
8766     default:
8767       internal_error (__FILE__, __LINE__,
8768                       _("Invalid watchpoint type."));
8769     }
8770
8771   fprintf_unfiltered (fp, " %s", w->exp_string);
8772   print_recreate_thread (b, fp);
8773 }
8774
8775 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
8776
8777 static struct breakpoint_ops watchpoint_breakpoint_ops;
8778
8779 /* Implement the "insert" breakpoint_ops method for
8780    masked hardware watchpoints.  */
8781
8782 static int
8783 insert_masked_watchpoint (struct bp_location *bl)
8784 {
8785   struct watchpoint *w = (struct watchpoint *) bl->owner;
8786
8787   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
8788                                         bl->watchpoint_type);
8789 }
8790
8791 /* Implement the "remove" breakpoint_ops method for
8792    masked hardware watchpoints.  */
8793
8794 static int
8795 remove_masked_watchpoint (struct bp_location *bl)
8796 {
8797   struct watchpoint *w = (struct watchpoint *) bl->owner;
8798
8799   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
8800                                         bl->watchpoint_type);
8801 }
8802
8803 /* Implement the "resources_needed" breakpoint_ops method for
8804    masked hardware watchpoints.  */
8805
8806 static int
8807 resources_needed_masked_watchpoint (const struct bp_location *bl)
8808 {
8809   struct watchpoint *w = (struct watchpoint *) bl->owner;
8810
8811   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
8812 }
8813
8814 /* Implement the "works_in_software_mode" breakpoint_ops method for
8815    masked hardware watchpoints.  */
8816
8817 static int
8818 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
8819 {
8820   return 0;
8821 }
8822
8823 /* Implement the "print_it" breakpoint_ops method for
8824    masked hardware watchpoints.  */
8825
8826 static enum print_stop_action
8827 print_it_masked_watchpoint (bpstat bs)
8828 {
8829   struct breakpoint *b = bs->breakpoint_at;
8830   struct ui_out *uiout = current_uiout;
8831
8832   /* Masked watchpoints have only one location.  */
8833   gdb_assert (b->loc && b->loc->next == NULL);
8834
8835   switch (b->type)
8836     {
8837     case bp_hardware_watchpoint:
8838       annotate_watchpoint (b->number);
8839       if (ui_out_is_mi_like_p (uiout))
8840         ui_out_field_string
8841           (uiout, "reason",
8842            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
8843       break;
8844
8845     case bp_read_watchpoint:
8846       if (ui_out_is_mi_like_p (uiout))
8847         ui_out_field_string
8848           (uiout, "reason",
8849            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
8850       break;
8851
8852     case bp_access_watchpoint:
8853       if (ui_out_is_mi_like_p (uiout))
8854         ui_out_field_string
8855           (uiout, "reason",
8856            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
8857       break;
8858     default:
8859       internal_error (__FILE__, __LINE__,
8860                       _("Invalid hardware watchpoint type."));
8861     }
8862
8863   mention (b);
8864   ui_out_text (uiout, _("\n\
8865 Check the underlying instruction at PC for the memory\n\
8866 address and value which triggered this watchpoint.\n"));
8867   ui_out_text (uiout, "\n");
8868
8869   /* More than one watchpoint may have been triggered.  */
8870   return PRINT_UNKNOWN;
8871 }
8872
8873 /* Implement the "print_one_detail" breakpoint_ops method for
8874    masked hardware watchpoints.  */
8875
8876 static void
8877 print_one_detail_masked_watchpoint (const struct breakpoint *b,
8878                                     struct ui_out *uiout)
8879 {
8880   struct watchpoint *w = (struct watchpoint *) b;
8881
8882   /* Masked watchpoints have only one location.  */
8883   gdb_assert (b->loc && b->loc->next == NULL);
8884
8885   ui_out_text (uiout, "\tmask ");
8886   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
8887   ui_out_text (uiout, "\n");
8888 }
8889
8890 /* Implement the "print_mention" breakpoint_ops method for
8891    masked hardware watchpoints.  */
8892
8893 static void
8894 print_mention_masked_watchpoint (struct breakpoint *b)
8895 {
8896   struct watchpoint *w = (struct watchpoint *) b;
8897   struct ui_out *uiout = current_uiout;
8898   struct cleanup *ui_out_chain;
8899
8900   switch (b->type)
8901     {
8902     case bp_hardware_watchpoint:
8903       ui_out_text (uiout, "Masked hardware watchpoint ");
8904       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
8905       break;
8906     case bp_read_watchpoint:
8907       ui_out_text (uiout, "Masked hardware read watchpoint ");
8908       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
8909       break;
8910     case bp_access_watchpoint:
8911       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
8912       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
8913       break;
8914     default:
8915       internal_error (__FILE__, __LINE__,
8916                       _("Invalid hardware watchpoint type."));
8917     }
8918
8919   ui_out_field_int (uiout, "number", b->number);
8920   ui_out_text (uiout, ": ");
8921   ui_out_field_string (uiout, "exp", w->exp_string);
8922   do_cleanups (ui_out_chain);
8923 }
8924
8925 /* Implement the "print_recreate" breakpoint_ops method for
8926    masked hardware watchpoints.  */
8927
8928 static void
8929 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
8930 {
8931   struct watchpoint *w = (struct watchpoint *) b;
8932   char tmp[40];
8933
8934   switch (b->type)
8935     {
8936     case bp_hardware_watchpoint:
8937       fprintf_unfiltered (fp, "watch");
8938       break;
8939     case bp_read_watchpoint:
8940       fprintf_unfiltered (fp, "rwatch");
8941       break;
8942     case bp_access_watchpoint:
8943       fprintf_unfiltered (fp, "awatch");
8944       break;
8945     default:
8946       internal_error (__FILE__, __LINE__,
8947                       _("Invalid hardware watchpoint type."));
8948     }
8949
8950   sprintf_vma (tmp, w->hw_wp_mask);
8951   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
8952   print_recreate_thread (b, fp);
8953 }
8954
8955 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
8956
8957 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
8958
8959 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
8960
8961 static int
8962 is_masked_watchpoint (const struct breakpoint *b)
8963 {
8964   return b->ops == &masked_watchpoint_breakpoint_ops;
8965 }
8966
8967 /* accessflag:  hw_write:  watch write, 
8968                 hw_read:   watch read, 
8969                 hw_access: watch access (read or write) */
8970 static void
8971 watch_command_1 (char *arg, int accessflag, int from_tty,
8972                  int just_location, int internal)
8973 {
8974   volatile struct gdb_exception e;
8975   struct breakpoint *b, *scope_breakpoint = NULL;
8976   struct expression *exp;
8977   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
8978   struct value *val, *mark, *result;
8979   struct frame_info *frame;
8980   char *exp_start = NULL;
8981   char *exp_end = NULL;
8982   char *tok, *end_tok;
8983   int toklen = -1;
8984   char *cond_start = NULL;
8985   char *cond_end = NULL;
8986   enum bptype bp_type;
8987   int thread = -1;
8988   int pc = 0;
8989   /* Flag to indicate whether we are going to use masks for
8990      the hardware watchpoint.  */
8991   int use_mask = 0;
8992   CORE_ADDR mask = 0;
8993   struct watchpoint *w;
8994
8995   /* Make sure that we actually have parameters to parse.  */
8996   if (arg != NULL && arg[0] != '\0')
8997     {
8998       char *value_start;
8999
9000       /* Look for "parameter value" pairs at the end
9001          of the arguments string.  */
9002       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
9003         {
9004           /* Skip whitespace at the end of the argument list.  */
9005           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9006             tok--;
9007
9008           /* Find the beginning of the last token.
9009              This is the value of the parameter.  */
9010           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9011             tok--;
9012           value_start = tok + 1;
9013
9014           /* Skip whitespace.  */
9015           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9016             tok--;
9017
9018           end_tok = tok;
9019
9020           /* Find the beginning of the second to last token.
9021              This is the parameter itself.  */
9022           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9023             tok--;
9024           tok++;
9025           toklen = end_tok - tok + 1;
9026
9027           if (toklen == 6 && !strncmp (tok, "thread", 6))
9028             {
9029               /* At this point we've found a "thread" token, which means
9030                  the user is trying to set a watchpoint that triggers
9031                  only in a specific thread.  */
9032               char *endp;
9033
9034               if (thread != -1)
9035                 error(_("You can specify only one thread."));
9036
9037               /* Extract the thread ID from the next token.  */
9038               thread = strtol (value_start, &endp, 0);
9039
9040               /* Check if the user provided a valid numeric value for the
9041                  thread ID.  */
9042               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
9043                 error (_("Invalid thread ID specification %s."), value_start);
9044
9045               /* Check if the thread actually exists.  */
9046               if (!valid_thread_id (thread))
9047                 error (_("Unknown thread %d."), thread);
9048             }
9049           else if (toklen == 4 && !strncmp (tok, "mask", 4))
9050             {
9051               /* We've found a "mask" token, which means the user wants to
9052                  create a hardware watchpoint that is going to have the mask
9053                  facility.  */
9054               struct value *mask_value, *mark;
9055
9056               if (use_mask)
9057                 error(_("You can specify only one mask."));
9058
9059               use_mask = just_location = 1;
9060
9061               mark = value_mark ();
9062               mask_value = parse_to_comma_and_eval (&value_start);
9063               mask = value_as_address (mask_value);
9064               value_free_to_mark (mark);
9065             }
9066           else
9067             /* We didn't recognize what we found.  We should stop here.  */
9068             break;
9069
9070           /* Truncate the string and get rid of the "parameter value" pair before
9071              the arguments string is parsed by the parse_exp_1 function.  */
9072           *tok = '\0';
9073         }
9074     }
9075
9076   /* Parse the rest of the arguments.  */
9077   innermost_block = NULL;
9078   exp_start = arg;
9079   exp = parse_exp_1 (&arg, 0, 0);
9080   exp_end = arg;
9081   /* Remove trailing whitespace from the expression before saving it.
9082      This makes the eventual display of the expression string a bit
9083      prettier.  */
9084   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
9085     --exp_end;
9086
9087   /* Checking if the expression is not constant.  */
9088   if (watchpoint_exp_is_const (exp))
9089     {
9090       int len;
9091
9092       len = exp_end - exp_start;
9093       while (len > 0 && isspace (exp_start[len - 1]))
9094         len--;
9095       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
9096     }
9097
9098   exp_valid_block = innermost_block;
9099   mark = value_mark ();
9100   fetch_subexp_value (exp, &pc, &val, &result, NULL);
9101
9102   if (just_location)
9103     {
9104       int ret;
9105
9106       exp_valid_block = NULL;
9107       val = value_addr (result);
9108       release_value (val);
9109       value_free_to_mark (mark);
9110
9111       if (use_mask)
9112         {
9113           ret = target_masked_watch_num_registers (value_as_address (val),
9114                                                    mask);
9115           if (ret == -1)
9116             error (_("This target does not support masked watchpoints."));
9117           else if (ret == -2)
9118             error (_("Invalid mask or memory region."));
9119         }
9120     }
9121   else if (val != NULL)
9122     release_value (val);
9123
9124   tok = skip_spaces (arg);
9125   end_tok = skip_to_space (tok);
9126
9127   toklen = end_tok - tok;
9128   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9129     {
9130       struct expression *cond;
9131
9132       innermost_block = NULL;
9133       tok = cond_start = end_tok + 1;
9134       cond = parse_exp_1 (&tok, 0, 0);
9135
9136       /* The watchpoint expression may not be local, but the condition
9137          may still be.  E.g.: `watch global if local > 0'.  */
9138       cond_exp_valid_block = innermost_block;
9139
9140       xfree (cond);
9141       cond_end = tok;
9142     }
9143   if (*tok)
9144     error (_("Junk at end of command."));
9145
9146   if (accessflag == hw_read)
9147     bp_type = bp_read_watchpoint;
9148   else if (accessflag == hw_access)
9149     bp_type = bp_access_watchpoint;
9150   else
9151     bp_type = bp_hardware_watchpoint;
9152
9153   frame = block_innermost_frame (exp_valid_block);
9154
9155   /* If the expression is "local", then set up a "watchpoint scope"
9156      breakpoint at the point where we've left the scope of the watchpoint
9157      expression.  Create the scope breakpoint before the watchpoint, so
9158      that we will encounter it first in bpstat_stop_status.  */
9159   if (exp_valid_block && frame)
9160     {
9161       if (frame_id_p (frame_unwind_caller_id (frame)))
9162         {
9163           scope_breakpoint
9164             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
9165                                           frame_unwind_caller_pc (frame),
9166                                           bp_watchpoint_scope,
9167                                           &momentary_breakpoint_ops);
9168
9169           scope_breakpoint->enable_state = bp_enabled;
9170
9171           /* Automatically delete the breakpoint when it hits.  */
9172           scope_breakpoint->disposition = disp_del;
9173
9174           /* Only break in the proper frame (help with recursion).  */
9175           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
9176
9177           /* Set the address at which we will stop.  */
9178           scope_breakpoint->loc->gdbarch
9179             = frame_unwind_caller_arch (frame);
9180           scope_breakpoint->loc->requested_address
9181             = frame_unwind_caller_pc (frame);
9182           scope_breakpoint->loc->address
9183             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
9184                                          scope_breakpoint->loc->requested_address,
9185                                          scope_breakpoint->type);
9186         }
9187     }
9188
9189   /* Now set up the breakpoint.  */
9190
9191   w = XCNEW (struct watchpoint);
9192   b = &w->base;
9193   if (use_mask)
9194     init_raw_breakpoint_without_location (b, NULL, bp_type,
9195                                           &masked_watchpoint_breakpoint_ops);
9196   else
9197     init_raw_breakpoint_without_location (b, NULL, bp_type,
9198                                           &watchpoint_breakpoint_ops);
9199   b->thread = thread;
9200   b->disposition = disp_donttouch;
9201   b->pspace = current_program_space;
9202   w->exp = exp;
9203   w->exp_valid_block = exp_valid_block;
9204   w->cond_exp_valid_block = cond_exp_valid_block;
9205   if (just_location)
9206     {
9207       struct type *t = value_type (val);
9208       CORE_ADDR addr = value_as_address (val);
9209       char *name;
9210
9211       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
9212       name = type_to_string (t);
9213
9214       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
9215                                           core_addr_to_string (addr));
9216       xfree (name);
9217
9218       w->exp_string = xstrprintf ("-location %.*s",
9219                                   (int) (exp_end - exp_start), exp_start);
9220
9221       /* The above expression is in C.  */
9222       b->language = language_c;
9223     }
9224   else
9225     w->exp_string = savestring (exp_start, exp_end - exp_start);
9226
9227   if (use_mask)
9228     {
9229       w->hw_wp_mask = mask;
9230     }
9231   else
9232     {
9233       w->val = val;
9234       w->val_valid = 1;
9235     }
9236
9237   if (cond_start)
9238     b->cond_string = savestring (cond_start, cond_end - cond_start);
9239   else
9240     b->cond_string = 0;
9241
9242   if (frame)
9243     {
9244       w->watchpoint_frame = get_frame_id (frame);
9245       w->watchpoint_thread = inferior_ptid;
9246     }
9247   else
9248     {
9249       w->watchpoint_frame = null_frame_id;
9250       w->watchpoint_thread = null_ptid;
9251     }
9252
9253   if (scope_breakpoint != NULL)
9254     {
9255       /* The scope breakpoint is related to the watchpoint.  We will
9256          need to act on them together.  */
9257       b->related_breakpoint = scope_breakpoint;
9258       scope_breakpoint->related_breakpoint = b;
9259     }
9260
9261   if (!just_location)
9262     value_free_to_mark (mark);
9263
9264   TRY_CATCH (e, RETURN_MASK_ALL)
9265     {
9266       /* Finally update the new watchpoint.  This creates the locations
9267          that should be inserted.  */
9268       update_watchpoint (w, 1);
9269     }
9270   if (e.reason < 0)
9271     {
9272       delete_breakpoint (b);
9273       throw_exception (e);
9274     }
9275
9276   install_breakpoint (internal, b, 1);
9277 }
9278
9279 /* Return count of debug registers needed to watch the given expression.
9280    If the watchpoint cannot be handled in hardware return zero.  */
9281
9282 static int
9283 can_use_hardware_watchpoint (struct value *v)
9284 {
9285   int found_memory_cnt = 0;
9286   struct value *head = v;
9287
9288   /* Did the user specifically forbid us to use hardware watchpoints? */
9289   if (!can_use_hw_watchpoints)
9290     return 0;
9291
9292   /* Make sure that the value of the expression depends only upon
9293      memory contents, and values computed from them within GDB.  If we
9294      find any register references or function calls, we can't use a
9295      hardware watchpoint.
9296
9297      The idea here is that evaluating an expression generates a series
9298      of values, one holding the value of every subexpression.  (The
9299      expression a*b+c has five subexpressions: a, b, a*b, c, and
9300      a*b+c.)  GDB's values hold almost enough information to establish
9301      the criteria given above --- they identify memory lvalues,
9302      register lvalues, computed values, etcetera.  So we can evaluate
9303      the expression, and then scan the chain of values that leaves
9304      behind to decide whether we can detect any possible change to the
9305      expression's final value using only hardware watchpoints.
9306
9307      However, I don't think that the values returned by inferior
9308      function calls are special in any way.  So this function may not
9309      notice that an expression involving an inferior function call
9310      can't be watched with hardware watchpoints.  FIXME.  */
9311   for (; v; v = value_next (v))
9312     {
9313       if (VALUE_LVAL (v) == lval_memory)
9314         {
9315           if (v != head && value_lazy (v))
9316             /* A lazy memory lvalue in the chain is one that GDB never
9317                needed to fetch; we either just used its address (e.g.,
9318                `a' in `a.b') or we never needed it at all (e.g., `a'
9319                in `a,b').  This doesn't apply to HEAD; if that is
9320                lazy then it was not readable, but watch it anyway.  */
9321             ;
9322           else
9323             {
9324               /* Ahh, memory we actually used!  Check if we can cover
9325                  it with hardware watchpoints.  */
9326               struct type *vtype = check_typedef (value_type (v));
9327
9328               /* We only watch structs and arrays if user asked for it
9329                  explicitly, never if they just happen to appear in a
9330                  middle of some value chain.  */
9331               if (v == head
9332                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
9333                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
9334                 {
9335                   CORE_ADDR vaddr = value_address (v);
9336                   int len;
9337                   int num_regs;
9338
9339                   len = (target_exact_watchpoints
9340                          && is_scalar_type_recursive (vtype))?
9341                     1 : TYPE_LENGTH (value_type (v));
9342
9343                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
9344                   if (!num_regs)
9345                     return 0;
9346                   else
9347                     found_memory_cnt += num_regs;
9348                 }
9349             }
9350         }
9351       else if (VALUE_LVAL (v) != not_lval
9352                && deprecated_value_modifiable (v) == 0)
9353         return 0;       /* These are values from the history (e.g., $1).  */
9354       else if (VALUE_LVAL (v) == lval_register)
9355         return 0;       /* Cannot watch a register with a HW watchpoint.  */
9356     }
9357
9358   /* The expression itself looks suitable for using a hardware
9359      watchpoint, but give the target machine a chance to reject it.  */
9360   return found_memory_cnt;
9361 }
9362
9363 void
9364 watch_command_wrapper (char *arg, int from_tty, int internal)
9365 {
9366   watch_command_1 (arg, hw_write, from_tty, 0, internal);
9367 }
9368
9369 /* A helper function that looks for an argument at the start of a
9370    string.  The argument must also either be at the end of the string,
9371    or be followed by whitespace.  Returns 1 if it finds the argument,
9372    0 otherwise.  If the argument is found, it updates *STR.  */
9373
9374 static int
9375 check_for_argument (char **str, char *arg, int arg_len)
9376 {
9377   if (strncmp (*str, arg, arg_len) == 0
9378       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
9379     {
9380       *str += arg_len;
9381       return 1;
9382     }
9383   return 0;
9384 }
9385
9386 /* A helper function that looks for the "-location" argument and then
9387    calls watch_command_1.  */
9388
9389 static void
9390 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
9391 {
9392   int just_location = 0;
9393
9394   if (arg
9395       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
9396           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
9397     {
9398       arg = skip_spaces (arg);
9399       just_location = 1;
9400     }
9401
9402   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
9403 }
9404
9405 static void
9406 watch_command (char *arg, int from_tty)
9407 {
9408   watch_maybe_just_location (arg, hw_write, from_tty);
9409 }
9410
9411 void
9412 rwatch_command_wrapper (char *arg, int from_tty, int internal)
9413 {
9414   watch_command_1 (arg, hw_read, from_tty, 0, internal);
9415 }
9416
9417 static void
9418 rwatch_command (char *arg, int from_tty)
9419 {
9420   watch_maybe_just_location (arg, hw_read, from_tty);
9421 }
9422
9423 void
9424 awatch_command_wrapper (char *arg, int from_tty, int internal)
9425 {
9426   watch_command_1 (arg, hw_access, from_tty, 0, internal);
9427 }
9428
9429 static void
9430 awatch_command (char *arg, int from_tty)
9431 {
9432   watch_maybe_just_location (arg, hw_access, from_tty);
9433 }
9434 \f
9435
9436 /* Helper routines for the until_command routine in infcmd.c.  Here
9437    because it uses the mechanisms of breakpoints.  */
9438
9439 struct until_break_command_continuation_args
9440 {
9441   struct breakpoint *breakpoint;
9442   struct breakpoint *breakpoint2;
9443   int thread_num;
9444 };
9445
9446 /* This function is called by fetch_inferior_event via the
9447    cmd_continuation pointer, to complete the until command.  It takes
9448    care of cleaning up the temporary breakpoints set up by the until
9449    command.  */
9450 static void
9451 until_break_command_continuation (void *arg, int err)
9452 {
9453   struct until_break_command_continuation_args *a = arg;
9454
9455   delete_breakpoint (a->breakpoint);
9456   if (a->breakpoint2)
9457     delete_breakpoint (a->breakpoint2);
9458   delete_longjmp_breakpoint (a->thread_num);
9459 }
9460
9461 void
9462 until_break_command (char *arg, int from_tty, int anywhere)
9463 {
9464   struct symtabs_and_lines sals;
9465   struct symtab_and_line sal;
9466   struct frame_info *frame = get_selected_frame (NULL);
9467   struct breakpoint *breakpoint;
9468   struct breakpoint *breakpoint2 = NULL;
9469   struct cleanup *old_chain;
9470   int thread;
9471   struct thread_info *tp;
9472
9473   clear_proceed_status ();
9474
9475   /* Set a breakpoint where the user wants it and at return from
9476      this function.  */
9477
9478   if (last_displayed_sal_is_valid ())
9479     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
9480                           get_last_displayed_symtab (),
9481                           get_last_displayed_line ());
9482   else
9483     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
9484                           (struct symtab *) NULL, 0);
9485
9486   if (sals.nelts != 1)
9487     error (_("Couldn't get information on specified line."));
9488
9489   sal = sals.sals[0];
9490   xfree (sals.sals);    /* malloc'd, so freed.  */
9491
9492   if (*arg)
9493     error (_("Junk at end of arguments."));
9494
9495   resolve_sal_pc (&sal);
9496
9497   if (anywhere)
9498     /* If the user told us to continue until a specified location,
9499        we don't specify a frame at which we need to stop.  */
9500     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
9501                                            null_frame_id, bp_until);
9502   else
9503     /* Otherwise, specify the selected frame, because we want to stop
9504        only at the very same frame.  */
9505     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
9506                                            get_stack_frame_id (frame),
9507                                            bp_until);
9508
9509   old_chain = make_cleanup_delete_breakpoint (breakpoint);
9510
9511   tp = inferior_thread ();
9512   thread = tp->num;
9513
9514   /* Keep within the current frame, or in frames called by the current
9515      one.  */
9516
9517   if (frame_id_p (frame_unwind_caller_id (frame)))
9518     {
9519       sal = find_pc_line (frame_unwind_caller_pc (frame), 0);
9520       sal.pc = frame_unwind_caller_pc (frame);
9521       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
9522                                               sal,
9523                                               frame_unwind_caller_id (frame),
9524                                               bp_until);
9525       make_cleanup_delete_breakpoint (breakpoint2);
9526
9527       set_longjmp_breakpoint (tp, frame_unwind_caller_id (frame));
9528       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
9529     }
9530
9531   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
9532
9533   /* If we are running asynchronously, and proceed call above has
9534      actually managed to start the target, arrange for breakpoints to
9535      be deleted when the target stops.  Otherwise, we're already
9536      stopped and delete breakpoints via cleanup chain.  */
9537
9538   if (target_can_async_p () && is_running (inferior_ptid))
9539     {
9540       struct until_break_command_continuation_args *args;
9541       args = xmalloc (sizeof (*args));
9542
9543       args->breakpoint = breakpoint;
9544       args->breakpoint2 = breakpoint2;
9545       args->thread_num = thread;
9546
9547       discard_cleanups (old_chain);
9548       add_continuation (inferior_thread (),
9549                         until_break_command_continuation, args,
9550                         xfree);
9551     }
9552   else
9553     do_cleanups (old_chain);
9554 }
9555
9556 /* This function attempts to parse an optional "if <cond>" clause
9557    from the arg string.  If one is not found, it returns NULL.
9558
9559    Else, it returns a pointer to the condition string.  (It does not
9560    attempt to evaluate the string against a particular block.)  And,
9561    it updates arg to point to the first character following the parsed
9562    if clause in the arg string.  */
9563
9564 static char *
9565 ep_parse_optional_if_clause (char **arg)
9566 {
9567   char *cond_string;
9568
9569   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
9570     return NULL;
9571
9572   /* Skip the "if" keyword.  */
9573   (*arg) += 2;
9574
9575   /* Skip any extra leading whitespace, and record the start of the
9576      condition string.  */
9577   *arg = skip_spaces (*arg);
9578   cond_string = *arg;
9579
9580   /* Assume that the condition occupies the remainder of the arg
9581      string.  */
9582   (*arg) += strlen (cond_string);
9583
9584   return cond_string;
9585 }
9586
9587 /* Commands to deal with catching events, such as signals, exceptions,
9588    process start/exit, etc.  */
9589
9590 typedef enum
9591 {
9592   catch_fork_temporary, catch_vfork_temporary,
9593   catch_fork_permanent, catch_vfork_permanent
9594 }
9595 catch_fork_kind;
9596
9597 static void
9598 catch_fork_command_1 (char *arg, int from_tty, 
9599                       struct cmd_list_element *command)
9600 {
9601   struct gdbarch *gdbarch = get_current_arch ();
9602   char *cond_string = NULL;
9603   catch_fork_kind fork_kind;
9604   int tempflag;
9605
9606   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
9607   tempflag = (fork_kind == catch_fork_temporary
9608               || fork_kind == catch_vfork_temporary);
9609
9610   if (!arg)
9611     arg = "";
9612   arg = skip_spaces (arg);
9613
9614   /* The allowed syntax is:
9615      catch [v]fork
9616      catch [v]fork if <cond>
9617
9618      First, check if there's an if clause.  */
9619   cond_string = ep_parse_optional_if_clause (&arg);
9620
9621   if ((*arg != '\0') && !isspace (*arg))
9622     error (_("Junk at end of arguments."));
9623
9624   /* If this target supports it, create a fork or vfork catchpoint
9625      and enable reporting of such events.  */
9626   switch (fork_kind)
9627     {
9628     case catch_fork_temporary:
9629     case catch_fork_permanent:
9630       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
9631                                           &catch_fork_breakpoint_ops);
9632       break;
9633     case catch_vfork_temporary:
9634     case catch_vfork_permanent:
9635       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
9636                                           &catch_vfork_breakpoint_ops);
9637       break;
9638     default:
9639       error (_("unsupported or unknown fork kind; cannot catch it"));
9640       break;
9641     }
9642 }
9643
9644 static void
9645 catch_exec_command_1 (char *arg, int from_tty, 
9646                       struct cmd_list_element *command)
9647 {
9648   struct exec_catchpoint *c;
9649   struct gdbarch *gdbarch = get_current_arch ();
9650   int tempflag;
9651   char *cond_string = NULL;
9652
9653   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
9654
9655   if (!arg)
9656     arg = "";
9657   arg = skip_spaces (arg);
9658
9659   /* The allowed syntax is:
9660      catch exec
9661      catch exec if <cond>
9662
9663      First, check if there's an if clause.  */
9664   cond_string = ep_parse_optional_if_clause (&arg);
9665
9666   if ((*arg != '\0') && !isspace (*arg))
9667     error (_("Junk at end of arguments."));
9668
9669   c = XNEW (struct exec_catchpoint);
9670   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
9671                    &catch_exec_breakpoint_ops);
9672   c->exec_pathname = NULL;
9673
9674   install_breakpoint (0, &c->base, 1);
9675 }
9676
9677 static enum print_stop_action
9678 print_it_exception_catchpoint (bpstat bs)
9679 {
9680   struct ui_out *uiout = current_uiout;
9681   struct breakpoint *b = bs->breakpoint_at;
9682   int bp_temp, bp_throw;
9683
9684   annotate_catchpoint (b->number);
9685
9686   bp_throw = strstr (b->addr_string, "throw") != NULL;
9687   if (b->loc->address != b->loc->requested_address)
9688     breakpoint_adjustment_warning (b->loc->requested_address,
9689                                    b->loc->address,
9690                                    b->number, 1);
9691   bp_temp = b->disposition == disp_del;
9692   ui_out_text (uiout, 
9693                bp_temp ? "Temporary catchpoint "
9694                        : "Catchpoint ");
9695   if (!ui_out_is_mi_like_p (uiout))
9696     ui_out_field_int (uiout, "bkptno", b->number);
9697   ui_out_text (uiout,
9698                bp_throw ? " (exception thrown), "
9699                         : " (exception caught), ");
9700   if (ui_out_is_mi_like_p (uiout))
9701     {
9702       ui_out_field_string (uiout, "reason", 
9703                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9704       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9705       ui_out_field_int (uiout, "bkptno", b->number);
9706     }
9707   return PRINT_SRC_AND_LOC;
9708 }
9709
9710 static void
9711 print_one_exception_catchpoint (struct breakpoint *b, 
9712                                 struct bp_location **last_loc)
9713 {
9714   struct value_print_options opts;
9715   struct ui_out *uiout = current_uiout;
9716
9717   get_user_print_options (&opts);
9718   if (opts.addressprint)
9719     {
9720       annotate_field (4);
9721       if (b->loc == NULL || b->loc->shlib_disabled)
9722         ui_out_field_string (uiout, "addr", "<PENDING>");
9723       else
9724         ui_out_field_core_addr (uiout, "addr",
9725                                 b->loc->gdbarch, b->loc->address);
9726     }
9727   annotate_field (5);
9728   if (b->loc)
9729     *last_loc = b->loc;
9730   if (strstr (b->addr_string, "throw") != NULL)
9731     ui_out_field_string (uiout, "what", "exception throw");
9732   else
9733     ui_out_field_string (uiout, "what", "exception catch");
9734 }
9735
9736 static void
9737 print_mention_exception_catchpoint (struct breakpoint *b)
9738 {
9739   struct ui_out *uiout = current_uiout;
9740   int bp_temp;
9741   int bp_throw;
9742
9743   bp_temp = b->disposition == disp_del;
9744   bp_throw = strstr (b->addr_string, "throw") != NULL;
9745   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
9746                               : _("Catchpoint "));
9747   ui_out_field_int (uiout, "bkptno", b->number);
9748   ui_out_text (uiout, bp_throw ? _(" (throw)")
9749                                : _(" (catch)"));
9750 }
9751
9752 /* Implement the "print_recreate" breakpoint_ops method for throw and
9753    catch catchpoints.  */
9754
9755 static void
9756 print_recreate_exception_catchpoint (struct breakpoint *b, 
9757                                      struct ui_file *fp)
9758 {
9759   int bp_temp;
9760   int bp_throw;
9761
9762   bp_temp = b->disposition == disp_del;
9763   bp_throw = strstr (b->addr_string, "throw") != NULL;
9764   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
9765   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
9766   print_recreate_thread (b, fp);
9767 }
9768
9769 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
9770
9771 static int
9772 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
9773                           enum exception_event_kind ex_event, int from_tty)
9774 {
9775   char *trigger_func_name;
9776  
9777   if (ex_event == EX_EVENT_CATCH)
9778     trigger_func_name = "__cxa_begin_catch";
9779   else
9780     trigger_func_name = "__cxa_throw";
9781
9782   create_breakpoint (get_current_arch (),
9783                      trigger_func_name, cond_string, -1,
9784                      0 /* condition and thread are valid.  */,
9785                      tempflag, bp_breakpoint,
9786                      0,
9787                      AUTO_BOOLEAN_TRUE /* pending */,
9788                      &gnu_v3_exception_catchpoint_ops, from_tty,
9789                      1 /* enabled */,
9790                      0 /* internal */);
9791
9792   return 1;
9793 }
9794
9795 /* Deal with "catch catch" and "catch throw" commands.  */
9796
9797 static void
9798 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
9799                            int tempflag, int from_tty)
9800 {
9801   char *cond_string = NULL;
9802
9803   if (!arg)
9804     arg = "";
9805   arg = skip_spaces (arg);
9806
9807   cond_string = ep_parse_optional_if_clause (&arg);
9808
9809   if ((*arg != '\0') && !isspace (*arg))
9810     error (_("Junk at end of arguments."));
9811
9812   if (ex_event != EX_EVENT_THROW
9813       && ex_event != EX_EVENT_CATCH)
9814     error (_("Unsupported or unknown exception event; cannot catch it"));
9815
9816   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
9817     return;
9818
9819   warning (_("Unsupported with this platform/compiler combination."));
9820 }
9821
9822 /* Implementation of "catch catch" command.  */
9823
9824 static void
9825 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
9826 {
9827   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
9828
9829   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
9830 }
9831
9832 /* Implementation of "catch throw" command.  */
9833
9834 static void
9835 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
9836 {
9837   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
9838
9839   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
9840 }
9841
9842 void
9843 init_ada_exception_breakpoint (struct breakpoint *b,
9844                                struct gdbarch *gdbarch,
9845                                struct symtab_and_line sal,
9846                                char *addr_string,
9847                                const struct breakpoint_ops *ops,
9848                                int tempflag,
9849                                int from_tty)
9850 {
9851   if (from_tty)
9852     {
9853       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9854       if (!loc_gdbarch)
9855         loc_gdbarch = gdbarch;
9856
9857       describe_other_breakpoints (loc_gdbarch,
9858                                   sal.pspace, sal.pc, sal.section, -1);
9859       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
9860          version for exception catchpoints, because two catchpoints
9861          used for different exception names will use the same address.
9862          In this case, a "breakpoint ... also set at..." warning is
9863          unproductive.  Besides, the warning phrasing is also a bit
9864          inappropriate, we should use the word catchpoint, and tell
9865          the user what type of catchpoint it is.  The above is good
9866          enough for now, though.  */
9867     }
9868
9869   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
9870
9871   b->enable_state = bp_enabled;
9872   b->disposition = tempflag ? disp_del : disp_donttouch;
9873   b->addr_string = addr_string;
9874   b->language = language_ada;
9875 }
9876
9877 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
9878    filter list, or NULL if no filtering is required.  */
9879 static VEC(int) *
9880 catch_syscall_split_args (char *arg)
9881 {
9882   VEC(int) *result = NULL;
9883   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
9884
9885   while (*arg != '\0')
9886     {
9887       int i, syscall_number;
9888       char *endptr;
9889       char cur_name[128];
9890       struct syscall s;
9891
9892       /* Skip whitespace.  */
9893       while (isspace (*arg))
9894         arg++;
9895
9896       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
9897         cur_name[i] = arg[i];
9898       cur_name[i] = '\0';
9899       arg += i;
9900
9901       /* Check if the user provided a syscall name or a number.  */
9902       syscall_number = (int) strtol (cur_name, &endptr, 0);
9903       if (*endptr == '\0')
9904         get_syscall_by_number (syscall_number, &s);
9905       else
9906         {
9907           /* We have a name.  Let's check if it's valid and convert it
9908              to a number.  */
9909           get_syscall_by_name (cur_name, &s);
9910
9911           if (s.number == UNKNOWN_SYSCALL)
9912             /* Here we have to issue an error instead of a warning,
9913                because GDB cannot do anything useful if there's no
9914                syscall number to be caught.  */
9915             error (_("Unknown syscall name '%s'."), cur_name);
9916         }
9917
9918       /* Ok, it's valid.  */
9919       VEC_safe_push (int, result, s.number);
9920     }
9921
9922   discard_cleanups (cleanup);
9923   return result;
9924 }
9925
9926 /* Implement the "catch syscall" command.  */
9927
9928 static void
9929 catch_syscall_command_1 (char *arg, int from_tty, 
9930                          struct cmd_list_element *command)
9931 {
9932   int tempflag;
9933   VEC(int) *filter;
9934   struct syscall s;
9935   struct gdbarch *gdbarch = get_current_arch ();
9936
9937   /* Checking if the feature if supported.  */
9938   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
9939     error (_("The feature 'catch syscall' is not supported on \
9940 this architecture yet."));
9941
9942   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
9943
9944   arg = skip_spaces (arg);
9945
9946   /* We need to do this first "dummy" translation in order
9947      to get the syscall XML file loaded or, most important,
9948      to display a warning to the user if there's no XML file
9949      for his/her architecture.  */
9950   get_syscall_by_number (0, &s);
9951
9952   /* The allowed syntax is:
9953      catch syscall
9954      catch syscall <name | number> [<name | number> ... <name | number>]
9955
9956      Let's check if there's a syscall name.  */
9957
9958   if (arg != NULL)
9959     filter = catch_syscall_split_args (arg);
9960   else
9961     filter = NULL;
9962
9963   create_syscall_event_catchpoint (tempflag, filter,
9964                                    &catch_syscall_breakpoint_ops);
9965 }
9966
9967 static void
9968 catch_command (char *arg, int from_tty)
9969 {
9970   error (_("Catch requires an event name."));
9971 }
9972 \f
9973
9974 static void
9975 tcatch_command (char *arg, int from_tty)
9976 {
9977   error (_("Catch requires an event name."));
9978 }
9979
9980 /* A qsort comparison function that sorts breakpoints in order.  */
9981
9982 static int
9983 compare_breakpoints (const void *a, const void *b)
9984 {
9985   const breakpoint_p *ba = a;
9986   uintptr_t ua = (uintptr_t) *ba;
9987   const breakpoint_p *bb = b;
9988   uintptr_t ub = (uintptr_t) *bb;
9989
9990   if ((*ba)->number < (*bb)->number)
9991     return -1;
9992   else if ((*ba)->number > (*bb)->number)
9993     return 1;
9994
9995   /* Now sort by address, in case we see, e..g, two breakpoints with
9996      the number 0.  */
9997   if (ua < ub)
9998     return -1;
9999   return ub > ub ? 1 : 0;
10000 }
10001
10002 /* Delete breakpoints by address or line.  */
10003
10004 static void
10005 clear_command (char *arg, int from_tty)
10006 {
10007   struct breakpoint *b, *prev;
10008   VEC(breakpoint_p) *found = 0;
10009   int ix;
10010   int default_match;
10011   struct symtabs_and_lines sals;
10012   struct symtab_and_line sal;
10013   int i;
10014   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
10015
10016   if (arg)
10017     {
10018       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
10019                                      | DECODE_LINE_LIST_MODE));
10020       default_match = 0;
10021     }
10022   else
10023     {
10024       sals.sals = (struct symtab_and_line *)
10025         xmalloc (sizeof (struct symtab_and_line));
10026       make_cleanup (xfree, sals.sals);
10027       init_sal (&sal);          /* Initialize to zeroes.  */
10028
10029       /* Set sal's line, symtab, pc, and pspace to the values
10030          corresponding to the last call to print_frame_info.  If the
10031          codepoint is not valid, this will set all the fields to 0.  */
10032       get_last_displayed_sal (&sal);
10033       if (sal.symtab == 0)
10034         error (_("No source file specified."));
10035
10036       sals.sals[0] = sal;
10037       sals.nelts = 1;
10038
10039       default_match = 1;
10040     }
10041
10042   /* We don't call resolve_sal_pc here.  That's not as bad as it
10043      seems, because all existing breakpoints typically have both
10044      file/line and pc set.  So, if clear is given file/line, we can
10045      match this to existing breakpoint without obtaining pc at all.
10046
10047      We only support clearing given the address explicitly 
10048      present in breakpoint table.  Say, we've set breakpoint 
10049      at file:line.  There were several PC values for that file:line,
10050      due to optimization, all in one block.
10051
10052      We've picked one PC value.  If "clear" is issued with another
10053      PC corresponding to the same file:line, the breakpoint won't
10054      be cleared.  We probably can still clear the breakpoint, but 
10055      since the other PC value is never presented to user, user
10056      can only find it by guessing, and it does not seem important
10057      to support that.  */
10058
10059   /* For each line spec given, delete bps which correspond to it.  Do
10060      it in two passes, solely to preserve the current behavior that
10061      from_tty is forced true if we delete more than one
10062      breakpoint.  */
10063
10064   found = NULL;
10065   make_cleanup (VEC_cleanup (breakpoint_p), &found);
10066   for (i = 0; i < sals.nelts; i++)
10067     {
10068       int is_abs, sal_name_len;
10069
10070       /* If exact pc given, clear bpts at that pc.
10071          If line given (pc == 0), clear all bpts on specified line.
10072          If defaulting, clear all bpts on default line
10073          or at default pc.
10074
10075          defaulting    sal.pc != 0    tests to do
10076
10077          0              1             pc
10078          1              1             pc _and_ line
10079          0              0             line
10080          1              0             <can't happen> */
10081
10082       sal = sals.sals[i];
10083       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
10084       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
10085
10086       /* Find all matching breakpoints and add them to 'found'.  */
10087       ALL_BREAKPOINTS (b)
10088         {
10089           int match = 0;
10090           /* Are we going to delete b?  */
10091           if (b->type != bp_none && !is_watchpoint (b))
10092             {
10093               struct bp_location *loc = b->loc;
10094               for (; loc; loc = loc->next)
10095                 {
10096                   /* If the user specified file:line, don't allow a PC
10097                      match.  This matches historical gdb behavior.  */
10098                   int pc_match = (!sal.explicit_line
10099                                   && sal.pc
10100                                   && (loc->pspace == sal.pspace)
10101                                   && (loc->address == sal.pc)
10102                                   && (!section_is_overlay (loc->section)
10103                                       || loc->section == sal.section));
10104                   int line_match = 0;
10105
10106                   if ((default_match || sal.explicit_line)
10107                       && loc->source_file != NULL
10108                       && sal.symtab != NULL
10109                       && sal.pspace == loc->pspace
10110                       && loc->line_number == sal.line)
10111                     {
10112                       if (filename_cmp (loc->source_file,
10113                                         sal.symtab->filename) == 0)
10114                         line_match = 1;
10115                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
10116                                && compare_filenames_for_search (loc->source_file,
10117                                                                 sal.symtab->filename,
10118                                                                 sal_name_len))
10119                         line_match = 1;
10120                     }
10121
10122                   if (pc_match || line_match)
10123                     {
10124                       match = 1;
10125                       break;
10126                     }
10127                 }
10128             }
10129
10130           if (match)
10131             VEC_safe_push(breakpoint_p, found, b);
10132         }
10133     }
10134
10135   /* Now go thru the 'found' chain and delete them.  */
10136   if (VEC_empty(breakpoint_p, found))
10137     {
10138       if (arg)
10139         error (_("No breakpoint at %s."), arg);
10140       else
10141         error (_("No breakpoint at this line."));
10142     }
10143
10144   /* Remove duplicates from the vec.  */
10145   qsort (VEC_address (breakpoint_p, found),
10146          VEC_length (breakpoint_p, found),
10147          sizeof (breakpoint_p),
10148          compare_breakpoints);
10149   prev = VEC_index (breakpoint_p, found, 0);
10150   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
10151     {
10152       if (b == prev)
10153         {
10154           VEC_ordered_remove (breakpoint_p, found, ix);
10155           --ix;
10156         }
10157     }
10158
10159   if (VEC_length(breakpoint_p, found) > 1)
10160     from_tty = 1;       /* Always report if deleted more than one.  */
10161   if (from_tty)
10162     {
10163       if (VEC_length(breakpoint_p, found) == 1)
10164         printf_unfiltered (_("Deleted breakpoint "));
10165       else
10166         printf_unfiltered (_("Deleted breakpoints "));
10167     }
10168   breakpoints_changed ();
10169
10170   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
10171     {
10172       if (from_tty)
10173         printf_unfiltered ("%d ", b->number);
10174       delete_breakpoint (b);
10175     }
10176   if (from_tty)
10177     putchar_unfiltered ('\n');
10178
10179   do_cleanups (cleanups);
10180 }
10181 \f
10182 /* Delete breakpoint in BS if they are `delete' breakpoints and
10183    all breakpoints that are marked for deletion, whether hit or not.
10184    This is called after any breakpoint is hit, or after errors.  */
10185
10186 void
10187 breakpoint_auto_delete (bpstat bs)
10188 {
10189   struct breakpoint *b, *b_tmp;
10190
10191   for (; bs; bs = bs->next)
10192     if (bs->breakpoint_at
10193         && bs->breakpoint_at->disposition == disp_del
10194         && bs->stop)
10195       delete_breakpoint (bs->breakpoint_at);
10196
10197   ALL_BREAKPOINTS_SAFE (b, b_tmp)
10198   {
10199     if (b->disposition == disp_del_at_next_stop)
10200       delete_breakpoint (b);
10201   }
10202 }
10203
10204 /* A comparison function for bp_location AP and BP being interfaced to
10205    qsort.  Sort elements primarily by their ADDRESS (no matter what
10206    does breakpoint_address_is_meaningful say for its OWNER),
10207    secondarily by ordering first bp_permanent OWNERed elements and
10208    terciarily just ensuring the array is sorted stable way despite
10209    qsort being an unstable algorithm.  */
10210
10211 static int
10212 bp_location_compare (const void *ap, const void *bp)
10213 {
10214   struct bp_location *a = *(void **) ap;
10215   struct bp_location *b = *(void **) bp;
10216   /* A and B come from existing breakpoints having non-NULL OWNER.  */
10217   int a_perm = a->owner->enable_state == bp_permanent;
10218   int b_perm = b->owner->enable_state == bp_permanent;
10219
10220   if (a->address != b->address)
10221     return (a->address > b->address) - (a->address < b->address);
10222
10223   /* Sort permanent breakpoints first.  */
10224   if (a_perm != b_perm)
10225     return (a_perm < b_perm) - (a_perm > b_perm);
10226
10227   /* Make the user-visible order stable across GDB runs.  Locations of
10228      the same breakpoint can be sorted in arbitrary order.  */
10229
10230   if (a->owner->number != b->owner->number)
10231     return (a->owner->number > b->owner->number)
10232            - (a->owner->number < b->owner->number);
10233
10234   return (a > b) - (a < b);
10235 }
10236
10237 /* Set bp_location_placed_address_before_address_max and
10238    bp_location_shadow_len_after_address_max according to the current
10239    content of the bp_location array.  */
10240
10241 static void
10242 bp_location_target_extensions_update (void)
10243 {
10244   struct bp_location *bl, **blp_tmp;
10245
10246   bp_location_placed_address_before_address_max = 0;
10247   bp_location_shadow_len_after_address_max = 0;
10248
10249   ALL_BP_LOCATIONS (bl, blp_tmp)
10250     {
10251       CORE_ADDR start, end, addr;
10252
10253       if (!bp_location_has_shadow (bl))
10254         continue;
10255
10256       start = bl->target_info.placed_address;
10257       end = start + bl->target_info.shadow_len;
10258
10259       gdb_assert (bl->address >= start);
10260       addr = bl->address - start;
10261       if (addr > bp_location_placed_address_before_address_max)
10262         bp_location_placed_address_before_address_max = addr;
10263
10264       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
10265
10266       gdb_assert (bl->address < end);
10267       addr = end - bl->address;
10268       if (addr > bp_location_shadow_len_after_address_max)
10269         bp_location_shadow_len_after_address_max = addr;
10270     }
10271 }
10272
10273 /* Download tracepoint locations if they haven't been.  */
10274
10275 static void
10276 download_tracepoint_locations (void)
10277 {
10278   struct bp_location *bl, **blp_tmp;
10279   struct cleanup *old_chain;
10280
10281   if (!target_can_download_tracepoint ())
10282     return;
10283
10284   old_chain = save_current_space_and_thread ();
10285
10286   ALL_BP_LOCATIONS (bl, blp_tmp)
10287     {
10288       struct tracepoint *t;
10289
10290       if (!is_tracepoint (bl->owner))
10291         continue;
10292
10293       if ((bl->owner->type == bp_fast_tracepoint
10294            ? !may_insert_fast_tracepoints
10295            : !may_insert_tracepoints))
10296         continue;
10297
10298       /* In tracepoint, locations are _never_ duplicated, so
10299          should_be_inserted is equivalent to
10300          unduplicated_should_be_inserted.  */
10301       if (!should_be_inserted (bl) || bl->inserted)
10302         continue;
10303
10304       switch_to_program_space_and_thread (bl->pspace);
10305
10306       target_download_tracepoint (bl);
10307
10308       bl->inserted = 1;
10309       t = (struct tracepoint *) bl->owner;
10310       t->number_on_target = bl->owner->number;
10311     }
10312
10313   do_cleanups (old_chain);
10314 }
10315
10316 /* Swap the insertion/duplication state between two locations.  */
10317
10318 static void
10319 swap_insertion (struct bp_location *left, struct bp_location *right)
10320 {
10321   const int left_inserted = left->inserted;
10322   const int left_duplicate = left->duplicate;
10323   const struct bp_target_info left_target_info = left->target_info;
10324
10325   /* Locations of tracepoints can never be duplicated.  */
10326   if (is_tracepoint (left->owner))
10327     gdb_assert (!left->duplicate);
10328   if (is_tracepoint (right->owner))
10329     gdb_assert (!right->duplicate);
10330
10331   left->inserted = right->inserted;
10332   left->duplicate = right->duplicate;
10333   left->target_info = right->target_info;
10334   right->inserted = left_inserted;
10335   right->duplicate = left_duplicate;
10336   right->target_info = left_target_info;
10337 }
10338
10339 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
10340    into the inferior, only remove already-inserted locations that no
10341    longer should be inserted.  Functions that delete a breakpoint or
10342    breakpoints should pass false, so that deleting a breakpoint
10343    doesn't have the side effect of inserting the locations of other
10344    breakpoints that are marked not-inserted, but should_be_inserted
10345    returns true on them.
10346
10347    This behaviour is useful is situations close to tear-down -- e.g.,
10348    after an exec, while the target still has execution, but breakpoint
10349    shadows of the previous executable image should *NOT* be restored
10350    to the new image; or before detaching, where the target still has
10351    execution and wants to delete breakpoints from GDB's lists, and all
10352    breakpoints had already been removed from the inferior.  */
10353
10354 static void
10355 update_global_location_list (int should_insert)
10356 {
10357   struct breakpoint *b;
10358   struct bp_location **locp, *loc;
10359   struct cleanup *cleanups;
10360
10361   /* Used in the duplicates detection below.  When iterating over all
10362      bp_locations, points to the first bp_location of a given address.
10363      Breakpoints and watchpoints of different types are never
10364      duplicates of each other.  Keep one pointer for each type of
10365      breakpoint/watchpoint, so we only need to loop over all locations
10366      once.  */
10367   struct bp_location *bp_loc_first;  /* breakpoint */
10368   struct bp_location *wp_loc_first;  /* hardware watchpoint */
10369   struct bp_location *awp_loc_first; /* access watchpoint */
10370   struct bp_location *rwp_loc_first; /* read watchpoint */
10371
10372   /* Saved former bp_location array which we compare against the newly
10373      built bp_location from the current state of ALL_BREAKPOINTS.  */
10374   struct bp_location **old_location, **old_locp;
10375   unsigned old_location_count;
10376
10377   old_location = bp_location;
10378   old_location_count = bp_location_count;
10379   bp_location = NULL;
10380   bp_location_count = 0;
10381   cleanups = make_cleanup (xfree, old_location);
10382
10383   ALL_BREAKPOINTS (b)
10384     for (loc = b->loc; loc; loc = loc->next)
10385       bp_location_count++;
10386
10387   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
10388   locp = bp_location;
10389   ALL_BREAKPOINTS (b)
10390     for (loc = b->loc; loc; loc = loc->next)
10391       *locp++ = loc;
10392   qsort (bp_location, bp_location_count, sizeof (*bp_location),
10393          bp_location_compare);
10394
10395   bp_location_target_extensions_update ();
10396
10397   /* Identify bp_location instances that are no longer present in the
10398      new list, and therefore should be freed.  Note that it's not
10399      necessary that those locations should be removed from inferior --
10400      if there's another location at the same address (previously
10401      marked as duplicate), we don't need to remove/insert the
10402      location.
10403      
10404      LOCP is kept in sync with OLD_LOCP, each pointing to the current
10405      and former bp_location array state respectively.  */
10406
10407   locp = bp_location;
10408   for (old_locp = old_location; old_locp < old_location + old_location_count;
10409        old_locp++)
10410     {
10411       struct bp_location *old_loc = *old_locp;
10412       struct bp_location **loc2p;
10413
10414       /* Tells if 'old_loc' is found among the new locations.  If
10415          not, we have to free it.  */
10416       int found_object = 0;
10417       /* Tells if the location should remain inserted in the target.  */
10418       int keep_in_target = 0;
10419       int removed = 0;
10420
10421       /* Skip LOCP entries which will definitely never be needed.
10422          Stop either at or being the one matching OLD_LOC.  */
10423       while (locp < bp_location + bp_location_count
10424              && (*locp)->address < old_loc->address)
10425         locp++;
10426
10427       for (loc2p = locp;
10428            (loc2p < bp_location + bp_location_count
10429             && (*loc2p)->address == old_loc->address);
10430            loc2p++)
10431         {
10432           if (*loc2p == old_loc)
10433             {
10434               found_object = 1;
10435               break;
10436             }
10437         }
10438
10439       /* If this location is no longer present, and inserted, look if
10440          there's maybe a new location at the same address.  If so,
10441          mark that one inserted, and don't remove this one.  This is
10442          needed so that we don't have a time window where a breakpoint
10443          at certain location is not inserted.  */
10444
10445       if (old_loc->inserted)
10446         {
10447           /* If the location is inserted now, we might have to remove
10448              it.  */
10449
10450           if (found_object && should_be_inserted (old_loc))
10451             {
10452               /* The location is still present in the location list,
10453                  and still should be inserted.  Don't do anything.  */
10454               keep_in_target = 1;
10455             }
10456           else
10457             {
10458               /* The location is either no longer present, or got
10459                  disabled.  See if there's another location at the
10460                  same address, in which case we don't need to remove
10461                  this one from the target.  */
10462
10463               /* OLD_LOC comes from existing struct breakpoint.  */
10464               if (breakpoint_address_is_meaningful (old_loc->owner))
10465                 {
10466                   for (loc2p = locp;
10467                        (loc2p < bp_location + bp_location_count
10468                         && (*loc2p)->address == old_loc->address);
10469                        loc2p++)
10470                     {
10471                       struct bp_location *loc2 = *loc2p;
10472
10473                       if (breakpoint_locations_match (loc2, old_loc))
10474                         {
10475                           /* Read watchpoint locations are switched to
10476                              access watchpoints, if the former are not
10477                              supported, but the latter are.  */
10478                           if (is_hardware_watchpoint (old_loc->owner))
10479                             {
10480                               gdb_assert (is_hardware_watchpoint (loc2->owner));
10481                               loc2->watchpoint_type = old_loc->watchpoint_type;
10482                             }
10483
10484                           /* loc2 is a duplicated location. We need to check
10485                              if it should be inserted in case it will be
10486                              unduplicated.  */
10487                           if (loc2 != old_loc
10488                               && unduplicated_should_be_inserted (loc2))
10489                             {
10490                               swap_insertion (old_loc, loc2);
10491                               keep_in_target = 1;
10492                               break;
10493                             }
10494                         }
10495                     }
10496                 }
10497             }
10498
10499           if (!keep_in_target)
10500             {
10501               if (remove_breakpoint (old_loc, mark_uninserted))
10502                 {
10503                   /* This is just about all we can do.  We could keep
10504                      this location on the global list, and try to
10505                      remove it next time, but there's no particular
10506                      reason why we will succeed next time.
10507                      
10508                      Note that at this point, old_loc->owner is still
10509                      valid, as delete_breakpoint frees the breakpoint
10510                      only after calling us.  */
10511                   printf_filtered (_("warning: Error removing "
10512                                      "breakpoint %d\n"), 
10513                                    old_loc->owner->number);
10514                 }
10515               removed = 1;
10516             }
10517         }
10518
10519       if (!found_object)
10520         {
10521           if (removed && non_stop
10522               && breakpoint_address_is_meaningful (old_loc->owner)
10523               && !is_hardware_watchpoint (old_loc->owner))
10524             {
10525               /* This location was removed from the target.  In
10526                  non-stop mode, a race condition is possible where
10527                  we've removed a breakpoint, but stop events for that
10528                  breakpoint are already queued and will arrive later.
10529                  We apply an heuristic to be able to distinguish such
10530                  SIGTRAPs from other random SIGTRAPs: we keep this
10531                  breakpoint location for a bit, and will retire it
10532                  after we see some number of events.  The theory here
10533                  is that reporting of events should, "on the average",
10534                  be fair, so after a while we'll see events from all
10535                  threads that have anything of interest, and no longer
10536                  need to keep this breakpoint location around.  We
10537                  don't hold locations forever so to reduce chances of
10538                  mistaking a non-breakpoint SIGTRAP for a breakpoint
10539                  SIGTRAP.
10540
10541                  The heuristic failing can be disastrous on
10542                  decr_pc_after_break targets.
10543
10544                  On decr_pc_after_break targets, like e.g., x86-linux,
10545                  if we fail to recognize a late breakpoint SIGTRAP,
10546                  because events_till_retirement has reached 0 too
10547                  soon, we'll fail to do the PC adjustment, and report
10548                  a random SIGTRAP to the user.  When the user resumes
10549                  the inferior, it will most likely immediately crash
10550                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
10551                  corrupted, because of being resumed e.g., in the
10552                  middle of a multi-byte instruction, or skipped a
10553                  one-byte instruction.  This was actually seen happen
10554                  on native x86-linux, and should be less rare on
10555                  targets that do not support new thread events, like
10556                  remote, due to the heuristic depending on
10557                  thread_count.
10558
10559                  Mistaking a random SIGTRAP for a breakpoint trap
10560                  causes similar symptoms (PC adjustment applied when
10561                  it shouldn't), but then again, playing with SIGTRAPs
10562                  behind the debugger's back is asking for trouble.
10563
10564                  Since hardware watchpoint traps are always
10565                  distinguishable from other traps, so we don't need to
10566                  apply keep hardware watchpoint moribund locations
10567                  around.  We simply always ignore hardware watchpoint
10568                  traps we can no longer explain.  */
10569
10570               old_loc->events_till_retirement = 3 * (thread_count () + 1);
10571               old_loc->owner = NULL;
10572
10573               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
10574             }
10575           else
10576             {
10577               old_loc->owner = NULL;
10578               decref_bp_location (&old_loc);
10579             }
10580         }
10581     }
10582
10583   /* Rescan breakpoints at the same address and section, marking the
10584      first one as "first" and any others as "duplicates".  This is so
10585      that the bpt instruction is only inserted once.  If we have a
10586      permanent breakpoint at the same place as BPT, make that one the
10587      official one, and the rest as duplicates.  Permanent breakpoints
10588      are sorted first for the same address.
10589
10590      Do the same for hardware watchpoints, but also considering the
10591      watchpoint's type (regular/access/read) and length.  */
10592
10593   bp_loc_first = NULL;
10594   wp_loc_first = NULL;
10595   awp_loc_first = NULL;
10596   rwp_loc_first = NULL;
10597   ALL_BP_LOCATIONS (loc, locp)
10598     {
10599       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
10600          non-NULL.  */
10601       struct bp_location **loc_first_p;
10602       b = loc->owner;
10603
10604       if (!should_be_inserted (loc)
10605           || !breakpoint_address_is_meaningful (b)
10606           /* Don't detect duplicate for tracepoint locations because they are
10607            never duplicated.  See the comments in field `duplicate' of
10608            `struct bp_location'.  */
10609           || is_tracepoint (b))
10610         continue;
10611
10612       /* Permanent breakpoint should always be inserted.  */
10613       if (b->enable_state == bp_permanent && ! loc->inserted)
10614         internal_error (__FILE__, __LINE__,
10615                         _("allegedly permanent breakpoint is not "
10616                         "actually inserted"));
10617
10618       if (b->type == bp_hardware_watchpoint)
10619         loc_first_p = &wp_loc_first;
10620       else if (b->type == bp_read_watchpoint)
10621         loc_first_p = &rwp_loc_first;
10622       else if (b->type == bp_access_watchpoint)
10623         loc_first_p = &awp_loc_first;
10624       else
10625         loc_first_p = &bp_loc_first;
10626
10627       if (*loc_first_p == NULL
10628           || (overlay_debugging && loc->section != (*loc_first_p)->section)
10629           || !breakpoint_locations_match (loc, *loc_first_p))
10630         {
10631           *loc_first_p = loc;
10632           loc->duplicate = 0;
10633           continue;
10634         }
10635
10636
10637       /* This and the above ensure the invariant that the first location
10638          is not duplicated, and is the inserted one.
10639          All following are marked as duplicated, and are not inserted.  */
10640       if (loc->inserted)
10641         swap_insertion (loc, *loc_first_p);
10642       loc->duplicate = 1;
10643
10644       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
10645           && b->enable_state != bp_permanent)
10646         internal_error (__FILE__, __LINE__,
10647                         _("another breakpoint was inserted on top of "
10648                         "a permanent breakpoint"));
10649     }
10650
10651   if (breakpoints_always_inserted_mode () && should_insert
10652       && (have_live_inferiors ()
10653           || (gdbarch_has_global_breakpoints (target_gdbarch))))
10654     insert_breakpoint_locations ();
10655
10656   if (should_insert)
10657     download_tracepoint_locations ();
10658
10659   do_cleanups (cleanups);
10660 }
10661
10662 void
10663 breakpoint_retire_moribund (void)
10664 {
10665   struct bp_location *loc;
10666   int ix;
10667
10668   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
10669     if (--(loc->events_till_retirement) == 0)
10670       {
10671         decref_bp_location (&loc);
10672         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
10673         --ix;
10674       }
10675 }
10676
10677 static void
10678 update_global_location_list_nothrow (int inserting)
10679 {
10680   volatile struct gdb_exception e;
10681
10682   TRY_CATCH (e, RETURN_MASK_ERROR)
10683     update_global_location_list (inserting);
10684 }
10685
10686 /* Clear BKP from a BPS.  */
10687
10688 static void
10689 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
10690 {
10691   bpstat bs;
10692
10693   for (bs = bps; bs; bs = bs->next)
10694     if (bs->breakpoint_at == bpt)
10695       {
10696         bs->breakpoint_at = NULL;
10697         bs->old_val = NULL;
10698         /* bs->commands will be freed later.  */
10699       }
10700 }
10701
10702 /* Callback for iterate_over_threads.  */
10703 static int
10704 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
10705 {
10706   struct breakpoint *bpt = data;
10707
10708   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
10709   return 0;
10710 }
10711
10712 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
10713    callbacks.  */
10714
10715 static void
10716 say_where (struct breakpoint *b)
10717 {
10718   struct ui_out *uiout = current_uiout;
10719   struct value_print_options opts;
10720
10721   get_user_print_options (&opts);
10722
10723   /* i18n: cagney/2005-02-11: Below needs to be merged into a
10724      single string.  */
10725   if (b->loc == NULL)
10726     {
10727       printf_filtered (_(" (%s) pending."), b->addr_string);
10728     }
10729   else
10730     {
10731       if (opts.addressprint || b->loc->source_file == NULL)
10732         {
10733           printf_filtered (" at ");
10734           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
10735                           gdb_stdout);
10736         }
10737       if (b->loc->source_file)
10738         {
10739           /* If there is a single location, we can print the location
10740              more nicely.  */
10741           if (b->loc->next == NULL)
10742             printf_filtered (": file %s, line %d.",
10743                              b->loc->source_file, b->loc->line_number);
10744           else
10745             /* This is not ideal, but each location may have a
10746                different file name, and this at least reflects the
10747                real situation somewhat.  */
10748             printf_filtered (": %s.", b->addr_string);
10749         }
10750
10751       if (b->loc->next)
10752         {
10753           struct bp_location *loc = b->loc;
10754           int n = 0;
10755           for (; loc; loc = loc->next)
10756             ++n;
10757           printf_filtered (" (%d locations)", n);
10758         }
10759     }
10760 }
10761
10762 /* Default bp_location_ops methods.  */
10763
10764 static void
10765 bp_location_dtor (struct bp_location *self)
10766 {
10767   xfree (self->cond);
10768   xfree (self->function_name);
10769   xfree (self->source_file);
10770 }
10771
10772 static const struct bp_location_ops bp_location_ops =
10773 {
10774   bp_location_dtor
10775 };
10776
10777 /* Default breakpoint_ops methods all breakpoint_ops ultimately
10778    inherit from.  */
10779
10780 static void
10781 base_breakpoint_dtor (struct breakpoint *self)
10782 {
10783   decref_counted_command_line (&self->commands);
10784   xfree (self->cond_string);
10785   xfree (self->addr_string);
10786   xfree (self->filter);
10787   xfree (self->addr_string_range_end);
10788 }
10789
10790 static struct bp_location *
10791 base_breakpoint_allocate_location (struct breakpoint *self)
10792 {
10793   struct bp_location *loc;
10794
10795   loc = XNEW (struct bp_location);
10796   init_bp_location (loc, &bp_location_ops, self);
10797   return loc;
10798 }
10799
10800 static void
10801 base_breakpoint_re_set (struct breakpoint *b)
10802 {
10803   /* Nothing to re-set. */
10804 }
10805
10806 #define internal_error_pure_virtual_called() \
10807   gdb_assert_not_reached ("pure virtual function called")
10808
10809 static int
10810 base_breakpoint_insert_location (struct bp_location *bl)
10811 {
10812   internal_error_pure_virtual_called ();
10813 }
10814
10815 static int
10816 base_breakpoint_remove_location (struct bp_location *bl)
10817 {
10818   internal_error_pure_virtual_called ();
10819 }
10820
10821 static int
10822 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
10823                                 struct address_space *aspace,
10824                                 CORE_ADDR bp_addr)
10825 {
10826   internal_error_pure_virtual_called ();
10827 }
10828
10829 static void
10830 base_breakpoint_check_status (bpstat bs)
10831 {
10832   /* Always stop.   */
10833 }
10834
10835 /* A "works_in_software_mode" breakpoint_ops method that just internal
10836    errors.  */
10837
10838 static int
10839 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
10840 {
10841   internal_error_pure_virtual_called ();
10842 }
10843
10844 /* A "resources_needed" breakpoint_ops method that just internal
10845    errors.  */
10846
10847 static int
10848 base_breakpoint_resources_needed (const struct bp_location *bl)
10849 {
10850   internal_error_pure_virtual_called ();
10851 }
10852
10853 static enum print_stop_action
10854 base_breakpoint_print_it (bpstat bs)
10855 {
10856   internal_error_pure_virtual_called ();
10857 }
10858
10859 static void
10860 base_breakpoint_print_one_detail (const struct breakpoint *self,
10861                                   struct ui_out *uiout)
10862 {
10863   /* nothing */
10864 }
10865
10866 static void
10867 base_breakpoint_print_mention (struct breakpoint *b)
10868 {
10869   internal_error_pure_virtual_called ();
10870 }
10871
10872 static void
10873 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
10874 {
10875   internal_error_pure_virtual_called ();
10876 }
10877
10878 static void
10879 base_breakpoint_create_sals_from_address (char **arg,
10880                                           struct linespec_result *canonical,
10881                                           enum bptype type_wanted,
10882                                           char *addr_start,
10883                                           char **copy_arg)
10884 {
10885   internal_error_pure_virtual_called ();
10886 }
10887
10888 static void
10889 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
10890                                         struct linespec_result *c,
10891                                         struct linespec_sals *lsal,
10892                                         char *cond_string,
10893                                         enum bptype type_wanted,
10894                                         enum bpdisp disposition,
10895                                         int thread,
10896                                         int task, int ignore_count,
10897                                         const struct breakpoint_ops *o,
10898                                         int from_tty, int enabled,
10899                                         int internal)
10900 {
10901   internal_error_pure_virtual_called ();
10902 }
10903
10904 static void
10905 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
10906                                  struct symtabs_and_lines *sals)
10907 {
10908   internal_error_pure_virtual_called ();
10909 }
10910
10911 static struct breakpoint_ops base_breakpoint_ops =
10912 {
10913   base_breakpoint_dtor,
10914   base_breakpoint_allocate_location,
10915   base_breakpoint_re_set,
10916   base_breakpoint_insert_location,
10917   base_breakpoint_remove_location,
10918   base_breakpoint_breakpoint_hit,
10919   base_breakpoint_check_status,
10920   base_breakpoint_resources_needed,
10921   base_breakpoint_works_in_software_mode,
10922   base_breakpoint_print_it,
10923   NULL,
10924   base_breakpoint_print_one_detail,
10925   base_breakpoint_print_mention,
10926   base_breakpoint_print_recreate,
10927   base_breakpoint_create_sals_from_address,
10928   base_breakpoint_create_breakpoints_sal,
10929   base_breakpoint_decode_linespec,
10930 };
10931
10932 /* Default breakpoint_ops methods.  */
10933
10934 static void
10935 bkpt_re_set (struct breakpoint *b)
10936 {
10937   /* FIXME: is this still reachable?  */
10938   if (b->addr_string == NULL)
10939     {
10940       /* Anything without a string can't be re-set.  */
10941       delete_breakpoint (b);
10942       return;
10943     }
10944
10945   breakpoint_re_set_default (b);
10946 }
10947
10948 static int
10949 bkpt_insert_location (struct bp_location *bl)
10950 {
10951   if (bl->loc_type == bp_loc_hardware_breakpoint)
10952     return target_insert_hw_breakpoint (bl->gdbarch,
10953                                         &bl->target_info);
10954   else
10955     return target_insert_breakpoint (bl->gdbarch,
10956                                      &bl->target_info);
10957 }
10958
10959 static int
10960 bkpt_remove_location (struct bp_location *bl)
10961 {
10962   if (bl->loc_type == bp_loc_hardware_breakpoint)
10963     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
10964   else
10965     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
10966 }
10967
10968 static int
10969 bkpt_breakpoint_hit (const struct bp_location *bl,
10970                      struct address_space *aspace, CORE_ADDR bp_addr)
10971 {
10972   struct breakpoint *b = bl->owner;
10973
10974   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
10975                                  aspace, bp_addr))
10976     return 0;
10977
10978   if (overlay_debugging         /* unmapped overlay section */
10979       && section_is_overlay (bl->section)
10980       && !section_is_mapped (bl->section))
10981     return 0;
10982
10983   return 1;
10984 }
10985
10986 static int
10987 bkpt_resources_needed (const struct bp_location *bl)
10988 {
10989   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
10990
10991   return 1;
10992 }
10993
10994 static enum print_stop_action
10995 bkpt_print_it (bpstat bs)
10996 {
10997   struct breakpoint *b;
10998   const struct bp_location *bl;
10999   int bp_temp;
11000   struct ui_out *uiout = current_uiout;
11001
11002   gdb_assert (bs->bp_location_at != NULL);
11003
11004   bl = bs->bp_location_at;
11005   b = bs->breakpoint_at;
11006
11007   bp_temp = b->disposition == disp_del;
11008   if (bl->address != bl->requested_address)
11009     breakpoint_adjustment_warning (bl->requested_address,
11010                                    bl->address,
11011                                    b->number, 1);
11012   annotate_breakpoint (b->number);
11013   if (bp_temp)
11014     ui_out_text (uiout, "\nTemporary breakpoint ");
11015   else
11016     ui_out_text (uiout, "\nBreakpoint ");
11017   if (ui_out_is_mi_like_p (uiout))
11018     {
11019       ui_out_field_string (uiout, "reason",
11020                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11021       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11022     }
11023   ui_out_field_int (uiout, "bkptno", b->number);
11024   ui_out_text (uiout, ", ");
11025
11026   return PRINT_SRC_AND_LOC;
11027 }
11028
11029 static void
11030 bkpt_print_mention (struct breakpoint *b)
11031 {
11032   if (ui_out_is_mi_like_p (current_uiout))
11033     return;
11034
11035   switch (b->type)
11036     {
11037     case bp_breakpoint:
11038     case bp_gnu_ifunc_resolver:
11039       if (b->disposition == disp_del)
11040         printf_filtered (_("Temporary breakpoint"));
11041       else
11042         printf_filtered (_("Breakpoint"));
11043       printf_filtered (_(" %d"), b->number);
11044       if (b->type == bp_gnu_ifunc_resolver)
11045         printf_filtered (_(" at gnu-indirect-function resolver"));
11046       break;
11047     case bp_hardware_breakpoint:
11048       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
11049       break;
11050     }
11051
11052   say_where (b);
11053 }
11054
11055 static void
11056 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
11057 {
11058   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
11059     fprintf_unfiltered (fp, "tbreak");
11060   else if (tp->type == bp_breakpoint)
11061     fprintf_unfiltered (fp, "break");
11062   else if (tp->type == bp_hardware_breakpoint
11063            && tp->disposition == disp_del)
11064     fprintf_unfiltered (fp, "thbreak");
11065   else if (tp->type == bp_hardware_breakpoint)
11066     fprintf_unfiltered (fp, "hbreak");
11067   else
11068     internal_error (__FILE__, __LINE__,
11069                     _("unhandled breakpoint type %d"), (int) tp->type);
11070
11071   fprintf_unfiltered (fp, " %s", tp->addr_string);
11072   print_recreate_thread (tp, fp);
11073 }
11074
11075 static void
11076 bkpt_create_sals_from_address (char **arg,
11077                                struct linespec_result *canonical,
11078                                enum bptype type_wanted,
11079                                char *addr_start, char **copy_arg)
11080 {
11081   create_sals_from_address_default (arg, canonical, type_wanted,
11082                                     addr_start, copy_arg);
11083 }
11084
11085 static void
11086 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
11087                              struct linespec_result *canonical,
11088                              struct linespec_sals *lsal,
11089                              char *cond_string,
11090                              enum bptype type_wanted,
11091                              enum bpdisp disposition,
11092                              int thread,
11093                              int task, int ignore_count,
11094                              const struct breakpoint_ops *ops,
11095                              int from_tty, int enabled,
11096                              int internal)
11097 {
11098   create_breakpoints_sal_default (gdbarch, canonical, lsal,
11099                                   cond_string, type_wanted,
11100                                   disposition, thread, task,
11101                                   ignore_count, ops, from_tty,
11102                                   enabled, internal);
11103 }
11104
11105 static void
11106 bkpt_decode_linespec (struct breakpoint *b, char **s,
11107                       struct symtabs_and_lines *sals)
11108 {
11109   decode_linespec_default (b, s, sals);
11110 }
11111
11112 /* Virtual table for internal breakpoints.  */
11113
11114 static void
11115 internal_bkpt_re_set (struct breakpoint *b)
11116 {
11117   switch (b->type)
11118     {
11119       /* Delete overlay event and longjmp master breakpoints; they
11120          will be reset later by breakpoint_re_set.  */
11121     case bp_overlay_event:
11122     case bp_longjmp_master:
11123     case bp_std_terminate_master:
11124     case bp_exception_master:
11125       delete_breakpoint (b);
11126       break;
11127
11128       /* This breakpoint is special, it's set up when the inferior
11129          starts and we really don't want to touch it.  */
11130     case bp_shlib_event:
11131
11132       /* Like bp_shlib_event, this breakpoint type is special.  Once
11133          it is set up, we do not want to touch it.  */
11134     case bp_thread_event:
11135       break;
11136     }
11137 }
11138
11139 static void
11140 internal_bkpt_check_status (bpstat bs)
11141 {
11142   if (bs->breakpoint_at->type == bp_shlib_event)
11143     {
11144       /* If requested, stop when the dynamic linker notifies GDB of
11145          events.  This allows the user to get control and place
11146          breakpoints in initializer routines for dynamically loaded
11147          objects (among other things).  */
11148       bs->stop = stop_on_solib_events;
11149       bs->print = stop_on_solib_events;
11150     }
11151   else
11152     bs->stop = 0;
11153 }
11154
11155 static enum print_stop_action
11156 internal_bkpt_print_it (bpstat bs)
11157 {
11158   struct ui_out *uiout = current_uiout;
11159   struct breakpoint *b;
11160
11161   b = bs->breakpoint_at;
11162
11163   switch (b->type)
11164     {
11165     case bp_shlib_event:
11166       /* Did we stop because the user set the stop_on_solib_events
11167          variable?  (If so, we report this as a generic, "Stopped due
11168          to shlib event" message.) */
11169       ui_out_text (uiout, _("Stopped due to shared library event\n"));
11170       if (ui_out_is_mi_like_p (uiout))
11171         ui_out_field_string (uiout, "reason",
11172                              async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
11173       break;
11174
11175     case bp_thread_event:
11176       /* Not sure how we will get here.
11177          GDB should not stop for these breakpoints.  */
11178       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
11179       break;
11180
11181     case bp_overlay_event:
11182       /* By analogy with the thread event, GDB should not stop for these.  */
11183       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
11184       break;
11185
11186     case bp_longjmp_master:
11187       /* These should never be enabled.  */
11188       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
11189       break;
11190
11191     case bp_std_terminate_master:
11192       /* These should never be enabled.  */
11193       printf_filtered (_("std::terminate Master Breakpoint: "
11194                          "gdb should not stop!\n"));
11195       break;
11196
11197     case bp_exception_master:
11198       /* These should never be enabled.  */
11199       printf_filtered (_("Exception Master Breakpoint: "
11200                          "gdb should not stop!\n"));
11201       break;
11202     }
11203
11204   return PRINT_NOTHING;
11205 }
11206
11207 static void
11208 internal_bkpt_print_mention (struct breakpoint *b)
11209 {
11210   /* Nothing to mention.  These breakpoints are internal.  */
11211 }
11212
11213 /* Virtual table for momentary breakpoints  */
11214
11215 static void
11216 momentary_bkpt_re_set (struct breakpoint *b)
11217 {
11218   /* Keep temporary breakpoints, which can be encountered when we step
11219      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
11220      Otherwise these should have been blown away via the cleanup chain
11221      or by breakpoint_init_inferior when we rerun the executable.  */
11222 }
11223
11224 static void
11225 momentary_bkpt_check_status (bpstat bs)
11226 {
11227   /* Nothing.  The point of these breakpoints is causing a stop.  */
11228 }
11229
11230 static enum print_stop_action
11231 momentary_bkpt_print_it (bpstat bs)
11232 {
11233   struct ui_out *uiout = current_uiout;
11234
11235   if (ui_out_is_mi_like_p (uiout))
11236     {
11237       struct breakpoint *b = bs->breakpoint_at;
11238
11239       switch (b->type)
11240         {
11241         case bp_finish:
11242           ui_out_field_string
11243             (uiout, "reason",
11244              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
11245           break;
11246
11247         case bp_until:
11248           ui_out_field_string
11249             (uiout, "reason",
11250              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
11251           break;
11252         }
11253     }
11254
11255   return PRINT_UNKNOWN;
11256 }
11257
11258 static void
11259 momentary_bkpt_print_mention (struct breakpoint *b)
11260 {
11261   /* Nothing to mention.  These breakpoints are internal.  */
11262 }
11263
11264 /* The breakpoint_ops structure to be used in tracepoints.  */
11265
11266 static void
11267 tracepoint_re_set (struct breakpoint *b)
11268 {
11269   breakpoint_re_set_default (b);
11270 }
11271
11272 static int
11273 tracepoint_breakpoint_hit (const struct bp_location *bl,
11274                            struct address_space *aspace, CORE_ADDR bp_addr)
11275 {
11276   /* By definition, the inferior does not report stops at
11277      tracepoints.  */
11278   return 0;
11279 }
11280
11281 static void
11282 tracepoint_print_one_detail (const struct breakpoint *self,
11283                              struct ui_out *uiout)
11284 {
11285   struct tracepoint *tp = (struct tracepoint *) self;
11286   if (tp->static_trace_marker_id)
11287     {
11288       gdb_assert (self->type == bp_static_tracepoint);
11289
11290       ui_out_text (uiout, "\tmarker id is ");
11291       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
11292                            tp->static_trace_marker_id);
11293       ui_out_text (uiout, "\n");
11294     }
11295 }
11296
11297 static void
11298 tracepoint_print_mention (struct breakpoint *b)
11299 {
11300   if (ui_out_is_mi_like_p (current_uiout))
11301     return;
11302
11303   switch (b->type)
11304     {
11305     case bp_tracepoint:
11306       printf_filtered (_("Tracepoint"));
11307       printf_filtered (_(" %d"), b->number);
11308       break;
11309     case bp_fast_tracepoint:
11310       printf_filtered (_("Fast tracepoint"));
11311       printf_filtered (_(" %d"), b->number);
11312       break;
11313     case bp_static_tracepoint:
11314       printf_filtered (_("Static tracepoint"));
11315       printf_filtered (_(" %d"), b->number);
11316       break;
11317     default:
11318       internal_error (__FILE__, __LINE__,
11319                       _("unhandled tracepoint type %d"), (int) b->type);
11320     }
11321
11322   say_where (b);
11323 }
11324
11325 static void
11326 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
11327 {
11328   struct tracepoint *tp = (struct tracepoint *) self;
11329
11330   if (self->type == bp_fast_tracepoint)
11331     fprintf_unfiltered (fp, "ftrace");
11332   if (self->type == bp_static_tracepoint)
11333     fprintf_unfiltered (fp, "strace");
11334   else if (self->type == bp_tracepoint)
11335     fprintf_unfiltered (fp, "trace");
11336   else
11337     internal_error (__FILE__, __LINE__,
11338                     _("unhandled tracepoint type %d"), (int) self->type);
11339
11340   fprintf_unfiltered (fp, " %s", self->addr_string);
11341   print_recreate_thread (self, fp);
11342
11343   if (tp->pass_count)
11344     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
11345 }
11346
11347 static void
11348 tracepoint_create_sals_from_address (char **arg,
11349                                      struct linespec_result *canonical,
11350                                      enum bptype type_wanted,
11351                                      char *addr_start, char **copy_arg)
11352 {
11353   create_sals_from_address_default (arg, canonical, type_wanted,
11354                                     addr_start, copy_arg);
11355 }
11356
11357 static void
11358 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
11359                                    struct linespec_result *canonical,
11360                                    struct linespec_sals *lsal,
11361                                    char *cond_string,
11362                                    enum bptype type_wanted,
11363                                    enum bpdisp disposition,
11364                                    int thread,
11365                                    int task, int ignore_count,
11366                                    const struct breakpoint_ops *ops,
11367                                    int from_tty, int enabled,
11368                                    int internal)
11369 {
11370   create_breakpoints_sal_default (gdbarch, canonical, lsal,
11371                                   cond_string, type_wanted,
11372                                   disposition, thread, task,
11373                                   ignore_count, ops, from_tty,
11374                                   enabled, internal);
11375 }
11376
11377 static void
11378 tracepoint_decode_linespec (struct breakpoint *b, char **s,
11379                             struct symtabs_and_lines *sals)
11380 {
11381   decode_linespec_default (b, s, sals);
11382 }
11383
11384 struct breakpoint_ops tracepoint_breakpoint_ops;
11385
11386 /* The breakpoint_ops structure to be used on static tracepoints with
11387    markers (`-m').  */
11388
11389 static void
11390 strace_marker_create_sals_from_address (char **arg,
11391                                         struct linespec_result *canonical,
11392                                         enum bptype type_wanted,
11393                                         char *addr_start, char **copy_arg)
11394 {
11395   struct linespec_sals lsal;
11396
11397   lsal.sals = decode_static_tracepoint_spec (arg);
11398
11399   *copy_arg = savestring (addr_start, *arg - addr_start);
11400
11401   canonical->addr_string = xstrdup (*copy_arg);
11402   lsal.canonical = xstrdup (*copy_arg);
11403   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
11404 }
11405
11406 static void
11407 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
11408                                       struct linespec_result *canonical,
11409                                       struct linespec_sals *lsal,
11410                                       char *cond_string,
11411                                       enum bptype type_wanted,
11412                                       enum bpdisp disposition,
11413                                       int thread,
11414                                       int task, int ignore_count,
11415                                       const struct breakpoint_ops *ops,
11416                                       int from_tty, int enabled,
11417                                       int internal)
11418 {
11419   int i;
11420
11421   /* If the user is creating a static tracepoint by marker id
11422      (strace -m MARKER_ID), then store the sals index, so that
11423      breakpoint_re_set can try to match up which of the newly
11424      found markers corresponds to this one, and, don't try to
11425      expand multiple locations for each sal, given than SALS
11426      already should contain all sals for MARKER_ID.  */
11427
11428   for (i = 0; i < lsal->sals.nelts; ++i)
11429     {
11430       struct symtabs_and_lines expanded;
11431       struct tracepoint *tp;
11432       struct cleanup *old_chain;
11433       char *addr_string;
11434
11435       expanded.nelts = 1;
11436       expanded.sals = &lsal->sals.sals[i];
11437
11438       addr_string = xstrdup (canonical->addr_string);
11439       old_chain = make_cleanup (xfree, addr_string);
11440
11441       tp = XCNEW (struct tracepoint);
11442       init_breakpoint_sal (&tp->base, gdbarch, expanded,
11443                            addr_string, NULL,
11444                            cond_string, type_wanted, disposition,
11445                            thread, task, ignore_count, ops,
11446                            from_tty, enabled, internal,
11447                            canonical->special_display);
11448       /* Given that its possible to have multiple markers with
11449          the same string id, if the user is creating a static
11450          tracepoint by marker id ("strace -m MARKER_ID"), then
11451          store the sals index, so that breakpoint_re_set can
11452          try to match up which of the newly found markers
11453          corresponds to this one  */
11454       tp->static_trace_marker_id_idx = i;
11455
11456       install_breakpoint (internal, &tp->base, 0);
11457
11458       discard_cleanups (old_chain);
11459     }
11460 }
11461
11462 static void
11463 strace_marker_decode_linespec (struct breakpoint *b, char **s,
11464                                struct symtabs_and_lines *sals)
11465 {
11466   struct tracepoint *tp = (struct tracepoint *) b;
11467
11468   *sals = decode_static_tracepoint_spec (s);
11469   if (sals->nelts > tp->static_trace_marker_id_idx)
11470     {
11471       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
11472       sals->nelts = 1;
11473     }
11474   else
11475     error (_("marker %s not found"), tp->static_trace_marker_id);
11476 }
11477
11478 static struct breakpoint_ops strace_marker_breakpoint_ops;
11479
11480 static int
11481 strace_marker_p (struct breakpoint *b)
11482 {
11483   return b->ops == &strace_marker_breakpoint_ops;
11484 }
11485
11486 /* Delete a breakpoint and clean up all traces of it in the data
11487    structures.  */
11488
11489 void
11490 delete_breakpoint (struct breakpoint *bpt)
11491 {
11492   struct breakpoint *b;
11493
11494   gdb_assert (bpt != NULL);
11495
11496   /* Has this bp already been deleted?  This can happen because
11497      multiple lists can hold pointers to bp's.  bpstat lists are
11498      especial culprits.
11499
11500      One example of this happening is a watchpoint's scope bp.  When
11501      the scope bp triggers, we notice that the watchpoint is out of
11502      scope, and delete it.  We also delete its scope bp.  But the
11503      scope bp is marked "auto-deleting", and is already on a bpstat.
11504      That bpstat is then checked for auto-deleting bp's, which are
11505      deleted.
11506
11507      A real solution to this problem might involve reference counts in
11508      bp's, and/or giving them pointers back to their referencing
11509      bpstat's, and teaching delete_breakpoint to only free a bp's
11510      storage when no more references were extent.  A cheaper bandaid
11511      was chosen.  */
11512   if (bpt->type == bp_none)
11513     return;
11514
11515   /* At least avoid this stale reference until the reference counting
11516      of breakpoints gets resolved.  */
11517   if (bpt->related_breakpoint != bpt)
11518     {
11519       struct breakpoint *related;
11520       struct watchpoint *w;
11521
11522       if (bpt->type == bp_watchpoint_scope)
11523         w = (struct watchpoint *) bpt->related_breakpoint;
11524       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
11525         w = (struct watchpoint *) bpt;
11526       else
11527         w = NULL;
11528       if (w != NULL)
11529         watchpoint_del_at_next_stop (w);
11530
11531       /* Unlink bpt from the bpt->related_breakpoint ring.  */
11532       for (related = bpt; related->related_breakpoint != bpt;
11533            related = related->related_breakpoint);
11534       related->related_breakpoint = bpt->related_breakpoint;
11535       bpt->related_breakpoint = bpt;
11536     }
11537
11538   /* watch_command_1 creates a watchpoint but only sets its number if
11539      update_watchpoint succeeds in creating its bp_locations.  If there's
11540      a problem in that process, we'll be asked to delete the half-created
11541      watchpoint.  In that case, don't announce the deletion.  */
11542   if (bpt->number)
11543     observer_notify_breakpoint_deleted (bpt);
11544
11545   if (breakpoint_chain == bpt)
11546     breakpoint_chain = bpt->next;
11547
11548   ALL_BREAKPOINTS (b)
11549     if (b->next == bpt)
11550     {
11551       b->next = bpt->next;
11552       break;
11553     }
11554
11555   /* Be sure no bpstat's are pointing at the breakpoint after it's
11556      been freed.  */
11557   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
11558      in all threads for now.  Note that we cannot just remove bpstats
11559      pointing at bpt from the stop_bpstat list entirely, as breakpoint
11560      commands are associated with the bpstat; if we remove it here,
11561      then the later call to bpstat_do_actions (&stop_bpstat); in
11562      event-top.c won't do anything, and temporary breakpoints with
11563      commands won't work.  */
11564
11565   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
11566
11567   /* Now that breakpoint is removed from breakpoint list, update the
11568      global location list.  This will remove locations that used to
11569      belong to this breakpoint.  Do this before freeing the breakpoint
11570      itself, since remove_breakpoint looks at location's owner.  It
11571      might be better design to have location completely
11572      self-contained, but it's not the case now.  */
11573   update_global_location_list (0);
11574
11575   bpt->ops->dtor (bpt);
11576   /* On the chance that someone will soon try again to delete this
11577      same bp, we mark it as deleted before freeing its storage.  */
11578   bpt->type = bp_none;
11579   xfree (bpt);
11580 }
11581
11582 static void
11583 do_delete_breakpoint_cleanup (void *b)
11584 {
11585   delete_breakpoint (b);
11586 }
11587
11588 struct cleanup *
11589 make_cleanup_delete_breakpoint (struct breakpoint *b)
11590 {
11591   return make_cleanup (do_delete_breakpoint_cleanup, b);
11592 }
11593
11594 /* Iterator function to call a user-provided callback function once
11595    for each of B and its related breakpoints.  */
11596
11597 static void
11598 iterate_over_related_breakpoints (struct breakpoint *b,
11599                                   void (*function) (struct breakpoint *,
11600                                                     void *),
11601                                   void *data)
11602 {
11603   struct breakpoint *related;
11604
11605   related = b;
11606   do
11607     {
11608       struct breakpoint *next;
11609
11610       /* FUNCTION may delete RELATED.  */
11611       next = related->related_breakpoint;
11612
11613       if (next == related)
11614         {
11615           /* RELATED is the last ring entry.  */
11616           function (related, data);
11617
11618           /* FUNCTION may have deleted it, so we'd never reach back to
11619              B.  There's nothing left to do anyway, so just break
11620              out.  */
11621           break;
11622         }
11623       else
11624         function (related, data);
11625
11626       related = next;
11627     }
11628   while (related != b);
11629 }
11630
11631 static void
11632 do_delete_breakpoint (struct breakpoint *b, void *ignore)
11633 {
11634   delete_breakpoint (b);
11635 }
11636
11637 /* A callback for map_breakpoint_numbers that calls
11638    delete_breakpoint.  */
11639
11640 static void
11641 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
11642 {
11643   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
11644 }
11645
11646 void
11647 delete_command (char *arg, int from_tty)
11648 {
11649   struct breakpoint *b, *b_tmp;
11650
11651   dont_repeat ();
11652
11653   if (arg == 0)
11654     {
11655       int breaks_to_delete = 0;
11656
11657       /* Delete all breakpoints if no argument.  Do not delete
11658          internal breakpoints, these have to be deleted with an
11659          explicit breakpoint number argument.  */
11660       ALL_BREAKPOINTS (b)
11661         if (user_breakpoint_p (b))
11662           {
11663             breaks_to_delete = 1;
11664             break;
11665           }
11666
11667       /* Ask user only if there are some breakpoints to delete.  */
11668       if (!from_tty
11669           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
11670         {
11671           ALL_BREAKPOINTS_SAFE (b, b_tmp)
11672             if (user_breakpoint_p (b))
11673               delete_breakpoint (b);
11674         }
11675     }
11676   else
11677     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
11678 }
11679
11680 static int
11681 all_locations_are_pending (struct bp_location *loc)
11682 {
11683   for (; loc; loc = loc->next)
11684     if (!loc->shlib_disabled
11685         && !loc->pspace->executing_startup)
11686       return 0;
11687   return 1;
11688 }
11689
11690 /* Subroutine of update_breakpoint_locations to simplify it.
11691    Return non-zero if multiple fns in list LOC have the same name.
11692    Null names are ignored.  */
11693
11694 static int
11695 ambiguous_names_p (struct bp_location *loc)
11696 {
11697   struct bp_location *l;
11698   htab_t htab = htab_create_alloc (13, htab_hash_string,
11699                                    (int (*) (const void *, 
11700                                              const void *)) streq,
11701                                    NULL, xcalloc, xfree);
11702
11703   for (l = loc; l != NULL; l = l->next)
11704     {
11705       const char **slot;
11706       const char *name = l->function_name;
11707
11708       /* Allow for some names to be NULL, ignore them.  */
11709       if (name == NULL)
11710         continue;
11711
11712       slot = (const char **) htab_find_slot (htab, (const void *) name,
11713                                              INSERT);
11714       /* NOTE: We can assume slot != NULL here because xcalloc never
11715          returns NULL.  */
11716       if (*slot != NULL)
11717         {
11718           htab_delete (htab);
11719           return 1;
11720         }
11721       *slot = name;
11722     }
11723
11724   htab_delete (htab);
11725   return 0;
11726 }
11727
11728 /* When symbols change, it probably means the sources changed as well,
11729    and it might mean the static tracepoint markers are no longer at
11730    the same address or line numbers they used to be at last we
11731    checked.  Losing your static tracepoints whenever you rebuild is
11732    undesirable.  This function tries to resync/rematch gdb static
11733    tracepoints with the markers on the target, for static tracepoints
11734    that have not been set by marker id.  Static tracepoint that have
11735    been set by marker id are reset by marker id in breakpoint_re_set.
11736    The heuristic is:
11737
11738    1) For a tracepoint set at a specific address, look for a marker at
11739    the old PC.  If one is found there, assume to be the same marker.
11740    If the name / string id of the marker found is different from the
11741    previous known name, assume that means the user renamed the marker
11742    in the sources, and output a warning.
11743
11744    2) For a tracepoint set at a given line number, look for a marker
11745    at the new address of the old line number.  If one is found there,
11746    assume to be the same marker.  If the name / string id of the
11747    marker found is different from the previous known name, assume that
11748    means the user renamed the marker in the sources, and output a
11749    warning.
11750
11751    3) If a marker is no longer found at the same address or line, it
11752    may mean the marker no longer exists.  But it may also just mean
11753    the code changed a bit.  Maybe the user added a few lines of code
11754    that made the marker move up or down (in line number terms).  Ask
11755    the target for info about the marker with the string id as we knew
11756    it.  If found, update line number and address in the matching
11757    static tracepoint.  This will get confused if there's more than one
11758    marker with the same ID (possible in UST, although unadvised
11759    precisely because it confuses tools).  */
11760
11761 static struct symtab_and_line
11762 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
11763 {
11764   struct tracepoint *tp = (struct tracepoint *) b;
11765   struct static_tracepoint_marker marker;
11766   CORE_ADDR pc;
11767   int i;
11768
11769   pc = sal.pc;
11770   if (sal.line)
11771     find_line_pc (sal.symtab, sal.line, &pc);
11772
11773   if (target_static_tracepoint_marker_at (pc, &marker))
11774     {
11775       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
11776         warning (_("static tracepoint %d changed probed marker from %s to %s"),
11777                  b->number,
11778                  tp->static_trace_marker_id, marker.str_id);
11779
11780       xfree (tp->static_trace_marker_id);
11781       tp->static_trace_marker_id = xstrdup (marker.str_id);
11782       release_static_tracepoint_marker (&marker);
11783
11784       return sal;
11785     }
11786
11787   /* Old marker wasn't found on target at lineno.  Try looking it up
11788      by string ID.  */
11789   if (!sal.explicit_pc
11790       && sal.line != 0
11791       && sal.symtab != NULL
11792       && tp->static_trace_marker_id != NULL)
11793     {
11794       VEC(static_tracepoint_marker_p) *markers;
11795
11796       markers
11797         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
11798
11799       if (!VEC_empty(static_tracepoint_marker_p, markers))
11800         {
11801           struct symtab_and_line sal2;
11802           struct symbol *sym;
11803           struct static_tracepoint_marker *tpmarker;
11804           struct ui_out *uiout = current_uiout;
11805
11806           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
11807
11808           xfree (tp->static_trace_marker_id);
11809           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
11810
11811           warning (_("marker for static tracepoint %d (%s) not "
11812                      "found at previous line number"),
11813                    b->number, tp->static_trace_marker_id);
11814
11815           init_sal (&sal2);
11816
11817           sal2.pc = tpmarker->address;
11818
11819           sal2 = find_pc_line (tpmarker->address, 0);
11820           sym = find_pc_sect_function (tpmarker->address, NULL);
11821           ui_out_text (uiout, "Now in ");
11822           if (sym)
11823             {
11824               ui_out_field_string (uiout, "func",
11825                                    SYMBOL_PRINT_NAME (sym));
11826               ui_out_text (uiout, " at ");
11827             }
11828           ui_out_field_string (uiout, "file", sal2.symtab->filename);
11829           ui_out_text (uiout, ":");
11830
11831           if (ui_out_is_mi_like_p (uiout))
11832             {
11833               char *fullname = symtab_to_fullname (sal2.symtab);
11834
11835               if (fullname)
11836                 ui_out_field_string (uiout, "fullname", fullname);
11837             }
11838
11839           ui_out_field_int (uiout, "line", sal2.line);
11840           ui_out_text (uiout, "\n");
11841
11842           b->loc->line_number = sal2.line;
11843
11844           xfree (b->loc->source_file);
11845           if (sym)
11846             b->loc->source_file = xstrdup (sal2.symtab->filename);
11847           else
11848             b->loc->source_file = NULL;
11849
11850           xfree (b->addr_string);
11851           b->addr_string = xstrprintf ("%s:%d",
11852                                        sal2.symtab->filename,
11853                                        b->loc->line_number);
11854
11855           /* Might be nice to check if function changed, and warn if
11856              so.  */
11857
11858           release_static_tracepoint_marker (tpmarker);
11859         }
11860     }
11861   return sal;
11862 }
11863
11864 /* Returns 1 iff locations A and B are sufficiently same that
11865    we don't need to report breakpoint as changed.  */
11866
11867 static int
11868 locations_are_equal (struct bp_location *a, struct bp_location *b)
11869 {
11870   while (a && b)
11871     {
11872       if (a->address != b->address)
11873         return 0;
11874
11875       if (a->shlib_disabled != b->shlib_disabled)
11876         return 0;
11877
11878       if (a->enabled != b->enabled)
11879         return 0;
11880
11881       a = a->next;
11882       b = b->next;
11883     }
11884
11885   if ((a == NULL) != (b == NULL))
11886     return 0;
11887
11888   return 1;
11889 }
11890
11891 /* Create new breakpoint locations for B (a hardware or software breakpoint)
11892    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
11893    a ranged breakpoint.  */
11894
11895 void
11896 update_breakpoint_locations (struct breakpoint *b,
11897                              struct symtabs_and_lines sals,
11898                              struct symtabs_and_lines sals_end)
11899 {
11900   int i;
11901   struct bp_location *existing_locations = b->loc;
11902
11903   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
11904     {
11905       /* Ranged breakpoints have only one start location and one end
11906          location.  */
11907       b->enable_state = bp_disabled;
11908       update_global_location_list (1);
11909       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
11910                            "multiple locations found\n"),
11911                          b->number);
11912       return;
11913     }
11914
11915   /* If there's no new locations, and all existing locations are
11916      pending, don't do anything.  This optimizes the common case where
11917      all locations are in the same shared library, that was unloaded.
11918      We'd like to retain the location, so that when the library is
11919      loaded again, we don't loose the enabled/disabled status of the
11920      individual locations.  */
11921   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
11922     return;
11923
11924   b->loc = NULL;
11925
11926   for (i = 0; i < sals.nelts; ++i)
11927     {
11928       struct bp_location *new_loc;
11929
11930       switch_to_program_space_and_thread (sals.sals[i].pspace);
11931
11932       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
11933
11934       /* Reparse conditions, they might contain references to the
11935          old symtab.  */
11936       if (b->cond_string != NULL)
11937         {
11938           char *s;
11939           volatile struct gdb_exception e;
11940
11941           s = b->cond_string;
11942           TRY_CATCH (e, RETURN_MASK_ERROR)
11943             {
11944               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
11945                                            0);
11946             }
11947           if (e.reason < 0)
11948             {
11949               warning (_("failed to reevaluate condition "
11950                          "for breakpoint %d: %s"), 
11951                        b->number, e.message);
11952               new_loc->enabled = 0;
11953             }
11954         }
11955
11956       if (sals_end.nelts)
11957         {
11958           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
11959
11960           new_loc->length = end - sals.sals[0].pc + 1;
11961         }
11962     }
11963
11964   /* Update locations of permanent breakpoints.  */
11965   if (b->enable_state == bp_permanent)
11966     make_breakpoint_permanent (b);
11967
11968   /* If possible, carry over 'disable' status from existing
11969      breakpoints.  */
11970   {
11971     struct bp_location *e = existing_locations;
11972     /* If there are multiple breakpoints with the same function name,
11973        e.g. for inline functions, comparing function names won't work.
11974        Instead compare pc addresses; this is just a heuristic as things
11975        may have moved, but in practice it gives the correct answer
11976        often enough until a better solution is found.  */
11977     int have_ambiguous_names = ambiguous_names_p (b->loc);
11978
11979     for (; e; e = e->next)
11980       {
11981         if (!e->enabled && e->function_name)
11982           {
11983             struct bp_location *l = b->loc;
11984             if (have_ambiguous_names)
11985               {
11986                 for (; l; l = l->next)
11987                   if (breakpoint_locations_match (e, l))
11988                     {
11989                       l->enabled = 0;
11990                       break;
11991                     }
11992               }
11993             else
11994               {
11995                 for (; l; l = l->next)
11996                   if (l->function_name
11997                       && strcmp (e->function_name, l->function_name) == 0)
11998                     {
11999                       l->enabled = 0;
12000                       break;
12001                     }
12002               }
12003           }
12004       }
12005   }
12006
12007   if (!locations_are_equal (existing_locations, b->loc))
12008     observer_notify_breakpoint_modified (b);
12009
12010   update_global_location_list (1);
12011 }
12012
12013 /* Find the SaL locations corresponding to the given ADDR_STRING.
12014    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
12015
12016 static struct symtabs_and_lines
12017 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
12018 {
12019   char *s;
12020   struct symtabs_and_lines sals = {0};
12021   volatile struct gdb_exception e;
12022
12023   gdb_assert (b->ops != NULL);
12024   s = addr_string;
12025
12026   TRY_CATCH (e, RETURN_MASK_ERROR)
12027     {
12028       b->ops->decode_linespec (b, &s, &sals);
12029     }
12030   if (e.reason < 0)
12031     {
12032       int not_found_and_ok = 0;
12033       /* For pending breakpoints, it's expected that parsing will
12034          fail until the right shared library is loaded.  User has
12035          already told to create pending breakpoints and don't need
12036          extra messages.  If breakpoint is in bp_shlib_disabled
12037          state, then user already saw the message about that
12038          breakpoint being disabled, and don't want to see more
12039          errors.  */
12040       if (e.error == NOT_FOUND_ERROR
12041           && (b->condition_not_parsed 
12042               || (b->loc && b->loc->shlib_disabled)
12043               || (b->loc && b->loc->pspace->executing_startup)
12044               || b->enable_state == bp_disabled))
12045         not_found_and_ok = 1;
12046
12047       if (!not_found_and_ok)
12048         {
12049           /* We surely don't want to warn about the same breakpoint
12050              10 times.  One solution, implemented here, is disable
12051              the breakpoint on error.  Another solution would be to
12052              have separate 'warning emitted' flag.  Since this
12053              happens only when a binary has changed, I don't know
12054              which approach is better.  */
12055           b->enable_state = bp_disabled;
12056           throw_exception (e);
12057         }
12058     }
12059
12060   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
12061     {
12062       int i;
12063
12064       for (i = 0; i < sals.nelts; ++i)
12065         resolve_sal_pc (&sals.sals[i]);
12066       if (b->condition_not_parsed && s && s[0])
12067         {
12068           char *cond_string = 0;
12069           int thread = -1;
12070           int task = 0;
12071
12072           find_condition_and_thread (s, sals.sals[0].pc,
12073                                      &cond_string, &thread, &task);
12074           if (cond_string)
12075             b->cond_string = cond_string;
12076           b->thread = thread;
12077           b->task = task;
12078           b->condition_not_parsed = 0;
12079         }
12080
12081       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
12082         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
12083
12084       *found = 1;
12085     }
12086   else
12087     *found = 0;
12088
12089   return sals;
12090 }
12091
12092 /* The default re_set method, for typical hardware or software
12093    breakpoints.  Reevaluate the breakpoint and recreate its
12094    locations.  */
12095
12096 static void
12097 breakpoint_re_set_default (struct breakpoint *b)
12098 {
12099   int found;
12100   struct symtabs_and_lines sals, sals_end;
12101   struct symtabs_and_lines expanded = {0};
12102   struct symtabs_and_lines expanded_end = {0};
12103
12104   sals = addr_string_to_sals (b, b->addr_string, &found);
12105   if (found)
12106     {
12107       make_cleanup (xfree, sals.sals);
12108       expanded = sals;
12109     }
12110
12111   if (b->addr_string_range_end)
12112     {
12113       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
12114       if (found)
12115         {
12116           make_cleanup (xfree, sals_end.sals);
12117           expanded_end = sals_end;
12118         }
12119     }
12120
12121   update_breakpoint_locations (b, expanded, expanded_end);
12122 }
12123
12124 /* Default method for creating SALs from an address string.  It basically
12125    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
12126
12127 static void
12128 create_sals_from_address_default (char **arg,
12129                                   struct linespec_result *canonical,
12130                                   enum bptype type_wanted,
12131                                   char *addr_start, char **copy_arg)
12132 {
12133   parse_breakpoint_sals (arg, canonical);
12134 }
12135
12136 /* Call create_breakpoints_sal for the given arguments.  This is the default
12137    function for the `create_breakpoints_sal' method of
12138    breakpoint_ops.  */
12139
12140 static void
12141 create_breakpoints_sal_default (struct gdbarch *gdbarch,
12142                                 struct linespec_result *canonical,
12143                                 struct linespec_sals *lsal,
12144                                 char *cond_string,
12145                                 enum bptype type_wanted,
12146                                 enum bpdisp disposition,
12147                                 int thread,
12148                                 int task, int ignore_count,
12149                                 const struct breakpoint_ops *ops,
12150                                 int from_tty, int enabled,
12151                                 int internal)
12152 {
12153   create_breakpoints_sal (gdbarch, canonical, cond_string,
12154                           type_wanted, disposition,
12155                           thread, task, ignore_count, ops, from_tty,
12156                           enabled, internal);
12157 }
12158
12159 /* Decode the line represented by S by calling decode_line_full.  This is the
12160    default function for the `decode_linespec' method of breakpoint_ops.  */
12161
12162 static void
12163 decode_linespec_default (struct breakpoint *b, char **s,
12164                          struct symtabs_and_lines *sals)
12165 {
12166   struct linespec_result canonical;
12167
12168   init_linespec_result (&canonical);
12169   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
12170                     (struct symtab *) NULL, 0,
12171                     &canonical, multiple_symbols_all,
12172                     b->filter);
12173
12174   /* We should get 0 or 1 resulting SALs.  */
12175   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
12176
12177   if (VEC_length (linespec_sals, canonical.sals) > 0)
12178     {
12179       struct linespec_sals *lsal;
12180
12181       lsal = VEC_index (linespec_sals, canonical.sals, 0);
12182       *sals = lsal->sals;
12183       /* Arrange it so the destructor does not free the
12184          contents.  */
12185       lsal->sals.sals = NULL;
12186     }
12187
12188   destroy_linespec_result (&canonical);
12189 }
12190
12191 /* Prepare the global context for a re-set of breakpoint B.  */
12192
12193 static struct cleanup *
12194 prepare_re_set_context (struct breakpoint *b)
12195 {
12196   struct cleanup *cleanups;
12197
12198   input_radix = b->input_radix;
12199   cleanups = save_current_space_and_thread ();
12200   if (b->pspace != NULL)
12201     switch_to_program_space_and_thread (b->pspace);
12202   set_language (b->language);
12203
12204   return cleanups;
12205 }
12206
12207 /* Reset a breakpoint given it's struct breakpoint * BINT.
12208    The value we return ends up being the return value from catch_errors.
12209    Unused in this case.  */
12210
12211 static int
12212 breakpoint_re_set_one (void *bint)
12213 {
12214   /* Get past catch_errs.  */
12215   struct breakpoint *b = (struct breakpoint *) bint;
12216   struct cleanup *cleanups;
12217
12218   cleanups = prepare_re_set_context (b);
12219   b->ops->re_set (b);
12220   do_cleanups (cleanups);
12221   return 0;
12222 }
12223
12224 /* Re-set all breakpoints after symbols have been re-loaded.  */
12225 void
12226 breakpoint_re_set (void)
12227 {
12228   struct breakpoint *b, *b_tmp;
12229   enum language save_language;
12230   int save_input_radix;
12231   struct cleanup *old_chain;
12232
12233   save_language = current_language->la_language;
12234   save_input_radix = input_radix;
12235   old_chain = save_current_program_space ();
12236
12237   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12238   {
12239     /* Format possible error msg.  */
12240     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
12241                                 b->number);
12242     struct cleanup *cleanups = make_cleanup (xfree, message);
12243     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
12244     do_cleanups (cleanups);
12245   }
12246   set_language (save_language);
12247   input_radix = save_input_radix;
12248
12249   jit_breakpoint_re_set ();
12250
12251   do_cleanups (old_chain);
12252
12253   create_overlay_event_breakpoint ();
12254   create_longjmp_master_breakpoint ();
12255   create_std_terminate_master_breakpoint ();
12256   create_exception_master_breakpoint ();
12257
12258   /* While we're at it, reset the skip list too.  */
12259   skip_re_set ();
12260 }
12261 \f
12262 /* Reset the thread number of this breakpoint:
12263
12264    - If the breakpoint is for all threads, leave it as-is.
12265    - Else, reset it to the current thread for inferior_ptid.  */
12266 void
12267 breakpoint_re_set_thread (struct breakpoint *b)
12268 {
12269   if (b->thread != -1)
12270     {
12271       if (in_thread_list (inferior_ptid))
12272         b->thread = pid_to_thread_id (inferior_ptid);
12273
12274       /* We're being called after following a fork.  The new fork is
12275          selected as current, and unless this was a vfork will have a
12276          different program space from the original thread.  Reset that
12277          as well.  */
12278       b->loc->pspace = current_program_space;
12279     }
12280 }
12281
12282 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
12283    If from_tty is nonzero, it prints a message to that effect,
12284    which ends with a period (no newline).  */
12285
12286 void
12287 set_ignore_count (int bptnum, int count, int from_tty)
12288 {
12289   struct breakpoint *b;
12290
12291   if (count < 0)
12292     count = 0;
12293
12294   ALL_BREAKPOINTS (b)
12295     if (b->number == bptnum)
12296     {
12297       if (is_tracepoint (b))
12298         {
12299           if (from_tty && count != 0)
12300             printf_filtered (_("Ignore count ignored for tracepoint %d."),
12301                              bptnum);
12302           return;
12303         }
12304       
12305       b->ignore_count = count;
12306       if (from_tty)
12307         {
12308           if (count == 0)
12309             printf_filtered (_("Will stop next time "
12310                                "breakpoint %d is reached."),
12311                              bptnum);
12312           else if (count == 1)
12313             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
12314                              bptnum);
12315           else
12316             printf_filtered (_("Will ignore next %d "
12317                                "crossings of breakpoint %d."),
12318                              count, bptnum);
12319         }
12320       breakpoints_changed ();
12321       observer_notify_breakpoint_modified (b);
12322       return;
12323     }
12324
12325   error (_("No breakpoint number %d."), bptnum);
12326 }
12327
12328 /* Command to set ignore-count of breakpoint N to COUNT.  */
12329
12330 static void
12331 ignore_command (char *args, int from_tty)
12332 {
12333   char *p = args;
12334   int num;
12335
12336   if (p == 0)
12337     error_no_arg (_("a breakpoint number"));
12338
12339   num = get_number (&p);
12340   if (num == 0)
12341     error (_("bad breakpoint number: '%s'"), args);
12342   if (*p == 0)
12343     error (_("Second argument (specified ignore-count) is missing."));
12344
12345   set_ignore_count (num,
12346                     longest_to_int (value_as_long (parse_and_eval (p))),
12347                     from_tty);
12348   if (from_tty)
12349     printf_filtered ("\n");
12350 }
12351 \f
12352 /* Call FUNCTION on each of the breakpoints
12353    whose numbers are given in ARGS.  */
12354
12355 static void
12356 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
12357                                                       void *),
12358                         void *data)
12359 {
12360   int num;
12361   struct breakpoint *b, *tmp;
12362   int match;
12363   struct get_number_or_range_state state;
12364
12365   if (args == 0)
12366     error_no_arg (_("one or more breakpoint numbers"));
12367
12368   init_number_or_range (&state, args);
12369
12370   while (!state.finished)
12371     {
12372       char *p = state.string;
12373
12374       match = 0;
12375
12376       num = get_number_or_range (&state);
12377       if (num == 0)
12378         {
12379           warning (_("bad breakpoint number at or near '%s'"), p);
12380         }
12381       else
12382         {
12383           ALL_BREAKPOINTS_SAFE (b, tmp)
12384             if (b->number == num)
12385               {
12386                 match = 1;
12387                 function (b, data);
12388                 break;
12389               }
12390           if (match == 0)
12391             printf_unfiltered (_("No breakpoint number %d.\n"), num);
12392         }
12393     }
12394 }
12395
12396 static struct bp_location *
12397 find_location_by_number (char *number)
12398 {
12399   char *dot = strchr (number, '.');
12400   char *p1;
12401   int bp_num;
12402   int loc_num;
12403   struct breakpoint *b;
12404   struct bp_location *loc;  
12405
12406   *dot = '\0';
12407
12408   p1 = number;
12409   bp_num = get_number (&p1);
12410   if (bp_num == 0)
12411     error (_("Bad breakpoint number '%s'"), number);
12412
12413   ALL_BREAKPOINTS (b)
12414     if (b->number == bp_num)
12415       {
12416         break;
12417       }
12418
12419   if (!b || b->number != bp_num)
12420     error (_("Bad breakpoint number '%s'"), number);
12421   
12422   p1 = dot+1;
12423   loc_num = get_number (&p1);
12424   if (loc_num == 0)
12425     error (_("Bad breakpoint location number '%s'"), number);
12426
12427   --loc_num;
12428   loc = b->loc;
12429   for (;loc_num && loc; --loc_num, loc = loc->next)
12430     ;
12431   if (!loc)
12432     error (_("Bad breakpoint location number '%s'"), dot+1);
12433     
12434   return loc;  
12435 }
12436
12437
12438 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
12439    If from_tty is nonzero, it prints a message to that effect,
12440    which ends with a period (no newline).  */
12441
12442 void
12443 disable_breakpoint (struct breakpoint *bpt)
12444 {
12445   /* Never disable a watchpoint scope breakpoint; we want to
12446      hit them when we leave scope so we can delete both the
12447      watchpoint and its scope breakpoint at that time.  */
12448   if (bpt->type == bp_watchpoint_scope)
12449     return;
12450
12451   /* You can't disable permanent breakpoints.  */
12452   if (bpt->enable_state == bp_permanent)
12453     return;
12454
12455   bpt->enable_state = bp_disabled;
12456
12457   if (target_supports_enable_disable_tracepoint ()
12458       && current_trace_status ()->running && is_tracepoint (bpt))
12459     {
12460       struct bp_location *location;
12461      
12462       for (location = bpt->loc; location; location = location->next)
12463         target_disable_tracepoint (location);
12464     }
12465
12466   update_global_location_list (0);
12467
12468   observer_notify_breakpoint_modified (bpt);
12469 }
12470
12471 /* A callback for iterate_over_related_breakpoints.  */
12472
12473 static void
12474 do_disable_breakpoint (struct breakpoint *b, void *ignore)
12475 {
12476   disable_breakpoint (b);
12477 }
12478
12479 /* A callback for map_breakpoint_numbers that calls
12480    disable_breakpoint.  */
12481
12482 static void
12483 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
12484 {
12485   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
12486 }
12487
12488 static void
12489 disable_command (char *args, int from_tty)
12490 {
12491   if (args == 0)
12492     {
12493       struct breakpoint *bpt;
12494
12495       ALL_BREAKPOINTS (bpt)
12496         if (user_breakpoint_p (bpt))
12497           disable_breakpoint (bpt);
12498     }
12499   else if (strchr (args, '.'))
12500     {
12501       struct bp_location *loc = find_location_by_number (args);
12502       if (loc)
12503         {
12504           loc->enabled = 0;
12505           if (target_supports_enable_disable_tracepoint ()
12506               && current_trace_status ()->running && loc->owner
12507               && is_tracepoint (loc->owner))
12508             target_disable_tracepoint (loc);
12509         }
12510       update_global_location_list (0);
12511     }
12512   else
12513     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
12514 }
12515
12516 static void
12517 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition)
12518 {
12519   int target_resources_ok;
12520
12521   if (bpt->type == bp_hardware_breakpoint)
12522     {
12523       int i;
12524       i = hw_breakpoint_used_count ();
12525       target_resources_ok = 
12526         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
12527                                             i + 1, 0);
12528       if (target_resources_ok == 0)
12529         error (_("No hardware breakpoint support in the target."));
12530       else if (target_resources_ok < 0)
12531         error (_("Hardware breakpoints used exceeds limit."));
12532     }
12533
12534   if (is_watchpoint (bpt))
12535     {
12536       /* Initialize it just to avoid a GCC false warning.  */
12537       enum enable_state orig_enable_state = 0;
12538       volatile struct gdb_exception e;
12539
12540       TRY_CATCH (e, RETURN_MASK_ALL)
12541         {
12542           struct watchpoint *w = (struct watchpoint *) bpt;
12543
12544           orig_enable_state = bpt->enable_state;
12545           bpt->enable_state = bp_enabled;
12546           update_watchpoint (w, 1 /* reparse */);
12547         }
12548       if (e.reason < 0)
12549         {
12550           bpt->enable_state = orig_enable_state;
12551           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
12552                              bpt->number);
12553           return;
12554         }
12555     }
12556
12557   if (bpt->enable_state != bp_permanent)
12558     bpt->enable_state = bp_enabled;
12559
12560   if (target_supports_enable_disable_tracepoint ()
12561       && current_trace_status ()->running && is_tracepoint (bpt))
12562     {
12563       struct bp_location *location;
12564
12565       for (location = bpt->loc; location; location = location->next)
12566         target_enable_tracepoint (location);
12567     }
12568
12569   bpt->disposition = disposition;
12570   update_global_location_list (1);
12571   breakpoints_changed ();
12572   
12573   observer_notify_breakpoint_modified (bpt);
12574 }
12575
12576
12577 void
12578 enable_breakpoint (struct breakpoint *bpt)
12579 {
12580   enable_breakpoint_disp (bpt, bpt->disposition);
12581 }
12582
12583 static void
12584 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
12585 {
12586   enable_breakpoint (bpt);
12587 }
12588
12589 /* A callback for map_breakpoint_numbers that calls
12590    enable_breakpoint.  */
12591
12592 static void
12593 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
12594 {
12595   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
12596 }
12597
12598 /* The enable command enables the specified breakpoints (or all defined
12599    breakpoints) so they once again become (or continue to be) effective
12600    in stopping the inferior.  */
12601
12602 static void
12603 enable_command (char *args, int from_tty)
12604 {
12605   if (args == 0)
12606     {
12607       struct breakpoint *bpt;
12608
12609       ALL_BREAKPOINTS (bpt)
12610         if (user_breakpoint_p (bpt))
12611           enable_breakpoint (bpt);
12612     }
12613   else if (strchr (args, '.'))
12614     {
12615       struct bp_location *loc = find_location_by_number (args);
12616       if (loc)
12617         {
12618           loc->enabled = 1;
12619           if (target_supports_enable_disable_tracepoint ()
12620               && current_trace_status ()->running && loc->owner
12621               && is_tracepoint (loc->owner))
12622             target_enable_tracepoint (loc);
12623         }
12624       update_global_location_list (1);
12625     }
12626   else
12627     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
12628 }
12629
12630 static void
12631 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
12632 {
12633   enum bpdisp disp = *(enum bpdisp *) arg;
12634
12635   enable_breakpoint_disp (bpt, disp);
12636 }
12637
12638 static void
12639 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
12640 {
12641   enum bpdisp disp = disp_disable;
12642
12643   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
12644 }
12645
12646 static void
12647 enable_once_command (char *args, int from_tty)
12648 {
12649   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
12650 }
12651
12652 static void
12653 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
12654 {
12655   enum bpdisp disp = disp_del;
12656
12657   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
12658 }
12659
12660 static void
12661 enable_delete_command (char *args, int from_tty)
12662 {
12663   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
12664 }
12665 \f
12666 static void
12667 set_breakpoint_cmd (char *args, int from_tty)
12668 {
12669 }
12670
12671 static void
12672 show_breakpoint_cmd (char *args, int from_tty)
12673 {
12674 }
12675
12676 /* Invalidate last known value of any hardware watchpoint if
12677    the memory which that value represents has been written to by
12678    GDB itself.  */
12679
12680 static void
12681 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
12682                                       const bfd_byte *data)
12683 {
12684   struct breakpoint *bp;
12685
12686   ALL_BREAKPOINTS (bp)
12687     if (bp->enable_state == bp_enabled
12688         && bp->type == bp_hardware_watchpoint)
12689       {
12690         struct watchpoint *wp = (struct watchpoint *) bp;
12691
12692         if (wp->val_valid && wp->val)
12693           {
12694             struct bp_location *loc;
12695
12696             for (loc = bp->loc; loc != NULL; loc = loc->next)
12697               if (loc->loc_type == bp_loc_hardware_watchpoint
12698                   && loc->address + loc->length > addr
12699                   && addr + len > loc->address)
12700                 {
12701                   value_free (wp->val);
12702                   wp->val = NULL;
12703                   wp->val_valid = 0;
12704                 }
12705           }
12706       }
12707 }
12708
12709 /* Use the last displayed codepoint's values, or nothing
12710    if they aren't valid.  */
12711
12712 struct symtabs_and_lines
12713 decode_line_spec_1 (char *string, int flags)
12714 {
12715   struct symtabs_and_lines sals;
12716
12717   if (string == 0)
12718     error (_("Empty line specification."));
12719   if (last_displayed_sal_is_valid ())
12720     sals = decode_line_1 (&string, flags,
12721                           get_last_displayed_symtab (),
12722                           get_last_displayed_line ());
12723   else
12724     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
12725   if (*string)
12726     error (_("Junk at end of line specification: %s"), string);
12727   return sals;
12728 }
12729
12730 /* Create and insert a raw software breakpoint at PC.  Return an
12731    identifier, which should be used to remove the breakpoint later.
12732    In general, places which call this should be using something on the
12733    breakpoint chain instead; this function should be eliminated
12734    someday.  */
12735
12736 void *
12737 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
12738                                   struct address_space *aspace, CORE_ADDR pc)
12739 {
12740   struct bp_target_info *bp_tgt;
12741
12742   bp_tgt = XZALLOC (struct bp_target_info);
12743
12744   bp_tgt->placed_address_space = aspace;
12745   bp_tgt->placed_address = pc;
12746
12747   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
12748     {
12749       /* Could not insert the breakpoint.  */
12750       xfree (bp_tgt);
12751       return NULL;
12752     }
12753
12754   return bp_tgt;
12755 }
12756
12757 /* Remove a breakpoint BP inserted by
12758    deprecated_insert_raw_breakpoint.  */
12759
12760 int
12761 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
12762 {
12763   struct bp_target_info *bp_tgt = bp;
12764   int ret;
12765
12766   ret = target_remove_breakpoint (gdbarch, bp_tgt);
12767   xfree (bp_tgt);
12768
12769   return ret;
12770 }
12771
12772 /* One (or perhaps two) breakpoints used for software single
12773    stepping.  */
12774
12775 static void *single_step_breakpoints[2];
12776 static struct gdbarch *single_step_gdbarch[2];
12777
12778 /* Create and insert a breakpoint for software single step.  */
12779
12780 void
12781 insert_single_step_breakpoint (struct gdbarch *gdbarch,
12782                                struct address_space *aspace, 
12783                                CORE_ADDR next_pc)
12784 {
12785   void **bpt_p;
12786
12787   if (single_step_breakpoints[0] == NULL)
12788     {
12789       bpt_p = &single_step_breakpoints[0];
12790       single_step_gdbarch[0] = gdbarch;
12791     }
12792   else
12793     {
12794       gdb_assert (single_step_breakpoints[1] == NULL);
12795       bpt_p = &single_step_breakpoints[1];
12796       single_step_gdbarch[1] = gdbarch;
12797     }
12798
12799   /* NOTE drow/2006-04-11: A future improvement to this function would
12800      be to only create the breakpoints once, and actually put them on
12801      the breakpoint chain.  That would let us use set_raw_breakpoint.
12802      We could adjust the addresses each time they were needed.  Doing
12803      this requires corresponding changes elsewhere where single step
12804      breakpoints are handled, however.  So, for now, we use this.  */
12805
12806   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
12807   if (*bpt_p == NULL)
12808     error (_("Could not insert single-step breakpoint at %s"),
12809              paddress (gdbarch, next_pc));
12810 }
12811
12812 /* Check if the breakpoints used for software single stepping
12813    were inserted or not.  */
12814
12815 int
12816 single_step_breakpoints_inserted (void)
12817 {
12818   return (single_step_breakpoints[0] != NULL
12819           || single_step_breakpoints[1] != NULL);
12820 }
12821
12822 /* Remove and delete any breakpoints used for software single step.  */
12823
12824 void
12825 remove_single_step_breakpoints (void)
12826 {
12827   gdb_assert (single_step_breakpoints[0] != NULL);
12828
12829   /* See insert_single_step_breakpoint for more about this deprecated
12830      call.  */
12831   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
12832                                     single_step_breakpoints[0]);
12833   single_step_gdbarch[0] = NULL;
12834   single_step_breakpoints[0] = NULL;
12835
12836   if (single_step_breakpoints[1] != NULL)
12837     {
12838       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
12839                                         single_step_breakpoints[1]);
12840       single_step_gdbarch[1] = NULL;
12841       single_step_breakpoints[1] = NULL;
12842     }
12843 }
12844
12845 /* Delete software single step breakpoints without removing them from
12846    the inferior.  This is intended to be used if the inferior's address
12847    space where they were inserted is already gone, e.g. after exit or
12848    exec.  */
12849
12850 void
12851 cancel_single_step_breakpoints (void)
12852 {
12853   int i;
12854
12855   for (i = 0; i < 2; i++)
12856     if (single_step_breakpoints[i])
12857       {
12858         xfree (single_step_breakpoints[i]);
12859         single_step_breakpoints[i] = NULL;
12860         single_step_gdbarch[i] = NULL;
12861       }
12862 }
12863
12864 /* Detach software single-step breakpoints from INFERIOR_PTID without
12865    removing them.  */
12866
12867 static void
12868 detach_single_step_breakpoints (void)
12869 {
12870   int i;
12871
12872   for (i = 0; i < 2; i++)
12873     if (single_step_breakpoints[i])
12874       target_remove_breakpoint (single_step_gdbarch[i],
12875                                 single_step_breakpoints[i]);
12876 }
12877
12878 /* Check whether a software single-step breakpoint is inserted at
12879    PC.  */
12880
12881 static int
12882 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
12883                                         CORE_ADDR pc)
12884 {
12885   int i;
12886
12887   for (i = 0; i < 2; i++)
12888     {
12889       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
12890       if (bp_tgt
12891           && breakpoint_address_match (bp_tgt->placed_address_space,
12892                                        bp_tgt->placed_address,
12893                                        aspace, pc))
12894         return 1;
12895     }
12896
12897   return 0;
12898 }
12899
12900 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
12901    non-zero otherwise.  */
12902 static int
12903 is_syscall_catchpoint_enabled (struct breakpoint *bp)
12904 {
12905   if (syscall_catchpoint_p (bp)
12906       && bp->enable_state != bp_disabled
12907       && bp->enable_state != bp_call_disabled)
12908     return 1;
12909   else
12910     return 0;
12911 }
12912
12913 int
12914 catch_syscall_enabled (void)
12915 {
12916   struct inferior *inf = current_inferior ();
12917
12918   return inf->total_syscalls_count != 0;
12919 }
12920
12921 int
12922 catching_syscall_number (int syscall_number)
12923 {
12924   struct breakpoint *bp;
12925
12926   ALL_BREAKPOINTS (bp)
12927     if (is_syscall_catchpoint_enabled (bp))
12928       {
12929         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
12930
12931         if (c->syscalls_to_be_caught)
12932           {
12933             int i, iter;
12934             for (i = 0;
12935                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
12936                  i++)
12937               if (syscall_number == iter)
12938                 return 1;
12939           }
12940         else
12941           return 1;
12942       }
12943
12944   return 0;
12945 }
12946
12947 /* Complete syscall names.  Used by "catch syscall".  */
12948 static char **
12949 catch_syscall_completer (struct cmd_list_element *cmd,
12950                          char *text, char *word)
12951 {
12952   const char **list = get_syscall_names ();
12953   char **retlist
12954     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
12955
12956   xfree (list);
12957   return retlist;
12958 }
12959
12960 /* Tracepoint-specific operations.  */
12961
12962 /* Set tracepoint count to NUM.  */
12963 static void
12964 set_tracepoint_count (int num)
12965 {
12966   tracepoint_count = num;
12967   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
12968 }
12969
12970 void
12971 trace_command (char *arg, int from_tty)
12972 {
12973   if (create_breakpoint (get_current_arch (),
12974                          arg,
12975                          NULL, 0, 1 /* parse arg */,
12976                          0 /* tempflag */,
12977                          bp_tracepoint /* type_wanted */,
12978                          0 /* Ignore count */,
12979                          pending_break_support,
12980                          &tracepoint_breakpoint_ops,
12981                          from_tty,
12982                          1 /* enabled */,
12983                          0 /* internal */))
12984     set_tracepoint_count (breakpoint_count);
12985 }
12986
12987 void
12988 ftrace_command (char *arg, int from_tty)
12989 {
12990   if (create_breakpoint (get_current_arch (),
12991                          arg,
12992                          NULL, 0, 1 /* parse arg */,
12993                          0 /* tempflag */,
12994                          bp_fast_tracepoint /* type_wanted */,
12995                          0 /* Ignore count */,
12996                          pending_break_support,
12997                          &tracepoint_breakpoint_ops,
12998                          from_tty,
12999                          1 /* enabled */,
13000                          0 /* internal */))
13001     set_tracepoint_count (breakpoint_count);
13002 }
13003
13004 /* strace command implementation.  Creates a static tracepoint.  */
13005
13006 void
13007 strace_command (char *arg, int from_tty)
13008 {
13009   struct breakpoint_ops *ops;
13010
13011   /* Decide if we are dealing with a static tracepoint marker (`-m'),
13012      or with a normal static tracepoint.  */
13013   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
13014     ops = &strace_marker_breakpoint_ops;
13015   else
13016     ops = &tracepoint_breakpoint_ops;
13017
13018   if (create_breakpoint (get_current_arch (),
13019                          arg,
13020                          NULL, 0, 1 /* parse arg */,
13021                          0 /* tempflag */,
13022                          bp_static_tracepoint /* type_wanted */,
13023                          0 /* Ignore count */,
13024                          pending_break_support,
13025                          ops,
13026                          from_tty,
13027                          1 /* enabled */,
13028                          0 /* internal */))
13029     set_tracepoint_count (breakpoint_count);
13030 }
13031
13032 /* Set up a fake reader function that gets command lines from a linked
13033    list that was acquired during tracepoint uploading.  */
13034
13035 static struct uploaded_tp *this_utp;
13036 static int next_cmd;
13037
13038 static char *
13039 read_uploaded_action (void)
13040 {
13041   char *rslt;
13042
13043   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
13044
13045   next_cmd++;
13046
13047   return rslt;
13048 }
13049
13050 /* Given information about a tracepoint as recorded on a target (which
13051    can be either a live system or a trace file), attempt to create an
13052    equivalent GDB tracepoint.  This is not a reliable process, since
13053    the target does not necessarily have all the information used when
13054    the tracepoint was originally defined.  */
13055   
13056 struct tracepoint *
13057 create_tracepoint_from_upload (struct uploaded_tp *utp)
13058 {
13059   char *addr_str, small_buf[100];
13060   struct tracepoint *tp;
13061
13062   if (utp->at_string)
13063     addr_str = utp->at_string;
13064   else
13065     {
13066       /* In the absence of a source location, fall back to raw
13067          address.  Since there is no way to confirm that the address
13068          means the same thing as when the trace was started, warn the
13069          user.  */
13070       warning (_("Uploaded tracepoint %d has no "
13071                  "source location, using raw address"),
13072                utp->number);
13073       sprintf (small_buf, "*%s", hex_string (utp->addr));
13074       addr_str = small_buf;
13075     }
13076
13077   /* There's not much we can do with a sequence of bytecodes.  */
13078   if (utp->cond && !utp->cond_string)
13079     warning (_("Uploaded tracepoint %d condition "
13080                "has no source form, ignoring it"),
13081              utp->number);
13082
13083   if (!create_breakpoint (get_current_arch (),
13084                           addr_str,
13085                           utp->cond_string, -1, 0 /* parse cond/thread */,
13086                           0 /* tempflag */,
13087                           utp->type /* type_wanted */,
13088                           0 /* Ignore count */,
13089                           pending_break_support,
13090                           &tracepoint_breakpoint_ops,
13091                           0 /* from_tty */,
13092                           utp->enabled /* enabled */,
13093                           0 /* internal */))
13094     return NULL;
13095
13096   set_tracepoint_count (breakpoint_count);
13097   
13098   /* Get the tracepoint we just created.  */
13099   tp = get_tracepoint (tracepoint_count);
13100   gdb_assert (tp != NULL);
13101
13102   if (utp->pass > 0)
13103     {
13104       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
13105
13106       trace_pass_command (small_buf, 0);
13107     }
13108
13109   /* If we have uploaded versions of the original commands, set up a
13110      special-purpose "reader" function and call the usual command line
13111      reader, then pass the result to the breakpoint command-setting
13112      function.  */
13113   if (!VEC_empty (char_ptr, utp->cmd_strings))
13114     {
13115       struct command_line *cmd_list;
13116
13117       this_utp = utp;
13118       next_cmd = 0;
13119
13120       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
13121
13122       breakpoint_set_commands (&tp->base, cmd_list);
13123     }
13124   else if (!VEC_empty (char_ptr, utp->actions)
13125            || !VEC_empty (char_ptr, utp->step_actions))
13126     warning (_("Uploaded tracepoint %d actions "
13127                "have no source form, ignoring them"),
13128              utp->number);
13129
13130   /* Copy any status information that might be available.  */
13131   tp->base.hit_count = utp->hit_count;
13132   tp->traceframe_usage = utp->traceframe_usage;
13133
13134   return tp;
13135 }
13136   
13137 /* Print information on tracepoint number TPNUM_EXP, or all if
13138    omitted.  */
13139
13140 static void
13141 tracepoints_info (char *args, int from_tty)
13142 {
13143   struct ui_out *uiout = current_uiout;
13144   int num_printed;
13145
13146   num_printed = breakpoint_1 (args, 0, is_tracepoint);
13147
13148   if (num_printed == 0)
13149     {
13150       if (args == NULL || *args == '\0')
13151         ui_out_message (uiout, 0, "No tracepoints.\n");
13152       else
13153         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
13154     }
13155
13156   default_collect_info ();
13157 }
13158
13159 /* The 'enable trace' command enables tracepoints.
13160    Not supported by all targets.  */
13161 static void
13162 enable_trace_command (char *args, int from_tty)
13163 {
13164   enable_command (args, from_tty);
13165 }
13166
13167 /* The 'disable trace' command disables tracepoints.
13168    Not supported by all targets.  */
13169 static void
13170 disable_trace_command (char *args, int from_tty)
13171 {
13172   disable_command (args, from_tty);
13173 }
13174
13175 /* Remove a tracepoint (or all if no argument).  */
13176 static void
13177 delete_trace_command (char *arg, int from_tty)
13178 {
13179   struct breakpoint *b, *b_tmp;
13180
13181   dont_repeat ();
13182
13183   if (arg == 0)
13184     {
13185       int breaks_to_delete = 0;
13186
13187       /* Delete all breakpoints if no argument.
13188          Do not delete internal or call-dummy breakpoints, these
13189          have to be deleted with an explicit breakpoint number 
13190          argument.  */
13191       ALL_TRACEPOINTS (b)
13192         if (is_tracepoint (b) && user_breakpoint_p (b))
13193           {
13194             breaks_to_delete = 1;
13195             break;
13196           }
13197
13198       /* Ask user only if there are some breakpoints to delete.  */
13199       if (!from_tty
13200           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
13201         {
13202           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13203             if (is_tracepoint (b) && user_breakpoint_p (b))
13204               delete_breakpoint (b);
13205         }
13206     }
13207   else
13208     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13209 }
13210
13211 /* Helper function for trace_pass_command.  */
13212
13213 static void
13214 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
13215 {
13216   tp->pass_count = count;
13217   observer_notify_tracepoint_modified (tp->base.number);
13218   if (from_tty)
13219     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
13220                      tp->base.number, count);
13221 }
13222
13223 /* Set passcount for tracepoint.
13224
13225    First command argument is passcount, second is tracepoint number.
13226    If tracepoint number omitted, apply to most recently defined.
13227    Also accepts special argument "all".  */
13228
13229 static void
13230 trace_pass_command (char *args, int from_tty)
13231 {
13232   struct tracepoint *t1;
13233   unsigned int count;
13234
13235   if (args == 0 || *args == 0)
13236     error (_("passcount command requires an "
13237              "argument (count + optional TP num)"));
13238
13239   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
13240
13241   while (*args && isspace ((int) *args))
13242     args++;
13243
13244   if (*args && strncasecmp (args, "all", 3) == 0)
13245     {
13246       struct breakpoint *b;
13247
13248       args += 3;                        /* Skip special argument "all".  */
13249       if (*args)
13250         error (_("Junk at end of arguments."));
13251
13252       ALL_TRACEPOINTS (b)
13253       {
13254         t1 = (struct tracepoint *) b;
13255         trace_pass_set_count (t1, count, from_tty);
13256       }
13257     }
13258   else if (*args == '\0')
13259     {
13260       t1 = get_tracepoint_by_number (&args, NULL, 1);
13261       if (t1)
13262         trace_pass_set_count (t1, count, from_tty);
13263     }
13264   else
13265     {
13266       struct get_number_or_range_state state;
13267
13268       init_number_or_range (&state, args);
13269       while (!state.finished)
13270         {
13271           t1 = get_tracepoint_by_number (&args, &state, 1);
13272           if (t1)
13273             trace_pass_set_count (t1, count, from_tty);
13274         }
13275     }
13276 }
13277
13278 struct tracepoint *
13279 get_tracepoint (int num)
13280 {
13281   struct breakpoint *t;
13282
13283   ALL_TRACEPOINTS (t)
13284     if (t->number == num)
13285       return (struct tracepoint *) t;
13286
13287   return NULL;
13288 }
13289
13290 /* Find the tracepoint with the given target-side number (which may be
13291    different from the tracepoint number after disconnecting and
13292    reconnecting).  */
13293
13294 struct tracepoint *
13295 get_tracepoint_by_number_on_target (int num)
13296 {
13297   struct breakpoint *b;
13298
13299   ALL_TRACEPOINTS (b)
13300     {
13301       struct tracepoint *t = (struct tracepoint *) b;
13302
13303       if (t->number_on_target == num)
13304         return t;
13305     }
13306
13307   return NULL;
13308 }
13309
13310 /* Utility: parse a tracepoint number and look it up in the list.
13311    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
13312    If OPTIONAL_P is true, then if the argument is missing, the most
13313    recent tracepoint (tracepoint_count) is returned.  */
13314 struct tracepoint *
13315 get_tracepoint_by_number (char **arg,
13316                           struct get_number_or_range_state *state,
13317                           int optional_p)
13318 {
13319   extern int tracepoint_count;
13320   struct breakpoint *t;
13321   int tpnum;
13322   char *instring = arg == NULL ? NULL : *arg;
13323
13324   if (state)
13325     {
13326       gdb_assert (!state->finished);
13327       tpnum = get_number_or_range (state);
13328     }
13329   else if (arg == NULL || *arg == NULL || ! **arg)
13330     {
13331       if (optional_p)
13332         tpnum = tracepoint_count;
13333       else
13334         error_no_arg (_("tracepoint number"));
13335     }
13336   else
13337     tpnum = get_number (arg);
13338
13339   if (tpnum <= 0)
13340     {
13341       if (instring && *instring)
13342         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
13343                          instring);
13344       else
13345         printf_filtered (_("Tracepoint argument missing "
13346                            "and no previous tracepoint\n"));
13347       return NULL;
13348     }
13349
13350   ALL_TRACEPOINTS (t)
13351     if (t->number == tpnum)
13352     {
13353       return (struct tracepoint *) t;
13354     }
13355
13356   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
13357   return NULL;
13358 }
13359
13360 void
13361 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
13362 {
13363   if (b->thread != -1)
13364     fprintf_unfiltered (fp, " thread %d", b->thread);
13365
13366   if (b->task != 0)
13367     fprintf_unfiltered (fp, " task %d", b->task);
13368
13369   fprintf_unfiltered (fp, "\n");
13370 }
13371
13372 /* Save information on user settable breakpoints (watchpoints, etc) to
13373    a new script file named FILENAME.  If FILTER is non-NULL, call it
13374    on each breakpoint and only include the ones for which it returns
13375    non-zero.  */
13376
13377 static void
13378 save_breakpoints (char *filename, int from_tty,
13379                   int (*filter) (const struct breakpoint *))
13380 {
13381   struct breakpoint *tp;
13382   int any = 0;
13383   char *pathname;
13384   struct cleanup *cleanup;
13385   struct ui_file *fp;
13386   int extra_trace_bits = 0;
13387
13388   if (filename == 0 || *filename == 0)
13389     error (_("Argument required (file name in which to save)"));
13390
13391   /* See if we have anything to save.  */
13392   ALL_BREAKPOINTS (tp)
13393   {
13394     /* Skip internal and momentary breakpoints.  */
13395     if (!user_breakpoint_p (tp))
13396       continue;
13397
13398     /* If we have a filter, only save the breakpoints it accepts.  */
13399     if (filter && !filter (tp))
13400       continue;
13401
13402     any = 1;
13403
13404     if (is_tracepoint (tp))
13405       {
13406         extra_trace_bits = 1;
13407
13408         /* We can stop searching.  */
13409         break;
13410       }
13411   }
13412
13413   if (!any)
13414     {
13415       warning (_("Nothing to save."));
13416       return;
13417     }
13418
13419   pathname = tilde_expand (filename);
13420   cleanup = make_cleanup (xfree, pathname);
13421   fp = gdb_fopen (pathname, "w");
13422   if (!fp)
13423     error (_("Unable to open file '%s' for saving (%s)"),
13424            filename, safe_strerror (errno));
13425   make_cleanup_ui_file_delete (fp);
13426
13427   if (extra_trace_bits)
13428     save_trace_state_variables (fp);
13429
13430   ALL_BREAKPOINTS (tp)
13431   {
13432     /* Skip internal and momentary breakpoints.  */
13433     if (!user_breakpoint_p (tp))
13434       continue;
13435
13436     /* If we have a filter, only save the breakpoints it accepts.  */
13437     if (filter && !filter (tp))
13438       continue;
13439
13440     tp->ops->print_recreate (tp, fp);
13441
13442     /* Note, we can't rely on tp->number for anything, as we can't
13443        assume the recreated breakpoint numbers will match.  Use $bpnum
13444        instead.  */
13445
13446     if (tp->cond_string)
13447       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
13448
13449     if (tp->ignore_count)
13450       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
13451
13452     if (tp->commands)
13453       {
13454         volatile struct gdb_exception ex;       
13455
13456         fprintf_unfiltered (fp, "  commands\n");
13457         
13458         ui_out_redirect (current_uiout, fp);
13459         TRY_CATCH (ex, RETURN_MASK_ALL)
13460           {
13461             print_command_lines (current_uiout, tp->commands->commands, 2);
13462           }
13463         ui_out_redirect (current_uiout, NULL);
13464
13465         if (ex.reason < 0)
13466           throw_exception (ex);
13467
13468         fprintf_unfiltered (fp, "  end\n");
13469       }
13470
13471     if (tp->enable_state == bp_disabled)
13472       fprintf_unfiltered (fp, "disable\n");
13473
13474     /* If this is a multi-location breakpoint, check if the locations
13475        should be individually disabled.  Watchpoint locations are
13476        special, and not user visible.  */
13477     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
13478       {
13479         struct bp_location *loc;
13480         int n = 1;
13481
13482         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
13483           if (!loc->enabled)
13484             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
13485       }
13486   }
13487
13488   if (extra_trace_bits && *default_collect)
13489     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
13490
13491   do_cleanups (cleanup);
13492   if (from_tty)
13493     printf_filtered (_("Saved to file '%s'.\n"), filename);
13494 }
13495
13496 /* The `save breakpoints' command.  */
13497
13498 static void
13499 save_breakpoints_command (char *args, int from_tty)
13500 {
13501   save_breakpoints (args, from_tty, NULL);
13502 }
13503
13504 /* The `save tracepoints' command.  */
13505
13506 static void
13507 save_tracepoints_command (char *args, int from_tty)
13508 {
13509   save_breakpoints (args, from_tty, is_tracepoint);
13510 }
13511
13512 /* Create a vector of all tracepoints.  */
13513
13514 VEC(breakpoint_p) *
13515 all_tracepoints (void)
13516 {
13517   VEC(breakpoint_p) *tp_vec = 0;
13518   struct breakpoint *tp;
13519
13520   ALL_TRACEPOINTS (tp)
13521   {
13522     VEC_safe_push (breakpoint_p, tp_vec, tp);
13523   }
13524
13525   return tp_vec;
13526 }
13527
13528 \f
13529 /* This help string is used for the break, hbreak, tbreak and thbreak
13530    commands.  It is defined as a macro to prevent duplication.
13531    COMMAND should be a string constant containing the name of the
13532    command.  */
13533 #define BREAK_ARGS_HELP(command) \
13534 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
13535 LOCATION may be a line number, function name, or \"*\" and an address.\n\
13536 If a line number is specified, break at start of code for that line.\n\
13537 If a function is specified, break at start of code for that function.\n\
13538 If an address is specified, break at that exact address.\n\
13539 With no LOCATION, uses current execution address of the selected\n\
13540 stack frame.  This is useful for breaking on return to a stack frame.\n\
13541 \n\
13542 THREADNUM is the number from \"info threads\".\n\
13543 CONDITION is a boolean expression.\n\
13544 \n\
13545 Multiple breakpoints at one place are permitted, and useful if their\n\
13546 conditions are different.\n\
13547 \n\
13548 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
13549
13550 /* List of subcommands for "catch".  */
13551 static struct cmd_list_element *catch_cmdlist;
13552
13553 /* List of subcommands for "tcatch".  */
13554 static struct cmd_list_element *tcatch_cmdlist;
13555
13556 void
13557 add_catch_command (char *name, char *docstring,
13558                    void (*sfunc) (char *args, int from_tty,
13559                                   struct cmd_list_element *command),
13560                    char **(*completer) (struct cmd_list_element *cmd,
13561                                          char *text, char *word),
13562                    void *user_data_catch,
13563                    void *user_data_tcatch)
13564 {
13565   struct cmd_list_element *command;
13566
13567   command = add_cmd (name, class_breakpoint, NULL, docstring,
13568                      &catch_cmdlist);
13569   set_cmd_sfunc (command, sfunc);
13570   set_cmd_context (command, user_data_catch);
13571   set_cmd_completer (command, completer);
13572
13573   command = add_cmd (name, class_breakpoint, NULL, docstring,
13574                      &tcatch_cmdlist);
13575   set_cmd_sfunc (command, sfunc);
13576   set_cmd_context (command, user_data_tcatch);
13577   set_cmd_completer (command, completer);
13578 }
13579
13580 static void
13581 clear_syscall_counts (struct inferior *inf)
13582 {
13583   inf->total_syscalls_count = 0;
13584   inf->any_syscall_count = 0;
13585   VEC_free (int, inf->syscalls_counts);
13586 }
13587
13588 static void
13589 save_command (char *arg, int from_tty)
13590 {
13591   printf_unfiltered (_("\"save\" must be followed by "
13592                        "the name of a save subcommand.\n"));
13593   help_list (save_cmdlist, "save ", -1, gdb_stdout);
13594 }
13595
13596 struct breakpoint *
13597 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
13598                           void *data)
13599 {
13600   struct breakpoint *b, *b_tmp;
13601
13602   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13603     {
13604       if ((*callback) (b, data))
13605         return b;
13606     }
13607
13608   return NULL;
13609 }
13610
13611 /* Zero if any of the breakpoint's locations could be a location where
13612    functions have been inlined, nonzero otherwise.  */
13613
13614 static int
13615 is_non_inline_function (struct breakpoint *b)
13616 {
13617   /* The shared library event breakpoint is set on the address of a
13618      non-inline function.  */
13619   if (b->type == bp_shlib_event)
13620     return 1;
13621
13622   return 0;
13623 }
13624
13625 /* Nonzero if the specified PC cannot be a location where functions
13626    have been inlined.  */
13627
13628 int
13629 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc)
13630 {
13631   struct breakpoint *b;
13632   struct bp_location *bl;
13633
13634   ALL_BREAKPOINTS (b)
13635     {
13636       if (!is_non_inline_function (b))
13637         continue;
13638
13639       for (bl = b->loc; bl != NULL; bl = bl->next)
13640         {
13641           if (!bl->shlib_disabled
13642               && bpstat_check_location (bl, aspace, pc))
13643             return 1;
13644         }
13645     }
13646
13647   return 0;
13648 }
13649
13650 void
13651 initialize_breakpoint_ops (void)
13652 {
13653   static int initialized = 0;
13654
13655   struct breakpoint_ops *ops;
13656
13657   if (initialized)
13658     return;
13659   initialized = 1;
13660
13661   /* The breakpoint_ops structure to be inherit by all kinds of
13662      breakpoints (real breakpoints, i.e., user "break" breakpoints,
13663      internal and momentary breakpoints, etc.).  */
13664   ops = &bkpt_base_breakpoint_ops;
13665   *ops = base_breakpoint_ops;
13666   ops->re_set = bkpt_re_set;
13667   ops->insert_location = bkpt_insert_location;
13668   ops->remove_location = bkpt_remove_location;
13669   ops->breakpoint_hit = bkpt_breakpoint_hit;
13670   ops->create_sals_from_address = bkpt_create_sals_from_address;
13671   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
13672   ops->decode_linespec = bkpt_decode_linespec;
13673
13674   /* The breakpoint_ops structure to be used in regular breakpoints.  */
13675   ops = &bkpt_breakpoint_ops;
13676   *ops = bkpt_base_breakpoint_ops;
13677   ops->re_set = bkpt_re_set;
13678   ops->resources_needed = bkpt_resources_needed;
13679   ops->print_it = bkpt_print_it;
13680   ops->print_mention = bkpt_print_mention;
13681   ops->print_recreate = bkpt_print_recreate;
13682
13683   /* Ranged breakpoints.  */
13684   ops = &ranged_breakpoint_ops;
13685   *ops = bkpt_breakpoint_ops;
13686   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
13687   ops->resources_needed = resources_needed_ranged_breakpoint;
13688   ops->print_it = print_it_ranged_breakpoint;
13689   ops->print_one = print_one_ranged_breakpoint;
13690   ops->print_one_detail = print_one_detail_ranged_breakpoint;
13691   ops->print_mention = print_mention_ranged_breakpoint;
13692   ops->print_recreate = print_recreate_ranged_breakpoint;
13693
13694   /* Internal breakpoints.  */
13695   ops = &internal_breakpoint_ops;
13696   *ops = bkpt_base_breakpoint_ops;
13697   ops->re_set = internal_bkpt_re_set;
13698   ops->check_status = internal_bkpt_check_status;
13699   ops->print_it = internal_bkpt_print_it;
13700   ops->print_mention = internal_bkpt_print_mention;
13701
13702   /* Momentary breakpoints.  */
13703   ops = &momentary_breakpoint_ops;
13704   *ops = bkpt_base_breakpoint_ops;
13705   ops->re_set = momentary_bkpt_re_set;
13706   ops->check_status = momentary_bkpt_check_status;
13707   ops->print_it = momentary_bkpt_print_it;
13708   ops->print_mention = momentary_bkpt_print_mention;
13709
13710   /* GNU v3 exception catchpoints.  */
13711   ops = &gnu_v3_exception_catchpoint_ops;
13712   *ops = bkpt_breakpoint_ops;
13713   ops->print_it = print_it_exception_catchpoint;
13714   ops->print_one = print_one_exception_catchpoint;
13715   ops->print_mention = print_mention_exception_catchpoint;
13716   ops->print_recreate = print_recreate_exception_catchpoint;
13717
13718   /* Watchpoints.  */
13719   ops = &watchpoint_breakpoint_ops;
13720   *ops = base_breakpoint_ops;
13721   ops->dtor = dtor_watchpoint;
13722   ops->re_set = re_set_watchpoint;
13723   ops->insert_location = insert_watchpoint;
13724   ops->remove_location = remove_watchpoint;
13725   ops->breakpoint_hit = breakpoint_hit_watchpoint;
13726   ops->check_status = check_status_watchpoint;
13727   ops->resources_needed = resources_needed_watchpoint;
13728   ops->works_in_software_mode = works_in_software_mode_watchpoint;
13729   ops->print_it = print_it_watchpoint;
13730   ops->print_mention = print_mention_watchpoint;
13731   ops->print_recreate = print_recreate_watchpoint;
13732
13733   /* Masked watchpoints.  */
13734   ops = &masked_watchpoint_breakpoint_ops;
13735   *ops = watchpoint_breakpoint_ops;
13736   ops->insert_location = insert_masked_watchpoint;
13737   ops->remove_location = remove_masked_watchpoint;
13738   ops->resources_needed = resources_needed_masked_watchpoint;
13739   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
13740   ops->print_it = print_it_masked_watchpoint;
13741   ops->print_one_detail = print_one_detail_masked_watchpoint;
13742   ops->print_mention = print_mention_masked_watchpoint;
13743   ops->print_recreate = print_recreate_masked_watchpoint;
13744
13745   /* Tracepoints.  */
13746   ops = &tracepoint_breakpoint_ops;
13747   *ops = base_breakpoint_ops;
13748   ops->re_set = tracepoint_re_set;
13749   ops->breakpoint_hit = tracepoint_breakpoint_hit;
13750   ops->print_one_detail = tracepoint_print_one_detail;
13751   ops->print_mention = tracepoint_print_mention;
13752   ops->print_recreate = tracepoint_print_recreate;
13753   ops->create_sals_from_address = tracepoint_create_sals_from_address;
13754   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
13755   ops->decode_linespec = tracepoint_decode_linespec;
13756
13757   /* Static tracepoints with marker (`-m').  */
13758   ops = &strace_marker_breakpoint_ops;
13759   *ops = tracepoint_breakpoint_ops;
13760   ops->create_sals_from_address = strace_marker_create_sals_from_address;
13761   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
13762   ops->decode_linespec = strace_marker_decode_linespec;
13763
13764   /* Fork catchpoints.  */
13765   ops = &catch_fork_breakpoint_ops;
13766   *ops = base_breakpoint_ops;
13767   ops->insert_location = insert_catch_fork;
13768   ops->remove_location = remove_catch_fork;
13769   ops->breakpoint_hit = breakpoint_hit_catch_fork;
13770   ops->print_it = print_it_catch_fork;
13771   ops->print_one = print_one_catch_fork;
13772   ops->print_mention = print_mention_catch_fork;
13773   ops->print_recreate = print_recreate_catch_fork;
13774
13775   /* Vfork catchpoints.  */
13776   ops = &catch_vfork_breakpoint_ops;
13777   *ops = base_breakpoint_ops;
13778   ops->insert_location = insert_catch_vfork;
13779   ops->remove_location = remove_catch_vfork;
13780   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
13781   ops->print_it = print_it_catch_vfork;
13782   ops->print_one = print_one_catch_vfork;
13783   ops->print_mention = print_mention_catch_vfork;
13784   ops->print_recreate = print_recreate_catch_vfork;
13785
13786   /* Exec catchpoints.  */
13787   ops = &catch_exec_breakpoint_ops;
13788   *ops = base_breakpoint_ops;
13789   ops->dtor = dtor_catch_exec;
13790   ops->insert_location = insert_catch_exec;
13791   ops->remove_location = remove_catch_exec;
13792   ops->breakpoint_hit = breakpoint_hit_catch_exec;
13793   ops->print_it = print_it_catch_exec;
13794   ops->print_one = print_one_catch_exec;
13795   ops->print_mention = print_mention_catch_exec;
13796   ops->print_recreate = print_recreate_catch_exec;
13797
13798   /* Syscall catchpoints.  */
13799   ops = &catch_syscall_breakpoint_ops;
13800   *ops = base_breakpoint_ops;
13801   ops->dtor = dtor_catch_syscall;
13802   ops->insert_location = insert_catch_syscall;
13803   ops->remove_location = remove_catch_syscall;
13804   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
13805   ops->print_it = print_it_catch_syscall;
13806   ops->print_one = print_one_catch_syscall;
13807   ops->print_mention = print_mention_catch_syscall;
13808   ops->print_recreate = print_recreate_catch_syscall;
13809 }
13810
13811 void
13812 _initialize_breakpoint (void)
13813 {
13814   struct cmd_list_element *c;
13815
13816   initialize_breakpoint_ops ();
13817
13818   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
13819   observer_attach_inferior_exit (clear_syscall_counts);
13820   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
13821
13822   breakpoint_objfile_key = register_objfile_data ();
13823
13824   breakpoint_chain = 0;
13825   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
13826      before a breakpoint is set.  */
13827   breakpoint_count = 0;
13828
13829   tracepoint_count = 0;
13830
13831   add_com ("ignore", class_breakpoint, ignore_command, _("\
13832 Set ignore-count of breakpoint number N to COUNT.\n\
13833 Usage is `ignore N COUNT'."));
13834   if (xdb_commands)
13835     add_com_alias ("bc", "ignore", class_breakpoint, 1);
13836
13837   add_com ("commands", class_breakpoint, commands_command, _("\
13838 Set commands to be executed when a breakpoint is hit.\n\
13839 Give breakpoint number as argument after \"commands\".\n\
13840 With no argument, the targeted breakpoint is the last one set.\n\
13841 The commands themselves follow starting on the next line.\n\
13842 Type a line containing \"end\" to indicate the end of them.\n\
13843 Give \"silent\" as the first line to make the breakpoint silent;\n\
13844 then no output is printed when it is hit, except what the commands print."));
13845
13846   add_com ("condition", class_breakpoint, condition_command, _("\
13847 Specify breakpoint number N to break only if COND is true.\n\
13848 Usage is `condition N COND', where N is an integer and COND is an\n\
13849 expression to be evaluated whenever breakpoint N is reached."));
13850
13851   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
13852 Set a temporary breakpoint.\n\
13853 Like \"break\" except the breakpoint is only temporary,\n\
13854 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
13855 by using \"enable delete\" on the breakpoint number.\n\
13856 \n"
13857 BREAK_ARGS_HELP ("tbreak")));
13858   set_cmd_completer (c, location_completer);
13859
13860   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
13861 Set a hardware assisted breakpoint.\n\
13862 Like \"break\" except the breakpoint requires hardware support,\n\
13863 some target hardware may not have this support.\n\
13864 \n"
13865 BREAK_ARGS_HELP ("hbreak")));
13866   set_cmd_completer (c, location_completer);
13867
13868   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
13869 Set a temporary hardware assisted breakpoint.\n\
13870 Like \"hbreak\" except the breakpoint is only temporary,\n\
13871 so it will be deleted when hit.\n\
13872 \n"
13873 BREAK_ARGS_HELP ("thbreak")));
13874   set_cmd_completer (c, location_completer);
13875
13876   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
13877 Enable some breakpoints.\n\
13878 Give breakpoint numbers (separated by spaces) as arguments.\n\
13879 With no subcommand, breakpoints are enabled until you command otherwise.\n\
13880 This is used to cancel the effect of the \"disable\" command.\n\
13881 With a subcommand you can enable temporarily."),
13882                   &enablelist, "enable ", 1, &cmdlist);
13883   if (xdb_commands)
13884     add_com ("ab", class_breakpoint, enable_command, _("\
13885 Enable some breakpoints.\n\
13886 Give breakpoint numbers (separated by spaces) as arguments.\n\
13887 With no subcommand, breakpoints are enabled until you command otherwise.\n\
13888 This is used to cancel the effect of the \"disable\" command.\n\
13889 With a subcommand you can enable temporarily."));
13890
13891   add_com_alias ("en", "enable", class_breakpoint, 1);
13892
13893   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
13894 Enable some breakpoints.\n\
13895 Give breakpoint numbers (separated by spaces) as arguments.\n\
13896 This is used to cancel the effect of the \"disable\" command.\n\
13897 May be abbreviated to simply \"enable\".\n"),
13898                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
13899
13900   add_cmd ("once", no_class, enable_once_command, _("\
13901 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
13902 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
13903            &enablebreaklist);
13904
13905   add_cmd ("delete", no_class, enable_delete_command, _("\
13906 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
13907 If a breakpoint is hit while enabled in this fashion, it is deleted."),
13908            &enablebreaklist);
13909
13910   add_cmd ("delete", no_class, enable_delete_command, _("\
13911 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
13912 If a breakpoint is hit while enabled in this fashion, it is deleted."),
13913            &enablelist);
13914
13915   add_cmd ("once", no_class, enable_once_command, _("\
13916 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
13917 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
13918            &enablelist);
13919
13920   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
13921 Disable some breakpoints.\n\
13922 Arguments are breakpoint numbers with spaces in between.\n\
13923 To disable all breakpoints, give no argument.\n\
13924 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
13925                   &disablelist, "disable ", 1, &cmdlist);
13926   add_com_alias ("dis", "disable", class_breakpoint, 1);
13927   add_com_alias ("disa", "disable", class_breakpoint, 1);
13928   if (xdb_commands)
13929     add_com ("sb", class_breakpoint, disable_command, _("\
13930 Disable some breakpoints.\n\
13931 Arguments are breakpoint numbers with spaces in between.\n\
13932 To disable all breakpoints, give no argument.\n\
13933 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
13934
13935   add_cmd ("breakpoints", class_alias, disable_command, _("\
13936 Disable some breakpoints.\n\
13937 Arguments are breakpoint numbers with spaces in between.\n\
13938 To disable all breakpoints, give no argument.\n\
13939 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
13940 This command may be abbreviated \"disable\"."),
13941            &disablelist);
13942
13943   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
13944 Delete some breakpoints or auto-display expressions.\n\
13945 Arguments are breakpoint numbers with spaces in between.\n\
13946 To delete all breakpoints, give no argument.\n\
13947 \n\
13948 Also a prefix command for deletion of other GDB objects.\n\
13949 The \"unset\" command is also an alias for \"delete\"."),
13950                   &deletelist, "delete ", 1, &cmdlist);
13951   add_com_alias ("d", "delete", class_breakpoint, 1);
13952   add_com_alias ("del", "delete", class_breakpoint, 1);
13953   if (xdb_commands)
13954     add_com ("db", class_breakpoint, delete_command, _("\
13955 Delete some breakpoints.\n\
13956 Arguments are breakpoint numbers with spaces in between.\n\
13957 To delete all breakpoints, give no argument.\n"));
13958
13959   add_cmd ("breakpoints", class_alias, delete_command, _("\
13960 Delete some breakpoints or auto-display expressions.\n\
13961 Arguments are breakpoint numbers with spaces in between.\n\
13962 To delete all breakpoints, give no argument.\n\
13963 This command may be abbreviated \"delete\"."),
13964            &deletelist);
13965
13966   add_com ("clear", class_breakpoint, clear_command, _("\
13967 Clear breakpoint at specified line or function.\n\
13968 Argument may be line number, function name, or \"*\" and an address.\n\
13969 If line number is specified, all breakpoints in that line are cleared.\n\
13970 If function is specified, breakpoints at beginning of function are cleared.\n\
13971 If an address is specified, breakpoints at that address are cleared.\n\
13972 \n\
13973 With no argument, clears all breakpoints in the line that the selected frame\n\
13974 is executing in.\n\
13975 \n\
13976 See also the \"delete\" command which clears breakpoints by number."));
13977   add_com_alias ("cl", "clear", class_breakpoint, 1);
13978
13979   c = add_com ("break", class_breakpoint, break_command, _("\
13980 Set breakpoint at specified line or function.\n"
13981 BREAK_ARGS_HELP ("break")));
13982   set_cmd_completer (c, location_completer);
13983
13984   add_com_alias ("b", "break", class_run, 1);
13985   add_com_alias ("br", "break", class_run, 1);
13986   add_com_alias ("bre", "break", class_run, 1);
13987   add_com_alias ("brea", "break", class_run, 1);
13988
13989   if (xdb_commands)
13990    add_com_alias ("ba", "break", class_breakpoint, 1);
13991
13992   if (dbx_commands)
13993     {
13994       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
13995 Break in function/address or break at a line in the current file."),
13996                              &stoplist, "stop ", 1, &cmdlist);
13997       add_cmd ("in", class_breakpoint, stopin_command,
13998                _("Break in function or address."), &stoplist);
13999       add_cmd ("at", class_breakpoint, stopat_command,
14000                _("Break at a line in the current file."), &stoplist);
14001       add_com ("status", class_info, breakpoints_info, _("\
14002 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
14003 The \"Type\" column indicates one of:\n\
14004 \tbreakpoint     - normal breakpoint\n\
14005 \twatchpoint     - watchpoint\n\
14006 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14007 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14008 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14009 address and file/line number respectively.\n\
14010 \n\
14011 Convenience variable \"$_\" and default examine address for \"x\"\n\
14012 are set to the address of the last breakpoint listed unless the command\n\
14013 is prefixed with \"server \".\n\n\
14014 Convenience variable \"$bpnum\" contains the number of the last\n\
14015 breakpoint set."));
14016     }
14017
14018   add_info ("breakpoints", breakpoints_info, _("\
14019 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
14020 The \"Type\" column indicates one of:\n\
14021 \tbreakpoint     - normal breakpoint\n\
14022 \twatchpoint     - watchpoint\n\
14023 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14024 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14025 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14026 address and file/line number respectively.\n\
14027 \n\
14028 Convenience variable \"$_\" and default examine address for \"x\"\n\
14029 are set to the address of the last breakpoint listed unless the command\n\
14030 is prefixed with \"server \".\n\n\
14031 Convenience variable \"$bpnum\" contains the number of the last\n\
14032 breakpoint set."));
14033
14034   add_info_alias ("b", "breakpoints", 1);
14035
14036   if (xdb_commands)
14037     add_com ("lb", class_breakpoint, breakpoints_info, _("\
14038 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
14039 The \"Type\" column indicates one of:\n\
14040 \tbreakpoint     - normal breakpoint\n\
14041 \twatchpoint     - watchpoint\n\
14042 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14043 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14044 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14045 address and file/line number respectively.\n\
14046 \n\
14047 Convenience variable \"$_\" and default examine address for \"x\"\n\
14048 are set to the address of the last breakpoint listed unless the command\n\
14049 is prefixed with \"server \".\n\n\
14050 Convenience variable \"$bpnum\" contains the number of the last\n\
14051 breakpoint set."));
14052
14053   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
14054 Status of all breakpoints, or breakpoint number NUMBER.\n\
14055 The \"Type\" column indicates one of:\n\
14056 \tbreakpoint     - normal breakpoint\n\
14057 \twatchpoint     - watchpoint\n\
14058 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
14059 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
14060 \tuntil          - internal breakpoint used by the \"until\" command\n\
14061 \tfinish         - internal breakpoint used by the \"finish\" command\n\
14062 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14063 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14064 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14065 address and file/line number respectively.\n\
14066 \n\
14067 Convenience variable \"$_\" and default examine address for \"x\"\n\
14068 are set to the address of the last breakpoint listed unless the command\n\
14069 is prefixed with \"server \".\n\n\
14070 Convenience variable \"$bpnum\" contains the number of the last\n\
14071 breakpoint set."),
14072            &maintenanceinfolist);
14073
14074   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
14075 Set catchpoints to catch events."),
14076                   &catch_cmdlist, "catch ",
14077                   0/*allow-unknown*/, &cmdlist);
14078
14079   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
14080 Set temporary catchpoints to catch events."),
14081                   &tcatch_cmdlist, "tcatch ",
14082                   0/*allow-unknown*/, &cmdlist);
14083
14084   /* Add catch and tcatch sub-commands.  */
14085   add_catch_command ("catch", _("\
14086 Catch an exception, when caught."),
14087                      catch_catch_command,
14088                      NULL,
14089                      CATCH_PERMANENT,
14090                      CATCH_TEMPORARY);
14091   add_catch_command ("throw", _("\
14092 Catch an exception, when thrown."),
14093                      catch_throw_command,
14094                      NULL,
14095                      CATCH_PERMANENT,
14096                      CATCH_TEMPORARY);
14097   add_catch_command ("fork", _("Catch calls to fork."),
14098                      catch_fork_command_1,
14099                      NULL,
14100                      (void *) (uintptr_t) catch_fork_permanent,
14101                      (void *) (uintptr_t) catch_fork_temporary);
14102   add_catch_command ("vfork", _("Catch calls to vfork."),
14103                      catch_fork_command_1,
14104                      NULL,
14105                      (void *) (uintptr_t) catch_vfork_permanent,
14106                      (void *) (uintptr_t) catch_vfork_temporary);
14107   add_catch_command ("exec", _("Catch calls to exec."),
14108                      catch_exec_command_1,
14109                      NULL,
14110                      CATCH_PERMANENT,
14111                      CATCH_TEMPORARY);
14112   add_catch_command ("syscall", _("\
14113 Catch system calls by their names and/or numbers.\n\
14114 Arguments say which system calls to catch.  If no arguments\n\
14115 are given, every system call will be caught.\n\
14116 Arguments, if given, should be one or more system call names\n\
14117 (if your system supports that), or system call numbers."),
14118                      catch_syscall_command_1,
14119                      catch_syscall_completer,
14120                      CATCH_PERMANENT,
14121                      CATCH_TEMPORARY);
14122
14123   c = add_com ("watch", class_breakpoint, watch_command, _("\
14124 Set a watchpoint for an expression.\n\
14125 Usage: watch [-l|-location] EXPRESSION\n\
14126 A watchpoint stops execution of your program whenever the value of\n\
14127 an expression changes.\n\
14128 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14129 the memory to which it refers."));
14130   set_cmd_completer (c, expression_completer);
14131
14132   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
14133 Set a read watchpoint for an expression.\n\
14134 Usage: rwatch [-l|-location] EXPRESSION\n\
14135 A watchpoint stops execution of your program whenever the value of\n\
14136 an expression is read.\n\
14137 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14138 the memory to which it refers."));
14139   set_cmd_completer (c, expression_completer);
14140
14141   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
14142 Set a watchpoint for an expression.\n\
14143 Usage: awatch [-l|-location] EXPRESSION\n\
14144 A watchpoint stops execution of your program whenever the value of\n\
14145 an expression is either read or written.\n\
14146 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14147 the memory to which it refers."));
14148   set_cmd_completer (c, expression_completer);
14149
14150   add_info ("watchpoints", watchpoints_info, _("\
14151 Status of specified watchpoints (all watchpoints if no argument)."));
14152
14153   /* XXX: cagney/2005-02-23: This should be a boolean, and should
14154      respond to changes - contrary to the description.  */
14155   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
14156                             &can_use_hw_watchpoints, _("\
14157 Set debugger's willingness to use watchpoint hardware."), _("\
14158 Show debugger's willingness to use watchpoint hardware."), _("\
14159 If zero, gdb will not use hardware for new watchpoints, even if\n\
14160 such is available.  (However, any hardware watchpoints that were\n\
14161 created before setting this to nonzero, will continue to use watchpoint\n\
14162 hardware.)"),
14163                             NULL,
14164                             show_can_use_hw_watchpoints,
14165                             &setlist, &showlist);
14166
14167   can_use_hw_watchpoints = 1;
14168
14169   /* Tracepoint manipulation commands.  */
14170
14171   c = add_com ("trace", class_breakpoint, trace_command, _("\
14172 Set a tracepoint at specified line or function.\n\
14173 \n"
14174 BREAK_ARGS_HELP ("trace") "\n\
14175 Do \"help tracepoints\" for info on other tracepoint commands."));
14176   set_cmd_completer (c, location_completer);
14177
14178   add_com_alias ("tp", "trace", class_alias, 0);
14179   add_com_alias ("tr", "trace", class_alias, 1);
14180   add_com_alias ("tra", "trace", class_alias, 1);
14181   add_com_alias ("trac", "trace", class_alias, 1);
14182
14183   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
14184 Set a fast tracepoint at specified line or function.\n\
14185 \n"
14186 BREAK_ARGS_HELP ("ftrace") "\n\
14187 Do \"help tracepoints\" for info on other tracepoint commands."));
14188   set_cmd_completer (c, location_completer);
14189
14190   c = add_com ("strace", class_breakpoint, strace_command, _("\
14191 Set a static tracepoint at specified line, function or marker.\n\
14192 \n\
14193 strace [LOCATION] [if CONDITION]\n\
14194 LOCATION may be a line number, function name, \"*\" and an address,\n\
14195 or -m MARKER_ID.\n\
14196 If a line number is specified, probe the marker at start of code\n\
14197 for that line.  If a function is specified, probe the marker at start\n\
14198 of code for that function.  If an address is specified, probe the marker\n\
14199 at that exact address.  If a marker id is specified, probe the marker\n\
14200 with that name.  With no LOCATION, uses current execution address of\n\
14201 the selected stack frame.\n\
14202 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
14203 This collects arbitrary user data passed in the probe point call to the\n\
14204 tracing library.  You can inspect it when analyzing the trace buffer,\n\
14205 by printing the $_sdata variable like any other convenience variable.\n\
14206 \n\
14207 CONDITION is a boolean expression.\n\
14208 \n\
14209 Multiple tracepoints at one place are permitted, and useful if their\n\
14210 conditions are different.\n\
14211 \n\
14212 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
14213 Do \"help tracepoints\" for info on other tracepoint commands."));
14214   set_cmd_completer (c, location_completer);
14215
14216   add_info ("tracepoints", tracepoints_info, _("\
14217 Status of specified tracepoints (all tracepoints if no argument).\n\
14218 Convenience variable \"$tpnum\" contains the number of the\n\
14219 last tracepoint set."));
14220
14221   add_info_alias ("tp", "tracepoints", 1);
14222
14223   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
14224 Delete specified tracepoints.\n\
14225 Arguments are tracepoint numbers, separated by spaces.\n\
14226 No argument means delete all tracepoints."),
14227            &deletelist);
14228
14229   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
14230 Disable specified tracepoints.\n\
14231 Arguments are tracepoint numbers, separated by spaces.\n\
14232 No argument means disable all tracepoints."),
14233            &disablelist);
14234   deprecate_cmd (c, "disable");
14235
14236   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
14237 Enable specified tracepoints.\n\
14238 Arguments are tracepoint numbers, separated by spaces.\n\
14239 No argument means enable all tracepoints."),
14240            &enablelist);
14241   deprecate_cmd (c, "enable");
14242
14243   add_com ("passcount", class_trace, trace_pass_command, _("\
14244 Set the passcount for a tracepoint.\n\
14245 The trace will end when the tracepoint has been passed 'count' times.\n\
14246 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
14247 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
14248
14249   add_prefix_cmd ("save", class_breakpoint, save_command,
14250                   _("Save breakpoint definitions as a script."),
14251                   &save_cmdlist, "save ",
14252                   0/*allow-unknown*/, &cmdlist);
14253
14254   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
14255 Save current breakpoint definitions as a script.\n\
14256 This includes all types of breakpoints (breakpoints, watchpoints,\n\
14257 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
14258 session to restore them."),
14259                &save_cmdlist);
14260   set_cmd_completer (c, filename_completer);
14261
14262   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
14263 Save current tracepoint definitions as a script.\n\
14264 Use the 'source' command in another debug session to restore them."),
14265                &save_cmdlist);
14266   set_cmd_completer (c, filename_completer);
14267
14268   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
14269   deprecate_cmd (c, "save tracepoints");
14270
14271   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
14272 Breakpoint specific settings\n\
14273 Configure various breakpoint-specific variables such as\n\
14274 pending breakpoint behavior"),
14275                   &breakpoint_set_cmdlist, "set breakpoint ",
14276                   0/*allow-unknown*/, &setlist);
14277   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
14278 Breakpoint specific settings\n\
14279 Configure various breakpoint-specific variables such as\n\
14280 pending breakpoint behavior"),
14281                   &breakpoint_show_cmdlist, "show breakpoint ",
14282                   0/*allow-unknown*/, &showlist);
14283
14284   add_setshow_auto_boolean_cmd ("pending", no_class,
14285                                 &pending_break_support, _("\
14286 Set debugger's behavior regarding pending breakpoints."), _("\
14287 Show debugger's behavior regarding pending breakpoints."), _("\
14288 If on, an unrecognized breakpoint location will cause gdb to create a\n\
14289 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
14290 an error.  If auto, an unrecognized breakpoint location results in a\n\
14291 user-query to see if a pending breakpoint should be created."),
14292                                 NULL,
14293                                 show_pending_break_support,
14294                                 &breakpoint_set_cmdlist,
14295                                 &breakpoint_show_cmdlist);
14296
14297   pending_break_support = AUTO_BOOLEAN_AUTO;
14298
14299   add_setshow_boolean_cmd ("auto-hw", no_class,
14300                            &automatic_hardware_breakpoints, _("\
14301 Set automatic usage of hardware breakpoints."), _("\
14302 Show automatic usage of hardware breakpoints."), _("\
14303 If set, the debugger will automatically use hardware breakpoints for\n\
14304 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
14305 a warning will be emitted for such breakpoints."),
14306                            NULL,
14307                            show_automatic_hardware_breakpoints,
14308                            &breakpoint_set_cmdlist,
14309                            &breakpoint_show_cmdlist);
14310
14311   add_setshow_enum_cmd ("always-inserted", class_support,
14312                         always_inserted_enums, &always_inserted_mode, _("\
14313 Set mode for inserting breakpoints."), _("\
14314 Show mode for inserting breakpoints."), _("\
14315 When this mode is off, breakpoints are inserted in inferior when it is\n\
14316 resumed, and removed when execution stops.  When this mode is on,\n\
14317 breakpoints are inserted immediately and removed only when the user\n\
14318 deletes the breakpoint.  When this mode is auto (which is the default),\n\
14319 the behaviour depends on the non-stop setting (see help set non-stop).\n\
14320 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
14321 behaves as if always-inserted mode is on; if gdb is controlling the\n\
14322 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
14323                            NULL,
14324                            &show_always_inserted_mode,
14325                            &breakpoint_set_cmdlist,
14326                            &breakpoint_show_cmdlist);
14327
14328   add_com ("break-range", class_breakpoint, break_range_command, _("\
14329 Set a breakpoint for an address range.\n\
14330 break-range START-LOCATION, END-LOCATION\n\
14331 where START-LOCATION and END-LOCATION can be one of the following:\n\
14332   LINENUM, for that line in the current file,\n\
14333   FILE:LINENUM, for that line in that file,\n\
14334   +OFFSET, for that number of lines after the current line\n\
14335            or the start of the range\n\
14336   FUNCTION, for the first line in that function,\n\
14337   FILE:FUNCTION, to distinguish among like-named static functions.\n\
14338   *ADDRESS, for the instruction at that address.\n\
14339 \n\
14340 The breakpoint will stop execution of the inferior whenever it executes\n\
14341 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
14342 range (including START-LOCATION and END-LOCATION)."));
14343
14344   automatic_hardware_breakpoints = 1;
14345
14346   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
14347 }