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