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