2012-01-20 Pedro Alves <palves@redhat.com>
[platform/upstream/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "cli/cli-utils.h"
64 #include "continuations.h"
65 #include "stack.h"
66 #include "skip.h"
67 #include "record.h"
68
69 /* readline include files */
70 #include "readline/readline.h"
71 #include "readline/history.h"
72
73 /* readline defines this.  */
74 #undef savestring
75
76 #include "mi/mi-common.h"
77 #include "python/python.h"
78
79 /* Prototypes for local functions.  */
80
81 static void enable_delete_command (char *, int);
82
83 static void enable_once_command (char *, int);
84
85 static void disable_command (char *, int);
86
87 static void enable_command (char *, int);
88
89 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
90                                                       void *),
91                                     void *);
92
93 static void ignore_command (char *, int);
94
95 static int breakpoint_re_set_one (void *);
96
97 static void breakpoint_re_set_default (struct breakpoint *);
98
99 static void create_sals_from_address_default (char **,
100                                               struct linespec_result *,
101                                               enum bptype, char *,
102                                               char **);
103
104 static void create_breakpoints_sal_default (struct gdbarch *,
105                                             struct linespec_result *,
106                                             struct linespec_sals *,
107                                             char *, enum bptype,
108                                             enum bpdisp, int, int,
109                                             int,
110                                             const struct breakpoint_ops *,
111                                             int, int, int);
112
113 static void decode_linespec_default (struct breakpoint *, char **,
114                                      struct symtabs_and_lines *);
115
116 static void clear_command (char *, int);
117
118 static void catch_command (char *, int);
119
120 static int can_use_hardware_watchpoint (struct value *);
121
122 static void break_command_1 (char *, int, int);
123
124 static void mention (struct breakpoint *);
125
126 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
127                                                                enum bptype,
128                                                                const struct breakpoint_ops *);
129 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
130                                                        const struct symtab_and_line *);
131
132 /* This function is used in gdbtk sources and thus can not be made
133    static.  */
134 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
135                                        struct symtab_and_line,
136                                        enum bptype,
137                                        const struct breakpoint_ops *);
138
139 static struct breakpoint *
140   momentary_breakpoint_from_master (struct breakpoint *orig,
141                                     enum bptype type,
142                                     const struct breakpoint_ops *ops);
143
144 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
145
146 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
147                                             CORE_ADDR bpaddr,
148                                             enum bptype bptype);
149
150 static void describe_other_breakpoints (struct gdbarch *,
151                                         struct program_space *, CORE_ADDR,
152                                         struct obj_section *, int);
153
154 static int breakpoint_address_match (struct address_space *aspace1,
155                                      CORE_ADDR addr1,
156                                      struct address_space *aspace2,
157                                      CORE_ADDR addr2);
158
159 static int watchpoint_locations_match (struct bp_location *loc1,
160                                        struct bp_location *loc2);
161
162 static int breakpoint_location_address_match (struct bp_location *bl,
163                                               struct address_space *aspace,
164                                               CORE_ADDR addr);
165
166 static void breakpoints_info (char *, int);
167
168 static void watchpoints_info (char *, int);
169
170 static int breakpoint_1 (char *, int, 
171                          int (*) (const struct breakpoint *));
172
173 static int breakpoint_cond_eval (void *);
174
175 static void cleanup_executing_breakpoints (void *);
176
177 static void commands_command (char *, int);
178
179 static void condition_command (char *, int);
180
181 typedef enum
182   {
183     mark_inserted,
184     mark_uninserted
185   }
186 insertion_state_t;
187
188 static int remove_breakpoint (struct bp_location *, insertion_state_t);
189 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
190
191 static enum print_stop_action print_bp_stop_message (bpstat bs);
192
193 static int watchpoint_check (void *);
194
195 static void maintenance_info_breakpoints (char *, int);
196
197 static int hw_breakpoint_used_count (void);
198
199 static int hw_watchpoint_use_count (struct breakpoint *);
200
201 static int hw_watchpoint_used_count_others (struct breakpoint *except,
202                                             enum bptype type,
203                                             int *other_type_used);
204
205 static void hbreak_command (char *, int);
206
207 static void thbreak_command (char *, int);
208
209 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp);
210
211 static void stop_command (char *arg, int from_tty);
212
213 static void stopin_command (char *arg, int from_tty);
214
215 static void stopat_command (char *arg, int from_tty);
216
217 static char *ep_parse_optional_if_clause (char **arg);
218
219 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
220                                        char *arg, int tempflag, int from_tty);
221
222 static void tcatch_command (char *arg, int from_tty);
223
224 static void detach_single_step_breakpoints (void);
225
226 static int single_step_breakpoint_inserted_here_p (struct address_space *,
227                                                    CORE_ADDR pc);
228
229 static void free_bp_location (struct bp_location *loc);
230 static void incref_bp_location (struct bp_location *loc);
231 static void decref_bp_location (struct bp_location **loc);
232
233 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
234
235 static void update_global_location_list (int);
236
237 static void update_global_location_list_nothrow (int);
238
239 static int is_hardware_watchpoint (const struct breakpoint *bpt);
240
241 static void insert_breakpoint_locations (void);
242
243 static int syscall_catchpoint_p (struct breakpoint *b);
244
245 static void tracepoints_info (char *, int);
246
247 static void delete_trace_command (char *, int);
248
249 static void enable_trace_command (char *, int);
250
251 static void disable_trace_command (char *, int);
252
253 static void trace_pass_command (char *, int);
254
255 static int is_masked_watchpoint (const struct breakpoint *b);
256
257 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
258    otherwise.  */
259
260 static int strace_marker_p (struct breakpoint *b);
261
262 /* The abstract base class all breakpoint_ops structures inherit
263    from.  */
264 static struct breakpoint_ops base_breakpoint_ops;
265
266 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
267    that are implemented on top of software or hardware breakpoints
268    (user breakpoints, internal and momentary breakpoints, etc.).  */
269 static struct breakpoint_ops bkpt_base_breakpoint_ops;
270
271 /* Internal breakpoints class type.  */
272 static struct breakpoint_ops internal_breakpoint_ops;
273
274 /* Momentary breakpoints class type.  */
275 static struct breakpoint_ops momentary_breakpoint_ops;
276
277 /* The breakpoint_ops structure to be used in regular user created
278    breakpoints.  */
279 struct breakpoint_ops bkpt_breakpoint_ops;
280
281 /* A reference-counted struct command_line.  This lets multiple
282    breakpoints share a single command list.  */
283 struct counted_command_line
284 {
285   /* The reference count.  */
286   int refc;
287
288   /* The command list.  */
289   struct command_line *commands;
290 };
291
292 struct command_line *
293 breakpoint_commands (struct breakpoint *b)
294 {
295   return b->commands ? b->commands->commands : NULL;
296 }
297
298 /* Flag indicating that a command has proceeded the inferior past the
299    current breakpoint.  */
300
301 static int breakpoint_proceeded;
302
303 const char *
304 bpdisp_text (enum bpdisp disp)
305 {
306   /* NOTE: the following values are a part of MI protocol and
307      represent values of 'disp' field returned when inferior stops at
308      a breakpoint.  */
309   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
310
311   return bpdisps[(int) disp];
312 }
313
314 /* Prototypes for exported functions.  */
315 /* If FALSE, gdb will not use hardware support for watchpoints, even
316    if such is available.  */
317 static int can_use_hw_watchpoints;
318
319 static void
320 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
321                              struct cmd_list_element *c,
322                              const char *value)
323 {
324   fprintf_filtered (file,
325                     _("Debugger's willingness to use "
326                       "watchpoint hardware is %s.\n"),
327                     value);
328 }
329
330 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
331    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
332    for unrecognized breakpoint locations.
333    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
334 static enum auto_boolean pending_break_support;
335 static void
336 show_pending_break_support (struct ui_file *file, int from_tty,
337                             struct cmd_list_element *c,
338                             const char *value)
339 {
340   fprintf_filtered (file,
341                     _("Debugger's behavior regarding "
342                       "pending breakpoints is %s.\n"),
343                     value);
344 }
345
346 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
347    set with "break" but falling in read-only memory.
348    If 0, gdb will warn about such breakpoints, but won't automatically
349    use hardware breakpoints.  */
350 static int automatic_hardware_breakpoints;
351 static void
352 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
353                                      struct cmd_list_element *c,
354                                      const char *value)
355 {
356   fprintf_filtered (file,
357                     _("Automatic usage of hardware breakpoints is %s.\n"),
358                     value);
359 }
360
361 /* If on, gdb will keep breakpoints inserted even as inferior is
362    stopped, and immediately insert any new breakpoints.  If off, gdb
363    will insert breakpoints into inferior only when resuming it, and
364    will remove breakpoints upon stop.  If auto, GDB will behave as ON
365    if in non-stop mode, and as OFF if all-stop mode.*/
366
367 static const char always_inserted_auto[] = "auto";
368 static const char always_inserted_on[] = "on";
369 static const char always_inserted_off[] = "off";
370 static const char *always_inserted_enums[] = {
371   always_inserted_auto,
372   always_inserted_off,
373   always_inserted_on,
374   NULL
375 };
376 static const char *always_inserted_mode = always_inserted_auto;
377 static void
378 show_always_inserted_mode (struct ui_file *file, int from_tty,
379                      struct cmd_list_element *c, const char *value)
380 {
381   if (always_inserted_mode == always_inserted_auto)
382     fprintf_filtered (file,
383                       _("Always inserted breakpoint "
384                         "mode is %s (currently %s).\n"),
385                       value,
386                       breakpoints_always_inserted_mode () ? "on" : "off");
387   else
388     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
389                       value);
390 }
391
392 int
393 breakpoints_always_inserted_mode (void)
394 {
395   return ((always_inserted_mode == always_inserted_on
396            || (always_inserted_mode == always_inserted_auto && non_stop))
397           && !RECORD_IS_USED);
398 }
399
400 void _initialize_breakpoint (void);
401
402 /* Are we executing breakpoint commands?  */
403 static int executing_breakpoint_commands;
404
405 /* Are overlay event breakpoints enabled? */
406 static int overlay_events_enabled;
407
408 /* See description in breakpoint.h. */
409 int target_exact_watchpoints = 0;
410
411 /* Walk the following statement or block through all breakpoints.
412    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
413    current breakpoint.  */
414
415 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
416
417 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
418         for (B = breakpoint_chain;      \
419              B ? (TMP=B->next, 1): 0;   \
420              B = TMP)
421
422 /* Similar iterator for the low-level breakpoints.  SAFE variant is
423    not provided so update_global_location_list must not be called
424    while executing the block of ALL_BP_LOCATIONS.  */
425
426 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
427         for (BP_TMP = bp_location;                                      \
428              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
429              BP_TMP++)
430
431 /* Iterator for tracepoints only.  */
432
433 #define ALL_TRACEPOINTS(B)  \
434   for (B = breakpoint_chain; B; B = B->next)  \
435     if (is_tracepoint (B))
436
437 /* Chains of all breakpoints defined.  */
438
439 struct breakpoint *breakpoint_chain;
440
441 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
442
443 static struct bp_location **bp_location;
444
445 /* Number of elements of BP_LOCATION.  */
446
447 static unsigned bp_location_count;
448
449 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
450    ADDRESS for the current elements of BP_LOCATION which get a valid
451    result from bp_location_has_shadow.  You can use it for roughly
452    limiting the subrange of BP_LOCATION to scan for shadow bytes for
453    an address you need to read.  */
454
455 static CORE_ADDR bp_location_placed_address_before_address_max;
456
457 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
458    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
459    BP_LOCATION which get a valid result from bp_location_has_shadow.
460    You can use it for roughly limiting the subrange of BP_LOCATION to
461    scan for shadow bytes for an address you need to read.  */
462
463 static CORE_ADDR bp_location_shadow_len_after_address_max;
464
465 /* The locations that no longer correspond to any breakpoint, unlinked
466    from bp_location array, but for which a hit may still be reported
467    by a target.  */
468 VEC(bp_location_p) *moribund_locations = NULL;
469
470 /* Number of last breakpoint made.  */
471
472 static int breakpoint_count;
473
474 /* The value of `breakpoint_count' before the last command that
475    created breakpoints.  If the last (break-like) command created more
476    than one breakpoint, then the difference between BREAKPOINT_COUNT
477    and PREV_BREAKPOINT_COUNT is more than one.  */
478 static int prev_breakpoint_count;
479
480 /* Number of last tracepoint made.  */
481
482 static int tracepoint_count;
483
484 static struct cmd_list_element *breakpoint_set_cmdlist;
485 static struct cmd_list_element *breakpoint_show_cmdlist;
486 struct cmd_list_element *save_cmdlist;
487
488 /* Return whether a breakpoint is an active enabled breakpoint.  */
489 static int
490 breakpoint_enabled (struct breakpoint *b)
491 {
492   return (b->enable_state == bp_enabled);
493 }
494
495 /* Set breakpoint count to NUM.  */
496
497 static void
498 set_breakpoint_count (int num)
499 {
500   prev_breakpoint_count = breakpoint_count;
501   breakpoint_count = num;
502   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
503 }
504
505 /* Used by `start_rbreak_breakpoints' below, to record the current
506    breakpoint count before "rbreak" creates any breakpoint.  */
507 static int rbreak_start_breakpoint_count;
508
509 /* Called at the start an "rbreak" command to record the first
510    breakpoint made.  */
511
512 void
513 start_rbreak_breakpoints (void)
514 {
515   rbreak_start_breakpoint_count = breakpoint_count;
516 }
517
518 /* Called at the end of an "rbreak" command to record the last
519    breakpoint made.  */
520
521 void
522 end_rbreak_breakpoints (void)
523 {
524   prev_breakpoint_count = rbreak_start_breakpoint_count;
525 }
526
527 /* Used in run_command to zero the hit count when a new run starts.  */
528
529 void
530 clear_breakpoint_hit_counts (void)
531 {
532   struct breakpoint *b;
533
534   ALL_BREAKPOINTS (b)
535     b->hit_count = 0;
536 }
537
538 /* Allocate a new counted_command_line with reference count of 1.
539    The new structure owns COMMANDS.  */
540
541 static struct counted_command_line *
542 alloc_counted_command_line (struct command_line *commands)
543 {
544   struct counted_command_line *result
545     = xmalloc (sizeof (struct counted_command_line));
546
547   result->refc = 1;
548   result->commands = commands;
549   return result;
550 }
551
552 /* Increment reference count.  This does nothing if CMD is NULL.  */
553
554 static void
555 incref_counted_command_line (struct counted_command_line *cmd)
556 {
557   if (cmd)
558     ++cmd->refc;
559 }
560
561 /* Decrement reference count.  If the reference count reaches 0,
562    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
563    nothing if *CMDP is NULL.  */
564
565 static void
566 decref_counted_command_line (struct counted_command_line **cmdp)
567 {
568   if (*cmdp)
569     {
570       if (--(*cmdp)->refc == 0)
571         {
572           free_command_lines (&(*cmdp)->commands);
573           xfree (*cmdp);
574         }
575       *cmdp = NULL;
576     }
577 }
578
579 /* A cleanup function that calls decref_counted_command_line.  */
580
581 static void
582 do_cleanup_counted_command_line (void *arg)
583 {
584   decref_counted_command_line (arg);
585 }
586
587 /* Create a cleanup that calls decref_counted_command_line on the
588    argument.  */
589
590 static struct cleanup *
591 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
592 {
593   return make_cleanup (do_cleanup_counted_command_line, cmdp);
594 }
595
596 \f
597 /* Return the breakpoint with the specified number, or NULL
598    if the number does not refer to an existing breakpoint.  */
599
600 struct breakpoint *
601 get_breakpoint (int num)
602 {
603   struct breakpoint *b;
604
605   ALL_BREAKPOINTS (b)
606     if (b->number == num)
607       return b;
608   
609   return NULL;
610 }
611
612 \f
613
614 void
615 set_breakpoint_condition (struct breakpoint *b, char *exp,
616                           int from_tty)
617 {
618   xfree (b->cond_string);
619   b->cond_string = NULL;
620
621   if (is_watchpoint (b))
622     {
623       struct watchpoint *w = (struct watchpoint *) b;
624
625       xfree (w->cond_exp);
626       w->cond_exp = NULL;
627     }
628   else
629     {
630       struct bp_location *loc;
631
632       for (loc = b->loc; loc; loc = loc->next)
633         {
634           xfree (loc->cond);
635           loc->cond = NULL;
636         }
637     }
638
639   if (*exp == 0)
640     {
641       if (from_tty)
642         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
643     }
644   else
645     {
646       char *arg = exp;
647
648       /* I don't know if it matters whether this is the string the user
649          typed in or the decompiled expression.  */
650       b->cond_string = xstrdup (arg);
651       b->condition_not_parsed = 0;
652
653       if (is_watchpoint (b))
654         {
655           struct watchpoint *w = (struct watchpoint *) b;
656
657           innermost_block = NULL;
658           arg = exp;
659           w->cond_exp = parse_exp_1 (&arg, 0, 0);
660           if (*arg)
661             error (_("Junk at end of expression"));
662           w->cond_exp_valid_block = innermost_block;
663         }
664       else
665         {
666           struct bp_location *loc;
667
668           for (loc = b->loc; loc; loc = loc->next)
669             {
670               arg = exp;
671               loc->cond =
672                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
673               if (*arg)
674                 error (_("Junk at end of expression"));
675             }
676         }
677     }
678   breakpoints_changed ();
679   observer_notify_breakpoint_modified (b);
680 }
681
682 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
683
684 static void
685 condition_command (char *arg, int from_tty)
686 {
687   struct breakpoint *b;
688   char *p;
689   int bnum;
690
691   if (arg == 0)
692     error_no_arg (_("breakpoint number"));
693
694   p = arg;
695   bnum = get_number (&p);
696   if (bnum == 0)
697     error (_("Bad breakpoint argument: '%s'"), arg);
698
699   ALL_BREAKPOINTS (b)
700     if (b->number == bnum)
701       {
702         /* Check if this breakpoint has a Python object assigned to
703            it, and if it has a definition of the "stop"
704            method.  This method and conditions entered into GDB from
705            the CLI are mutually exclusive.  */
706         if (b->py_bp_object
707             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
708           error (_("Cannot set a condition where a Python 'stop' "
709                    "method has been defined in the breakpoint."));
710         set_breakpoint_condition (b, p, from_tty);
711         return;
712       }
713
714   error (_("No breakpoint number %d."), bnum);
715 }
716
717 /* Check that COMMAND do not contain commands that are suitable
718    only for tracepoints and not suitable for ordinary breakpoints.
719    Throw if any such commands is found.  */
720
721 static void
722 check_no_tracepoint_commands (struct command_line *commands)
723 {
724   struct command_line *c;
725
726   for (c = commands; c; c = c->next)
727     {
728       int i;
729
730       if (c->control_type == while_stepping_control)
731         error (_("The 'while-stepping' command can "
732                  "only be used for tracepoints"));
733
734       for (i = 0; i < c->body_count; ++i)
735         check_no_tracepoint_commands ((c->body_list)[i]);
736
737       /* Not that command parsing removes leading whitespace and comment
738          lines and also empty lines.  So, we only need to check for
739          command directly.  */
740       if (strstr (c->line, "collect ") == c->line)
741         error (_("The 'collect' command can only be used for tracepoints"));
742
743       if (strstr (c->line, "teval ") == c->line)
744         error (_("The 'teval' command can only be used for tracepoints"));
745     }
746 }
747
748 /* Encapsulate tests for different types of tracepoints.  */
749
750 static int
751 is_tracepoint_type (enum bptype type)
752 {
753   return (type == bp_tracepoint
754           || type == bp_fast_tracepoint
755           || type == bp_static_tracepoint);
756 }
757
758 int
759 is_tracepoint (const struct breakpoint *b)
760 {
761   return is_tracepoint_type (b->type);
762 }
763
764 /* A helper function that validates that COMMANDS are valid for a
765    breakpoint.  This function will throw an exception if a problem is
766    found.  */
767
768 static void
769 validate_commands_for_breakpoint (struct breakpoint *b,
770                                   struct command_line *commands)
771 {
772   if (is_tracepoint (b))
773     {
774       /* We need to verify that each top-level element of commands is
775          valid for tracepoints, that there's at most one
776          while-stepping element, and that while-stepping's body has
777          valid tracing commands excluding nested while-stepping.  */
778       struct command_line *c;
779       struct command_line *while_stepping = 0;
780       for (c = commands; c; c = c->next)
781         {
782           if (c->control_type == while_stepping_control)
783             {
784               if (b->type == bp_fast_tracepoint)
785                 error (_("The 'while-stepping' command "
786                          "cannot be used for fast tracepoint"));
787               else if (b->type == bp_static_tracepoint)
788                 error (_("The 'while-stepping' command "
789                          "cannot be used for static tracepoint"));
790
791               if (while_stepping)
792                 error (_("The 'while-stepping' command "
793                          "can be used only once"));
794               else
795                 while_stepping = c;
796             }
797         }
798       if (while_stepping)
799         {
800           struct command_line *c2;
801
802           gdb_assert (while_stepping->body_count == 1);
803           c2 = while_stepping->body_list[0];
804           for (; c2; c2 = c2->next)
805             {
806               if (c2->control_type == while_stepping_control)
807                 error (_("The 'while-stepping' command cannot be nested"));
808             }
809         }
810     }
811   else
812     {
813       check_no_tracepoint_commands (commands);
814     }
815 }
816
817 /* Return a vector of all the static tracepoints set at ADDR.  The
818    caller is responsible for releasing the vector.  */
819
820 VEC(breakpoint_p) *
821 static_tracepoints_here (CORE_ADDR addr)
822 {
823   struct breakpoint *b;
824   VEC(breakpoint_p) *found = 0;
825   struct bp_location *loc;
826
827   ALL_BREAKPOINTS (b)
828     if (b->type == bp_static_tracepoint)
829       {
830         for (loc = b->loc; loc; loc = loc->next)
831           if (loc->address == addr)
832             VEC_safe_push(breakpoint_p, found, b);
833       }
834
835   return found;
836 }
837
838 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
839    validate that only allowed commands are included.  */
840
841 void
842 breakpoint_set_commands (struct breakpoint *b, 
843                          struct command_line *commands)
844 {
845   validate_commands_for_breakpoint (b, commands);
846
847   decref_counted_command_line (&b->commands);
848   b->commands = alloc_counted_command_line (commands);
849   breakpoints_changed ();
850   observer_notify_breakpoint_modified (b);
851 }
852
853 /* Set the internal `silent' flag on the breakpoint.  Note that this
854    is not the same as the "silent" that may appear in the breakpoint's
855    commands.  */
856
857 void
858 breakpoint_set_silent (struct breakpoint *b, int silent)
859 {
860   int old_silent = b->silent;
861
862   b->silent = silent;
863   if (old_silent != silent)
864     observer_notify_breakpoint_modified (b);
865 }
866
867 /* Set the thread for this breakpoint.  If THREAD is -1, make the
868    breakpoint work for any thread.  */
869
870 void
871 breakpoint_set_thread (struct breakpoint *b, int thread)
872 {
873   int old_thread = b->thread;
874
875   b->thread = thread;
876   if (old_thread != thread)
877     observer_notify_breakpoint_modified (b);
878 }
879
880 /* Set the task for this breakpoint.  If TASK is 0, make the
881    breakpoint work for any task.  */
882
883 void
884 breakpoint_set_task (struct breakpoint *b, int task)
885 {
886   int old_task = b->task;
887
888   b->task = task;
889   if (old_task != task)
890     observer_notify_breakpoint_modified (b);
891 }
892
893 void
894 check_tracepoint_command (char *line, void *closure)
895 {
896   struct breakpoint *b = closure;
897
898   validate_actionline (&line, b);
899 }
900
901 /* A structure used to pass information through
902    map_breakpoint_numbers.  */
903
904 struct commands_info
905 {
906   /* True if the command was typed at a tty.  */
907   int from_tty;
908
909   /* The breakpoint range spec.  */
910   char *arg;
911
912   /* Non-NULL if the body of the commands are being read from this
913      already-parsed command.  */
914   struct command_line *control;
915
916   /* The command lines read from the user, or NULL if they have not
917      yet been read.  */
918   struct counted_command_line *cmd;
919 };
920
921 /* A callback for map_breakpoint_numbers that sets the commands for
922    commands_command.  */
923
924 static void
925 do_map_commands_command (struct breakpoint *b, void *data)
926 {
927   struct commands_info *info = data;
928
929   if (info->cmd == NULL)
930     {
931       struct command_line *l;
932
933       if (info->control != NULL)
934         l = copy_command_lines (info->control->body_list[0]);
935       else
936         {
937           struct cleanup *old_chain;
938           char *str;
939
940           str = xstrprintf (_("Type commands for breakpoint(s) "
941                               "%s, one per line."),
942                             info->arg);
943
944           old_chain = make_cleanup (xfree, str);
945
946           l = read_command_lines (str,
947                                   info->from_tty, 1,
948                                   (is_tracepoint (b)
949                                    ? check_tracepoint_command : 0),
950                                   b);
951
952           do_cleanups (old_chain);
953         }
954
955       info->cmd = alloc_counted_command_line (l);
956     }
957
958   /* If a breakpoint was on the list more than once, we don't need to
959      do anything.  */
960   if (b->commands != info->cmd)
961     {
962       validate_commands_for_breakpoint (b, info->cmd->commands);
963       incref_counted_command_line (info->cmd);
964       decref_counted_command_line (&b->commands);
965       b->commands = info->cmd;
966       breakpoints_changed ();
967       observer_notify_breakpoint_modified (b);
968     }
969 }
970
971 static void
972 commands_command_1 (char *arg, int from_tty, 
973                     struct command_line *control)
974 {
975   struct cleanup *cleanups;
976   struct commands_info info;
977
978   info.from_tty = from_tty;
979   info.control = control;
980   info.cmd = NULL;
981   /* If we read command lines from the user, then `info' will hold an
982      extra reference to the commands that we must clean up.  */
983   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
984
985   if (arg == NULL || !*arg)
986     {
987       if (breakpoint_count - prev_breakpoint_count > 1)
988         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
989                           breakpoint_count);
990       else if (breakpoint_count > 0)
991         arg = xstrprintf ("%d", breakpoint_count);
992       else
993         {
994           /* So that we don't try to free the incoming non-NULL
995              argument in the cleanup below.  Mapping breakpoint
996              numbers will fail in this case.  */
997           arg = NULL;
998         }
999     }
1000   else
1001     /* The command loop has some static state, so we need to preserve
1002        our argument.  */
1003     arg = xstrdup (arg);
1004
1005   if (arg != NULL)
1006     make_cleanup (xfree, arg);
1007
1008   info.arg = arg;
1009
1010   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1011
1012   if (info.cmd == NULL)
1013     error (_("No breakpoints specified."));
1014
1015   do_cleanups (cleanups);
1016 }
1017
1018 static void
1019 commands_command (char *arg, int from_tty)
1020 {
1021   commands_command_1 (arg, from_tty, NULL);
1022 }
1023
1024 /* Like commands_command, but instead of reading the commands from
1025    input stream, takes them from an already parsed command structure.
1026
1027    This is used by cli-script.c to DTRT with breakpoint commands
1028    that are part of if and while bodies.  */
1029 enum command_control_type
1030 commands_from_control_command (char *arg, struct command_line *cmd)
1031 {
1032   commands_command_1 (arg, 0, cmd);
1033   return simple_control;
1034 }
1035
1036 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1037
1038 static int
1039 bp_location_has_shadow (struct bp_location *bl)
1040 {
1041   if (bl->loc_type != bp_loc_software_breakpoint)
1042     return 0;
1043   if (!bl->inserted)
1044     return 0;
1045   if (bl->target_info.shadow_len == 0)
1046     /* BL isn't valid, or doesn't shadow memory.  */
1047     return 0;
1048   return 1;
1049 }
1050
1051 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1052    by replacing any memory breakpoints with their shadowed contents.
1053
1054    The range of shadowed area by each bp_location is:
1055      bl->address - bp_location_placed_address_before_address_max
1056      up to bl->address + bp_location_shadow_len_after_address_max
1057    The range we were requested to resolve shadows for is:
1058      memaddr ... memaddr + len
1059    Thus the safe cutoff boundaries for performance optimization are
1060      memaddr + len <= (bl->address
1061                        - bp_location_placed_address_before_address_max)
1062    and:
1063      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1064
1065 void
1066 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1067                         const gdb_byte *writebuf_org,
1068                         ULONGEST memaddr, LONGEST len)
1069 {
1070   /* Left boundary, right boundary and median element of our binary
1071      search.  */
1072   unsigned bc_l, bc_r, bc;
1073
1074   /* Find BC_L which is a leftmost element which may affect BUF
1075      content.  It is safe to report lower value but a failure to
1076      report higher one.  */
1077
1078   bc_l = 0;
1079   bc_r = bp_location_count;
1080   while (bc_l + 1 < bc_r)
1081     {
1082       struct bp_location *bl;
1083
1084       bc = (bc_l + bc_r) / 2;
1085       bl = bp_location[bc];
1086
1087       /* Check first BL->ADDRESS will not overflow due to the added
1088          constant.  Then advance the left boundary only if we are sure
1089          the BC element can in no way affect the BUF content (MEMADDR
1090          to MEMADDR + LEN range).
1091
1092          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1093          offset so that we cannot miss a breakpoint with its shadow
1094          range tail still reaching MEMADDR.  */
1095
1096       if ((bl->address + bp_location_shadow_len_after_address_max
1097            >= bl->address)
1098           && (bl->address + bp_location_shadow_len_after_address_max
1099               <= memaddr))
1100         bc_l = bc;
1101       else
1102         bc_r = bc;
1103     }
1104
1105   /* Due to the binary search above, we need to make sure we pick the
1106      first location that's at BC_L's address.  E.g., if there are
1107      multiple locations at the same address, BC_L may end up pointing
1108      at a duplicate location, and miss the "master"/"inserted"
1109      location.  Say, given locations L1, L2 and L3 at addresses A and
1110      B:
1111
1112       L1@A, L2@A, L3@B, ...
1113
1114      BC_L could end up pointing at location L2, while the "master"
1115      location could be L1.  Since the `loc->inserted' flag is only set
1116      on "master" locations, we'd forget to restore the shadow of L1
1117      and L2.  */
1118   while (bc_l > 0
1119          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1120     bc_l--;
1121
1122   /* Now do full processing of the found relevant range of elements.  */
1123
1124   for (bc = bc_l; bc < bp_location_count; bc++)
1125   {
1126     struct bp_location *bl = bp_location[bc];
1127     CORE_ADDR bp_addr = 0;
1128     int bp_size = 0;
1129     int bptoffset = 0;
1130
1131     /* bp_location array has BL->OWNER always non-NULL.  */
1132     if (bl->owner->type == bp_none)
1133       warning (_("reading through apparently deleted breakpoint #%d?"),
1134                bl->owner->number);
1135
1136     /* Performance optimization: any further element can no longer affect BUF
1137        content.  */
1138
1139     if (bl->address >= bp_location_placed_address_before_address_max
1140         && memaddr + len <= (bl->address
1141                              - bp_location_placed_address_before_address_max))
1142       break;
1143
1144     if (!bp_location_has_shadow (bl))
1145       continue;
1146     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1147                                    current_program_space->aspace, 0))
1148       continue;
1149
1150     /* Addresses and length of the part of the breakpoint that
1151        we need to copy.  */
1152     bp_addr = bl->target_info.placed_address;
1153     bp_size = bl->target_info.shadow_len;
1154
1155     if (bp_addr + bp_size <= memaddr)
1156       /* The breakpoint is entirely before the chunk of memory we
1157          are reading.  */
1158       continue;
1159
1160     if (bp_addr >= memaddr + len)
1161       /* The breakpoint is entirely after the chunk of memory we are
1162          reading.  */
1163       continue;
1164
1165     /* Offset within shadow_contents.  */
1166     if (bp_addr < memaddr)
1167       {
1168         /* Only copy the second part of the breakpoint.  */
1169         bp_size -= memaddr - bp_addr;
1170         bptoffset = memaddr - bp_addr;
1171         bp_addr = memaddr;
1172       }
1173
1174     if (bp_addr + bp_size > memaddr + len)
1175       {
1176         /* Only copy the first part of the breakpoint.  */
1177         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1178       }
1179
1180     if (readbuf != NULL)
1181       {
1182         /* Update the read buffer with this inserted breakpoint's
1183            shadow.  */
1184         memcpy (readbuf + bp_addr - memaddr,
1185                 bl->target_info.shadow_contents + bptoffset, bp_size);
1186       }
1187     else
1188       {
1189         struct gdbarch *gdbarch = bl->gdbarch;
1190         const unsigned char *bp;
1191         CORE_ADDR placed_address = bl->target_info.placed_address;
1192         unsigned placed_size = bl->target_info.placed_size;
1193
1194         /* Update the shadow with what we want to write to memory.  */
1195         memcpy (bl->target_info.shadow_contents + bptoffset,
1196                 writebuf_org + bp_addr - memaddr, bp_size);
1197
1198         /* Determine appropriate breakpoint contents and size for this
1199            address.  */
1200         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1201
1202         /* Update the final write buffer with this inserted
1203            breakpoint's INSN.  */
1204         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1205       }
1206   }
1207 }
1208 \f
1209
1210 /* Return true if BPT is of any hardware watchpoint kind.  */
1211
1212 static int
1213 is_hardware_watchpoint (const struct breakpoint *bpt)
1214 {
1215   return (bpt->type == bp_hardware_watchpoint
1216           || bpt->type == bp_read_watchpoint
1217           || bpt->type == bp_access_watchpoint);
1218 }
1219
1220 /* Return true if BPT is of any watchpoint kind, hardware or
1221    software.  */
1222
1223 int
1224 is_watchpoint (const struct breakpoint *bpt)
1225 {
1226   return (is_hardware_watchpoint (bpt)
1227           || bpt->type == bp_watchpoint);
1228 }
1229
1230 /* Returns true if the current thread and its running state are safe
1231    to evaluate or update watchpoint B.  Watchpoints on local
1232    expressions need to be evaluated in the context of the thread that
1233    was current when the watchpoint was created, and, that thread needs
1234    to be stopped to be able to select the correct frame context.
1235    Watchpoints on global expressions can be evaluated on any thread,
1236    and in any state.  It is presently left to the target allowing
1237    memory accesses when threads are running.  */
1238
1239 static int
1240 watchpoint_in_thread_scope (struct watchpoint *b)
1241 {
1242   return (ptid_equal (b->watchpoint_thread, null_ptid)
1243           || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1244               && !is_executing (inferior_ptid)));
1245 }
1246
1247 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1248    associated bp_watchpoint_scope breakpoint.  */
1249
1250 static void
1251 watchpoint_del_at_next_stop (struct watchpoint *w)
1252 {
1253   struct breakpoint *b = &w->base;
1254
1255   if (b->related_breakpoint != b)
1256     {
1257       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1258       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1259       b->related_breakpoint->disposition = disp_del_at_next_stop;
1260       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1261       b->related_breakpoint = b;
1262     }
1263   b->disposition = disp_del_at_next_stop;
1264 }
1265
1266 /* Assuming that B is a watchpoint:
1267    - Reparse watchpoint expression, if REPARSE is non-zero
1268    - Evaluate expression and store the result in B->val
1269    - Evaluate the condition if there is one, and store the result
1270      in b->loc->cond.
1271    - Update the list of values that must be watched in B->loc.
1272
1273    If the watchpoint disposition is disp_del_at_next_stop, then do
1274    nothing.  If this is local watchpoint that is out of scope, delete
1275    it.
1276
1277    Even with `set breakpoint always-inserted on' the watchpoints are
1278    removed + inserted on each stop here.  Normal breakpoints must
1279    never be removed because they might be missed by a running thread
1280    when debugging in non-stop mode.  On the other hand, hardware
1281    watchpoints (is_hardware_watchpoint; processed here) are specific
1282    to each LWP since they are stored in each LWP's hardware debug
1283    registers.  Therefore, such LWP must be stopped first in order to
1284    be able to modify its hardware watchpoints.
1285
1286    Hardware watchpoints must be reset exactly once after being
1287    presented to the user.  It cannot be done sooner, because it would
1288    reset the data used to present the watchpoint hit to the user.  And
1289    it must not be done later because it could display the same single
1290    watchpoint hit during multiple GDB stops.  Note that the latter is
1291    relevant only to the hardware watchpoint types bp_read_watchpoint
1292    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1293    not user-visible - its hit is suppressed if the memory content has
1294    not changed.
1295
1296    The following constraints influence the location where we can reset
1297    hardware watchpoints:
1298
1299    * target_stopped_by_watchpoint and target_stopped_data_address are
1300      called several times when GDB stops.
1301
1302    [linux] 
1303    * Multiple hardware watchpoints can be hit at the same time,
1304      causing GDB to stop.  GDB only presents one hardware watchpoint
1305      hit at a time as the reason for stopping, and all the other hits
1306      are presented later, one after the other, each time the user
1307      requests the execution to be resumed.  Execution is not resumed
1308      for the threads still having pending hit event stored in
1309      LWP_INFO->STATUS.  While the watchpoint is already removed from
1310      the inferior on the first stop the thread hit event is kept being
1311      reported from its cached value by linux_nat_stopped_data_address
1312      until the real thread resume happens after the watchpoint gets
1313      presented and thus its LWP_INFO->STATUS gets reset.
1314
1315    Therefore the hardware watchpoint hit can get safely reset on the
1316    watchpoint removal from inferior.  */
1317
1318 static void
1319 update_watchpoint (struct watchpoint *b, int reparse)
1320 {
1321   int within_current_scope;
1322   struct frame_id saved_frame_id;
1323   int frame_saved;
1324
1325   /* If this is a local watchpoint, we only want to check if the
1326      watchpoint frame is in scope if the current thread is the thread
1327      that was used to create the watchpoint.  */
1328   if (!watchpoint_in_thread_scope (b))
1329     return;
1330
1331   if (b->base.disposition == disp_del_at_next_stop)
1332     return;
1333  
1334   frame_saved = 0;
1335
1336   /* Determine if the watchpoint is within scope.  */
1337   if (b->exp_valid_block == NULL)
1338     within_current_scope = 1;
1339   else
1340     {
1341       struct frame_info *fi = get_current_frame ();
1342       struct gdbarch *frame_arch = get_frame_arch (fi);
1343       CORE_ADDR frame_pc = get_frame_pc (fi);
1344
1345       /* If we're in a function epilogue, unwinding may not work
1346          properly, so do not attempt to recreate locations at this
1347          point.  See similar comments in watchpoint_check.  */
1348       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1349         return;
1350
1351       /* Save the current frame's ID so we can restore it after
1352          evaluating the watchpoint expression on its own frame.  */
1353       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1354          took a frame parameter, so that we didn't have to change the
1355          selected frame.  */
1356       frame_saved = 1;
1357       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1358
1359       fi = frame_find_by_id (b->watchpoint_frame);
1360       within_current_scope = (fi != NULL);
1361       if (within_current_scope)
1362         select_frame (fi);
1363     }
1364
1365   /* We don't free locations.  They are stored in the bp_location array
1366      and update_global_location_list will eventually delete them and
1367      remove breakpoints if needed.  */
1368   b->base.loc = NULL;
1369
1370   if (within_current_scope && reparse)
1371     {
1372       char *s;
1373
1374       if (b->exp)
1375         {
1376           xfree (b->exp);
1377           b->exp = NULL;
1378         }
1379       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1380       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1381       /* If the meaning of expression itself changed, the old value is
1382          no longer relevant.  We don't want to report a watchpoint hit
1383          to the user when the old value and the new value may actually
1384          be completely different objects.  */
1385       value_free (b->val);
1386       b->val = NULL;
1387       b->val_valid = 0;
1388
1389       /* Note that unlike with breakpoints, the watchpoint's condition
1390          expression is stored in the breakpoint object, not in the
1391          locations (re)created below.  */
1392       if (b->base.cond_string != NULL)
1393         {
1394           if (b->cond_exp != NULL)
1395             {
1396               xfree (b->cond_exp);
1397               b->cond_exp = NULL;
1398             }
1399
1400           s = b->base.cond_string;
1401           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1402         }
1403     }
1404
1405   /* If we failed to parse the expression, for example because
1406      it refers to a global variable in a not-yet-loaded shared library,
1407      don't try to insert watchpoint.  We don't automatically delete
1408      such watchpoint, though, since failure to parse expression
1409      is different from out-of-scope watchpoint.  */
1410   if ( !target_has_execution)
1411     {
1412       /* Without execution, memory can't change.  No use to try and
1413          set watchpoint locations.  The watchpoint will be reset when
1414          the target gains execution, through breakpoint_re_set.  */
1415     }
1416   else if (within_current_scope && b->exp)
1417     {
1418       int pc = 0;
1419       struct value *val_chain, *v, *result, *next;
1420       struct program_space *frame_pspace;
1421
1422       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1423
1424       /* Avoid setting b->val if it's already set.  The meaning of
1425          b->val is 'the last value' user saw, and we should update
1426          it only if we reported that last value to user.  As it
1427          happens, the code that reports it updates b->val directly.
1428          We don't keep track of the memory value for masked
1429          watchpoints.  */
1430       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1431         {
1432           b->val = v;
1433           b->val_valid = 1;
1434         }
1435
1436       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1437
1438       /* Look at each value on the value chain.  */
1439       for (v = val_chain; v; v = value_next (v))
1440         {
1441           /* If it's a memory location, and GDB actually needed
1442              its contents to evaluate the expression, then we
1443              must watch it.  If the first value returned is
1444              still lazy, that means an error occurred reading it;
1445              watch it anyway in case it becomes readable.  */
1446           if (VALUE_LVAL (v) == lval_memory
1447               && (v == val_chain || ! value_lazy (v)))
1448             {
1449               struct type *vtype = check_typedef (value_type (v));
1450
1451               /* We only watch structs and arrays if user asked
1452                  for it explicitly, never if they just happen to
1453                  appear in the middle of some value chain.  */
1454               if (v == result
1455                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1456                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1457                 {
1458                   CORE_ADDR addr;
1459                   int len, type;
1460                   struct bp_location *loc, **tmp;
1461
1462                   addr = value_address (v);
1463                   len = TYPE_LENGTH (value_type (v));
1464                   type = hw_write;
1465                   if (b->base.type == bp_read_watchpoint)
1466                     type = hw_read;
1467                   else if (b->base.type == bp_access_watchpoint)
1468                     type = hw_access;
1469
1470                   loc = allocate_bp_location (&b->base);
1471                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1472                     ;
1473                   *tmp = loc;
1474                   loc->gdbarch = get_type_arch (value_type (v));
1475
1476                   loc->pspace = frame_pspace;
1477                   loc->address = addr;
1478                   loc->length = len;
1479                   loc->watchpoint_type = type;
1480                 }
1481             }
1482         }
1483
1484       /* Change the type of breakpoint between hardware assisted or
1485          an ordinary watchpoint depending on the hardware support
1486          and free hardware slots.  REPARSE is set when the inferior
1487          is started.  */
1488       if (reparse)
1489         {
1490           int reg_cnt;
1491           enum bp_loc_type loc_type;
1492           struct bp_location *bl;
1493
1494           reg_cnt = can_use_hardware_watchpoint (val_chain);
1495
1496           if (reg_cnt)
1497             {
1498               int i, target_resources_ok, other_type_used;
1499               enum bptype type;
1500
1501               /* Use an exact watchpoint when there's only one memory region to be
1502                  watched, and only one debug register is needed to watch it.  */
1503               b->exact = target_exact_watchpoints && reg_cnt == 1;
1504
1505               /* We need to determine how many resources are already
1506                  used for all other hardware watchpoints plus this one
1507                  to see if we still have enough resources to also fit
1508                  this watchpoint in as well.  */
1509
1510               /* If this is a software watchpoint, we try to turn it
1511                  to a hardware one -- count resources as if B was of
1512                  hardware watchpoint type.  */
1513               type = b->base.type;
1514               if (type == bp_watchpoint)
1515                 type = bp_hardware_watchpoint;
1516
1517               /* This watchpoint may or may not have been placed on
1518                  the list yet at this point (it won't be in the list
1519                  if we're trying to create it for the first time,
1520                  through watch_command), so always account for it
1521                  manually.  */
1522
1523               /* Count resources used by all watchpoints except B.  */
1524               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1525
1526               /* Add in the resources needed for B.  */
1527               i += hw_watchpoint_use_count (&b->base);
1528
1529               target_resources_ok
1530                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1531               if (target_resources_ok <= 0)
1532                 {
1533                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1534
1535                   if (target_resources_ok == 0 && !sw_mode)
1536                     error (_("Target does not support this type of "
1537                              "hardware watchpoint."));
1538                   else if (target_resources_ok < 0 && !sw_mode)
1539                     error (_("There are not enough available hardware "
1540                              "resources for this watchpoint."));
1541
1542                   /* Downgrade to software watchpoint.  */
1543                   b->base.type = bp_watchpoint;
1544                 }
1545               else
1546                 {
1547                   /* If this was a software watchpoint, we've just
1548                      found we have enough resources to turn it to a
1549                      hardware watchpoint.  Otherwise, this is a
1550                      nop.  */
1551                   b->base.type = type;
1552                 }
1553             }
1554           else if (!b->base.ops->works_in_software_mode (&b->base))
1555             error (_("Expression cannot be implemented with "
1556                      "read/access watchpoint."));
1557           else
1558             b->base.type = bp_watchpoint;
1559
1560           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1561                       : bp_loc_hardware_watchpoint);
1562           for (bl = b->base.loc; bl; bl = bl->next)
1563             bl->loc_type = loc_type;
1564         }
1565
1566       for (v = val_chain; v; v = next)
1567         {
1568           next = value_next (v);
1569           if (v != b->val)
1570             value_free (v);
1571         }
1572
1573       /* If a software watchpoint is not watching any memory, then the
1574          above left it without any location set up.  But,
1575          bpstat_stop_status requires a location to be able to report
1576          stops, so make sure there's at least a dummy one.  */
1577       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1578         {
1579           struct breakpoint *base = &b->base;
1580           base->loc = allocate_bp_location (base);
1581           base->loc->pspace = frame_pspace;
1582           base->loc->address = -1;
1583           base->loc->length = -1;
1584           base->loc->watchpoint_type = -1;
1585         }
1586     }
1587   else if (!within_current_scope)
1588     {
1589       printf_filtered (_("\
1590 Watchpoint %d deleted because the program has left the block\n\
1591 in which its expression is valid.\n"),
1592                        b->base.number);
1593       watchpoint_del_at_next_stop (b);
1594     }
1595
1596   /* Restore the selected frame.  */
1597   if (frame_saved)
1598     select_frame (frame_find_by_id (saved_frame_id));
1599 }
1600
1601
1602 /* Returns 1 iff breakpoint location should be
1603    inserted in the inferior.  We don't differentiate the type of BL's owner
1604    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1605    breakpoint_ops is not defined, because in insert_bp_location,
1606    tracepoint's insert_location will not be called.  */
1607 static int
1608 should_be_inserted (struct bp_location *bl)
1609 {
1610   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1611     return 0;
1612
1613   if (bl->owner->disposition == disp_del_at_next_stop)
1614     return 0;
1615
1616   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1617     return 0;
1618
1619   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1620     return 0;
1621
1622   /* This is set for example, when we're attached to the parent of a
1623      vfork, and have detached from the child.  The child is running
1624      free, and we expect it to do an exec or exit, at which point the
1625      OS makes the parent schedulable again (and the target reports
1626      that the vfork is done).  Until the child is done with the shared
1627      memory region, do not insert breakpoints in the parent, otherwise
1628      the child could still trip on the parent's breakpoints.  Since
1629      the parent is blocked anyway, it won't miss any breakpoint.  */
1630   if (bl->pspace->breakpoints_not_allowed)
1631     return 0;
1632
1633   return 1;
1634 }
1635
1636 /* Same as should_be_inserted but does the check assuming
1637    that the location is not duplicated.  */
1638
1639 static int
1640 unduplicated_should_be_inserted (struct bp_location *bl)
1641 {
1642   int result;
1643   const int save_duplicate = bl->duplicate;
1644
1645   bl->duplicate = 0;
1646   result = should_be_inserted (bl);
1647   bl->duplicate = save_duplicate;
1648   return result;
1649 }
1650
1651 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
1652    location.  Any error messages are printed to TMP_ERROR_STREAM; and
1653    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
1654    Returns 0 for success, 1 if the bp_location type is not supported or
1655    -1 for failure.
1656
1657    NOTE drow/2003-09-09: This routine could be broken down to an
1658    object-style method for each breakpoint or catchpoint type.  */
1659 static int
1660 insert_bp_location (struct bp_location *bl,
1661                     struct ui_file *tmp_error_stream,
1662                     int *disabled_breaks,
1663                     int *hw_breakpoint_error)
1664 {
1665   int val = 0;
1666
1667   if (!should_be_inserted (bl) || bl->inserted)
1668     return 0;
1669
1670   /* Initialize the target-specific information.  */
1671   memset (&bl->target_info, 0, sizeof (bl->target_info));
1672   bl->target_info.placed_address = bl->address;
1673   bl->target_info.placed_address_space = bl->pspace->aspace;
1674   bl->target_info.length = bl->length;
1675
1676   if (bl->loc_type == bp_loc_software_breakpoint
1677       || bl->loc_type == bp_loc_hardware_breakpoint)
1678     {
1679       if (bl->owner->type != bp_hardware_breakpoint)
1680         {
1681           /* If the explicitly specified breakpoint type
1682              is not hardware breakpoint, check the memory map to see
1683              if the breakpoint address is in read only memory or not.
1684
1685              Two important cases are:
1686              - location type is not hardware breakpoint, memory
1687              is readonly.  We change the type of the location to
1688              hardware breakpoint.
1689              - location type is hardware breakpoint, memory is
1690              read-write.  This means we've previously made the
1691              location hardware one, but then the memory map changed,
1692              so we undo.
1693              
1694              When breakpoints are removed, remove_breakpoints will use
1695              location types we've just set here, the only possible
1696              problem is that memory map has changed during running
1697              program, but it's not going to work anyway with current
1698              gdb.  */
1699           struct mem_region *mr 
1700             = lookup_mem_region (bl->target_info.placed_address);
1701           
1702           if (mr)
1703             {
1704               if (automatic_hardware_breakpoints)
1705                 {
1706                   enum bp_loc_type new_type;
1707                   
1708                   if (mr->attrib.mode != MEM_RW)
1709                     new_type = bp_loc_hardware_breakpoint;
1710                   else 
1711                     new_type = bp_loc_software_breakpoint;
1712                   
1713                   if (new_type != bl->loc_type)
1714                     {
1715                       static int said = 0;
1716
1717                       bl->loc_type = new_type;
1718                       if (!said)
1719                         {
1720                           fprintf_filtered (gdb_stdout,
1721                                             _("Note: automatically using "
1722                                               "hardware breakpoints for "
1723                                               "read-only addresses.\n"));
1724                           said = 1;
1725                         }
1726                     }
1727                 }
1728               else if (bl->loc_type == bp_loc_software_breakpoint
1729                        && mr->attrib.mode != MEM_RW)        
1730                 warning (_("cannot set software breakpoint "
1731                            "at readonly address %s"),
1732                          paddress (bl->gdbarch, bl->address));
1733             }
1734         }
1735         
1736       /* First check to see if we have to handle an overlay.  */
1737       if (overlay_debugging == ovly_off
1738           || bl->section == NULL
1739           || !(section_is_overlay (bl->section)))
1740         {
1741           /* No overlay handling: just set the breakpoint.  */
1742
1743           val = bl->owner->ops->insert_location (bl);
1744         }
1745       else
1746         {
1747           /* This breakpoint is in an overlay section.
1748              Shall we set a breakpoint at the LMA?  */
1749           if (!overlay_events_enabled)
1750             {
1751               /* Yes -- overlay event support is not active, 
1752                  so we must try to set a breakpoint at the LMA.
1753                  This will not work for a hardware breakpoint.  */
1754               if (bl->loc_type == bp_loc_hardware_breakpoint)
1755                 warning (_("hardware breakpoint %d not supported in overlay!"),
1756                          bl->owner->number);
1757               else
1758                 {
1759                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
1760                                                              bl->section);
1761                   /* Set a software (trap) breakpoint at the LMA.  */
1762                   bl->overlay_target_info = bl->target_info;
1763                   bl->overlay_target_info.placed_address = addr;
1764                   val = target_insert_breakpoint (bl->gdbarch,
1765                                                   &bl->overlay_target_info);
1766                   if (val != 0)
1767                     fprintf_unfiltered (tmp_error_stream,
1768                                         "Overlay breakpoint %d "
1769                                         "failed: in ROM?\n",
1770                                         bl->owner->number);
1771                 }
1772             }
1773           /* Shall we set a breakpoint at the VMA? */
1774           if (section_is_mapped (bl->section))
1775             {
1776               /* Yes.  This overlay section is mapped into memory.  */
1777               val = bl->owner->ops->insert_location (bl);
1778             }
1779           else
1780             {
1781               /* No.  This breakpoint will not be inserted.  
1782                  No error, but do not mark the bp as 'inserted'.  */
1783               return 0;
1784             }
1785         }
1786
1787       if (val)
1788         {
1789           /* Can't set the breakpoint.  */
1790           if (solib_name_from_address (bl->pspace, bl->address))
1791             {
1792               /* See also: disable_breakpoints_in_shlibs.  */
1793               val = 0;
1794               bl->shlib_disabled = 1;
1795               observer_notify_breakpoint_modified (bl->owner);
1796               if (!*disabled_breaks)
1797                 {
1798                   fprintf_unfiltered (tmp_error_stream, 
1799                                       "Cannot insert breakpoint %d.\n", 
1800                                       bl->owner->number);
1801                   fprintf_unfiltered (tmp_error_stream, 
1802                                       "Temporarily disabling shared "
1803                                       "library breakpoints:\n");
1804                 }
1805               *disabled_breaks = 1;
1806               fprintf_unfiltered (tmp_error_stream,
1807                                   "breakpoint #%d\n", bl->owner->number);
1808             }
1809           else
1810             {
1811               if (bl->loc_type == bp_loc_hardware_breakpoint)
1812                 {
1813                   *hw_breakpoint_error = 1;
1814                   fprintf_unfiltered (tmp_error_stream,
1815                                       "Cannot insert hardware "
1816                                       "breakpoint %d.\n",
1817                                       bl->owner->number);
1818                 }
1819               else
1820                 {
1821                   fprintf_unfiltered (tmp_error_stream, 
1822                                       "Cannot insert breakpoint %d.\n", 
1823                                       bl->owner->number);
1824                   fprintf_filtered (tmp_error_stream, 
1825                                     "Error accessing memory address ");
1826                   fputs_filtered (paddress (bl->gdbarch, bl->address),
1827                                   tmp_error_stream);
1828                   fprintf_filtered (tmp_error_stream, ": %s.\n",
1829                                     safe_strerror (val));
1830                 }
1831
1832             }
1833         }
1834       else
1835         bl->inserted = 1;
1836
1837       return val;
1838     }
1839
1840   else if (bl->loc_type == bp_loc_hardware_watchpoint
1841            /* NOTE drow/2003-09-08: This state only exists for removing
1842               watchpoints.  It's not clear that it's necessary...  */
1843            && bl->owner->disposition != disp_del_at_next_stop)
1844     {
1845       gdb_assert (bl->owner->ops != NULL
1846                   && bl->owner->ops->insert_location != NULL);
1847
1848       val = bl->owner->ops->insert_location (bl);
1849
1850       /* If trying to set a read-watchpoint, and it turns out it's not
1851          supported, try emulating one with an access watchpoint.  */
1852       if (val == 1 && bl->watchpoint_type == hw_read)
1853         {
1854           struct bp_location *loc, **loc_temp;
1855
1856           /* But don't try to insert it, if there's already another
1857              hw_access location that would be considered a duplicate
1858              of this one.  */
1859           ALL_BP_LOCATIONS (loc, loc_temp)
1860             if (loc != bl
1861                 && loc->watchpoint_type == hw_access
1862                 && watchpoint_locations_match (bl, loc))
1863               {
1864                 bl->duplicate = 1;
1865                 bl->inserted = 1;
1866                 bl->target_info = loc->target_info;
1867                 bl->watchpoint_type = hw_access;
1868                 val = 0;
1869                 break;
1870               }
1871
1872           if (val == 1)
1873             {
1874               bl->watchpoint_type = hw_access;
1875               val = bl->owner->ops->insert_location (bl);
1876
1877               if (val)
1878                 /* Back to the original value.  */
1879                 bl->watchpoint_type = hw_read;
1880             }
1881         }
1882
1883       bl->inserted = (val == 0);
1884     }
1885
1886   else if (bl->owner->type == bp_catchpoint)
1887     {
1888       gdb_assert (bl->owner->ops != NULL
1889                   && bl->owner->ops->insert_location != NULL);
1890
1891       val = bl->owner->ops->insert_location (bl);
1892       if (val)
1893         {
1894           bl->owner->enable_state = bp_disabled;
1895
1896           if (val == 1)
1897             warning (_("\
1898 Error inserting catchpoint %d: Your system does not support this type\n\
1899 of catchpoint."), bl->owner->number);
1900           else
1901             warning (_("Error inserting catchpoint %d."), bl->owner->number);
1902         }
1903
1904       bl->inserted = (val == 0);
1905
1906       /* We've already printed an error message if there was a problem
1907          inserting this catchpoint, and we've disabled the catchpoint,
1908          so just return success.  */
1909       return 0;
1910     }
1911
1912   return 0;
1913 }
1914
1915 /* This function is called when program space PSPACE is about to be
1916    deleted.  It takes care of updating breakpoints to not reference
1917    PSPACE anymore.  */
1918
1919 void
1920 breakpoint_program_space_exit (struct program_space *pspace)
1921 {
1922   struct breakpoint *b, *b_temp;
1923   struct bp_location *loc, **loc_temp;
1924
1925   /* Remove any breakpoint that was set through this program space.  */
1926   ALL_BREAKPOINTS_SAFE (b, b_temp)
1927     {
1928       if (b->pspace == pspace)
1929         delete_breakpoint (b);
1930     }
1931
1932   /* Breakpoints set through other program spaces could have locations
1933      bound to PSPACE as well.  Remove those.  */
1934   ALL_BP_LOCATIONS (loc, loc_temp)
1935     {
1936       struct bp_location *tmp;
1937
1938       if (loc->pspace == pspace)
1939         {
1940           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
1941           if (loc->owner->loc == loc)
1942             loc->owner->loc = loc->next;
1943           else
1944             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
1945               if (tmp->next == loc)
1946                 {
1947                   tmp->next = loc->next;
1948                   break;
1949                 }
1950         }
1951     }
1952
1953   /* Now update the global location list to permanently delete the
1954      removed locations above.  */
1955   update_global_location_list (0);
1956 }
1957
1958 /* Make sure all breakpoints are inserted in inferior.
1959    Throws exception on any error.
1960    A breakpoint that is already inserted won't be inserted
1961    again, so calling this function twice is safe.  */
1962 void
1963 insert_breakpoints (void)
1964 {
1965   struct breakpoint *bpt;
1966
1967   ALL_BREAKPOINTS (bpt)
1968     if (is_hardware_watchpoint (bpt))
1969       {
1970         struct watchpoint *w = (struct watchpoint *) bpt;
1971
1972         update_watchpoint (w, 0 /* don't reparse.  */);
1973       }
1974
1975   update_global_location_list (1);
1976
1977   /* update_global_location_list does not insert breakpoints when
1978      always_inserted_mode is not enabled.  Explicitly insert them
1979      now.  */
1980   if (!breakpoints_always_inserted_mode ())
1981     insert_breakpoint_locations ();
1982 }
1983
1984 /* Used when starting or continuing the program.  */
1985
1986 static void
1987 insert_breakpoint_locations (void)
1988 {
1989   struct breakpoint *bpt;
1990   struct bp_location *bl, **blp_tmp;
1991   int error_flag = 0;
1992   int val = 0;
1993   int disabled_breaks = 0;
1994   int hw_breakpoint_error = 0;
1995
1996   struct ui_file *tmp_error_stream = mem_fileopen ();
1997   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
1998   
1999   /* Explicitly mark the warning -- this will only be printed if
2000      there was an error.  */
2001   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2002
2003   save_current_space_and_thread ();
2004
2005   ALL_BP_LOCATIONS (bl, blp_tmp)
2006     {
2007       if (!should_be_inserted (bl) || bl->inserted)
2008         continue;
2009
2010       /* There is no point inserting thread-specific breakpoints if
2011          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2012          has BL->OWNER always non-NULL.  */
2013       if (bl->owner->thread != -1
2014           && !valid_thread_id (bl->owner->thread))
2015         continue;
2016
2017       switch_to_program_space_and_thread (bl->pspace);
2018
2019       /* For targets that support global breakpoints, there's no need
2020          to select an inferior to insert breakpoint to.  In fact, even
2021          if we aren't attached to any process yet, we should still
2022          insert breakpoints.  */
2023       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2024           && ptid_equal (inferior_ptid, null_ptid))
2025         continue;
2026
2027       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2028                                     &hw_breakpoint_error);
2029       if (val)
2030         error_flag = val;
2031     }
2032
2033   /* If we failed to insert all locations of a watchpoint, remove
2034      them, as half-inserted watchpoint is of limited use.  */
2035   ALL_BREAKPOINTS (bpt)  
2036     {
2037       int some_failed = 0;
2038       struct bp_location *loc;
2039
2040       if (!is_hardware_watchpoint (bpt))
2041         continue;
2042
2043       if (!breakpoint_enabled (bpt))
2044         continue;
2045
2046       if (bpt->disposition == disp_del_at_next_stop)
2047         continue;
2048       
2049       for (loc = bpt->loc; loc; loc = loc->next)
2050         if (!loc->inserted && should_be_inserted (loc))
2051           {
2052             some_failed = 1;
2053             break;
2054           }
2055       if (some_failed)
2056         {
2057           for (loc = bpt->loc; loc; loc = loc->next)
2058             if (loc->inserted)
2059               remove_breakpoint (loc, mark_uninserted);
2060
2061           hw_breakpoint_error = 1;
2062           fprintf_unfiltered (tmp_error_stream,
2063                               "Could not insert hardware watchpoint %d.\n", 
2064                               bpt->number);
2065           error_flag = -1;
2066         }
2067     }
2068
2069   if (error_flag)
2070     {
2071       /* If a hardware breakpoint or watchpoint was inserted, add a
2072          message about possibly exhausted resources.  */
2073       if (hw_breakpoint_error)
2074         {
2075           fprintf_unfiltered (tmp_error_stream, 
2076                               "Could not insert hardware breakpoints:\n\
2077 You may have requested too many hardware breakpoints/watchpoints.\n");
2078         }
2079       target_terminal_ours_for_output ();
2080       error_stream (tmp_error_stream);
2081     }
2082
2083   do_cleanups (cleanups);
2084 }
2085
2086 /* Used when the program stops.
2087    Returns zero if successful, or non-zero if there was a problem
2088    removing a breakpoint location.  */
2089
2090 int
2091 remove_breakpoints (void)
2092 {
2093   struct bp_location *bl, **blp_tmp;
2094   int val = 0;
2095
2096   ALL_BP_LOCATIONS (bl, blp_tmp)
2097   {
2098     if (bl->inserted && !is_tracepoint (bl->owner))
2099       val |= remove_breakpoint (bl, mark_uninserted);
2100   }
2101   return val;
2102 }
2103
2104 /* Remove breakpoints of process PID.  */
2105
2106 int
2107 remove_breakpoints_pid (int pid)
2108 {
2109   struct bp_location *bl, **blp_tmp;
2110   int val;
2111   struct inferior *inf = find_inferior_pid (pid);
2112
2113   ALL_BP_LOCATIONS (bl, blp_tmp)
2114   {
2115     if (bl->pspace != inf->pspace)
2116       continue;
2117
2118     if (bl->inserted)
2119       {
2120         val = remove_breakpoint (bl, mark_uninserted);
2121         if (val != 0)
2122           return val;
2123       }
2124   }
2125   return 0;
2126 }
2127
2128 int
2129 reattach_breakpoints (int pid)
2130 {
2131   struct cleanup *old_chain;
2132   struct bp_location *bl, **blp_tmp;
2133   int val;
2134   struct ui_file *tmp_error_stream;
2135   int dummy1 = 0, dummy2 = 0;
2136   struct inferior *inf;
2137   struct thread_info *tp;
2138
2139   tp = any_live_thread_of_process (pid);
2140   if (tp == NULL)
2141     return 1;
2142
2143   inf = find_inferior_pid (pid);
2144   old_chain = save_inferior_ptid ();
2145
2146   inferior_ptid = tp->ptid;
2147
2148   tmp_error_stream = mem_fileopen ();
2149   make_cleanup_ui_file_delete (tmp_error_stream);
2150
2151   ALL_BP_LOCATIONS (bl, blp_tmp)
2152   {
2153     if (bl->pspace != inf->pspace)
2154       continue;
2155
2156     if (bl->inserted)
2157       {
2158         bl->inserted = 0;
2159         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2160         if (val != 0)
2161           {
2162             do_cleanups (old_chain);
2163             return val;
2164           }
2165       }
2166   }
2167   do_cleanups (old_chain);
2168   return 0;
2169 }
2170
2171 static int internal_breakpoint_number = -1;
2172
2173 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2174    If INTERNAL is non-zero, the breakpoint number will be populated
2175    from internal_breakpoint_number and that variable decremented.
2176    Otherwise the breakpoint number will be populated from
2177    breakpoint_count and that value incremented.  Internal breakpoints
2178    do not set the internal var bpnum.  */
2179 static void
2180 set_breakpoint_number (int internal, struct breakpoint *b)
2181 {
2182   if (internal)
2183     b->number = internal_breakpoint_number--;
2184   else
2185     {
2186       set_breakpoint_count (breakpoint_count + 1);
2187       b->number = breakpoint_count;
2188     }
2189 }
2190
2191 static struct breakpoint *
2192 create_internal_breakpoint (struct gdbarch *gdbarch,
2193                             CORE_ADDR address, enum bptype type,
2194                             const struct breakpoint_ops *ops)
2195 {
2196   struct symtab_and_line sal;
2197   struct breakpoint *b;
2198
2199   init_sal (&sal);              /* Initialize to zeroes.  */
2200
2201   sal.pc = address;
2202   sal.section = find_pc_overlay (sal.pc);
2203   sal.pspace = current_program_space;
2204
2205   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2206   b->number = internal_breakpoint_number--;
2207   b->disposition = disp_donttouch;
2208
2209   return b;
2210 }
2211
2212 static const char *const longjmp_names[] =
2213   {
2214     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2215   };
2216 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2217
2218 /* Per-objfile data private to breakpoint.c.  */
2219 struct breakpoint_objfile_data
2220 {
2221   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2222   struct minimal_symbol *overlay_msym;
2223
2224   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2225   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2226
2227   /* Minimal symbol for "std::terminate()" (if any).  */
2228   struct minimal_symbol *terminate_msym;
2229
2230   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2231   struct minimal_symbol *exception_msym;
2232 };
2233
2234 static const struct objfile_data *breakpoint_objfile_key;
2235
2236 /* Minimal symbol not found sentinel.  */
2237 static struct minimal_symbol msym_not_found;
2238
2239 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2240
2241 static int
2242 msym_not_found_p (const struct minimal_symbol *msym)
2243 {
2244   return msym == &msym_not_found;
2245 }
2246
2247 /* Return per-objfile data needed by breakpoint.c.
2248    Allocate the data if necessary.  */
2249
2250 static struct breakpoint_objfile_data *
2251 get_breakpoint_objfile_data (struct objfile *objfile)
2252 {
2253   struct breakpoint_objfile_data *bp_objfile_data;
2254
2255   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2256   if (bp_objfile_data == NULL)
2257     {
2258       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2259                                        sizeof (*bp_objfile_data));
2260
2261       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2262       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2263     }
2264   return bp_objfile_data;
2265 }
2266
2267 static void
2268 create_overlay_event_breakpoint (void)
2269 {
2270   struct objfile *objfile;
2271   const char *const func_name = "_ovly_debug_event";
2272
2273   ALL_OBJFILES (objfile)
2274     {
2275       struct breakpoint *b;
2276       struct breakpoint_objfile_data *bp_objfile_data;
2277       CORE_ADDR addr;
2278
2279       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2280
2281       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2282         continue;
2283
2284       if (bp_objfile_data->overlay_msym == NULL)
2285         {
2286           struct minimal_symbol *m;
2287
2288           m = lookup_minimal_symbol_text (func_name, objfile);
2289           if (m == NULL)
2290             {
2291               /* Avoid future lookups in this objfile.  */
2292               bp_objfile_data->overlay_msym = &msym_not_found;
2293               continue;
2294             }
2295           bp_objfile_data->overlay_msym = m;
2296         }
2297
2298       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2299       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2300                                       bp_overlay_event,
2301                                       &internal_breakpoint_ops);
2302       b->addr_string = xstrdup (func_name);
2303
2304       if (overlay_debugging == ovly_auto)
2305         {
2306           b->enable_state = bp_enabled;
2307           overlay_events_enabled = 1;
2308         }
2309       else
2310        {
2311          b->enable_state = bp_disabled;
2312          overlay_events_enabled = 0;
2313        }
2314     }
2315   update_global_location_list (1);
2316 }
2317
2318 static void
2319 create_longjmp_master_breakpoint (void)
2320 {
2321   struct program_space *pspace;
2322   struct cleanup *old_chain;
2323
2324   old_chain = save_current_program_space ();
2325
2326   ALL_PSPACES (pspace)
2327   {
2328     struct objfile *objfile;
2329
2330     set_current_program_space (pspace);
2331
2332     ALL_OBJFILES (objfile)
2333     {
2334       int i;
2335       struct gdbarch *gdbarch;
2336       struct breakpoint_objfile_data *bp_objfile_data;
2337
2338       gdbarch = get_objfile_arch (objfile);
2339       if (!gdbarch_get_longjmp_target_p (gdbarch))
2340         continue;
2341
2342       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2343
2344       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2345         {
2346           struct breakpoint *b;
2347           const char *func_name;
2348           CORE_ADDR addr;
2349
2350           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2351             continue;
2352
2353           func_name = longjmp_names[i];
2354           if (bp_objfile_data->longjmp_msym[i] == NULL)
2355             {
2356               struct minimal_symbol *m;
2357
2358               m = lookup_minimal_symbol_text (func_name, objfile);
2359               if (m == NULL)
2360                 {
2361                   /* Prevent future lookups in this objfile.  */
2362                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2363                   continue;
2364                 }
2365               bp_objfile_data->longjmp_msym[i] = m;
2366             }
2367
2368           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2369           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2370                                           &internal_breakpoint_ops);
2371           b->addr_string = xstrdup (func_name);
2372           b->enable_state = bp_disabled;
2373         }
2374     }
2375   }
2376   update_global_location_list (1);
2377
2378   do_cleanups (old_chain);
2379 }
2380
2381 /* Create a master std::terminate breakpoint.  */
2382 static void
2383 create_std_terminate_master_breakpoint (void)
2384 {
2385   struct program_space *pspace;
2386   struct cleanup *old_chain;
2387   const char *const func_name = "std::terminate()";
2388
2389   old_chain = save_current_program_space ();
2390
2391   ALL_PSPACES (pspace)
2392   {
2393     struct objfile *objfile;
2394     CORE_ADDR addr;
2395
2396     set_current_program_space (pspace);
2397
2398     ALL_OBJFILES (objfile)
2399     {
2400       struct breakpoint *b;
2401       struct breakpoint_objfile_data *bp_objfile_data;
2402
2403       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2404
2405       if (msym_not_found_p (bp_objfile_data->terminate_msym))
2406         continue;
2407
2408       if (bp_objfile_data->terminate_msym == NULL)
2409         {
2410           struct minimal_symbol *m;
2411
2412           m = lookup_minimal_symbol (func_name, NULL, objfile);
2413           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
2414                             && MSYMBOL_TYPE (m) != mst_file_text))
2415             {
2416               /* Prevent future lookups in this objfile.  */
2417               bp_objfile_data->terminate_msym = &msym_not_found;
2418               continue;
2419             }
2420           bp_objfile_data->terminate_msym = m;
2421         }
2422
2423       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
2424       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2425                                       bp_std_terminate_master,
2426                                       &internal_breakpoint_ops);
2427       b->addr_string = xstrdup (func_name);
2428       b->enable_state = bp_disabled;
2429     }
2430   }
2431
2432   update_global_location_list (1);
2433
2434   do_cleanups (old_chain);
2435 }
2436
2437 /* Install a master breakpoint on the unwinder's debug hook.  */
2438
2439 void
2440 create_exception_master_breakpoint (void)
2441 {
2442   struct objfile *objfile;
2443   const char *const func_name = "_Unwind_DebugHook";
2444
2445   ALL_OBJFILES (objfile)
2446     {
2447       struct breakpoint *b;
2448       struct gdbarch *gdbarch;
2449       struct breakpoint_objfile_data *bp_objfile_data;
2450       CORE_ADDR addr;
2451
2452       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2453
2454       if (msym_not_found_p (bp_objfile_data->exception_msym))
2455         continue;
2456
2457       gdbarch = get_objfile_arch (objfile);
2458
2459       if (bp_objfile_data->exception_msym == NULL)
2460         {
2461           struct minimal_symbol *debug_hook;
2462
2463           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
2464           if (debug_hook == NULL)
2465             {
2466               bp_objfile_data->exception_msym = &msym_not_found;
2467               continue;
2468             }
2469
2470           bp_objfile_data->exception_msym = debug_hook;
2471         }
2472
2473       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
2474       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
2475                                                  &current_target);
2476       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
2477                                       &internal_breakpoint_ops);
2478       b->addr_string = xstrdup (func_name);
2479       b->enable_state = bp_disabled;
2480     }
2481
2482   update_global_location_list (1);
2483 }
2484
2485 void
2486 update_breakpoints_after_exec (void)
2487 {
2488   struct breakpoint *b, *b_tmp;
2489   struct bp_location *bploc, **bplocp_tmp;
2490
2491   /* We're about to delete breakpoints from GDB's lists.  If the
2492      INSERTED flag is true, GDB will try to lift the breakpoints by
2493      writing the breakpoints' "shadow contents" back into memory.  The
2494      "shadow contents" are NOT valid after an exec, so GDB should not
2495      do that.  Instead, the target is responsible from marking
2496      breakpoints out as soon as it detects an exec.  We don't do that
2497      here instead, because there may be other attempts to delete
2498      breakpoints after detecting an exec and before reaching here.  */
2499   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
2500     if (bploc->pspace == current_program_space)
2501       gdb_assert (!bploc->inserted);
2502
2503   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2504   {
2505     if (b->pspace != current_program_space)
2506       continue;
2507
2508     /* Solib breakpoints must be explicitly reset after an exec().  */
2509     if (b->type == bp_shlib_event)
2510       {
2511         delete_breakpoint (b);
2512         continue;
2513       }
2514
2515     /* JIT breakpoints must be explicitly reset after an exec().  */
2516     if (b->type == bp_jit_event)
2517       {
2518         delete_breakpoint (b);
2519         continue;
2520       }
2521
2522     /* Thread event breakpoints must be set anew after an exec(),
2523        as must overlay event and longjmp master breakpoints.  */
2524     if (b->type == bp_thread_event || b->type == bp_overlay_event
2525         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
2526         || b->type == bp_exception_master)
2527       {
2528         delete_breakpoint (b);
2529         continue;
2530       }
2531
2532     /* Step-resume breakpoints are meaningless after an exec().  */
2533     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
2534       {
2535         delete_breakpoint (b);
2536         continue;
2537       }
2538
2539     /* Longjmp and longjmp-resume breakpoints are also meaningless
2540        after an exec.  */
2541     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
2542         || b->type == bp_exception || b->type == bp_exception_resume)
2543       {
2544         delete_breakpoint (b);
2545         continue;
2546       }
2547
2548     if (b->type == bp_catchpoint)
2549       {
2550         /* For now, none of the bp_catchpoint breakpoints need to
2551            do anything at this point.  In the future, if some of
2552            the catchpoints need to something, we will need to add
2553            a new method, and call this method from here.  */
2554         continue;
2555       }
2556
2557     /* bp_finish is a special case.  The only way we ought to be able
2558        to see one of these when an exec() has happened, is if the user
2559        caught a vfork, and then said "finish".  Ordinarily a finish just
2560        carries them to the call-site of the current callee, by setting
2561        a temporary bp there and resuming.  But in this case, the finish
2562        will carry them entirely through the vfork & exec.
2563
2564        We don't want to allow a bp_finish to remain inserted now.  But
2565        we can't safely delete it, 'cause finish_command has a handle to
2566        the bp on a bpstat, and will later want to delete it.  There's a
2567        chance (and I've seen it happen) that if we delete the bp_finish
2568        here, that its storage will get reused by the time finish_command
2569        gets 'round to deleting the "use to be a bp_finish" breakpoint.
2570        We really must allow finish_command to delete a bp_finish.
2571
2572        In the absence of a general solution for the "how do we know
2573        it's safe to delete something others may have handles to?"
2574        problem, what we'll do here is just uninsert the bp_finish, and
2575        let finish_command delete it.
2576
2577        (We know the bp_finish is "doomed" in the sense that it's
2578        momentary, and will be deleted as soon as finish_command sees
2579        the inferior stopped.  So it doesn't matter that the bp's
2580        address is probably bogus in the new a.out, unlike e.g., the
2581        solib breakpoints.)  */
2582
2583     if (b->type == bp_finish)
2584       {
2585         continue;
2586       }
2587
2588     /* Without a symbolic address, we have little hope of the
2589        pre-exec() address meaning the same thing in the post-exec()
2590        a.out.  */
2591     if (b->addr_string == NULL)
2592       {
2593         delete_breakpoint (b);
2594         continue;
2595       }
2596   }
2597   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
2598   create_overlay_event_breakpoint ();
2599   create_longjmp_master_breakpoint ();
2600   create_std_terminate_master_breakpoint ();
2601   create_exception_master_breakpoint ();
2602 }
2603
2604 int
2605 detach_breakpoints (int pid)
2606 {
2607   struct bp_location *bl, **blp_tmp;
2608   int val = 0;
2609   struct cleanup *old_chain = save_inferior_ptid ();
2610   struct inferior *inf = current_inferior ();
2611
2612   if (pid == PIDGET (inferior_ptid))
2613     error (_("Cannot detach breakpoints of inferior_ptid"));
2614
2615   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
2616   inferior_ptid = pid_to_ptid (pid);
2617   ALL_BP_LOCATIONS (bl, blp_tmp)
2618   {
2619     if (bl->pspace != inf->pspace)
2620       continue;
2621
2622     if (bl->inserted)
2623       val |= remove_breakpoint_1 (bl, mark_inserted);
2624   }
2625
2626   /* Detach single-step breakpoints as well.  */
2627   detach_single_step_breakpoints ();
2628
2629   do_cleanups (old_chain);
2630   return val;
2631 }
2632
2633 /* Remove the breakpoint location BL from the current address space.
2634    Note that this is used to detach breakpoints from a child fork.
2635    When we get here, the child isn't in the inferior list, and neither
2636    do we have objects to represent its address space --- we should
2637    *not* look at bl->pspace->aspace here.  */
2638
2639 static int
2640 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
2641 {
2642   int val;
2643
2644   /* BL is never in moribund_locations by our callers.  */
2645   gdb_assert (bl->owner != NULL);
2646
2647   if (bl->owner->enable_state == bp_permanent)
2648     /* Permanent breakpoints cannot be inserted or removed.  */
2649     return 0;
2650
2651   /* The type of none suggests that owner is actually deleted.
2652      This should not ever happen.  */
2653   gdb_assert (bl->owner->type != bp_none);
2654
2655   if (bl->loc_type == bp_loc_software_breakpoint
2656       || bl->loc_type == bp_loc_hardware_breakpoint)
2657     {
2658       /* "Normal" instruction breakpoint: either the standard
2659          trap-instruction bp (bp_breakpoint), or a
2660          bp_hardware_breakpoint.  */
2661
2662       /* First check to see if we have to handle an overlay.  */
2663       if (overlay_debugging == ovly_off
2664           || bl->section == NULL
2665           || !(section_is_overlay (bl->section)))
2666         {
2667           /* No overlay handling: just remove the breakpoint.  */
2668           val = bl->owner->ops->remove_location (bl);
2669         }
2670       else
2671         {
2672           /* This breakpoint is in an overlay section.
2673              Did we set a breakpoint at the LMA?  */
2674           if (!overlay_events_enabled)
2675               {
2676                 /* Yes -- overlay event support is not active, so we
2677                    should have set a breakpoint at the LMA.  Remove it.  
2678                 */
2679                 /* Ignore any failures: if the LMA is in ROM, we will
2680                    have already warned when we failed to insert it.  */
2681                 if (bl->loc_type == bp_loc_hardware_breakpoint)
2682                   target_remove_hw_breakpoint (bl->gdbarch,
2683                                                &bl->overlay_target_info);
2684                 else
2685                   target_remove_breakpoint (bl->gdbarch,
2686                                             &bl->overlay_target_info);
2687               }
2688           /* Did we set a breakpoint at the VMA? 
2689              If so, we will have marked the breakpoint 'inserted'.  */
2690           if (bl->inserted)
2691             {
2692               /* Yes -- remove it.  Previously we did not bother to
2693                  remove the breakpoint if the section had been
2694                  unmapped, but let's not rely on that being safe.  We
2695                  don't know what the overlay manager might do.  */
2696
2697               /* However, we should remove *software* breakpoints only
2698                  if the section is still mapped, or else we overwrite
2699                  wrong code with the saved shadow contents.  */
2700               if (bl->loc_type == bp_loc_hardware_breakpoint
2701                   || section_is_mapped (bl->section))
2702                 val = bl->owner->ops->remove_location (bl);
2703               else
2704                 val = 0;
2705             }
2706           else
2707             {
2708               /* No -- not inserted, so no need to remove.  No error.  */
2709               val = 0;
2710             }
2711         }
2712
2713       /* In some cases, we might not be able to remove a breakpoint
2714          in a shared library that has already been removed, but we
2715          have not yet processed the shlib unload event.  */
2716       if (val && solib_name_from_address (bl->pspace, bl->address))
2717         val = 0;
2718
2719       if (val)
2720         return val;
2721       bl->inserted = (is == mark_inserted);
2722     }
2723   else if (bl->loc_type == bp_loc_hardware_watchpoint)
2724     {
2725       gdb_assert (bl->owner->ops != NULL
2726                   && bl->owner->ops->remove_location != NULL);
2727
2728       bl->inserted = (is == mark_inserted);
2729       bl->owner->ops->remove_location (bl);
2730
2731       /* Failure to remove any of the hardware watchpoints comes here.  */
2732       if ((is == mark_uninserted) && (bl->inserted))
2733         warning (_("Could not remove hardware watchpoint %d."),
2734                  bl->owner->number);
2735     }
2736   else if (bl->owner->type == bp_catchpoint
2737            && breakpoint_enabled (bl->owner)
2738            && !bl->duplicate)
2739     {
2740       gdb_assert (bl->owner->ops != NULL
2741                   && bl->owner->ops->remove_location != NULL);
2742
2743       val = bl->owner->ops->remove_location (bl);
2744       if (val)
2745         return val;
2746
2747       bl->inserted = (is == mark_inserted);
2748     }
2749
2750   return 0;
2751 }
2752
2753 static int
2754 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
2755 {
2756   int ret;
2757   struct cleanup *old_chain;
2758
2759   /* BL is never in moribund_locations by our callers.  */
2760   gdb_assert (bl->owner != NULL);
2761
2762   if (bl->owner->enable_state == bp_permanent)
2763     /* Permanent breakpoints cannot be inserted or removed.  */
2764     return 0;
2765
2766   /* The type of none suggests that owner is actually deleted.
2767      This should not ever happen.  */
2768   gdb_assert (bl->owner->type != bp_none);
2769
2770   old_chain = save_current_space_and_thread ();
2771
2772   switch_to_program_space_and_thread (bl->pspace);
2773
2774   ret = remove_breakpoint_1 (bl, is);
2775
2776   do_cleanups (old_chain);
2777   return ret;
2778 }
2779
2780 /* Clear the "inserted" flag in all breakpoints.  */
2781
2782 void
2783 mark_breakpoints_out (void)
2784 {
2785   struct bp_location *bl, **blp_tmp;
2786
2787   ALL_BP_LOCATIONS (bl, blp_tmp)
2788     if (bl->pspace == current_program_space)
2789       bl->inserted = 0;
2790 }
2791
2792 /* Clear the "inserted" flag in all breakpoints and delete any
2793    breakpoints which should go away between runs of the program.
2794
2795    Plus other such housekeeping that has to be done for breakpoints
2796    between runs.
2797
2798    Note: this function gets called at the end of a run (by
2799    generic_mourn_inferior) and when a run begins (by
2800    init_wait_for_inferior).  */
2801
2802
2803
2804 void
2805 breakpoint_init_inferior (enum inf_context context)
2806 {
2807   struct breakpoint *b, *b_tmp;
2808   struct bp_location *bl, **blp_tmp;
2809   int ix;
2810   struct program_space *pspace = current_program_space;
2811
2812   /* If breakpoint locations are shared across processes, then there's
2813      nothing to do.  */
2814   if (gdbarch_has_global_breakpoints (target_gdbarch))
2815     return;
2816
2817   ALL_BP_LOCATIONS (bl, blp_tmp)
2818   {
2819     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
2820     if (bl->pspace == pspace
2821         && bl->owner->enable_state != bp_permanent)
2822       bl->inserted = 0;
2823   }
2824
2825   ALL_BREAKPOINTS_SAFE (b, b_tmp)
2826   {
2827     if (b->loc && b->loc->pspace != pspace)
2828       continue;
2829
2830     switch (b->type)
2831       {
2832       case bp_call_dummy:
2833
2834         /* If the call dummy breakpoint is at the entry point it will
2835            cause problems when the inferior is rerun, so we better get
2836            rid of it.  */
2837
2838       case bp_watchpoint_scope:
2839
2840         /* Also get rid of scope breakpoints.  */
2841
2842       case bp_shlib_event:
2843
2844         /* Also remove solib event breakpoints.  Their addresses may
2845            have changed since the last time we ran the program.
2846            Actually we may now be debugging against different target;
2847            and so the solib backend that installed this breakpoint may
2848            not be used in by the target.  E.g.,
2849
2850            (gdb) file prog-linux
2851            (gdb) run               # native linux target
2852            ...
2853            (gdb) kill
2854            (gdb) file prog-win.exe
2855            (gdb) tar rem :9999     # remote Windows gdbserver.
2856         */
2857
2858         delete_breakpoint (b);
2859         break;
2860
2861       case bp_watchpoint:
2862       case bp_hardware_watchpoint:
2863       case bp_read_watchpoint:
2864       case bp_access_watchpoint:
2865         {
2866           struct watchpoint *w = (struct watchpoint *) b;
2867
2868           /* Likewise for watchpoints on local expressions.  */
2869           if (w->exp_valid_block != NULL)
2870             delete_breakpoint (b);
2871           else if (context == inf_starting)
2872             {
2873               /* Reset val field to force reread of starting value in
2874                  insert_breakpoints.  */
2875               if (w->val)
2876                 value_free (w->val);
2877               w->val = NULL;
2878               w->val_valid = 0;
2879           }
2880         }
2881         break;
2882       default:
2883         break;
2884       }
2885   }
2886
2887   /* Get rid of the moribund locations.  */
2888   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
2889     decref_bp_location (&bl);
2890   VEC_free (bp_location_p, moribund_locations);
2891 }
2892
2893 /* These functions concern about actual breakpoints inserted in the
2894    target --- to e.g. check if we need to do decr_pc adjustment or if
2895    we need to hop over the bkpt --- so we check for address space
2896    match, not program space.  */
2897
2898 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
2899    exists at PC.  It returns ordinary_breakpoint_here if it's an
2900    ordinary breakpoint, or permanent_breakpoint_here if it's a
2901    permanent breakpoint.
2902    - When continuing from a location with an ordinary breakpoint, we
2903      actually single step once before calling insert_breakpoints.
2904    - When continuing from a location with a permanent breakpoint, we
2905      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
2906      the target, to advance the PC past the breakpoint.  */
2907
2908 enum breakpoint_here
2909 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
2910 {
2911   struct bp_location *bl, **blp_tmp;
2912   int any_breakpoint_here = 0;
2913
2914   ALL_BP_LOCATIONS (bl, blp_tmp)
2915     {
2916       if (bl->loc_type != bp_loc_software_breakpoint
2917           && bl->loc_type != bp_loc_hardware_breakpoint)
2918         continue;
2919
2920       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
2921       if ((breakpoint_enabled (bl->owner)
2922            || bl->owner->enable_state == bp_permanent)
2923           && breakpoint_location_address_match (bl, aspace, pc))
2924         {
2925           if (overlay_debugging 
2926               && section_is_overlay (bl->section)
2927               && !section_is_mapped (bl->section))
2928             continue;           /* unmapped overlay -- can't be a match */
2929           else if (bl->owner->enable_state == bp_permanent)
2930             return permanent_breakpoint_here;
2931           else
2932             any_breakpoint_here = 1;
2933         }
2934     }
2935
2936   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
2937 }
2938
2939 /* Return true if there's a moribund breakpoint at PC.  */
2940
2941 int
2942 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
2943 {
2944   struct bp_location *loc;
2945   int ix;
2946
2947   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
2948     if (breakpoint_location_address_match (loc, aspace, pc))
2949       return 1;
2950
2951   return 0;
2952 }
2953
2954 /* Returns non-zero if there's a breakpoint inserted at PC, which is
2955    inserted using regular breakpoint_chain / bp_location array
2956    mechanism.  This does not check for single-step breakpoints, which
2957    are inserted and removed using direct target manipulation.  */
2958
2959 int
2960 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
2961                                     CORE_ADDR pc)
2962 {
2963   struct bp_location *bl, **blp_tmp;
2964
2965   ALL_BP_LOCATIONS (bl, blp_tmp)
2966     {
2967       if (bl->loc_type != bp_loc_software_breakpoint
2968           && bl->loc_type != bp_loc_hardware_breakpoint)
2969         continue;
2970
2971       if (bl->inserted
2972           && breakpoint_location_address_match (bl, aspace, pc))
2973         {
2974           if (overlay_debugging 
2975               && section_is_overlay (bl->section)
2976               && !section_is_mapped (bl->section))
2977             continue;           /* unmapped overlay -- can't be a match */
2978           else
2979             return 1;
2980         }
2981     }
2982   return 0;
2983 }
2984
2985 /* Returns non-zero iff there's either regular breakpoint
2986    or a single step breakpoint inserted at PC.  */
2987
2988 int
2989 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
2990 {
2991   if (regular_breakpoint_inserted_here_p (aspace, pc))
2992     return 1;
2993
2994   if (single_step_breakpoint_inserted_here_p (aspace, pc))
2995     return 1;
2996
2997   return 0;
2998 }
2999
3000 /* This function returns non-zero iff there is a software breakpoint
3001    inserted at PC.  */
3002
3003 int
3004 software_breakpoint_inserted_here_p (struct address_space *aspace,
3005                                      CORE_ADDR pc)
3006 {
3007   struct bp_location *bl, **blp_tmp;
3008
3009   ALL_BP_LOCATIONS (bl, blp_tmp)
3010     {
3011       if (bl->loc_type != bp_loc_software_breakpoint)
3012         continue;
3013
3014       if (bl->inserted
3015           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3016                                        aspace, pc))
3017         {
3018           if (overlay_debugging 
3019               && section_is_overlay (bl->section)
3020               && !section_is_mapped (bl->section))
3021             continue;           /* unmapped overlay -- can't be a match */
3022           else
3023             return 1;
3024         }
3025     }
3026
3027   /* Also check for software single-step breakpoints.  */
3028   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3029     return 1;
3030
3031   return 0;
3032 }
3033
3034 int
3035 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3036                                        CORE_ADDR addr, ULONGEST len)
3037 {
3038   struct breakpoint *bpt;
3039
3040   ALL_BREAKPOINTS (bpt)
3041     {
3042       struct bp_location *loc;
3043
3044       if (bpt->type != bp_hardware_watchpoint
3045           && bpt->type != bp_access_watchpoint)
3046         continue;
3047
3048       if (!breakpoint_enabled (bpt))
3049         continue;
3050
3051       for (loc = bpt->loc; loc; loc = loc->next)
3052         if (loc->pspace->aspace == aspace && loc->inserted)
3053           {
3054             CORE_ADDR l, h;
3055
3056             /* Check for intersection.  */
3057             l = max (loc->address, addr);
3058             h = min (loc->address + loc->length, addr + len);
3059             if (l < h)
3060               return 1;
3061           }
3062     }
3063   return 0;
3064 }
3065
3066 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3067    PC is valid for process/thread PTID.  */
3068
3069 int
3070 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3071                          ptid_t ptid)
3072 {
3073   struct bp_location *bl, **blp_tmp;
3074   /* The thread and task IDs associated to PTID, computed lazily.  */
3075   int thread = -1;
3076   int task = 0;
3077   
3078   ALL_BP_LOCATIONS (bl, blp_tmp)
3079     {
3080       if (bl->loc_type != bp_loc_software_breakpoint
3081           && bl->loc_type != bp_loc_hardware_breakpoint)
3082         continue;
3083
3084       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3085       if (!breakpoint_enabled (bl->owner)
3086           && bl->owner->enable_state != bp_permanent)
3087         continue;
3088
3089       if (!breakpoint_location_address_match (bl, aspace, pc))
3090         continue;
3091
3092       if (bl->owner->thread != -1)
3093         {
3094           /* This is a thread-specific breakpoint.  Check that ptid
3095              matches that thread.  If thread hasn't been computed yet,
3096              it is now time to do so.  */
3097           if (thread == -1)
3098             thread = pid_to_thread_id (ptid);
3099           if (bl->owner->thread != thread)
3100             continue;
3101         }
3102
3103       if (bl->owner->task != 0)
3104         {
3105           /* This is a task-specific breakpoint.  Check that ptid
3106              matches that task.  If task hasn't been computed yet,
3107              it is now time to do so.  */
3108           if (task == 0)
3109             task = ada_get_task_number (ptid);
3110           if (bl->owner->task != task)
3111             continue;
3112         }
3113
3114       if (overlay_debugging 
3115           && section_is_overlay (bl->section)
3116           && !section_is_mapped (bl->section))
3117         continue;           /* unmapped overlay -- can't be a match */
3118
3119       return 1;
3120     }
3121
3122   return 0;
3123 }
3124 \f
3125
3126 /* bpstat stuff.  External routines' interfaces are documented
3127    in breakpoint.h.  */
3128
3129 int
3130 ep_is_catchpoint (struct breakpoint *ep)
3131 {
3132   return (ep->type == bp_catchpoint);
3133 }
3134
3135 /* Frees any storage that is part of a bpstat.  Does not walk the
3136    'next' chain.  */
3137
3138 static void
3139 bpstat_free (bpstat bs)
3140 {
3141   if (bs->old_val != NULL)
3142     value_free (bs->old_val);
3143   decref_counted_command_line (&bs->commands);
3144   decref_bp_location (&bs->bp_location_at);
3145   xfree (bs);
3146 }
3147
3148 /* Clear a bpstat so that it says we are not at any breakpoint.
3149    Also free any storage that is part of a bpstat.  */
3150
3151 void
3152 bpstat_clear (bpstat *bsp)
3153 {
3154   bpstat p;
3155   bpstat q;
3156
3157   if (bsp == 0)
3158     return;
3159   p = *bsp;
3160   while (p != NULL)
3161     {
3162       q = p->next;
3163       bpstat_free (p);
3164       p = q;
3165     }
3166   *bsp = NULL;
3167 }
3168
3169 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3170    is part of the bpstat is copied as well.  */
3171
3172 bpstat
3173 bpstat_copy (bpstat bs)
3174 {
3175   bpstat p = NULL;
3176   bpstat tmp;
3177   bpstat retval = NULL;
3178
3179   if (bs == NULL)
3180     return bs;
3181
3182   for (; bs != NULL; bs = bs->next)
3183     {
3184       tmp = (bpstat) xmalloc (sizeof (*tmp));
3185       memcpy (tmp, bs, sizeof (*tmp));
3186       incref_counted_command_line (tmp->commands);
3187       incref_bp_location (tmp->bp_location_at);
3188       if (bs->old_val != NULL)
3189         {
3190           tmp->old_val = value_copy (bs->old_val);
3191           release_value (tmp->old_val);
3192         }
3193
3194       if (p == NULL)
3195         /* This is the first thing in the chain.  */
3196         retval = tmp;
3197       else
3198         p->next = tmp;
3199       p = tmp;
3200     }
3201   p->next = NULL;
3202   return retval;
3203 }
3204
3205 /* Find the bpstat associated with this breakpoint.  */
3206
3207 bpstat
3208 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3209 {
3210   if (bsp == NULL)
3211     return NULL;
3212
3213   for (; bsp != NULL; bsp = bsp->next)
3214     {
3215       if (bsp->breakpoint_at == breakpoint)
3216         return bsp;
3217     }
3218   return NULL;
3219 }
3220
3221 /* Put in *NUM the breakpoint number of the first breakpoint we are
3222    stopped at.  *BSP upon return is a bpstat which points to the
3223    remaining breakpoints stopped at (but which is not guaranteed to be
3224    good for anything but further calls to bpstat_num).
3225
3226    Return 0 if passed a bpstat which does not indicate any breakpoints.
3227    Return -1 if stopped at a breakpoint that has been deleted since
3228    we set it.
3229    Return 1 otherwise.  */
3230
3231 int
3232 bpstat_num (bpstat *bsp, int *num)
3233 {
3234   struct breakpoint *b;
3235
3236   if ((*bsp) == NULL)
3237     return 0;                   /* No more breakpoint values */
3238
3239   /* We assume we'll never have several bpstats that correspond to a
3240      single breakpoint -- otherwise, this function might return the
3241      same number more than once and this will look ugly.  */
3242   b = (*bsp)->breakpoint_at;
3243   *bsp = (*bsp)->next;
3244   if (b == NULL)
3245     return -1;                  /* breakpoint that's been deleted since */
3246
3247   *num = b->number;             /* We have its number */
3248   return 1;
3249 }
3250
3251 /* See breakpoint.h.  */
3252
3253 void
3254 bpstat_clear_actions (void)
3255 {
3256   struct thread_info *tp;
3257   bpstat bs;
3258
3259   if (ptid_equal (inferior_ptid, null_ptid))
3260     return;
3261
3262   tp = find_thread_ptid (inferior_ptid);
3263   if (tp == NULL)
3264     return;
3265
3266   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3267     {
3268       decref_counted_command_line (&bs->commands);
3269
3270       if (bs->old_val != NULL)
3271         {
3272           value_free (bs->old_val);
3273           bs->old_val = NULL;
3274         }
3275     }
3276 }
3277
3278 /* Called when a command is about to proceed the inferior.  */
3279
3280 static void
3281 breakpoint_about_to_proceed (void)
3282 {
3283   if (!ptid_equal (inferior_ptid, null_ptid))
3284     {
3285       struct thread_info *tp = inferior_thread ();
3286
3287       /* Allow inferior function calls in breakpoint commands to not
3288          interrupt the command list.  When the call finishes
3289          successfully, the inferior will be standing at the same
3290          breakpoint as if nothing happened.  */
3291       if (tp->control.in_infcall)
3292         return;
3293     }
3294
3295   breakpoint_proceeded = 1;
3296 }
3297
3298 /* Stub for cleaning up our state if we error-out of a breakpoint
3299    command.  */
3300 static void
3301 cleanup_executing_breakpoints (void *ignore)
3302 {
3303   executing_breakpoint_commands = 0;
3304 }
3305
3306 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3307    or its equivalent.  */
3308
3309 static int
3310 command_line_is_silent (struct command_line *cmd)
3311 {
3312   return cmd && (strcmp ("silent", cmd->line) == 0
3313                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3314 }
3315
3316 /* Execute all the commands associated with all the breakpoints at
3317    this location.  Any of these commands could cause the process to
3318    proceed beyond this point, etc.  We look out for such changes by
3319    checking the global "breakpoint_proceeded" after each command.
3320
3321    Returns true if a breakpoint command resumed the inferior.  In that
3322    case, it is the caller's responsibility to recall it again with the
3323    bpstat of the current thread.  */
3324
3325 static int
3326 bpstat_do_actions_1 (bpstat *bsp)
3327 {
3328   bpstat bs;
3329   struct cleanup *old_chain;
3330   int again = 0;
3331
3332   /* Avoid endless recursion if a `source' command is contained
3333      in bs->commands.  */
3334   if (executing_breakpoint_commands)
3335     return 0;
3336
3337   executing_breakpoint_commands = 1;
3338   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3339
3340   prevent_dont_repeat ();
3341
3342   /* This pointer will iterate over the list of bpstat's.  */
3343   bs = *bsp;
3344
3345   breakpoint_proceeded = 0;
3346   for (; bs != NULL; bs = bs->next)
3347     {
3348       struct counted_command_line *ccmd;
3349       struct command_line *cmd;
3350       struct cleanup *this_cmd_tree_chain;
3351
3352       /* Take ownership of the BSP's command tree, if it has one.
3353
3354          The command tree could legitimately contain commands like
3355          'step' and 'next', which call clear_proceed_status, which
3356          frees stop_bpstat's command tree.  To make sure this doesn't
3357          free the tree we're executing out from under us, we need to
3358          take ownership of the tree ourselves.  Since a given bpstat's
3359          commands are only executed once, we don't need to copy it; we
3360          can clear the pointer in the bpstat, and make sure we free
3361          the tree when we're done.  */
3362       ccmd = bs->commands;
3363       bs->commands = NULL;
3364       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3365       cmd = ccmd ? ccmd->commands : NULL;
3366       if (command_line_is_silent (cmd))
3367         {
3368           /* The action has been already done by bpstat_stop_status.  */
3369           cmd = cmd->next;
3370         }
3371
3372       while (cmd != NULL)
3373         {
3374           execute_control_command (cmd);
3375
3376           if (breakpoint_proceeded)
3377             break;
3378           else
3379             cmd = cmd->next;
3380         }
3381
3382       /* We can free this command tree now.  */
3383       do_cleanups (this_cmd_tree_chain);
3384
3385       if (breakpoint_proceeded)
3386         {
3387           if (target_can_async_p ())
3388             /* If we are in async mode, then the target might be still
3389                running, not stopped at any breakpoint, so nothing for
3390                us to do here -- just return to the event loop.  */
3391             ;
3392           else
3393             /* In sync mode, when execute_control_command returns
3394                we're already standing on the next breakpoint.
3395                Breakpoint commands for that stop were not run, since
3396                execute_command does not run breakpoint commands --
3397                only command_line_handler does, but that one is not
3398                involved in execution of breakpoint commands.  So, we
3399                can now execute breakpoint commands.  It should be
3400                noted that making execute_command do bpstat actions is
3401                not an option -- in this case we'll have recursive
3402                invocation of bpstat for each breakpoint with a
3403                command, and can easily blow up GDB stack.  Instead, we
3404                return true, which will trigger the caller to recall us
3405                with the new stop_bpstat.  */
3406             again = 1;
3407           break;
3408         }
3409     }
3410   do_cleanups (old_chain);
3411   return again;
3412 }
3413
3414 void
3415 bpstat_do_actions (void)
3416 {
3417   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
3418
3419   /* Do any commands attached to breakpoint we are stopped at.  */
3420   while (!ptid_equal (inferior_ptid, null_ptid)
3421          && target_has_execution
3422          && !is_exited (inferior_ptid)
3423          && !is_executing (inferior_ptid))
3424     /* Since in sync mode, bpstat_do_actions may resume the inferior,
3425        and only return when it is stopped at the next breakpoint, we
3426        keep doing breakpoint actions until it returns false to
3427        indicate the inferior was not resumed.  */
3428     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
3429       break;
3430
3431   discard_cleanups (cleanup_if_error);
3432 }
3433
3434 /* Print out the (old or new) value associated with a watchpoint.  */
3435
3436 static void
3437 watchpoint_value_print (struct value *val, struct ui_file *stream)
3438 {
3439   if (val == NULL)
3440     fprintf_unfiltered (stream, _("<unreadable>"));
3441   else
3442     {
3443       struct value_print_options opts;
3444       get_user_print_options (&opts);
3445       value_print (val, stream, &opts);
3446     }
3447 }
3448
3449 /* Generic routine for printing messages indicating why we
3450    stopped.  The behavior of this function depends on the value
3451    'print_it' in the bpstat structure.  Under some circumstances we
3452    may decide not to print anything here and delegate the task to
3453    normal_stop().  */
3454
3455 static enum print_stop_action
3456 print_bp_stop_message (bpstat bs)
3457 {
3458   switch (bs->print_it)
3459     {
3460     case print_it_noop:
3461       /* Nothing should be printed for this bpstat entry.  */
3462       return PRINT_UNKNOWN;
3463       break;
3464
3465     case print_it_done:
3466       /* We still want to print the frame, but we already printed the
3467          relevant messages.  */
3468       return PRINT_SRC_AND_LOC;
3469       break;
3470
3471     case print_it_normal:
3472       {
3473         struct breakpoint *b = bs->breakpoint_at;
3474
3475         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
3476            which has since been deleted.  */
3477         if (b == NULL)
3478           return PRINT_UNKNOWN;
3479
3480         /* Normal case.  Call the breakpoint's print_it method.  */
3481         return b->ops->print_it (bs);
3482       }
3483       break;
3484
3485     default:
3486       internal_error (__FILE__, __LINE__,
3487                       _("print_bp_stop_message: unrecognized enum value"));
3488       break;
3489     }
3490 }
3491
3492 /* Print a message indicating what happened.  This is called from
3493    normal_stop().  The input to this routine is the head of the bpstat
3494    list - a list of the eventpoints that caused this stop.  KIND is
3495    the target_waitkind for the stopping event.  This
3496    routine calls the generic print routine for printing a message
3497    about reasons for stopping.  This will print (for example) the
3498    "Breakpoint n," part of the output.  The return value of this
3499    routine is one of:
3500
3501    PRINT_UNKNOWN: Means we printed nothing.
3502    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
3503    code to print the location.  An example is 
3504    "Breakpoint 1, " which should be followed by
3505    the location.
3506    PRINT_SRC_ONLY: Means we printed something, but there is no need
3507    to also print the location part of the message.
3508    An example is the catch/throw messages, which
3509    don't require a location appended to the end.
3510    PRINT_NOTHING: We have done some printing and we don't need any 
3511    further info to be printed.  */
3512
3513 enum print_stop_action
3514 bpstat_print (bpstat bs, int kind)
3515 {
3516   int val;
3517
3518   /* Maybe another breakpoint in the chain caused us to stop.
3519      (Currently all watchpoints go on the bpstat whether hit or not.
3520      That probably could (should) be changed, provided care is taken
3521      with respect to bpstat_explains_signal).  */
3522   for (; bs; bs = bs->next)
3523     {
3524       val = print_bp_stop_message (bs);
3525       if (val == PRINT_SRC_ONLY 
3526           || val == PRINT_SRC_AND_LOC 
3527           || val == PRINT_NOTHING)
3528         return val;
3529     }
3530
3531   /* If we had hit a shared library event breakpoint,
3532      print_bp_stop_message would print out this message.  If we hit an
3533      OS-level shared library event, do the same thing.  */
3534   if (kind == TARGET_WAITKIND_LOADED)
3535     {
3536       ui_out_text (current_uiout, _("Stopped due to shared library event\n"));
3537       if (ui_out_is_mi_like_p (current_uiout))
3538         ui_out_field_string (current_uiout, "reason",
3539                              async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
3540       return PRINT_NOTHING;
3541     }
3542
3543   /* We reached the end of the chain, or we got a null BS to start
3544      with and nothing was printed.  */
3545   return PRINT_UNKNOWN;
3546 }
3547
3548 /* Evaluate the expression EXP and return 1 if value is zero.  This is
3549    used inside a catch_errors to evaluate the breakpoint condition.
3550    The argument is a "struct expression *" that has been cast to a
3551    "char *" to make it pass through catch_errors.  */
3552
3553 static int
3554 breakpoint_cond_eval (void *exp)
3555 {
3556   struct value *mark = value_mark ();
3557   int i = !value_true (evaluate_expression ((struct expression *) exp));
3558
3559   value_free_to_mark (mark);
3560   return i;
3561 }
3562
3563 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
3564
3565 static bpstat
3566 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
3567 {
3568   bpstat bs;
3569
3570   bs = (bpstat) xmalloc (sizeof (*bs));
3571   bs->next = NULL;
3572   **bs_link_pointer = bs;
3573   *bs_link_pointer = &bs->next;
3574   bs->breakpoint_at = bl->owner;
3575   bs->bp_location_at = bl;
3576   incref_bp_location (bl);
3577   /* If the condition is false, etc., don't do the commands.  */
3578   bs->commands = NULL;
3579   bs->old_val = NULL;
3580   bs->print_it = print_it_normal;
3581   return bs;
3582 }
3583 \f
3584 /* The target has stopped with waitstatus WS.  Check if any hardware
3585    watchpoints have triggered, according to the target.  */
3586
3587 int
3588 watchpoints_triggered (struct target_waitstatus *ws)
3589 {
3590   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
3591   CORE_ADDR addr;
3592   struct breakpoint *b;
3593
3594   if (!stopped_by_watchpoint)
3595     {
3596       /* We were not stopped by a watchpoint.  Mark all watchpoints
3597          as not triggered.  */
3598       ALL_BREAKPOINTS (b)
3599         if (is_hardware_watchpoint (b))
3600           {
3601             struct watchpoint *w = (struct watchpoint *) b;
3602
3603             w->watchpoint_triggered = watch_triggered_no;
3604           }
3605
3606       return 0;
3607     }
3608
3609   if (!target_stopped_data_address (&current_target, &addr))
3610     {
3611       /* We were stopped by a watchpoint, but we don't know where.
3612          Mark all watchpoints as unknown.  */
3613       ALL_BREAKPOINTS (b)
3614         if (is_hardware_watchpoint (b))
3615           {
3616             struct watchpoint *w = (struct watchpoint *) b;
3617
3618             w->watchpoint_triggered = watch_triggered_unknown;
3619           }
3620
3621       return stopped_by_watchpoint;
3622     }
3623
3624   /* The target could report the data address.  Mark watchpoints
3625      affected by this data address as triggered, and all others as not
3626      triggered.  */
3627
3628   ALL_BREAKPOINTS (b)
3629     if (is_hardware_watchpoint (b))
3630       {
3631         struct watchpoint *w = (struct watchpoint *) b;
3632         struct bp_location *loc;
3633
3634         w->watchpoint_triggered = watch_triggered_no;
3635         for (loc = b->loc; loc; loc = loc->next)
3636           {
3637             if (is_masked_watchpoint (b))
3638               {
3639                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
3640                 CORE_ADDR start = loc->address & w->hw_wp_mask;
3641
3642                 if (newaddr == start)
3643                   {
3644                     w->watchpoint_triggered = watch_triggered_yes;
3645                     break;
3646                   }
3647               }
3648             /* Exact match not required.  Within range is sufficient.  */
3649             else if (target_watchpoint_addr_within_range (&current_target,
3650                                                          addr, loc->address,
3651                                                          loc->length))
3652               {
3653                 w->watchpoint_triggered = watch_triggered_yes;
3654                 break;
3655               }
3656           }
3657       }
3658
3659   return 1;
3660 }
3661
3662 /* Possible return values for watchpoint_check (this can't be an enum
3663    because of check_errors).  */
3664 /* The watchpoint has been deleted.  */
3665 #define WP_DELETED 1
3666 /* The value has changed.  */
3667 #define WP_VALUE_CHANGED 2
3668 /* The value has not changed.  */
3669 #define WP_VALUE_NOT_CHANGED 3
3670 /* Ignore this watchpoint, no matter if the value changed or not.  */
3671 #define WP_IGNORE 4
3672
3673 #define BP_TEMPFLAG 1
3674 #define BP_HARDWAREFLAG 2
3675
3676 /* Evaluate watchpoint condition expression and check if its value
3677    changed.
3678
3679    P should be a pointer to struct bpstat, but is defined as a void *
3680    in order for this function to be usable with catch_errors.  */
3681
3682 static int
3683 watchpoint_check (void *p)
3684 {
3685   bpstat bs = (bpstat) p;
3686   struct watchpoint *b;
3687   struct frame_info *fr;
3688   int within_current_scope;
3689
3690   /* BS is built from an existing struct breakpoint.  */
3691   gdb_assert (bs->breakpoint_at != NULL);
3692   b = (struct watchpoint *) bs->breakpoint_at;
3693
3694   /* If this is a local watchpoint, we only want to check if the
3695      watchpoint frame is in scope if the current thread is the thread
3696      that was used to create the watchpoint.  */
3697   if (!watchpoint_in_thread_scope (b))
3698     return WP_IGNORE;
3699
3700   if (b->exp_valid_block == NULL)
3701     within_current_scope = 1;
3702   else
3703     {
3704       struct frame_info *frame = get_current_frame ();
3705       struct gdbarch *frame_arch = get_frame_arch (frame);
3706       CORE_ADDR frame_pc = get_frame_pc (frame);
3707
3708       /* in_function_epilogue_p() returns a non-zero value if we're
3709          still in the function but the stack frame has already been
3710          invalidated.  Since we can't rely on the values of local
3711          variables after the stack has been destroyed, we are treating
3712          the watchpoint in that state as `not changed' without further
3713          checking.  Don't mark watchpoints as changed if the current
3714          frame is in an epilogue - even if they are in some other
3715          frame, our view of the stack is likely to be wrong and
3716          frame_find_by_id could error out.  */
3717       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
3718         return WP_IGNORE;
3719
3720       fr = frame_find_by_id (b->watchpoint_frame);
3721       within_current_scope = (fr != NULL);
3722
3723       /* If we've gotten confused in the unwinder, we might have
3724          returned a frame that can't describe this variable.  */
3725       if (within_current_scope)
3726         {
3727           struct symbol *function;
3728
3729           function = get_frame_function (fr);
3730           if (function == NULL
3731               || !contained_in (b->exp_valid_block,
3732                                 SYMBOL_BLOCK_VALUE (function)))
3733             within_current_scope = 0;
3734         }
3735
3736       if (within_current_scope)
3737         /* If we end up stopping, the current frame will get selected
3738            in normal_stop.  So this call to select_frame won't affect
3739            the user.  */
3740         select_frame (fr);
3741     }
3742
3743   if (within_current_scope)
3744     {
3745       /* We use value_{,free_to_}mark because it could be a *long*
3746          time before we return to the command level and call
3747          free_all_values.  We can't call free_all_values because we
3748          might be in the middle of evaluating a function call.  */
3749
3750       int pc = 0;
3751       struct value *mark;
3752       struct value *new_val;
3753
3754       if (is_masked_watchpoint (&b->base))
3755         /* Since we don't know the exact trigger address (from
3756            stopped_data_address), just tell the user we've triggered
3757            a mask watchpoint.  */
3758         return WP_VALUE_CHANGED;
3759
3760       mark = value_mark ();
3761       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
3762
3763       /* We use value_equal_contents instead of value_equal because
3764          the latter coerces an array to a pointer, thus comparing just
3765          the address of the array instead of its contents.  This is
3766          not what we want.  */
3767       if ((b->val != NULL) != (new_val != NULL)
3768           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
3769         {
3770           if (new_val != NULL)
3771             {
3772               release_value (new_val);
3773               value_free_to_mark (mark);
3774             }
3775           bs->old_val = b->val;
3776           b->val = new_val;
3777           b->val_valid = 1;
3778           return WP_VALUE_CHANGED;
3779         }
3780       else
3781         {
3782           /* Nothing changed.  */
3783           value_free_to_mark (mark);
3784           return WP_VALUE_NOT_CHANGED;
3785         }
3786     }
3787   else
3788     {
3789       struct ui_out *uiout = current_uiout;
3790
3791       /* This seems like the only logical thing to do because
3792          if we temporarily ignored the watchpoint, then when
3793          we reenter the block in which it is valid it contains
3794          garbage (in the case of a function, it may have two
3795          garbage values, one before and one after the prologue).
3796          So we can't even detect the first assignment to it and
3797          watch after that (since the garbage may or may not equal
3798          the first value assigned).  */
3799       /* We print all the stop information in
3800          breakpoint_ops->print_it, but in this case, by the time we
3801          call breakpoint_ops->print_it this bp will be deleted
3802          already.  So we have no choice but print the information
3803          here.  */
3804       if (ui_out_is_mi_like_p (uiout))
3805         ui_out_field_string
3806           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
3807       ui_out_text (uiout, "\nWatchpoint ");
3808       ui_out_field_int (uiout, "wpnum", b->base.number);
3809       ui_out_text (uiout,
3810                    " deleted because the program has left the block in\n\
3811 which its expression is valid.\n");     
3812
3813       /* Make sure the watchpoint's commands aren't executed.  */
3814       decref_counted_command_line (&b->base.commands);
3815       watchpoint_del_at_next_stop (b);
3816
3817       return WP_DELETED;
3818     }
3819 }
3820
3821 /* Return true if it looks like target has stopped due to hitting
3822    breakpoint location BL.  This function does not check if we should
3823    stop, only if BL explains the stop.  */
3824
3825 static int
3826 bpstat_check_location (const struct bp_location *bl,
3827                        struct address_space *aspace, CORE_ADDR bp_addr)
3828 {
3829   struct breakpoint *b = bl->owner;
3830
3831   /* BL is from an existing breakpoint.  */
3832   gdb_assert (b != NULL);
3833
3834   return b->ops->breakpoint_hit (bl, aspace, bp_addr);
3835 }
3836
3837 /* Determine if the watched values have actually changed, and we
3838    should stop.  If not, set BS->stop to 0.  */
3839
3840 static void
3841 bpstat_check_watchpoint (bpstat bs)
3842 {
3843   const struct bp_location *bl;
3844   struct watchpoint *b;
3845
3846   /* BS is built for existing struct breakpoint.  */
3847   bl = bs->bp_location_at;
3848   gdb_assert (bl != NULL);
3849   b = (struct watchpoint *) bs->breakpoint_at;
3850   gdb_assert (b != NULL);
3851
3852     {
3853       int must_check_value = 0;
3854       
3855       if (b->base.type == bp_watchpoint)
3856         /* For a software watchpoint, we must always check the
3857            watched value.  */
3858         must_check_value = 1;
3859       else if (b->watchpoint_triggered == watch_triggered_yes)
3860         /* We have a hardware watchpoint (read, write, or access)
3861            and the target earlier reported an address watched by
3862            this watchpoint.  */
3863         must_check_value = 1;
3864       else if (b->watchpoint_triggered == watch_triggered_unknown
3865                && b->base.type == bp_hardware_watchpoint)
3866         /* We were stopped by a hardware watchpoint, but the target could
3867            not report the data address.  We must check the watchpoint's
3868            value.  Access and read watchpoints are out of luck; without
3869            a data address, we can't figure it out.  */
3870         must_check_value = 1;
3871
3872       if (must_check_value)
3873         {
3874           char *message
3875             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
3876                           b->base.number);
3877           struct cleanup *cleanups = make_cleanup (xfree, message);
3878           int e = catch_errors (watchpoint_check, bs, message,
3879                                 RETURN_MASK_ALL);
3880           do_cleanups (cleanups);
3881           switch (e)
3882             {
3883             case WP_DELETED:
3884               /* We've already printed what needs to be printed.  */
3885               bs->print_it = print_it_done;
3886               /* Stop.  */
3887               break;
3888             case WP_IGNORE:
3889               bs->print_it = print_it_noop;
3890               bs->stop = 0;
3891               break;
3892             case WP_VALUE_CHANGED:
3893               if (b->base.type == bp_read_watchpoint)
3894                 {
3895                   /* There are two cases to consider here:
3896
3897                      1. We're watching the triggered memory for reads.
3898                      In that case, trust the target, and always report
3899                      the watchpoint hit to the user.  Even though
3900                      reads don't cause value changes, the value may
3901                      have changed since the last time it was read, and
3902                      since we're not trapping writes, we will not see
3903                      those, and as such we should ignore our notion of
3904                      old value.
3905
3906                      2. We're watching the triggered memory for both
3907                      reads and writes.  There are two ways this may
3908                      happen:
3909
3910                      2.1. This is a target that can't break on data
3911                      reads only, but can break on accesses (reads or
3912                      writes), such as e.g., x86.  We detect this case
3913                      at the time we try to insert read watchpoints.
3914
3915                      2.2. Otherwise, the target supports read
3916                      watchpoints, but, the user set an access or write
3917                      watchpoint watching the same memory as this read
3918                      watchpoint.
3919
3920                      If we're watching memory writes as well as reads,
3921                      ignore watchpoint hits when we find that the
3922                      value hasn't changed, as reads don't cause
3923                      changes.  This still gives false positives when
3924                      the program writes the same value to memory as
3925                      what there was already in memory (we will confuse
3926                      it for a read), but it's much better than
3927                      nothing.  */
3928
3929                   int other_write_watchpoint = 0;
3930
3931                   if (bl->watchpoint_type == hw_read)
3932                     {
3933                       struct breakpoint *other_b;
3934
3935                       ALL_BREAKPOINTS (other_b)
3936                         if (other_b->type == bp_hardware_watchpoint
3937                             || other_b->type == bp_access_watchpoint)
3938                           {
3939                             struct watchpoint *other_w =
3940                               (struct watchpoint *) other_b;
3941
3942                             if (other_w->watchpoint_triggered
3943                                 == watch_triggered_yes)
3944                               {
3945                                 other_write_watchpoint = 1;
3946                                 break;
3947                               }
3948                           }
3949                     }
3950
3951                   if (other_write_watchpoint
3952                       || bl->watchpoint_type == hw_access)
3953                     {
3954                       /* We're watching the same memory for writes,
3955                          and the value changed since the last time we
3956                          updated it, so this trap must be for a write.
3957                          Ignore it.  */
3958                       bs->print_it = print_it_noop;
3959                       bs->stop = 0;
3960                     }
3961                 }
3962               break;
3963             case WP_VALUE_NOT_CHANGED:
3964               if (b->base.type == bp_hardware_watchpoint
3965                   || b->base.type == bp_watchpoint)
3966                 {
3967                   /* Don't stop: write watchpoints shouldn't fire if
3968                      the value hasn't changed.  */
3969                   bs->print_it = print_it_noop;
3970                   bs->stop = 0;
3971                 }
3972               /* Stop.  */
3973               break;
3974             default:
3975               /* Can't happen.  */
3976             case 0:
3977               /* Error from catch_errors.  */
3978               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
3979               watchpoint_del_at_next_stop (b);
3980               /* We've already printed what needs to be printed.  */
3981               bs->print_it = print_it_done;
3982               break;
3983             }
3984         }
3985       else      /* must_check_value == 0 */
3986         {
3987           /* This is a case where some watchpoint(s) triggered, but
3988              not at the address of this watchpoint, or else no
3989              watchpoint triggered after all.  So don't print
3990              anything for this watchpoint.  */
3991           bs->print_it = print_it_noop;
3992           bs->stop = 0;
3993         }
3994     }
3995 }
3996
3997
3998 /* Check conditions (condition proper, frame, thread and ignore count)
3999    of breakpoint referred to by BS.  If we should not stop for this
4000    breakpoint, set BS->stop to 0.  */
4001
4002 static void
4003 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4004 {
4005   int thread_id = pid_to_thread_id (ptid);
4006   const struct bp_location *bl;
4007   struct breakpoint *b;
4008
4009   /* BS is built for existing struct breakpoint.  */
4010   bl = bs->bp_location_at;
4011   gdb_assert (bl != NULL);
4012   b = bs->breakpoint_at;
4013   gdb_assert (b != NULL);
4014
4015   if (frame_id_p (b->frame_id)
4016       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4017     bs->stop = 0;
4018   else if (bs->stop)
4019     {
4020       int value_is_zero = 0;
4021       struct expression *cond;
4022
4023       /* Evaluate Python breakpoints that have a "stop"
4024          method implemented.  */
4025       if (b->py_bp_object)
4026         bs->stop = gdbpy_should_stop (b->py_bp_object);
4027
4028       if (is_watchpoint (b))
4029         {
4030           struct watchpoint *w = (struct watchpoint *) b;
4031
4032           cond = w->cond_exp;
4033         }
4034       else
4035         cond = bl->cond;
4036
4037       if (cond && b->disposition != disp_del_at_next_stop)
4038         {
4039           int within_current_scope = 1;
4040           struct watchpoint * w;
4041
4042           /* We use value_mark and value_free_to_mark because it could
4043              be a long time before we return to the command level and
4044              call free_all_values.  We can't call free_all_values
4045              because we might be in the middle of evaluating a
4046              function call.  */
4047           struct value *mark = value_mark ();
4048
4049           if (is_watchpoint (b))
4050             w = (struct watchpoint *) b;
4051           else
4052             w = NULL;
4053
4054           /* Need to select the frame, with all that implies so that
4055              the conditions will have the right context.  Because we
4056              use the frame, we will not see an inlined function's
4057              variables when we arrive at a breakpoint at the start
4058              of the inlined function; the current frame will be the
4059              call site.  */
4060           if (w == NULL || w->cond_exp_valid_block == NULL)
4061             select_frame (get_current_frame ());
4062           else
4063             {
4064               struct frame_info *frame;
4065
4066               /* For local watchpoint expressions, which particular
4067                  instance of a local is being watched matters, so we
4068                  keep track of the frame to evaluate the expression
4069                  in.  To evaluate the condition however, it doesn't
4070                  really matter which instantiation of the function
4071                  where the condition makes sense triggers the
4072                  watchpoint.  This allows an expression like "watch
4073                  global if q > 10" set in `func', catch writes to
4074                  global on all threads that call `func', or catch
4075                  writes on all recursive calls of `func' by a single
4076                  thread.  We simply always evaluate the condition in
4077                  the innermost frame that's executing where it makes
4078                  sense to evaluate the condition.  It seems
4079                  intuitive.  */
4080               frame = block_innermost_frame (w->cond_exp_valid_block);
4081               if (frame != NULL)
4082                 select_frame (frame);
4083               else
4084                 within_current_scope = 0;
4085             }
4086           if (within_current_scope)
4087             value_is_zero
4088               = catch_errors (breakpoint_cond_eval, cond,
4089                               "Error in testing breakpoint condition:\n",
4090                               RETURN_MASK_ALL);
4091           else
4092             {
4093               warning (_("Watchpoint condition cannot be tested "
4094                          "in the current scope"));
4095               /* If we failed to set the right context for this
4096                  watchpoint, unconditionally report it.  */
4097               value_is_zero = 0;
4098             }
4099           /* FIXME-someday, should give breakpoint #.  */
4100           value_free_to_mark (mark);
4101         }
4102
4103       if (cond && value_is_zero)
4104         {
4105           bs->stop = 0;
4106         }
4107       else if (b->thread != -1 && b->thread != thread_id)
4108         {
4109           bs->stop = 0;
4110         }
4111       else if (b->ignore_count > 0)
4112         {
4113           b->ignore_count--;
4114           annotate_ignore_count_change ();
4115           bs->stop = 0;
4116           /* Increase the hit count even though we don't stop.  */
4117           ++(b->hit_count);
4118           observer_notify_breakpoint_modified (b);
4119         }       
4120     }
4121 }
4122
4123
4124 /* Get a bpstat associated with having just stopped at address
4125    BP_ADDR in thread PTID.
4126
4127    Determine whether we stopped at a breakpoint, etc, or whether we
4128    don't understand this stop.  Result is a chain of bpstat's such
4129    that:
4130
4131    if we don't understand the stop, the result is a null pointer.
4132
4133    if we understand why we stopped, the result is not null.
4134
4135    Each element of the chain refers to a particular breakpoint or
4136    watchpoint at which we have stopped.  (We may have stopped for
4137    several reasons concurrently.)
4138
4139    Each element of the chain has valid next, breakpoint_at,
4140    commands, FIXME??? fields.  */
4141
4142 bpstat
4143 bpstat_stop_status (struct address_space *aspace,
4144                     CORE_ADDR bp_addr, ptid_t ptid)
4145 {
4146   struct breakpoint *b = NULL;
4147   struct bp_location *bl;
4148   struct bp_location *loc;
4149   /* First item of allocated bpstat's.  */
4150   bpstat bs_head = NULL, *bs_link = &bs_head;
4151   /* Pointer to the last thing in the chain currently.  */
4152   bpstat bs;
4153   int ix;
4154   int need_remove_insert;
4155   int removed_any;
4156
4157   /* First, build the bpstat chain with locations that explain a
4158      target stop, while being careful to not set the target running,
4159      as that may invalidate locations (in particular watchpoint
4160      locations are recreated).  Resuming will happen here with
4161      breakpoint conditions or watchpoint expressions that include
4162      inferior function calls.  */
4163
4164   ALL_BREAKPOINTS (b)
4165     {
4166       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4167         continue;
4168
4169       for (bl = b->loc; bl != NULL; bl = bl->next)
4170         {
4171           /* For hardware watchpoints, we look only at the first
4172              location.  The watchpoint_check function will work on the
4173              entire expression, not the individual locations.  For
4174              read watchpoints, the watchpoints_triggered function has
4175              checked all locations already.  */
4176           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4177             break;
4178
4179           if (bl->shlib_disabled)
4180             continue;
4181
4182           if (!bpstat_check_location (bl, aspace, bp_addr))
4183             continue;
4184
4185           /* Come here if it's a watchpoint, or if the break address
4186              matches.  */
4187
4188           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4189                                                    explain stop.  */
4190
4191           /* Assume we stop.  Should we find a watchpoint that is not
4192              actually triggered, or if the condition of the breakpoint
4193              evaluates as false, we'll reset 'stop' to 0.  */
4194           bs->stop = 1;
4195           bs->print = 1;
4196
4197           /* If this is a scope breakpoint, mark the associated
4198              watchpoint as triggered so that we will handle the
4199              out-of-scope event.  We'll get to the watchpoint next
4200              iteration.  */
4201           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4202             {
4203               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4204
4205               w->watchpoint_triggered = watch_triggered_yes;
4206             }
4207         }
4208     }
4209
4210   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4211     {
4212       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4213         {
4214           bs = bpstat_alloc (loc, &bs_link);
4215           /* For hits of moribund locations, we should just proceed.  */
4216           bs->stop = 0;
4217           bs->print = 0;
4218           bs->print_it = print_it_noop;
4219         }
4220     }
4221
4222   /* Now go through the locations that caused the target to stop, and
4223      check whether we're interested in reporting this stop to higher
4224      layers, or whether we should resume the target transparently.  */
4225
4226   removed_any = 0;
4227
4228   for (bs = bs_head; bs != NULL; bs = bs->next)
4229     {
4230       if (!bs->stop)
4231         continue;
4232
4233       b = bs->breakpoint_at;
4234       b->ops->check_status (bs);
4235       if (bs->stop)
4236         {
4237           bpstat_check_breakpoint_conditions (bs, ptid);
4238
4239           if (bs->stop)
4240             {
4241               ++(b->hit_count);
4242               observer_notify_breakpoint_modified (b);
4243
4244               /* We will stop here.  */
4245               if (b->disposition == disp_disable)
4246                 {
4247                   if (b->enable_state != bp_permanent)
4248                     b->enable_state = bp_disabled;
4249                   removed_any = 1;
4250                 }
4251               if (b->silent)
4252                 bs->print = 0;
4253               bs->commands = b->commands;
4254               incref_counted_command_line (bs->commands);
4255               if (command_line_is_silent (bs->commands
4256                                           ? bs->commands->commands : NULL))
4257                 bs->print = 0;
4258             }
4259
4260           /* Print nothing for this entry if we don't stop or don't print.  */
4261           if (bs->stop == 0 || bs->print == 0)
4262             bs->print_it = print_it_noop;
4263         }
4264     }
4265
4266   /* If we aren't stopping, the value of some hardware watchpoint may
4267      not have changed, but the intermediate memory locations we are
4268      watching may have.  Don't bother if we're stopping; this will get
4269      done later.  */
4270   need_remove_insert = 0;
4271   if (! bpstat_causes_stop (bs_head))
4272     for (bs = bs_head; bs != NULL; bs = bs->next)
4273       if (!bs->stop
4274           && bs->breakpoint_at
4275           && is_hardware_watchpoint (bs->breakpoint_at))
4276         {
4277           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4278
4279           update_watchpoint (w, 0 /* don't reparse.  */);
4280           need_remove_insert = 1;
4281         }
4282
4283   if (need_remove_insert)
4284     update_global_location_list (1);
4285   else if (removed_any)
4286     update_global_location_list (0);
4287
4288   return bs_head;
4289 }
4290
4291 static void
4292 handle_jit_event (void)
4293 {
4294   struct frame_info *frame;
4295   struct gdbarch *gdbarch;
4296
4297   /* Switch terminal for any messages produced by
4298      breakpoint_re_set.  */
4299   target_terminal_ours_for_output ();
4300
4301   frame = get_current_frame ();
4302   gdbarch = get_frame_arch (frame);
4303
4304   jit_event_handler (gdbarch);
4305
4306   target_terminal_inferior ();
4307 }
4308
4309 /* Prepare WHAT final decision for infrun.  */
4310
4311 /* Decide what infrun needs to do with this bpstat.  */
4312
4313 struct bpstat_what
4314 bpstat_what (bpstat bs_head)
4315 {
4316   struct bpstat_what retval;
4317   /* We need to defer calling `solib_add', as adding new symbols
4318      resets breakpoints, which in turn deletes breakpoint locations,
4319      and hence may clear unprocessed entries in the BS chain.  */
4320   int shlib_event = 0;
4321   int jit_event = 0;
4322   bpstat bs;
4323
4324   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
4325   retval.call_dummy = STOP_NONE;
4326   retval.is_longjmp = 0;
4327
4328   for (bs = bs_head; bs != NULL; bs = bs->next)
4329     {
4330       /* Extract this BS's action.  After processing each BS, we check
4331          if its action overrides all we've seem so far.  */
4332       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
4333       enum bptype bptype;
4334
4335       if (bs->breakpoint_at == NULL)
4336         {
4337           /* I suspect this can happen if it was a momentary
4338              breakpoint which has since been deleted.  */
4339           bptype = bp_none;
4340         }
4341       else
4342         bptype = bs->breakpoint_at->type;
4343
4344       switch (bptype)
4345         {
4346         case bp_none:
4347           break;
4348         case bp_breakpoint:
4349         case bp_hardware_breakpoint:
4350         case bp_until:
4351         case bp_finish:
4352           if (bs->stop)
4353             {
4354               if (bs->print)
4355                 this_action = BPSTAT_WHAT_STOP_NOISY;
4356               else
4357                 this_action = BPSTAT_WHAT_STOP_SILENT;
4358             }
4359           else
4360             this_action = BPSTAT_WHAT_SINGLE;
4361           break;
4362         case bp_watchpoint:
4363         case bp_hardware_watchpoint:
4364         case bp_read_watchpoint:
4365         case bp_access_watchpoint:
4366           if (bs->stop)
4367             {
4368               if (bs->print)
4369                 this_action = BPSTAT_WHAT_STOP_NOISY;
4370               else
4371                 this_action = BPSTAT_WHAT_STOP_SILENT;
4372             }
4373           else
4374             {
4375               /* There was a watchpoint, but we're not stopping.
4376                  This requires no further action.  */
4377             }
4378           break;
4379         case bp_longjmp:
4380         case bp_exception:
4381           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
4382           retval.is_longjmp = bptype == bp_longjmp;
4383           break;
4384         case bp_longjmp_resume:
4385         case bp_exception_resume:
4386           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
4387           retval.is_longjmp = bptype == bp_longjmp_resume;
4388           break;
4389         case bp_step_resume:
4390           if (bs->stop)
4391             this_action = BPSTAT_WHAT_STEP_RESUME;
4392           else
4393             {
4394               /* It is for the wrong frame.  */
4395               this_action = BPSTAT_WHAT_SINGLE;
4396             }
4397           break;
4398         case bp_hp_step_resume:
4399           if (bs->stop)
4400             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
4401           else
4402             {
4403               /* It is for the wrong frame.  */
4404               this_action = BPSTAT_WHAT_SINGLE;
4405             }
4406           break;
4407         case bp_watchpoint_scope:
4408         case bp_thread_event:
4409         case bp_overlay_event:
4410         case bp_longjmp_master:
4411         case bp_std_terminate_master:
4412         case bp_exception_master:
4413           this_action = BPSTAT_WHAT_SINGLE;
4414           break;
4415         case bp_catchpoint:
4416           if (bs->stop)
4417             {
4418               if (bs->print)
4419                 this_action = BPSTAT_WHAT_STOP_NOISY;
4420               else
4421                 this_action = BPSTAT_WHAT_STOP_SILENT;
4422             }
4423           else
4424             {
4425               /* There was a catchpoint, but we're not stopping.
4426                  This requires no further action.  */
4427             }
4428           break;
4429         case bp_shlib_event:
4430           shlib_event = 1;
4431
4432           /* If requested, stop when the dynamic linker notifies GDB
4433              of events.  This allows the user to get control and place
4434              breakpoints in initializer routines for dynamically
4435              loaded objects (among other things).  */
4436           if (stop_on_solib_events)
4437             this_action = BPSTAT_WHAT_STOP_NOISY;
4438           else
4439             this_action = BPSTAT_WHAT_SINGLE;
4440           break;
4441         case bp_jit_event:
4442           jit_event = 1;
4443           this_action = BPSTAT_WHAT_SINGLE;
4444           break;
4445         case bp_call_dummy:
4446           /* Make sure the action is stop (silent or noisy),
4447              so infrun.c pops the dummy frame.  */
4448           retval.call_dummy = STOP_STACK_DUMMY;
4449           this_action = BPSTAT_WHAT_STOP_SILENT;
4450           break;
4451         case bp_std_terminate:
4452           /* Make sure the action is stop (silent or noisy),
4453              so infrun.c pops the dummy frame.  */
4454           retval.call_dummy = STOP_STD_TERMINATE;
4455           this_action = BPSTAT_WHAT_STOP_SILENT;
4456           break;
4457         case bp_tracepoint:
4458         case bp_fast_tracepoint:
4459         case bp_static_tracepoint:
4460           /* Tracepoint hits should not be reported back to GDB, and
4461              if one got through somehow, it should have been filtered
4462              out already.  */
4463           internal_error (__FILE__, __LINE__,
4464                           _("bpstat_what: tracepoint encountered"));
4465           break;
4466         case bp_gnu_ifunc_resolver:
4467           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
4468           this_action = BPSTAT_WHAT_SINGLE;
4469           break;
4470         case bp_gnu_ifunc_resolver_return:
4471           /* The breakpoint will be removed, execution will restart from the
4472              PC of the former breakpoint.  */
4473           this_action = BPSTAT_WHAT_KEEP_CHECKING;
4474           break;
4475         default:
4476           internal_error (__FILE__, __LINE__,
4477                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
4478         }
4479
4480       retval.main_action = max (retval.main_action, this_action);
4481     }
4482
4483   /* These operations may affect the bs->breakpoint_at state so they are
4484      delayed after MAIN_ACTION is decided above.  */
4485
4486   if (shlib_event)
4487     {
4488       if (debug_infrun)
4489         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_shlib_event\n");
4490
4491       /* Check for any newly added shared libraries if we're supposed
4492          to be adding them automatically.  */
4493
4494       /* Switch terminal for any messages produced by
4495          breakpoint_re_set.  */
4496       target_terminal_ours_for_output ();
4497
4498 #ifdef SOLIB_ADD
4499       SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
4500 #else
4501       solib_add (NULL, 0, &current_target, auto_solib_add);
4502 #endif
4503
4504       target_terminal_inferior ();
4505     }
4506
4507   if (jit_event)
4508     {
4509       if (debug_infrun)
4510         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
4511
4512       handle_jit_event ();
4513     }
4514
4515   for (bs = bs_head; bs != NULL; bs = bs->next)
4516     {
4517       struct breakpoint *b = bs->breakpoint_at;
4518
4519       if (b == NULL)
4520         continue;
4521       switch (b->type)
4522         {
4523         case bp_gnu_ifunc_resolver:
4524           gnu_ifunc_resolver_stop (b);
4525           break;
4526         case bp_gnu_ifunc_resolver_return:
4527           gnu_ifunc_resolver_return_stop (b);
4528           break;
4529         }
4530     }
4531
4532   return retval;
4533 }
4534
4535 /* Nonzero if we should step constantly (e.g. watchpoints on machines
4536    without hardware support).  This isn't related to a specific bpstat,
4537    just to things like whether watchpoints are set.  */
4538
4539 int
4540 bpstat_should_step (void)
4541 {
4542   struct breakpoint *b;
4543
4544   ALL_BREAKPOINTS (b)
4545     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
4546       return 1;
4547   return 0;
4548 }
4549
4550 int
4551 bpstat_causes_stop (bpstat bs)
4552 {
4553   for (; bs != NULL; bs = bs->next)
4554     if (bs->stop)
4555       return 1;
4556
4557   return 0;
4558 }
4559
4560 \f
4561
4562 /* Compute a string of spaces suitable to indent the next line
4563    so it starts at the position corresponding to the table column
4564    named COL_NAME in the currently active table of UIOUT.  */
4565
4566 static char *
4567 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
4568 {
4569   static char wrap_indent[80];
4570   int i, total_width, width, align;
4571   char *text;
4572
4573   total_width = 0;
4574   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
4575     {
4576       if (strcmp (text, col_name) == 0)
4577         {
4578           gdb_assert (total_width < sizeof wrap_indent);
4579           memset (wrap_indent, ' ', total_width);
4580           wrap_indent[total_width] = 0;
4581
4582           return wrap_indent;
4583         }
4584
4585       total_width += width + 1;
4586     }
4587
4588   return NULL;
4589 }
4590
4591 /* Print the LOC location out of the list of B->LOC locations.  */
4592
4593 static void
4594 print_breakpoint_location (struct breakpoint *b,
4595                            struct bp_location *loc)
4596 {
4597   struct ui_out *uiout = current_uiout;
4598   struct cleanup *old_chain = save_current_program_space ();
4599
4600   if (loc != NULL && loc->shlib_disabled)
4601     loc = NULL;
4602
4603   if (loc != NULL)
4604     set_current_program_space (loc->pspace);
4605
4606   if (b->display_canonical)
4607     ui_out_field_string (uiout, "what", b->addr_string);
4608   else if (loc && loc->source_file)
4609     {
4610       struct symbol *sym 
4611         = find_pc_sect_function (loc->address, loc->section);
4612       if (sym)
4613         {
4614           ui_out_text (uiout, "in ");
4615           ui_out_field_string (uiout, "func",
4616                                SYMBOL_PRINT_NAME (sym));
4617           ui_out_text (uiout, " ");
4618           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
4619           ui_out_text (uiout, "at ");
4620         }
4621       ui_out_field_string (uiout, "file", loc->source_file);
4622       ui_out_text (uiout, ":");
4623       
4624       if (ui_out_is_mi_like_p (uiout))
4625         {
4626           struct symtab_and_line sal = find_pc_line (loc->address, 0);
4627           char *fullname = symtab_to_fullname (sal.symtab);
4628           
4629           if (fullname)
4630             ui_out_field_string (uiout, "fullname", fullname);
4631         }
4632       
4633       ui_out_field_int (uiout, "line", loc->line_number);
4634     }
4635   else if (loc)
4636     {
4637       struct ui_stream *stb = ui_out_stream_new (uiout);
4638       struct cleanup *stb_chain = make_cleanup_ui_out_stream_delete (stb);
4639
4640       print_address_symbolic (loc->gdbarch, loc->address, stb->stream,
4641                               demangle, "");
4642       ui_out_field_stream (uiout, "at", stb);
4643
4644       do_cleanups (stb_chain);
4645     }
4646   else
4647     ui_out_field_string (uiout, "pending", b->addr_string);
4648
4649   do_cleanups (old_chain);
4650 }
4651
4652 static const char *
4653 bptype_string (enum bptype type)
4654 {
4655   struct ep_type_description
4656     {
4657       enum bptype type;
4658       char *description;
4659     };
4660   static struct ep_type_description bptypes[] =
4661   {
4662     {bp_none, "?deleted?"},
4663     {bp_breakpoint, "breakpoint"},
4664     {bp_hardware_breakpoint, "hw breakpoint"},
4665     {bp_until, "until"},
4666     {bp_finish, "finish"},
4667     {bp_watchpoint, "watchpoint"},
4668     {bp_hardware_watchpoint, "hw watchpoint"},
4669     {bp_read_watchpoint, "read watchpoint"},
4670     {bp_access_watchpoint, "acc watchpoint"},
4671     {bp_longjmp, "longjmp"},
4672     {bp_longjmp_resume, "longjmp resume"},
4673     {bp_exception, "exception"},
4674     {bp_exception_resume, "exception resume"},
4675     {bp_step_resume, "step resume"},
4676     {bp_hp_step_resume, "high-priority step resume"},
4677     {bp_watchpoint_scope, "watchpoint scope"},
4678     {bp_call_dummy, "call dummy"},
4679     {bp_std_terminate, "std::terminate"},
4680     {bp_shlib_event, "shlib events"},
4681     {bp_thread_event, "thread events"},
4682     {bp_overlay_event, "overlay events"},
4683     {bp_longjmp_master, "longjmp master"},
4684     {bp_std_terminate_master, "std::terminate master"},
4685     {bp_exception_master, "exception master"},
4686     {bp_catchpoint, "catchpoint"},
4687     {bp_tracepoint, "tracepoint"},
4688     {bp_fast_tracepoint, "fast tracepoint"},
4689     {bp_static_tracepoint, "static tracepoint"},
4690     {bp_jit_event, "jit events"},
4691     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
4692     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
4693   };
4694
4695   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
4696       || ((int) type != bptypes[(int) type].type))
4697     internal_error (__FILE__, __LINE__,
4698                     _("bptypes table does not describe type #%d."),
4699                     (int) type);
4700
4701   return bptypes[(int) type].description;
4702 }
4703
4704 /* Print B to gdb_stdout.  */
4705
4706 static void
4707 print_one_breakpoint_location (struct breakpoint *b,
4708                                struct bp_location *loc,
4709                                int loc_number,
4710                                struct bp_location **last_loc,
4711                                int allflag)
4712 {
4713   struct command_line *l;
4714   static char bpenables[] = "nynny";
4715
4716   struct ui_out *uiout = current_uiout;
4717   int header_of_multiple = 0;
4718   int part_of_multiple = (loc != NULL);
4719   struct value_print_options opts;
4720
4721   get_user_print_options (&opts);
4722
4723   gdb_assert (!loc || loc_number != 0);
4724   /* See comment in print_one_breakpoint concerning treatment of
4725      breakpoints with single disabled location.  */
4726   if (loc == NULL 
4727       && (b->loc != NULL 
4728           && (b->loc->next != NULL || !b->loc->enabled)))
4729     header_of_multiple = 1;
4730   if (loc == NULL)
4731     loc = b->loc;
4732
4733   annotate_record ();
4734
4735   /* 1 */
4736   annotate_field (0);
4737   if (part_of_multiple)
4738     {
4739       char *formatted;
4740       formatted = xstrprintf ("%d.%d", b->number, loc_number);
4741       ui_out_field_string (uiout, "number", formatted);
4742       xfree (formatted);
4743     }
4744   else
4745     {
4746       ui_out_field_int (uiout, "number", b->number);
4747     }
4748
4749   /* 2 */
4750   annotate_field (1);
4751   if (part_of_multiple)
4752     ui_out_field_skip (uiout, "type");
4753   else
4754     ui_out_field_string (uiout, "type", bptype_string (b->type));
4755
4756   /* 3 */
4757   annotate_field (2);
4758   if (part_of_multiple)
4759     ui_out_field_skip (uiout, "disp");
4760   else
4761     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
4762
4763
4764   /* 4 */
4765   annotate_field (3);
4766   if (part_of_multiple)
4767     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
4768   else
4769     ui_out_field_fmt (uiout, "enabled", "%c", 
4770                       bpenables[(int) b->enable_state]);
4771   ui_out_spaces (uiout, 2);
4772
4773   
4774   /* 5 and 6 */
4775   if (b->ops != NULL && b->ops->print_one != NULL)
4776     {
4777       /* Although the print_one can possibly print all locations,
4778          calling it here is not likely to get any nice result.  So,
4779          make sure there's just one location.  */
4780       gdb_assert (b->loc == NULL || b->loc->next == NULL);
4781       b->ops->print_one (b, last_loc);
4782     }
4783   else
4784     switch (b->type)
4785       {
4786       case bp_none:
4787         internal_error (__FILE__, __LINE__,
4788                         _("print_one_breakpoint: bp_none encountered\n"));
4789         break;
4790
4791       case bp_watchpoint:
4792       case bp_hardware_watchpoint:
4793       case bp_read_watchpoint:
4794       case bp_access_watchpoint:
4795         {
4796           struct watchpoint *w = (struct watchpoint *) b;
4797
4798           /* Field 4, the address, is omitted (which makes the columns
4799              not line up too nicely with the headers, but the effect
4800              is relatively readable).  */
4801           if (opts.addressprint)
4802             ui_out_field_skip (uiout, "addr");
4803           annotate_field (5);
4804           ui_out_field_string (uiout, "what", w->exp_string);
4805         }
4806         break;
4807
4808       case bp_breakpoint:
4809       case bp_hardware_breakpoint:
4810       case bp_until:
4811       case bp_finish:
4812       case bp_longjmp:
4813       case bp_longjmp_resume:
4814       case bp_exception:
4815       case bp_exception_resume:
4816       case bp_step_resume:
4817       case bp_hp_step_resume:
4818       case bp_watchpoint_scope:
4819       case bp_call_dummy:
4820       case bp_std_terminate:
4821       case bp_shlib_event:
4822       case bp_thread_event:
4823       case bp_overlay_event:
4824       case bp_longjmp_master:
4825       case bp_std_terminate_master:
4826       case bp_exception_master:
4827       case bp_tracepoint:
4828       case bp_fast_tracepoint:
4829       case bp_static_tracepoint:
4830       case bp_jit_event:
4831       case bp_gnu_ifunc_resolver:
4832       case bp_gnu_ifunc_resolver_return:
4833         if (opts.addressprint)
4834           {
4835             annotate_field (4);
4836             if (header_of_multiple)
4837               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
4838             else if (b->loc == NULL || loc->shlib_disabled)
4839               ui_out_field_string (uiout, "addr", "<PENDING>");
4840             else
4841               ui_out_field_core_addr (uiout, "addr",
4842                                       loc->gdbarch, loc->address);
4843           }
4844         annotate_field (5);
4845         if (!header_of_multiple)
4846           print_breakpoint_location (b, loc);
4847         if (b->loc)
4848           *last_loc = b->loc;
4849         break;
4850       }
4851
4852
4853   /* For backward compatibility, don't display inferiors unless there
4854      are several.  */
4855   if (loc != NULL
4856       && !header_of_multiple
4857       && (allflag
4858           || (!gdbarch_has_global_breakpoints (target_gdbarch)
4859               && (number_of_program_spaces () > 1
4860                   || number_of_inferiors () > 1)
4861               /* LOC is for existing B, it cannot be in
4862                  moribund_locations and thus having NULL OWNER.  */
4863               && loc->owner->type != bp_catchpoint)))
4864     {
4865       struct inferior *inf;
4866       int first = 1;
4867
4868       for (inf = inferior_list; inf != NULL; inf = inf->next)
4869         {
4870           if (inf->pspace == loc->pspace)
4871             {
4872               if (first)
4873                 {
4874                   first = 0;
4875                   ui_out_text (uiout, " inf ");
4876                 }
4877               else
4878                 ui_out_text (uiout, ", ");
4879               ui_out_text (uiout, plongest (inf->num));
4880             }
4881         }
4882     }
4883
4884   if (!part_of_multiple)
4885     {
4886       if (b->thread != -1)
4887         {
4888           /* FIXME: This seems to be redundant and lost here; see the
4889              "stop only in" line a little further down.  */
4890           ui_out_text (uiout, " thread ");
4891           ui_out_field_int (uiout, "thread", b->thread);
4892         }
4893       else if (b->task != 0)
4894         {
4895           ui_out_text (uiout, " task ");
4896           ui_out_field_int (uiout, "task", b->task);
4897         }
4898     }
4899
4900   ui_out_text (uiout, "\n");
4901
4902   if (!part_of_multiple)
4903     b->ops->print_one_detail (b, uiout);
4904
4905   if (part_of_multiple && frame_id_p (b->frame_id))
4906     {
4907       annotate_field (6);
4908       ui_out_text (uiout, "\tstop only in stack frame at ");
4909       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
4910          the frame ID.  */
4911       ui_out_field_core_addr (uiout, "frame",
4912                               b->gdbarch, b->frame_id.stack_addr);
4913       ui_out_text (uiout, "\n");
4914     }
4915   
4916   if (!part_of_multiple && b->cond_string)
4917     {
4918       annotate_field (7);
4919       if (is_tracepoint (b))
4920         ui_out_text (uiout, "\ttrace only if ");
4921       else
4922         ui_out_text (uiout, "\tstop only if ");
4923       ui_out_field_string (uiout, "cond", b->cond_string);
4924       ui_out_text (uiout, "\n");
4925     }
4926
4927   if (!part_of_multiple && b->thread != -1)
4928     {
4929       /* FIXME should make an annotation for this.  */
4930       ui_out_text (uiout, "\tstop only in thread ");
4931       ui_out_field_int (uiout, "thread", b->thread);
4932       ui_out_text (uiout, "\n");
4933     }
4934   
4935   if (!part_of_multiple && b->hit_count)
4936     {
4937       /* FIXME should make an annotation for this.  */
4938       if (ep_is_catchpoint (b))
4939         ui_out_text (uiout, "\tcatchpoint");
4940       else if (is_tracepoint (b))
4941         ui_out_text (uiout, "\ttracepoint");
4942       else
4943         ui_out_text (uiout, "\tbreakpoint");
4944       ui_out_text (uiout, " already hit ");
4945       ui_out_field_int (uiout, "times", b->hit_count);
4946       if (b->hit_count == 1)
4947         ui_out_text (uiout, " time\n");
4948       else
4949         ui_out_text (uiout, " times\n");
4950     }
4951   
4952   /* Output the count also if it is zero, but only if this is mi.
4953      FIXME: Should have a better test for this.  */
4954   if (ui_out_is_mi_like_p (uiout))
4955     if (!part_of_multiple && b->hit_count == 0)
4956       ui_out_field_int (uiout, "times", b->hit_count);
4957
4958   if (!part_of_multiple && b->ignore_count)
4959     {
4960       annotate_field (8);
4961       ui_out_text (uiout, "\tignore next ");
4962       ui_out_field_int (uiout, "ignore", b->ignore_count);
4963       ui_out_text (uiout, " hits\n");
4964     }
4965
4966   if (!part_of_multiple && is_tracepoint (b))
4967     {
4968       struct tracepoint *tp = (struct tracepoint *) b;
4969
4970       if (tp->traceframe_usage)
4971         {
4972           ui_out_text (uiout, "\ttrace buffer usage ");
4973           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
4974           ui_out_text (uiout, " bytes\n");
4975         }
4976     }
4977   
4978   l = b->commands ? b->commands->commands : NULL;
4979   if (!part_of_multiple && l)
4980     {
4981       struct cleanup *script_chain;
4982
4983       annotate_field (9);
4984       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
4985       print_command_lines (uiout, l, 4);
4986       do_cleanups (script_chain);
4987     }
4988
4989   if (is_tracepoint (b))
4990     {
4991       struct tracepoint *t = (struct tracepoint *) b;
4992
4993       if (!part_of_multiple && t->pass_count)
4994         {
4995           annotate_field (10);
4996           ui_out_text (uiout, "\tpass count ");
4997           ui_out_field_int (uiout, "pass", t->pass_count);
4998           ui_out_text (uiout, " \n");
4999         }
5000     }
5001
5002   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5003     {
5004       if (is_watchpoint (b))
5005         {
5006           struct watchpoint *w = (struct watchpoint *) b;
5007
5008           ui_out_field_string (uiout, "original-location", w->exp_string);
5009         }
5010       else if (b->addr_string)
5011         ui_out_field_string (uiout, "original-location", b->addr_string);
5012     }
5013 }
5014
5015 static void
5016 print_one_breakpoint (struct breakpoint *b,
5017                       struct bp_location **last_loc, 
5018                       int allflag)
5019 {
5020   struct cleanup *bkpt_chain;
5021   struct ui_out *uiout = current_uiout;
5022
5023   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5024
5025   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5026   do_cleanups (bkpt_chain);
5027
5028   /* If this breakpoint has custom print function,
5029      it's already printed.  Otherwise, print individual
5030      locations, if any.  */
5031   if (b->ops == NULL || b->ops->print_one == NULL)
5032     {
5033       /* If breakpoint has a single location that is disabled, we
5034          print it as if it had several locations, since otherwise it's
5035          hard to represent "breakpoint enabled, location disabled"
5036          situation.
5037
5038          Note that while hardware watchpoints have several locations
5039          internally, that's not a property exposed to user.  */
5040       if (b->loc 
5041           && !is_hardware_watchpoint (b)
5042           && (b->loc->next || !b->loc->enabled))
5043         {
5044           struct bp_location *loc;
5045           int n = 1;
5046
5047           for (loc = b->loc; loc; loc = loc->next, ++n)
5048             {
5049               struct cleanup *inner2 =
5050                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5051               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5052               do_cleanups (inner2);
5053             }
5054         }
5055     }
5056 }
5057
5058 static int
5059 breakpoint_address_bits (struct breakpoint *b)
5060 {
5061   int print_address_bits = 0;
5062   struct bp_location *loc;
5063
5064   for (loc = b->loc; loc; loc = loc->next)
5065     {
5066       int addr_bit;
5067
5068       /* Software watchpoints that aren't watching memory don't have
5069          an address to print.  */
5070       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5071         continue;
5072
5073       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5074       if (addr_bit > print_address_bits)
5075         print_address_bits = addr_bit;
5076     }
5077
5078   return print_address_bits;
5079 }
5080
5081 struct captured_breakpoint_query_args
5082   {
5083     int bnum;
5084   };
5085
5086 static int
5087 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5088 {
5089   struct captured_breakpoint_query_args *args = data;
5090   struct breakpoint *b;
5091   struct bp_location *dummy_loc = NULL;
5092
5093   ALL_BREAKPOINTS (b)
5094     {
5095       if (args->bnum == b->number)
5096         {
5097           print_one_breakpoint (b, &dummy_loc, 0);
5098           return GDB_RC_OK;
5099         }
5100     }
5101   return GDB_RC_NONE;
5102 }
5103
5104 enum gdb_rc
5105 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5106                       char **error_message)
5107 {
5108   struct captured_breakpoint_query_args args;
5109
5110   args.bnum = bnum;
5111   /* For the moment we don't trust print_one_breakpoint() to not throw
5112      an error.  */
5113   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5114                                  error_message, RETURN_MASK_ALL) < 0)
5115     return GDB_RC_FAIL;
5116   else
5117     return GDB_RC_OK;
5118 }
5119
5120 /* Return true if this breakpoint was set by the user, false if it is
5121    internal or momentary.  */
5122
5123 int
5124 user_breakpoint_p (struct breakpoint *b)
5125 {
5126   return b->number > 0;
5127 }
5128
5129 /* Print information on user settable breakpoint (watchpoint, etc)
5130    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5131    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5132    FILTER is non-NULL, call it on each breakpoint and only include the
5133    ones for which it returns non-zero.  Return the total number of
5134    breakpoints listed.  */
5135
5136 static int
5137 breakpoint_1 (char *args, int allflag, 
5138               int (*filter) (const struct breakpoint *))
5139 {
5140   struct breakpoint *b;
5141   struct bp_location *last_loc = NULL;
5142   int nr_printable_breakpoints;
5143   struct cleanup *bkpttbl_chain;
5144   struct value_print_options opts;
5145   int print_address_bits = 0;
5146   int print_type_col_width = 14;
5147   struct ui_out *uiout = current_uiout;
5148
5149   get_user_print_options (&opts);
5150
5151   /* Compute the number of rows in the table, as well as the size
5152      required for address fields.  */
5153   nr_printable_breakpoints = 0;
5154   ALL_BREAKPOINTS (b)
5155     {
5156       /* If we have a filter, only list the breakpoints it accepts.  */
5157       if (filter && !filter (b))
5158         continue;
5159
5160       /* If we have an "args" string, it is a list of breakpoints to 
5161          accept.  Skip the others.  */
5162       if (args != NULL && *args != '\0')
5163         {
5164           if (allflag && parse_and_eval_long (args) != b->number)
5165             continue;
5166           if (!allflag && !number_is_in_list (args, b->number))
5167             continue;
5168         }
5169
5170       if (allflag || user_breakpoint_p (b))
5171         {
5172           int addr_bit, type_len;
5173
5174           addr_bit = breakpoint_address_bits (b);
5175           if (addr_bit > print_address_bits)
5176             print_address_bits = addr_bit;
5177
5178           type_len = strlen (bptype_string (b->type));
5179           if (type_len > print_type_col_width)
5180             print_type_col_width = type_len;
5181
5182           nr_printable_breakpoints++;
5183         }
5184     }
5185
5186   if (opts.addressprint)
5187     bkpttbl_chain 
5188       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5189                                              nr_printable_breakpoints,
5190                                              "BreakpointTable");
5191   else
5192     bkpttbl_chain 
5193       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5194                                              nr_printable_breakpoints,
5195                                              "BreakpointTable");
5196
5197   if (nr_printable_breakpoints > 0)
5198     annotate_breakpoints_headers ();
5199   if (nr_printable_breakpoints > 0)
5200     annotate_field (0);
5201   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5202   if (nr_printable_breakpoints > 0)
5203     annotate_field (1);
5204   ui_out_table_header (uiout, print_type_col_width, ui_left,
5205                        "type", "Type");                         /* 2 */
5206   if (nr_printable_breakpoints > 0)
5207     annotate_field (2);
5208   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
5209   if (nr_printable_breakpoints > 0)
5210     annotate_field (3);
5211   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
5212   if (opts.addressprint)
5213     {
5214       if (nr_printable_breakpoints > 0)
5215         annotate_field (4);
5216       if (print_address_bits <= 32)
5217         ui_out_table_header (uiout, 10, ui_left, 
5218                              "addr", "Address");                /* 5 */
5219       else
5220         ui_out_table_header (uiout, 18, ui_left, 
5221                              "addr", "Address");                /* 5 */
5222     }
5223   if (nr_printable_breakpoints > 0)
5224     annotate_field (5);
5225   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
5226   ui_out_table_body (uiout);
5227   if (nr_printable_breakpoints > 0)
5228     annotate_breakpoints_table ();
5229
5230   ALL_BREAKPOINTS (b)
5231     {
5232       QUIT;
5233       /* If we have a filter, only list the breakpoints it accepts.  */
5234       if (filter && !filter (b))
5235         continue;
5236
5237       /* If we have an "args" string, it is a list of breakpoints to 
5238          accept.  Skip the others.  */
5239
5240       if (args != NULL && *args != '\0')
5241         {
5242           if (allflag)  /* maintenance info breakpoint */
5243             {
5244               if (parse_and_eval_long (args) != b->number)
5245                 continue;
5246             }
5247           else          /* all others */
5248             {
5249               if (!number_is_in_list (args, b->number))
5250                 continue;
5251             }
5252         }
5253       /* We only print out user settable breakpoints unless the
5254          allflag is set.  */
5255       if (allflag || user_breakpoint_p (b))
5256         print_one_breakpoint (b, &last_loc, allflag);
5257     }
5258
5259   do_cleanups (bkpttbl_chain);
5260
5261   if (nr_printable_breakpoints == 0)
5262     {
5263       /* If there's a filter, let the caller decide how to report
5264          empty list.  */
5265       if (!filter)
5266         {
5267           if (args == NULL || *args == '\0')
5268             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
5269           else
5270             ui_out_message (uiout, 0, 
5271                             "No breakpoint or watchpoint matching '%s'.\n",
5272                             args);
5273         }
5274     }
5275   else
5276     {
5277       if (last_loc && !server_command)
5278         set_next_address (last_loc->gdbarch, last_loc->address);
5279     }
5280
5281   /* FIXME?  Should this be moved up so that it is only called when
5282      there have been breakpoints? */
5283   annotate_breakpoints_table_end ();
5284
5285   return nr_printable_breakpoints;
5286 }
5287
5288 /* Display the value of default-collect in a way that is generally
5289    compatible with the breakpoint list.  */
5290
5291 static void
5292 default_collect_info (void)
5293 {
5294   struct ui_out *uiout = current_uiout;
5295
5296   /* If it has no value (which is frequently the case), say nothing; a
5297      message like "No default-collect." gets in user's face when it's
5298      not wanted.  */
5299   if (!*default_collect)
5300     return;
5301
5302   /* The following phrase lines up nicely with per-tracepoint collect
5303      actions.  */
5304   ui_out_text (uiout, "default collect ");
5305   ui_out_field_string (uiout, "default-collect", default_collect);
5306   ui_out_text (uiout, " \n");
5307 }
5308   
5309 static void
5310 breakpoints_info (char *args, int from_tty)
5311 {
5312   breakpoint_1 (args, 0, NULL);
5313
5314   default_collect_info ();
5315 }
5316
5317 static void
5318 watchpoints_info (char *args, int from_tty)
5319 {
5320   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
5321   struct ui_out *uiout = current_uiout;
5322
5323   if (num_printed == 0)
5324     {
5325       if (args == NULL || *args == '\0')
5326         ui_out_message (uiout, 0, "No watchpoints.\n");
5327       else
5328         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
5329     }
5330 }
5331
5332 static void
5333 maintenance_info_breakpoints (char *args, int from_tty)
5334 {
5335   breakpoint_1 (args, 1, NULL);
5336
5337   default_collect_info ();
5338 }
5339
5340 static int
5341 breakpoint_has_pc (struct breakpoint *b,
5342                    struct program_space *pspace,
5343                    CORE_ADDR pc, struct obj_section *section)
5344 {
5345   struct bp_location *bl = b->loc;
5346
5347   for (; bl; bl = bl->next)
5348     {
5349       if (bl->pspace == pspace
5350           && bl->address == pc
5351           && (!overlay_debugging || bl->section == section))
5352         return 1;         
5353     }
5354   return 0;
5355 }
5356
5357 /* Print a message describing any user-breakpoints set at PC.  This
5358    concerns with logical breakpoints, so we match program spaces, not
5359    address spaces.  */
5360
5361 static void
5362 describe_other_breakpoints (struct gdbarch *gdbarch,
5363                             struct program_space *pspace, CORE_ADDR pc,
5364                             struct obj_section *section, int thread)
5365 {
5366   int others = 0;
5367   struct breakpoint *b;
5368
5369   ALL_BREAKPOINTS (b)
5370     others += (user_breakpoint_p (b)
5371                && breakpoint_has_pc (b, pspace, pc, section));
5372   if (others > 0)
5373     {
5374       if (others == 1)
5375         printf_filtered (_("Note: breakpoint "));
5376       else /* if (others == ???) */
5377         printf_filtered (_("Note: breakpoints "));
5378       ALL_BREAKPOINTS (b)
5379         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
5380           {
5381             others--;
5382             printf_filtered ("%d", b->number);
5383             if (b->thread == -1 && thread != -1)
5384               printf_filtered (" (all threads)");
5385             else if (b->thread != -1)
5386               printf_filtered (" (thread %d)", b->thread);
5387             printf_filtered ("%s%s ",
5388                              ((b->enable_state == bp_disabled
5389                                || b->enable_state == bp_call_disabled)
5390                               ? " (disabled)"
5391                               : b->enable_state == bp_permanent 
5392                               ? " (permanent)"
5393                               : ""),
5394                              (others > 1) ? "," 
5395                              : ((others == 1) ? " and" : ""));
5396           }
5397       printf_filtered (_("also set at pc "));
5398       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
5399       printf_filtered (".\n");
5400     }
5401 }
5402 \f
5403
5404 /* Return true iff it is meaningful to use the address member of
5405    BPT.  For some breakpoint types, the address member is irrelevant
5406    and it makes no sense to attempt to compare it to other addresses
5407    (or use it for any other purpose either).
5408
5409    More specifically, each of the following breakpoint types will
5410    always have a zero valued address and we don't want to mark
5411    breakpoints of any of these types to be a duplicate of an actual
5412    breakpoint at address zero:
5413
5414       bp_watchpoint
5415       bp_catchpoint
5416
5417 */
5418
5419 static int
5420 breakpoint_address_is_meaningful (struct breakpoint *bpt)
5421 {
5422   enum bptype type = bpt->type;
5423
5424   return (type != bp_watchpoint && type != bp_catchpoint);
5425 }
5426
5427 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
5428    true if LOC1 and LOC2 represent the same watchpoint location.  */
5429
5430 static int
5431 watchpoint_locations_match (struct bp_location *loc1, 
5432                             struct bp_location *loc2)
5433 {
5434   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
5435   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
5436
5437   /* Both of them must exist.  */
5438   gdb_assert (w1 != NULL);
5439   gdb_assert (w2 != NULL);
5440
5441   /* If the target can evaluate the condition expression in hardware,
5442      then we we need to insert both watchpoints even if they are at
5443      the same place.  Otherwise the watchpoint will only trigger when
5444      the condition of whichever watchpoint was inserted evaluates to
5445      true, not giving a chance for GDB to check the condition of the
5446      other watchpoint.  */
5447   if ((w1->cond_exp
5448        && target_can_accel_watchpoint_condition (loc1->address, 
5449                                                  loc1->length,
5450                                                  loc1->watchpoint_type,
5451                                                  w1->cond_exp))
5452       || (w2->cond_exp
5453           && target_can_accel_watchpoint_condition (loc2->address, 
5454                                                     loc2->length,
5455                                                     loc2->watchpoint_type,
5456                                                     w2->cond_exp)))
5457     return 0;
5458
5459   /* Note that this checks the owner's type, not the location's.  In
5460      case the target does not support read watchpoints, but does
5461      support access watchpoints, we'll have bp_read_watchpoint
5462      watchpoints with hw_access locations.  Those should be considered
5463      duplicates of hw_read locations.  The hw_read locations will
5464      become hw_access locations later.  */
5465   return (loc1->owner->type == loc2->owner->type
5466           && loc1->pspace->aspace == loc2->pspace->aspace
5467           && loc1->address == loc2->address
5468           && loc1->length == loc2->length);
5469 }
5470
5471 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
5472    same breakpoint location.  In most targets, this can only be true
5473    if ASPACE1 matches ASPACE2.  On targets that have global
5474    breakpoints, the address space doesn't really matter.  */
5475
5476 static int
5477 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
5478                           struct address_space *aspace2, CORE_ADDR addr2)
5479 {
5480   return ((gdbarch_has_global_breakpoints (target_gdbarch)
5481            || aspace1 == aspace2)
5482           && addr1 == addr2);
5483 }
5484
5485 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
5486    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
5487    matches ASPACE2.  On targets that have global breakpoints, the address
5488    space doesn't really matter.  */
5489
5490 static int
5491 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
5492                                 int len1, struct address_space *aspace2,
5493                                 CORE_ADDR addr2)
5494 {
5495   return ((gdbarch_has_global_breakpoints (target_gdbarch)
5496            || aspace1 == aspace2)
5497           && addr2 >= addr1 && addr2 < addr1 + len1);
5498 }
5499
5500 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
5501    a ranged breakpoint.  In most targets, a match happens only if ASPACE
5502    matches the breakpoint's address space.  On targets that have global
5503    breakpoints, the address space doesn't really matter.  */
5504
5505 static int
5506 breakpoint_location_address_match (struct bp_location *bl,
5507                                    struct address_space *aspace,
5508                                    CORE_ADDR addr)
5509 {
5510   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
5511                                     aspace, addr)
5512           || (bl->length
5513               && breakpoint_address_match_range (bl->pspace->aspace,
5514                                                  bl->address, bl->length,
5515                                                  aspace, addr)));
5516 }
5517
5518 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
5519    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
5520    true, otherwise returns false.  */
5521
5522 static int
5523 tracepoint_locations_match (struct bp_location *loc1,
5524                             struct bp_location *loc2)
5525 {
5526   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
5527     /* Since tracepoint locations are never duplicated with others', tracepoint
5528        locations at the same address of different tracepoints are regarded as
5529        different locations.  */
5530     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
5531   else
5532     return 0;
5533 }
5534
5535 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
5536    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
5537    represent the same location.  */
5538
5539 static int
5540 breakpoint_locations_match (struct bp_location *loc1, 
5541                             struct bp_location *loc2)
5542 {
5543   int hw_point1, hw_point2;
5544
5545   /* Both of them must not be in moribund_locations.  */
5546   gdb_assert (loc1->owner != NULL);
5547   gdb_assert (loc2->owner != NULL);
5548
5549   hw_point1 = is_hardware_watchpoint (loc1->owner);
5550   hw_point2 = is_hardware_watchpoint (loc2->owner);
5551
5552   if (hw_point1 != hw_point2)
5553     return 0;
5554   else if (hw_point1)
5555     return watchpoint_locations_match (loc1, loc2);
5556   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
5557     return tracepoint_locations_match (loc1, loc2);
5558   else
5559     /* We compare bp_location.length in order to cover ranged breakpoints.  */
5560     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
5561                                      loc2->pspace->aspace, loc2->address)
5562             && loc1->length == loc2->length);
5563 }
5564
5565 static void
5566 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
5567                                int bnum, int have_bnum)
5568 {
5569   /* The longest string possibly returned by hex_string_custom
5570      is 50 chars.  These must be at least that big for safety.  */
5571   char astr1[64];
5572   char astr2[64];
5573
5574   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
5575   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
5576   if (have_bnum)
5577     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
5578              bnum, astr1, astr2);
5579   else
5580     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
5581 }
5582
5583 /* Adjust a breakpoint's address to account for architectural
5584    constraints on breakpoint placement.  Return the adjusted address.
5585    Note: Very few targets require this kind of adjustment.  For most
5586    targets, this function is simply the identity function.  */
5587
5588 static CORE_ADDR
5589 adjust_breakpoint_address (struct gdbarch *gdbarch,
5590                            CORE_ADDR bpaddr, enum bptype bptype)
5591 {
5592   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
5593     {
5594       /* Very few targets need any kind of breakpoint adjustment.  */
5595       return bpaddr;
5596     }
5597   else if (bptype == bp_watchpoint
5598            || bptype == bp_hardware_watchpoint
5599            || bptype == bp_read_watchpoint
5600            || bptype == bp_access_watchpoint
5601            || bptype == bp_catchpoint)
5602     {
5603       /* Watchpoints and the various bp_catch_* eventpoints should not
5604          have their addresses modified.  */
5605       return bpaddr;
5606     }
5607   else
5608     {
5609       CORE_ADDR adjusted_bpaddr;
5610
5611       /* Some targets have architectural constraints on the placement
5612          of breakpoint instructions.  Obtain the adjusted address.  */
5613       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
5614
5615       /* An adjusted breakpoint address can significantly alter
5616          a user's expectations.  Print a warning if an adjustment
5617          is required.  */
5618       if (adjusted_bpaddr != bpaddr)
5619         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
5620
5621       return adjusted_bpaddr;
5622     }
5623 }
5624
5625 void
5626 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
5627                   struct breakpoint *owner)
5628 {
5629   memset (loc, 0, sizeof (*loc));
5630
5631   gdb_assert (ops != NULL);
5632
5633   loc->ops = ops;
5634   loc->owner = owner;
5635   loc->cond = NULL;
5636   loc->shlib_disabled = 0;
5637   loc->enabled = 1;
5638
5639   switch (owner->type)
5640     {
5641     case bp_breakpoint:
5642     case bp_until:
5643     case bp_finish:
5644     case bp_longjmp:
5645     case bp_longjmp_resume:
5646     case bp_exception:
5647     case bp_exception_resume:
5648     case bp_step_resume:
5649     case bp_hp_step_resume:
5650     case bp_watchpoint_scope:
5651     case bp_call_dummy:
5652     case bp_std_terminate:
5653     case bp_shlib_event:
5654     case bp_thread_event:
5655     case bp_overlay_event:
5656     case bp_jit_event:
5657     case bp_longjmp_master:
5658     case bp_std_terminate_master:
5659     case bp_exception_master:
5660     case bp_gnu_ifunc_resolver:
5661     case bp_gnu_ifunc_resolver_return:
5662       loc->loc_type = bp_loc_software_breakpoint;
5663       break;
5664     case bp_hardware_breakpoint:
5665       loc->loc_type = bp_loc_hardware_breakpoint;
5666       break;
5667     case bp_hardware_watchpoint:
5668     case bp_read_watchpoint:
5669     case bp_access_watchpoint:
5670       loc->loc_type = bp_loc_hardware_watchpoint;
5671       break;
5672     case bp_watchpoint:
5673     case bp_catchpoint:
5674     case bp_tracepoint:
5675     case bp_fast_tracepoint:
5676     case bp_static_tracepoint:
5677       loc->loc_type = bp_loc_other;
5678       break;
5679     default:
5680       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
5681     }
5682
5683   loc->refc = 1;
5684 }
5685
5686 /* Allocate a struct bp_location.  */
5687
5688 static struct bp_location *
5689 allocate_bp_location (struct breakpoint *bpt)
5690 {
5691   return bpt->ops->allocate_location (bpt);
5692 }
5693
5694 static void
5695 free_bp_location (struct bp_location *loc)
5696 {
5697   loc->ops->dtor (loc);
5698   xfree (loc);
5699 }
5700
5701 /* Increment reference count.  */
5702
5703 static void
5704 incref_bp_location (struct bp_location *bl)
5705 {
5706   ++bl->refc;
5707 }
5708
5709 /* Decrement reference count.  If the reference count reaches 0,
5710    destroy the bp_location.  Sets *BLP to NULL.  */
5711
5712 static void
5713 decref_bp_location (struct bp_location **blp)
5714 {
5715   gdb_assert ((*blp)->refc > 0);
5716
5717   if (--(*blp)->refc == 0)
5718     free_bp_location (*blp);
5719   *blp = NULL;
5720 }
5721
5722 /* Add breakpoint B at the end of the global breakpoint chain.  */
5723
5724 static void
5725 add_to_breakpoint_chain (struct breakpoint *b)
5726 {
5727   struct breakpoint *b1;
5728
5729   /* Add this breakpoint to the end of the chain so that a list of
5730      breakpoints will come out in order of increasing numbers.  */
5731
5732   b1 = breakpoint_chain;
5733   if (b1 == 0)
5734     breakpoint_chain = b;
5735   else
5736     {
5737       while (b1->next)
5738         b1 = b1->next;
5739       b1->next = b;
5740     }
5741 }
5742
5743 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
5744
5745 static void
5746 init_raw_breakpoint_without_location (struct breakpoint *b,
5747                                       struct gdbarch *gdbarch,
5748                                       enum bptype bptype,
5749                                       const struct breakpoint_ops *ops)
5750 {
5751   memset (b, 0, sizeof (*b));
5752
5753   gdb_assert (ops != NULL);
5754
5755   b->ops = ops;
5756   b->type = bptype;
5757   b->gdbarch = gdbarch;
5758   b->language = current_language->la_language;
5759   b->input_radix = input_radix;
5760   b->thread = -1;
5761   b->enable_state = bp_enabled;
5762   b->next = 0;
5763   b->silent = 0;
5764   b->ignore_count = 0;
5765   b->commands = NULL;
5766   b->frame_id = null_frame_id;
5767   b->condition_not_parsed = 0;
5768   b->py_bp_object = NULL;
5769   b->related_breakpoint = b;
5770 }
5771
5772 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
5773    that has type BPTYPE and has no locations as yet.  */
5774
5775 static struct breakpoint *
5776 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
5777                                      enum bptype bptype,
5778                                      const struct breakpoint_ops *ops)
5779 {
5780   struct breakpoint *b = XNEW (struct breakpoint);
5781
5782   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
5783   add_to_breakpoint_chain (b);
5784   return b;
5785 }
5786
5787 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
5788    resolutions should be made as the user specified the location explicitly
5789    enough.  */
5790
5791 static void
5792 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
5793 {
5794   gdb_assert (loc->owner != NULL);
5795
5796   if (loc->owner->type == bp_breakpoint
5797       || loc->owner->type == bp_hardware_breakpoint
5798       || is_tracepoint (loc->owner))
5799     {
5800       int is_gnu_ifunc;
5801
5802       find_pc_partial_function_gnu_ifunc (loc->address, &loc->function_name,
5803                                           NULL, NULL, &is_gnu_ifunc);
5804
5805       if (is_gnu_ifunc && !explicit_loc)
5806         {
5807           struct breakpoint *b = loc->owner;
5808
5809           gdb_assert (loc->pspace == current_program_space);
5810           if (gnu_ifunc_resolve_name (loc->function_name,
5811                                       &loc->requested_address))
5812             {
5813               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
5814               loc->address = adjust_breakpoint_address (loc->gdbarch,
5815                                                         loc->requested_address,
5816                                                         b->type);
5817             }
5818           else if (b->type == bp_breakpoint && b->loc == loc
5819                    && loc->next == NULL && b->related_breakpoint == b)
5820             {
5821               /* Create only the whole new breakpoint of this type but do not
5822                  mess more complicated breakpoints with multiple locations.  */
5823               b->type = bp_gnu_ifunc_resolver;
5824             }
5825         }
5826
5827       if (loc->function_name)
5828         loc->function_name = xstrdup (loc->function_name);
5829     }
5830 }
5831
5832 /* Attempt to determine architecture of location identified by SAL.  */
5833 struct gdbarch *
5834 get_sal_arch (struct symtab_and_line sal)
5835 {
5836   if (sal.section)
5837     return get_objfile_arch (sal.section->objfile);
5838   if (sal.symtab)
5839     return get_objfile_arch (sal.symtab->objfile);
5840
5841   return NULL;
5842 }
5843
5844 /* Low level routine for partially initializing a breakpoint of type
5845    BPTYPE.  The newly created breakpoint's address, section, source
5846    file name, and line number are provided by SAL.
5847
5848    It is expected that the caller will complete the initialization of
5849    the newly created breakpoint struct as well as output any status
5850    information regarding the creation of a new breakpoint.  */
5851
5852 static void
5853 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
5854                      struct symtab_and_line sal, enum bptype bptype,
5855                      const struct breakpoint_ops *ops)
5856 {
5857   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
5858
5859   add_location_to_breakpoint (b, &sal);
5860
5861   if (bptype != bp_catchpoint)
5862     gdb_assert (sal.pspace != NULL);
5863
5864   /* Store the program space that was used to set the breakpoint,
5865      except for ordinary breakpoints, which are independent of the
5866      program space.  */
5867   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
5868     b->pspace = sal.pspace;
5869
5870   breakpoints_changed ();
5871 }
5872
5873 /* set_raw_breakpoint is a low level routine for allocating and
5874    partially initializing a breakpoint of type BPTYPE.  The newly
5875    created breakpoint's address, section, source file name, and line
5876    number are provided by SAL.  The newly created and partially
5877    initialized breakpoint is added to the breakpoint chain and
5878    is also returned as the value of this function.
5879
5880    It is expected that the caller will complete the initialization of
5881    the newly created breakpoint struct as well as output any status
5882    information regarding the creation of a new breakpoint.  In
5883    particular, set_raw_breakpoint does NOT set the breakpoint
5884    number!  Care should be taken to not allow an error to occur
5885    prior to completing the initialization of the breakpoint.  If this
5886    should happen, a bogus breakpoint will be left on the chain.  */
5887
5888 struct breakpoint *
5889 set_raw_breakpoint (struct gdbarch *gdbarch,
5890                     struct symtab_and_line sal, enum bptype bptype,
5891                     const struct breakpoint_ops *ops)
5892 {
5893   struct breakpoint *b = XNEW (struct breakpoint);
5894
5895   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
5896   add_to_breakpoint_chain (b);
5897   return b;
5898 }
5899
5900
5901 /* Note that the breakpoint object B describes a permanent breakpoint
5902    instruction, hard-wired into the inferior's code.  */
5903 void
5904 make_breakpoint_permanent (struct breakpoint *b)
5905 {
5906   struct bp_location *bl;
5907
5908   b->enable_state = bp_permanent;
5909
5910   /* By definition, permanent breakpoints are already present in the
5911      code.  Mark all locations as inserted.  For now,
5912      make_breakpoint_permanent is called in just one place, so it's
5913      hard to say if it's reasonable to have permanent breakpoint with
5914      multiple locations or not, but it's easy to implement.  */
5915   for (bl = b->loc; bl; bl = bl->next)
5916     bl->inserted = 1;
5917 }
5918
5919 /* Call this routine when stepping and nexting to enable a breakpoint
5920    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
5921    initiated the operation.  */
5922
5923 void
5924 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
5925 {
5926   struct breakpoint *b, *b_tmp;
5927   int thread = tp->num;
5928
5929   /* To avoid having to rescan all objfile symbols at every step,
5930      we maintain a list of continually-inserted but always disabled
5931      longjmp "master" breakpoints.  Here, we simply create momentary
5932      clones of those and enable them for the requested thread.  */
5933   ALL_BREAKPOINTS_SAFE (b, b_tmp)
5934     if (b->pspace == current_program_space
5935         && (b->type == bp_longjmp_master
5936             || b->type == bp_exception_master))
5937       {
5938         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
5939         struct breakpoint *clone;
5940
5941         clone = momentary_breakpoint_from_master (b, type,
5942                                                   &momentary_breakpoint_ops);
5943         clone->thread = thread;
5944       }
5945
5946   tp->initiating_frame = frame;
5947 }
5948
5949 /* Delete all longjmp breakpoints from THREAD.  */
5950 void
5951 delete_longjmp_breakpoint (int thread)
5952 {
5953   struct breakpoint *b, *b_tmp;
5954
5955   ALL_BREAKPOINTS_SAFE (b, b_tmp)
5956     if (b->type == bp_longjmp || b->type == bp_exception)
5957       {
5958         if (b->thread == thread)
5959           delete_breakpoint (b);
5960       }
5961 }
5962
5963 void
5964 enable_overlay_breakpoints (void)
5965 {
5966   struct breakpoint *b;
5967
5968   ALL_BREAKPOINTS (b)
5969     if (b->type == bp_overlay_event)
5970     {
5971       b->enable_state = bp_enabled;
5972       update_global_location_list (1);
5973       overlay_events_enabled = 1;
5974     }
5975 }
5976
5977 void
5978 disable_overlay_breakpoints (void)
5979 {
5980   struct breakpoint *b;
5981
5982   ALL_BREAKPOINTS (b)
5983     if (b->type == bp_overlay_event)
5984     {
5985       b->enable_state = bp_disabled;
5986       update_global_location_list (0);
5987       overlay_events_enabled = 0;
5988     }
5989 }
5990
5991 /* Set an active std::terminate breakpoint for each std::terminate
5992    master breakpoint.  */
5993 void
5994 set_std_terminate_breakpoint (void)
5995 {
5996   struct breakpoint *b, *b_tmp;
5997
5998   ALL_BREAKPOINTS_SAFE (b, b_tmp)
5999     if (b->pspace == current_program_space
6000         && b->type == bp_std_terminate_master)
6001       {
6002         momentary_breakpoint_from_master (b, bp_std_terminate,
6003                                           &momentary_breakpoint_ops);
6004       }
6005 }
6006
6007 /* Delete all the std::terminate breakpoints.  */
6008 void
6009 delete_std_terminate_breakpoint (void)
6010 {
6011   struct breakpoint *b, *b_tmp;
6012
6013   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6014     if (b->type == bp_std_terminate)
6015       delete_breakpoint (b);
6016 }
6017
6018 struct breakpoint *
6019 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6020 {
6021   struct breakpoint *b;
6022
6023   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6024                                   &internal_breakpoint_ops);
6025
6026   b->enable_state = bp_enabled;
6027   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6028   b->addr_string
6029     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6030
6031   update_global_location_list_nothrow (1);
6032
6033   return b;
6034 }
6035
6036 void
6037 remove_thread_event_breakpoints (void)
6038 {
6039   struct breakpoint *b, *b_tmp;
6040
6041   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6042     if (b->type == bp_thread_event
6043         && b->loc->pspace == current_program_space)
6044       delete_breakpoint (b);
6045 }
6046
6047 struct lang_and_radix
6048   {
6049     enum language lang;
6050     int radix;
6051   };
6052
6053 /* Create a breakpoint for JIT code registration and unregistration.  */
6054
6055 struct breakpoint *
6056 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6057 {
6058   struct breakpoint *b;
6059
6060   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6061                                   &internal_breakpoint_ops);
6062   update_global_location_list_nothrow (1);
6063   return b;
6064 }
6065
6066 /* Remove JIT code registration and unregistration breakpoint(s).  */
6067
6068 void
6069 remove_jit_event_breakpoints (void)
6070 {
6071   struct breakpoint *b, *b_tmp;
6072
6073   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6074     if (b->type == bp_jit_event
6075         && b->loc->pspace == current_program_space)
6076       delete_breakpoint (b);
6077 }
6078
6079 void
6080 remove_solib_event_breakpoints (void)
6081 {
6082   struct breakpoint *b, *b_tmp;
6083
6084   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6085     if (b->type == bp_shlib_event
6086         && b->loc->pspace == current_program_space)
6087       delete_breakpoint (b);
6088 }
6089
6090 struct breakpoint *
6091 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6092 {
6093   struct breakpoint *b;
6094
6095   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6096                                   &internal_breakpoint_ops);
6097   update_global_location_list_nothrow (1);
6098   return b;
6099 }
6100
6101 /* Disable any breakpoints that are on code in shared libraries.  Only
6102    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6103
6104 void
6105 disable_breakpoints_in_shlibs (void)
6106 {
6107   struct bp_location *loc, **locp_tmp;
6108
6109   ALL_BP_LOCATIONS (loc, locp_tmp)
6110   {
6111     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6112     struct breakpoint *b = loc->owner;
6113
6114     /* We apply the check to all breakpoints, including disabled for
6115        those with loc->duplicate set.  This is so that when breakpoint
6116        becomes enabled, or the duplicate is removed, gdb will try to
6117        insert all breakpoints.  If we don't set shlib_disabled here,
6118        we'll try to insert those breakpoints and fail.  */
6119     if (((b->type == bp_breakpoint)
6120          || (b->type == bp_jit_event)
6121          || (b->type == bp_hardware_breakpoint)
6122          || (is_tracepoint (b)))
6123         && loc->pspace == current_program_space
6124         && !loc->shlib_disabled
6125 #ifdef PC_SOLIB
6126         && PC_SOLIB (loc->address)
6127 #else
6128         && solib_name_from_address (loc->pspace, loc->address)
6129 #endif
6130         )
6131       {
6132         loc->shlib_disabled = 1;
6133       }
6134   }
6135 }
6136
6137 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6138    library.  Only apply to enabled breakpoints, disabled ones can just stay
6139    disabled.  */
6140
6141 static void
6142 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6143 {
6144   struct bp_location *loc, **locp_tmp;
6145   int disabled_shlib_breaks = 0;
6146
6147   /* SunOS a.out shared libraries are always mapped, so do not
6148      disable breakpoints; they will only be reported as unloaded
6149      through clear_solib when GDB discards its shared library
6150      list.  See clear_solib for more information.  */
6151   if (exec_bfd != NULL
6152       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6153     return;
6154
6155   ALL_BP_LOCATIONS (loc, locp_tmp)
6156   {
6157     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6158     struct breakpoint *b = loc->owner;
6159
6160     if (solib->pspace == loc->pspace
6161         && !loc->shlib_disabled
6162         && (((b->type == bp_breakpoint
6163               || b->type == bp_jit_event
6164               || b->type == bp_hardware_breakpoint)
6165              && (loc->loc_type == bp_loc_hardware_breakpoint
6166                  || loc->loc_type == bp_loc_software_breakpoint))
6167             || is_tracepoint (b))
6168         && solib_contains_address_p (solib, loc->address))
6169       {
6170         loc->shlib_disabled = 1;
6171         /* At this point, we cannot rely on remove_breakpoint
6172            succeeding so we must mark the breakpoint as not inserted
6173            to prevent future errors occurring in remove_breakpoints.  */
6174         loc->inserted = 0;
6175
6176         /* This may cause duplicate notifications for the same breakpoint.  */
6177         observer_notify_breakpoint_modified (b);
6178
6179         if (!disabled_shlib_breaks)
6180           {
6181             target_terminal_ours_for_output ();
6182             warning (_("Temporarily disabling breakpoints "
6183                        "for unloaded shared library \"%s\""),
6184                      solib->so_name);
6185           }
6186         disabled_shlib_breaks = 1;
6187       }
6188   }
6189 }
6190
6191 /* FORK & VFORK catchpoints.  */
6192
6193 /* An instance of this type is used to represent a fork or vfork
6194    catchpoint.  It includes a "struct breakpoint" as a kind of base
6195    class; users downcast to "struct breakpoint *" when needed.  A
6196    breakpoint is really of this type iff its ops pointer points to
6197    CATCH_FORK_BREAKPOINT_OPS.  */
6198
6199 struct fork_catchpoint
6200 {
6201   /* The base class.  */
6202   struct breakpoint base;
6203
6204   /* Process id of a child process whose forking triggered this
6205      catchpoint.  This field is only valid immediately after this
6206      catchpoint has triggered.  */
6207   ptid_t forked_inferior_pid;
6208 };
6209
6210 /* Implement the "insert" breakpoint_ops method for fork
6211    catchpoints.  */
6212
6213 static int
6214 insert_catch_fork (struct bp_location *bl)
6215 {
6216   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
6217 }
6218
6219 /* Implement the "remove" breakpoint_ops method for fork
6220    catchpoints.  */
6221
6222 static int
6223 remove_catch_fork (struct bp_location *bl)
6224 {
6225   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
6226 }
6227
6228 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
6229    catchpoints.  */
6230
6231 static int
6232 breakpoint_hit_catch_fork (const struct bp_location *bl,
6233                            struct address_space *aspace, CORE_ADDR bp_addr)
6234 {
6235   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6236
6237   return inferior_has_forked (inferior_ptid, &c->forked_inferior_pid);
6238 }
6239
6240 /* Implement the "print_it" breakpoint_ops method for fork
6241    catchpoints.  */
6242
6243 static enum print_stop_action
6244 print_it_catch_fork (bpstat bs)
6245 {
6246   struct ui_out *uiout = current_uiout;
6247   struct breakpoint *b = bs->breakpoint_at;
6248   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
6249
6250   annotate_catchpoint (b->number);
6251   if (b->disposition == disp_del)
6252     ui_out_text (uiout, "\nTemporary catchpoint ");
6253   else
6254     ui_out_text (uiout, "\nCatchpoint ");
6255   if (ui_out_is_mi_like_p (uiout))
6256     {
6257       ui_out_field_string (uiout, "reason",
6258                            async_reason_lookup (EXEC_ASYNC_FORK));
6259       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6260     }
6261   ui_out_field_int (uiout, "bkptno", b->number);
6262   ui_out_text (uiout, " (forked process ");
6263   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6264   ui_out_text (uiout, "), ");
6265   return PRINT_SRC_AND_LOC;
6266 }
6267
6268 /* Implement the "print_one" breakpoint_ops method for fork
6269    catchpoints.  */
6270
6271 static void
6272 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
6273 {
6274   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6275   struct value_print_options opts;
6276   struct ui_out *uiout = current_uiout;
6277
6278   get_user_print_options (&opts);
6279
6280   /* Field 4, the address, is omitted (which makes the columns not
6281      line up too nicely with the headers, but the effect is relatively
6282      readable).  */
6283   if (opts.addressprint)
6284     ui_out_field_skip (uiout, "addr");
6285   annotate_field (5);
6286   ui_out_text (uiout, "fork");
6287   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6288     {
6289       ui_out_text (uiout, ", process ");
6290       ui_out_field_int (uiout, "what",
6291                         ptid_get_pid (c->forked_inferior_pid));
6292       ui_out_spaces (uiout, 1);
6293     }
6294 }
6295
6296 /* Implement the "print_mention" breakpoint_ops method for fork
6297    catchpoints.  */
6298
6299 static void
6300 print_mention_catch_fork (struct breakpoint *b)
6301 {
6302   printf_filtered (_("Catchpoint %d (fork)"), b->number);
6303 }
6304
6305 /* Implement the "print_recreate" breakpoint_ops method for fork
6306    catchpoints.  */
6307
6308 static void
6309 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
6310 {
6311   fprintf_unfiltered (fp, "catch fork");
6312   print_recreate_thread (b, fp);
6313 }
6314
6315 /* The breakpoint_ops structure to be used in fork catchpoints.  */
6316
6317 static struct breakpoint_ops catch_fork_breakpoint_ops;
6318
6319 /* Implement the "insert" breakpoint_ops method for vfork
6320    catchpoints.  */
6321
6322 static int
6323 insert_catch_vfork (struct bp_location *bl)
6324 {
6325   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
6326 }
6327
6328 /* Implement the "remove" breakpoint_ops method for vfork
6329    catchpoints.  */
6330
6331 static int
6332 remove_catch_vfork (struct bp_location *bl)
6333 {
6334   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
6335 }
6336
6337 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
6338    catchpoints.  */
6339
6340 static int
6341 breakpoint_hit_catch_vfork (const struct bp_location *bl,
6342                             struct address_space *aspace, CORE_ADDR bp_addr)
6343 {
6344   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
6345
6346   return inferior_has_vforked (inferior_ptid, &c->forked_inferior_pid);
6347 }
6348
6349 /* Implement the "print_it" breakpoint_ops method for vfork
6350    catchpoints.  */
6351
6352 static enum print_stop_action
6353 print_it_catch_vfork (bpstat bs)
6354 {
6355   struct ui_out *uiout = current_uiout;
6356   struct breakpoint *b = bs->breakpoint_at;
6357   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6358
6359   annotate_catchpoint (b->number);
6360   if (b->disposition == disp_del)
6361     ui_out_text (uiout, "\nTemporary catchpoint ");
6362   else
6363     ui_out_text (uiout, "\nCatchpoint ");
6364   if (ui_out_is_mi_like_p (uiout))
6365     {
6366       ui_out_field_string (uiout, "reason",
6367                            async_reason_lookup (EXEC_ASYNC_VFORK));
6368       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6369     }
6370   ui_out_field_int (uiout, "bkptno", b->number);
6371   ui_out_text (uiout, " (vforked process ");
6372   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
6373   ui_out_text (uiout, "), ");
6374   return PRINT_SRC_AND_LOC;
6375 }
6376
6377 /* Implement the "print_one" breakpoint_ops method for vfork
6378    catchpoints.  */
6379
6380 static void
6381 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
6382 {
6383   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
6384   struct value_print_options opts;
6385   struct ui_out *uiout = current_uiout;
6386
6387   get_user_print_options (&opts);
6388   /* Field 4, the address, is omitted (which makes the columns not
6389      line up too nicely with the headers, but the effect is relatively
6390      readable).  */
6391   if (opts.addressprint)
6392     ui_out_field_skip (uiout, "addr");
6393   annotate_field (5);
6394   ui_out_text (uiout, "vfork");
6395   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
6396     {
6397       ui_out_text (uiout, ", process ");
6398       ui_out_field_int (uiout, "what",
6399                         ptid_get_pid (c->forked_inferior_pid));
6400       ui_out_spaces (uiout, 1);
6401     }
6402 }
6403
6404 /* Implement the "print_mention" breakpoint_ops method for vfork
6405    catchpoints.  */
6406
6407 static void
6408 print_mention_catch_vfork (struct breakpoint *b)
6409 {
6410   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
6411 }
6412
6413 /* Implement the "print_recreate" breakpoint_ops method for vfork
6414    catchpoints.  */
6415
6416 static void
6417 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
6418 {
6419   fprintf_unfiltered (fp, "catch vfork");
6420   print_recreate_thread (b, fp);
6421 }
6422
6423 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
6424
6425 static struct breakpoint_ops catch_vfork_breakpoint_ops;
6426
6427 /* An instance of this type is used to represent a syscall catchpoint.
6428    It includes a "struct breakpoint" as a kind of base class; users
6429    downcast to "struct breakpoint *" when needed.  A breakpoint is
6430    really of this type iff its ops pointer points to
6431    CATCH_SYSCALL_BREAKPOINT_OPS.  */
6432
6433 struct syscall_catchpoint
6434 {
6435   /* The base class.  */
6436   struct breakpoint base;
6437
6438   /* Syscall numbers used for the 'catch syscall' feature.  If no
6439      syscall has been specified for filtering, its value is NULL.
6440      Otherwise, it holds a list of all syscalls to be caught.  The
6441      list elements are allocated with xmalloc.  */
6442   VEC(int) *syscalls_to_be_caught;
6443 };
6444
6445 /* Implement the "dtor" breakpoint_ops method for syscall
6446    catchpoints.  */
6447
6448 static void
6449 dtor_catch_syscall (struct breakpoint *b)
6450 {
6451   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6452
6453   VEC_free (int, c->syscalls_to_be_caught);
6454
6455   base_breakpoint_ops.dtor (b);
6456 }
6457
6458 /* Implement the "insert" breakpoint_ops method for syscall
6459    catchpoints.  */
6460
6461 static int
6462 insert_catch_syscall (struct bp_location *bl)
6463 {
6464   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
6465   struct inferior *inf = current_inferior ();
6466
6467   ++inf->total_syscalls_count;
6468   if (!c->syscalls_to_be_caught)
6469     ++inf->any_syscall_count;
6470   else
6471     {
6472       int i, iter;
6473
6474       for (i = 0;
6475            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6476            i++)
6477         {
6478           int elem;
6479
6480           if (iter >= VEC_length (int, inf->syscalls_counts))
6481             {
6482               int old_size = VEC_length (int, inf->syscalls_counts);
6483               uintptr_t vec_addr_offset
6484                 = old_size * ((uintptr_t) sizeof (int));
6485               uintptr_t vec_addr;
6486               VEC_safe_grow (int, inf->syscalls_counts, iter + 1);
6487               vec_addr = (uintptr_t) VEC_address (int, inf->syscalls_counts) +
6488                 vec_addr_offset;
6489               memset ((void *) vec_addr, 0,
6490                       (iter + 1 - old_size) * sizeof (int));
6491             }
6492           elem = VEC_index (int, inf->syscalls_counts, iter);
6493           VEC_replace (int, inf->syscalls_counts, iter, ++elem);
6494         }
6495     }
6496
6497   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
6498                                         inf->total_syscalls_count != 0,
6499                                         inf->any_syscall_count,
6500                                         VEC_length (int, inf->syscalls_counts),
6501                                         VEC_address (int, inf->syscalls_counts));
6502 }
6503
6504 /* Implement the "remove" breakpoint_ops method for syscall
6505    catchpoints.  */
6506
6507 static int
6508 remove_catch_syscall (struct bp_location *bl)
6509 {
6510   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
6511   struct inferior *inf = current_inferior ();
6512
6513   --inf->total_syscalls_count;
6514   if (!c->syscalls_to_be_caught)
6515     --inf->any_syscall_count;
6516   else
6517     {
6518       int i, iter;
6519
6520       for (i = 0;
6521            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6522            i++)
6523         {
6524           int elem;
6525           if (iter >= VEC_length (int, inf->syscalls_counts))
6526             /* Shouldn't happen.  */
6527             continue;
6528           elem = VEC_index (int, inf->syscalls_counts, iter);
6529           VEC_replace (int, inf->syscalls_counts, iter, --elem);
6530         }
6531     }
6532
6533   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
6534                                         inf->total_syscalls_count != 0,
6535                                         inf->any_syscall_count,
6536                                         VEC_length (int, inf->syscalls_counts),
6537                                         VEC_address (int,
6538                                                      inf->syscalls_counts));
6539 }
6540
6541 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
6542    catchpoints.  */
6543
6544 static int
6545 breakpoint_hit_catch_syscall (const struct bp_location *bl,
6546                               struct address_space *aspace, CORE_ADDR bp_addr)
6547 {
6548   /* We must check if we are catching specific syscalls in this
6549      breakpoint.  If we are, then we must guarantee that the called
6550      syscall is the same syscall we are catching.  */
6551   int syscall_number = 0;
6552   const struct syscall_catchpoint *c
6553     = (const struct syscall_catchpoint *) bl->owner;
6554
6555   if (!inferior_has_called_syscall (inferior_ptid, &syscall_number))
6556     return 0;
6557
6558   /* Now, checking if the syscall is the same.  */
6559   if (c->syscalls_to_be_caught)
6560     {
6561       int i, iter;
6562
6563       for (i = 0;
6564            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6565            i++)
6566         if (syscall_number == iter)
6567           break;
6568       /* Not the same.  */
6569       if (!iter)
6570         return 0;
6571     }
6572
6573   return 1;
6574 }
6575
6576 /* Implement the "print_it" breakpoint_ops method for syscall
6577    catchpoints.  */
6578
6579 static enum print_stop_action
6580 print_it_catch_syscall (bpstat bs)
6581 {
6582   struct ui_out *uiout = current_uiout;
6583   struct breakpoint *b = bs->breakpoint_at;
6584   /* These are needed because we want to know in which state a
6585      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
6586      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
6587      must print "called syscall" or "returned from syscall".  */
6588   ptid_t ptid;
6589   struct target_waitstatus last;
6590   struct syscall s;
6591   char *syscall_id;
6592
6593   get_last_target_status (&ptid, &last);
6594
6595   get_syscall_by_number (last.value.syscall_number, &s);
6596
6597   annotate_catchpoint (b->number);
6598
6599   if (b->disposition == disp_del)
6600     ui_out_text (uiout, "\nTemporary catchpoint ");
6601   else
6602     ui_out_text (uiout, "\nCatchpoint ");
6603   if (ui_out_is_mi_like_p (uiout))
6604     {
6605       ui_out_field_string (uiout, "reason",
6606                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
6607                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
6608                                                 : EXEC_ASYNC_SYSCALL_RETURN));
6609       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6610     }
6611   ui_out_field_int (uiout, "bkptno", b->number);
6612
6613   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
6614     ui_out_text (uiout, " (call to syscall ");
6615   else
6616     ui_out_text (uiout, " (returned from syscall ");
6617
6618   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
6619     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
6620   if (s.name != NULL)
6621     ui_out_field_string (uiout, "syscall-name", s.name);
6622
6623   ui_out_text (uiout, "), ");
6624
6625   return PRINT_SRC_AND_LOC;
6626 }
6627
6628 /* Implement the "print_one" breakpoint_ops method for syscall
6629    catchpoints.  */
6630
6631 static void
6632 print_one_catch_syscall (struct breakpoint *b,
6633                          struct bp_location **last_loc)
6634 {
6635   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6636   struct value_print_options opts;
6637   struct ui_out *uiout = current_uiout;
6638
6639   get_user_print_options (&opts);
6640   /* Field 4, the address, is omitted (which makes the columns not
6641      line up too nicely with the headers, but the effect is relatively
6642      readable).  */
6643   if (opts.addressprint)
6644     ui_out_field_skip (uiout, "addr");
6645   annotate_field (5);
6646
6647   if (c->syscalls_to_be_caught
6648       && VEC_length (int, c->syscalls_to_be_caught) > 1)
6649     ui_out_text (uiout, "syscalls \"");
6650   else
6651     ui_out_text (uiout, "syscall \"");
6652
6653   if (c->syscalls_to_be_caught)
6654     {
6655       int i, iter;
6656       char *text = xstrprintf ("%s", "");
6657
6658       for (i = 0;
6659            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6660            i++)
6661         {
6662           char *x = text;
6663           struct syscall s;
6664           get_syscall_by_number (iter, &s);
6665
6666           if (s.name != NULL)
6667             text = xstrprintf ("%s%s, ", text, s.name);
6668           else
6669             text = xstrprintf ("%s%d, ", text, iter);
6670
6671           /* We have to xfree the last 'text' (now stored at 'x')
6672              because xstrprintf dynamically allocates new space for it
6673              on every call.  */
6674           xfree (x);
6675         }
6676       /* Remove the last comma.  */
6677       text[strlen (text) - 2] = '\0';
6678       ui_out_field_string (uiout, "what", text);
6679     }
6680   else
6681     ui_out_field_string (uiout, "what", "<any syscall>");
6682   ui_out_text (uiout, "\" ");
6683 }
6684
6685 /* Implement the "print_mention" breakpoint_ops method for syscall
6686    catchpoints.  */
6687
6688 static void
6689 print_mention_catch_syscall (struct breakpoint *b)
6690 {
6691   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6692
6693   if (c->syscalls_to_be_caught)
6694     {
6695       int i, iter;
6696
6697       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
6698         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
6699       else
6700         printf_filtered (_("Catchpoint %d (syscall"), b->number);
6701
6702       for (i = 0;
6703            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6704            i++)
6705         {
6706           struct syscall s;
6707           get_syscall_by_number (iter, &s);
6708
6709           if (s.name)
6710             printf_filtered (" '%s' [%d]", s.name, s.number);
6711           else
6712             printf_filtered (" %d", s.number);
6713         }
6714       printf_filtered (")");
6715     }
6716   else
6717     printf_filtered (_("Catchpoint %d (any syscall)"),
6718                      b->number);
6719 }
6720
6721 /* Implement the "print_recreate" breakpoint_ops method for syscall
6722    catchpoints.  */
6723
6724 static void
6725 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
6726 {
6727   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
6728
6729   fprintf_unfiltered (fp, "catch syscall");
6730
6731   if (c->syscalls_to_be_caught)
6732     {
6733       int i, iter;
6734
6735       for (i = 0;
6736            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
6737            i++)
6738         {
6739           struct syscall s;
6740
6741           get_syscall_by_number (iter, &s);
6742           if (s.name)
6743             fprintf_unfiltered (fp, " %s", s.name);
6744           else
6745             fprintf_unfiltered (fp, " %d", s.number);
6746         }
6747     }
6748   print_recreate_thread (b, fp);
6749 }
6750
6751 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
6752
6753 static struct breakpoint_ops catch_syscall_breakpoint_ops;
6754
6755 /* Returns non-zero if 'b' is a syscall catchpoint.  */
6756
6757 static int
6758 syscall_catchpoint_p (struct breakpoint *b)
6759 {
6760   return (b->ops == &catch_syscall_breakpoint_ops);
6761 }
6762
6763 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
6764    is non-zero, then make the breakpoint temporary.  If COND_STRING is
6765    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
6766    the breakpoint_ops structure associated to the catchpoint.  */
6767
6768 static void
6769 init_catchpoint (struct breakpoint *b,
6770                  struct gdbarch *gdbarch, int tempflag,
6771                  char *cond_string,
6772                  const struct breakpoint_ops *ops)
6773 {
6774   struct symtab_and_line sal;
6775
6776   init_sal (&sal);
6777   sal.pspace = current_program_space;
6778
6779   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
6780
6781   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
6782   b->disposition = tempflag ? disp_del : disp_donttouch;
6783 }
6784
6785 void
6786 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
6787 {
6788   add_to_breakpoint_chain (b);
6789   set_breakpoint_number (internal, b);
6790   if (!internal)
6791     mention (b);
6792   observer_notify_breakpoint_created (b);
6793
6794   if (update_gll)
6795     update_global_location_list (1);
6796 }
6797
6798 static void
6799 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
6800                                     int tempflag, char *cond_string,
6801                                     const struct breakpoint_ops *ops)
6802 {
6803   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
6804
6805   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
6806
6807   c->forked_inferior_pid = null_ptid;
6808
6809   install_breakpoint (0, &c->base, 1);
6810 }
6811
6812 /* Exec catchpoints.  */
6813
6814 /* An instance of this type is used to represent an exec catchpoint.
6815    It includes a "struct breakpoint" as a kind of base class; users
6816    downcast to "struct breakpoint *" when needed.  A breakpoint is
6817    really of this type iff its ops pointer points to
6818    CATCH_EXEC_BREAKPOINT_OPS.  */
6819
6820 struct exec_catchpoint
6821 {
6822   /* The base class.  */
6823   struct breakpoint base;
6824
6825   /* Filename of a program whose exec triggered this catchpoint.
6826      This field is only valid immediately after this catchpoint has
6827      triggered.  */
6828   char *exec_pathname;
6829 };
6830
6831 /* Implement the "dtor" breakpoint_ops method for exec
6832    catchpoints.  */
6833
6834 static void
6835 dtor_catch_exec (struct breakpoint *b)
6836 {
6837   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
6838
6839   xfree (c->exec_pathname);
6840
6841   base_breakpoint_ops.dtor (b);
6842 }
6843
6844 static int
6845 insert_catch_exec (struct bp_location *bl)
6846 {
6847   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
6848 }
6849
6850 static int
6851 remove_catch_exec (struct bp_location *bl)
6852 {
6853   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
6854 }
6855
6856 static int
6857 breakpoint_hit_catch_exec (const struct bp_location *bl,
6858                            struct address_space *aspace, CORE_ADDR bp_addr)
6859 {
6860   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
6861
6862   return inferior_has_execd (inferior_ptid, &c->exec_pathname);
6863 }
6864
6865 static enum print_stop_action
6866 print_it_catch_exec (bpstat bs)
6867 {
6868   struct ui_out *uiout = current_uiout;
6869   struct breakpoint *b = bs->breakpoint_at;
6870   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
6871
6872   annotate_catchpoint (b->number);
6873   if (b->disposition == disp_del)
6874     ui_out_text (uiout, "\nTemporary catchpoint ");
6875   else
6876     ui_out_text (uiout, "\nCatchpoint ");
6877   if (ui_out_is_mi_like_p (uiout))
6878     {
6879       ui_out_field_string (uiout, "reason",
6880                            async_reason_lookup (EXEC_ASYNC_EXEC));
6881       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
6882     }
6883   ui_out_field_int (uiout, "bkptno", b->number);
6884   ui_out_text (uiout, " (exec'd ");
6885   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
6886   ui_out_text (uiout, "), ");
6887
6888   return PRINT_SRC_AND_LOC;
6889 }
6890
6891 static void
6892 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
6893 {
6894   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
6895   struct value_print_options opts;
6896   struct ui_out *uiout = current_uiout;
6897
6898   get_user_print_options (&opts);
6899
6900   /* Field 4, the address, is omitted (which makes the columns
6901      not line up too nicely with the headers, but the effect
6902      is relatively readable).  */
6903   if (opts.addressprint)
6904     ui_out_field_skip (uiout, "addr");
6905   annotate_field (5);
6906   ui_out_text (uiout, "exec");
6907   if (c->exec_pathname != NULL)
6908     {
6909       ui_out_text (uiout, ", program \"");
6910       ui_out_field_string (uiout, "what", c->exec_pathname);
6911       ui_out_text (uiout, "\" ");
6912     }
6913 }
6914
6915 static void
6916 print_mention_catch_exec (struct breakpoint *b)
6917 {
6918   printf_filtered (_("Catchpoint %d (exec)"), b->number);
6919 }
6920
6921 /* Implement the "print_recreate" breakpoint_ops method for exec
6922    catchpoints.  */
6923
6924 static void
6925 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
6926 {
6927   fprintf_unfiltered (fp, "catch exec");
6928   print_recreate_thread (b, fp);
6929 }
6930
6931 static struct breakpoint_ops catch_exec_breakpoint_ops;
6932
6933 static void
6934 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
6935                                  const struct breakpoint_ops *ops)
6936 {
6937   struct syscall_catchpoint *c;
6938   struct gdbarch *gdbarch = get_current_arch ();
6939
6940   c = XNEW (struct syscall_catchpoint);
6941   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
6942   c->syscalls_to_be_caught = filter;
6943
6944   install_breakpoint (0, &c->base, 1);
6945 }
6946
6947 static int
6948 hw_breakpoint_used_count (void)
6949 {
6950   int i = 0;
6951   struct breakpoint *b;
6952   struct bp_location *bl;
6953
6954   ALL_BREAKPOINTS (b)
6955   {
6956     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
6957       for (bl = b->loc; bl; bl = bl->next)
6958         {
6959           /* Special types of hardware breakpoints may use more than
6960              one register.  */
6961           i += b->ops->resources_needed (bl);
6962         }
6963   }
6964
6965   return i;
6966 }
6967
6968 /* Returns the resources B would use if it were a hardware
6969    watchpoint.  */
6970
6971 static int
6972 hw_watchpoint_use_count (struct breakpoint *b)
6973 {
6974   int i = 0;
6975   struct bp_location *bl;
6976
6977   if (!breakpoint_enabled (b))
6978     return 0;
6979
6980   for (bl = b->loc; bl; bl = bl->next)
6981     {
6982       /* Special types of hardware watchpoints may use more than
6983          one register.  */
6984       i += b->ops->resources_needed (bl);
6985     }
6986
6987   return i;
6988 }
6989
6990 /* Returns the sum the used resources of all hardware watchpoints of
6991    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
6992    the sum of the used resources of all hardware watchpoints of other
6993    types _not_ TYPE.  */
6994
6995 static int
6996 hw_watchpoint_used_count_others (struct breakpoint *except,
6997                                  enum bptype type, int *other_type_used)
6998 {
6999   int i = 0;
7000   struct breakpoint *b;
7001
7002   *other_type_used = 0;
7003   ALL_BREAKPOINTS (b)
7004     {
7005       if (b == except)
7006         continue;
7007       if (!breakpoint_enabled (b))
7008         continue;
7009
7010       if (b->type == type)
7011         i += hw_watchpoint_use_count (b);
7012       else if (is_hardware_watchpoint (b))
7013         *other_type_used = 1;
7014     }
7015
7016   return i;
7017 }
7018
7019 void
7020 disable_watchpoints_before_interactive_call_start (void)
7021 {
7022   struct breakpoint *b;
7023
7024   ALL_BREAKPOINTS (b)
7025   {
7026     if (is_watchpoint (b) && breakpoint_enabled (b))
7027       {
7028         b->enable_state = bp_call_disabled;
7029         update_global_location_list (0);
7030       }
7031   }
7032 }
7033
7034 void
7035 enable_watchpoints_after_interactive_call_stop (void)
7036 {
7037   struct breakpoint *b;
7038
7039   ALL_BREAKPOINTS (b)
7040   {
7041     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
7042       {
7043         b->enable_state = bp_enabled;
7044         update_global_location_list (1);
7045       }
7046   }
7047 }
7048
7049 void
7050 disable_breakpoints_before_startup (void)
7051 {
7052   current_program_space->executing_startup = 1;
7053   update_global_location_list (0);
7054 }
7055
7056 void
7057 enable_breakpoints_after_startup (void)
7058 {
7059   current_program_space->executing_startup = 0;
7060   breakpoint_re_set ();
7061 }
7062
7063
7064 /* Set a breakpoint that will evaporate an end of command
7065    at address specified by SAL.
7066    Restrict it to frame FRAME if FRAME is nonzero.  */
7067
7068 struct breakpoint *
7069 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
7070                           struct frame_id frame_id, enum bptype type)
7071 {
7072   struct breakpoint *b;
7073
7074   /* If FRAME_ID is valid, it should be a real frame, not an inlined
7075      one.  */
7076   gdb_assert (!frame_id_inlined_p (frame_id));
7077
7078   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
7079   b->enable_state = bp_enabled;
7080   b->disposition = disp_donttouch;
7081   b->frame_id = frame_id;
7082
7083   /* If we're debugging a multi-threaded program, then we want
7084      momentary breakpoints to be active in only a single thread of
7085      control.  */
7086   if (in_thread_list (inferior_ptid))
7087     b->thread = pid_to_thread_id (inferior_ptid);
7088
7089   update_global_location_list_nothrow (1);
7090
7091   return b;
7092 }
7093
7094 /* Make a momentary breakpoint based on the master breakpoint ORIG.
7095    The new breakpoint will have type TYPE, and use OPS as it
7096    breakpoint_ops.  */
7097
7098 static struct breakpoint *
7099 momentary_breakpoint_from_master (struct breakpoint *orig,
7100                                   enum bptype type,
7101                                   const struct breakpoint_ops *ops)
7102 {
7103   struct breakpoint *copy;
7104
7105   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
7106   copy->loc = allocate_bp_location (copy);
7107   set_breakpoint_location_function (copy->loc, 1);
7108
7109   copy->loc->gdbarch = orig->loc->gdbarch;
7110   copy->loc->requested_address = orig->loc->requested_address;
7111   copy->loc->address = orig->loc->address;
7112   copy->loc->section = orig->loc->section;
7113   copy->loc->pspace = orig->loc->pspace;
7114
7115   if (orig->loc->source_file != NULL)
7116     copy->loc->source_file = xstrdup (orig->loc->source_file);
7117
7118   copy->loc->line_number = orig->loc->line_number;
7119   copy->frame_id = orig->frame_id;
7120   copy->thread = orig->thread;
7121   copy->pspace = orig->pspace;
7122
7123   copy->enable_state = bp_enabled;
7124   copy->disposition = disp_donttouch;
7125   copy->number = internal_breakpoint_number--;
7126
7127   update_global_location_list_nothrow (0);
7128   return copy;
7129 }
7130
7131 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
7132    ORIG is NULL.  */
7133
7134 struct breakpoint *
7135 clone_momentary_breakpoint (struct breakpoint *orig)
7136 {
7137   /* If there's nothing to clone, then return nothing.  */
7138   if (orig == NULL)
7139     return NULL;
7140
7141   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
7142 }
7143
7144 struct breakpoint *
7145 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
7146                                 enum bptype type)
7147 {
7148   struct symtab_and_line sal;
7149
7150   sal = find_pc_line (pc, 0);
7151   sal.pc = pc;
7152   sal.section = find_pc_overlay (pc);
7153   sal.explicit_pc = 1;
7154
7155   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
7156 }
7157 \f
7158
7159 /* Tell the user we have just set a breakpoint B.  */
7160
7161 static void
7162 mention (struct breakpoint *b)
7163 {
7164   b->ops->print_mention (b);
7165   if (ui_out_is_mi_like_p (current_uiout))
7166     return;
7167   printf_filtered ("\n");
7168 }
7169 \f
7170
7171 static struct bp_location *
7172 add_location_to_breakpoint (struct breakpoint *b,
7173                             const struct symtab_and_line *sal)
7174 {
7175   struct bp_location *loc, **tmp;
7176   CORE_ADDR adjusted_address;
7177   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
7178
7179   if (loc_gdbarch == NULL)
7180     loc_gdbarch = b->gdbarch;
7181
7182   /* Adjust the breakpoint's address prior to allocating a location.
7183      Once we call allocate_bp_location(), that mostly uninitialized
7184      location will be placed on the location chain.  Adjustment of the
7185      breakpoint may cause target_read_memory() to be called and we do
7186      not want its scan of the location chain to find a breakpoint and
7187      location that's only been partially initialized.  */
7188   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
7189                                                 sal->pc, b->type);
7190
7191   loc = allocate_bp_location (b);
7192   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
7193     ;
7194   *tmp = loc;
7195
7196   loc->requested_address = sal->pc;
7197   loc->address = adjusted_address;
7198   loc->pspace = sal->pspace;
7199   gdb_assert (loc->pspace != NULL);
7200   loc->section = sal->section;
7201   loc->gdbarch = loc_gdbarch;
7202
7203   if (sal->symtab != NULL)
7204     loc->source_file = xstrdup (sal->symtab->filename);
7205   loc->line_number = sal->line;
7206
7207   set_breakpoint_location_function (loc,
7208                                     sal->explicit_pc || sal->explicit_line);
7209   return loc;
7210 }
7211 \f
7212
7213 /* Return 1 if LOC is pointing to a permanent breakpoint, 
7214    return 0 otherwise.  */
7215
7216 static int
7217 bp_loc_is_permanent (struct bp_location *loc)
7218 {
7219   int len;
7220   CORE_ADDR addr;
7221   const gdb_byte *bpoint;
7222   gdb_byte *target_mem;
7223   struct cleanup *cleanup;
7224   int retval = 0;
7225
7226   gdb_assert (loc != NULL);
7227
7228   addr = loc->address;
7229   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
7230
7231   /* Software breakpoints unsupported?  */
7232   if (bpoint == NULL)
7233     return 0;
7234
7235   target_mem = alloca (len);
7236
7237   /* Enable the automatic memory restoration from breakpoints while
7238      we read the memory.  Otherwise we could say about our temporary
7239      breakpoints they are permanent.  */
7240   cleanup = save_current_space_and_thread ();
7241
7242   switch_to_program_space_and_thread (loc->pspace);
7243   make_show_memory_breakpoints_cleanup (0);
7244
7245   if (target_read_memory (loc->address, target_mem, len) == 0
7246       && memcmp (target_mem, bpoint, len) == 0)
7247     retval = 1;
7248
7249   do_cleanups (cleanup);
7250
7251   return retval;
7252 }
7253
7254
7255
7256 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
7257    as textual description of the location, and COND_STRING
7258    as condition expression.  */
7259
7260 static void
7261 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
7262                      struct symtabs_and_lines sals, char *addr_string,
7263                      char *filter, char *cond_string,
7264                      enum bptype type, enum bpdisp disposition,
7265                      int thread, int task, int ignore_count,
7266                      const struct breakpoint_ops *ops, int from_tty,
7267                      int enabled, int internal, int display_canonical)
7268 {
7269   int i;
7270
7271   if (type == bp_hardware_breakpoint)
7272     {
7273       int target_resources_ok;
7274
7275       i = hw_breakpoint_used_count ();
7276       target_resources_ok =
7277         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
7278                                             i + 1, 0);
7279       if (target_resources_ok == 0)
7280         error (_("No hardware breakpoint support in the target."));
7281       else if (target_resources_ok < 0)
7282         error (_("Hardware breakpoints used exceeds limit."));
7283     }
7284
7285   gdb_assert (sals.nelts > 0);
7286
7287   for (i = 0; i < sals.nelts; ++i)
7288     {
7289       struct symtab_and_line sal = sals.sals[i];
7290       struct bp_location *loc;
7291
7292       if (from_tty)
7293         {
7294           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
7295           if (!loc_gdbarch)
7296             loc_gdbarch = gdbarch;
7297
7298           describe_other_breakpoints (loc_gdbarch,
7299                                       sal.pspace, sal.pc, sal.section, thread);
7300         }
7301
7302       if (i == 0)
7303         {
7304           init_raw_breakpoint (b, gdbarch, sal, type, ops);
7305           b->thread = thread;
7306           b->task = task;
7307   
7308           b->cond_string = cond_string;
7309           b->ignore_count = ignore_count;
7310           b->enable_state = enabled ? bp_enabled : bp_disabled;
7311           b->disposition = disposition;
7312
7313           if (type == bp_static_tracepoint)
7314             {
7315               struct tracepoint *t = (struct tracepoint *) b;
7316               struct static_tracepoint_marker marker;
7317
7318               if (strace_marker_p (b))
7319                 {
7320                   /* We already know the marker exists, otherwise, we
7321                      wouldn't see a sal for it.  */
7322                   char *p = &addr_string[3];
7323                   char *endp;
7324                   char *marker_str;
7325
7326                   p = skip_spaces (p);
7327
7328                   endp = skip_to_space (p);
7329
7330                   marker_str = savestring (p, endp - p);
7331                   t->static_trace_marker_id = marker_str;
7332
7333                   printf_filtered (_("Probed static tracepoint "
7334                                      "marker \"%s\"\n"),
7335                                    t->static_trace_marker_id);
7336                 }
7337               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
7338                 {
7339                   t->static_trace_marker_id = xstrdup (marker.str_id);
7340                   release_static_tracepoint_marker (&marker);
7341
7342                   printf_filtered (_("Probed static tracepoint "
7343                                      "marker \"%s\"\n"),
7344                                    t->static_trace_marker_id);
7345                 }
7346               else
7347                 warning (_("Couldn't determine the static "
7348                            "tracepoint marker to probe"));
7349             }
7350
7351           loc = b->loc;
7352         }
7353       else
7354         {
7355           loc = add_location_to_breakpoint (b, &sal);
7356         }
7357
7358       if (bp_loc_is_permanent (loc))
7359         make_breakpoint_permanent (b);
7360
7361       if (b->cond_string)
7362         {
7363           char *arg = b->cond_string;
7364           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
7365           if (*arg)
7366               error (_("Garbage %s follows condition"), arg);
7367         }
7368     }   
7369
7370   b->display_canonical = display_canonical;
7371   if (addr_string)
7372     b->addr_string = addr_string;
7373   else
7374     /* addr_string has to be used or breakpoint_re_set will delete
7375        me.  */
7376     b->addr_string
7377       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
7378   b->filter = filter;
7379 }
7380
7381 static void
7382 create_breakpoint_sal (struct gdbarch *gdbarch,
7383                        struct symtabs_and_lines sals, char *addr_string,
7384                        char *filter, char *cond_string,
7385                        enum bptype type, enum bpdisp disposition,
7386                        int thread, int task, int ignore_count,
7387                        const struct breakpoint_ops *ops, int from_tty,
7388                        int enabled, int internal, int display_canonical)
7389 {
7390   struct breakpoint *b;
7391   struct cleanup *old_chain;
7392
7393   if (is_tracepoint_type (type))
7394     {
7395       struct tracepoint *t;
7396
7397       t = XCNEW (struct tracepoint);
7398       b = &t->base;
7399     }
7400   else
7401     b = XNEW (struct breakpoint);
7402
7403   old_chain = make_cleanup (xfree, b);
7404
7405   init_breakpoint_sal (b, gdbarch,
7406                        sals, addr_string,
7407                        filter, cond_string,
7408                        type, disposition,
7409                        thread, task, ignore_count,
7410                        ops, from_tty,
7411                        enabled, internal, display_canonical);
7412   discard_cleanups (old_chain);
7413
7414   install_breakpoint (internal, b, 0);
7415 }
7416
7417 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
7418    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
7419    value.  COND_STRING, if not NULL, specified the condition to be
7420    used for all breakpoints.  Essentially the only case where
7421    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
7422    function.  In that case, it's still not possible to specify
7423    separate conditions for different overloaded functions, so
7424    we take just a single condition string.
7425    
7426    NOTE: If the function succeeds, the caller is expected to cleanup
7427    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
7428    array contents).  If the function fails (error() is called), the
7429    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
7430    COND and SALS arrays and each of those arrays contents.  */
7431
7432 static void
7433 create_breakpoints_sal (struct gdbarch *gdbarch,
7434                         struct linespec_result *canonical,
7435                         char *cond_string,
7436                         enum bptype type, enum bpdisp disposition,
7437                         int thread, int task, int ignore_count,
7438                         const struct breakpoint_ops *ops, int from_tty,
7439                         int enabled, int internal)
7440 {
7441   int i;
7442   struct linespec_sals *lsal;
7443
7444   if (canonical->pre_expanded)
7445     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
7446
7447   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
7448     {
7449       /* Note that 'addr_string' can be NULL in the case of a plain
7450          'break', without arguments.  */
7451       char *addr_string = (canonical->addr_string
7452                            ? xstrdup (canonical->addr_string)
7453                            : NULL);
7454       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
7455       struct cleanup *inner = make_cleanup (xfree, addr_string);
7456
7457       make_cleanup (xfree, filter_string);
7458       create_breakpoint_sal (gdbarch, lsal->sals,
7459                              addr_string,
7460                              filter_string,
7461                              cond_string, type, disposition,
7462                              thread, task, ignore_count, ops,
7463                              from_tty, enabled, internal,
7464                              canonical->special_display);
7465       discard_cleanups (inner);
7466     }
7467 }
7468
7469 /* Parse ADDRESS which is assumed to be a SAL specification possibly
7470    followed by conditionals.  On return, SALS contains an array of SAL
7471    addresses found.  ADDR_STRING contains a vector of (canonical)
7472    address strings.  ADDRESS points to the end of the SAL.
7473
7474    The array and the line spec strings are allocated on the heap, it is
7475    the caller's responsibility to free them.  */
7476
7477 static void
7478 parse_breakpoint_sals (char **address,
7479                        struct linespec_result *canonical)
7480 {
7481   char *addr_start = *address;
7482
7483   /* If no arg given, or if first arg is 'if ', use the default
7484      breakpoint.  */
7485   if ((*address) == NULL
7486       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
7487     {
7488       /* The last displayed codepoint, if it's valid, is our default breakpoint
7489          address.  */
7490       if (last_displayed_sal_is_valid ())
7491         {
7492           struct linespec_sals lsal;
7493           struct symtab_and_line sal;
7494
7495           init_sal (&sal);              /* Initialize to zeroes.  */
7496           lsal.sals.sals = (struct symtab_and_line *)
7497             xmalloc (sizeof (struct symtab_and_line));
7498
7499           /* Set sal's pspace, pc, symtab, and line to the values
7500              corresponding to the last call to print_frame_info.  */
7501           get_last_displayed_sal (&sal);
7502           sal.section = find_pc_overlay (sal.pc);
7503
7504           /* "break" without arguments is equivalent to "break *PC"
7505              where PC is the last displayed codepoint's address.  So
7506              make sure to set sal.explicit_pc to prevent GDB from
7507              trying to expand the list of sals to include all other
7508              instances with the same symtab and line.  */
7509           sal.explicit_pc = 1;
7510
7511           lsal.sals.sals[0] = sal;
7512           lsal.sals.nelts = 1;
7513           lsal.canonical = NULL;
7514
7515           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
7516         }
7517       else
7518         error (_("No default breakpoint address now."));
7519     }
7520   else
7521     {
7522       /* Force almost all breakpoints to be in terms of the
7523          current_source_symtab (which is decode_line_1's default).
7524          This should produce the results we want almost all of the
7525          time while leaving default_breakpoint_* alone.  */
7526       if (last_displayed_sal_is_valid ())
7527         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
7528                           get_last_displayed_symtab (),
7529                           get_last_displayed_line (),
7530                           canonical, NULL, NULL);
7531       else
7532         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
7533                           (struct symtab *) NULL, 0,
7534                           canonical, NULL, NULL);
7535     }
7536 }
7537
7538
7539 /* Convert each SAL into a real PC.  Verify that the PC can be
7540    inserted as a breakpoint.  If it can't throw an error.  */
7541
7542 static void
7543 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
7544 {    
7545   int i;
7546
7547   for (i = 0; i < sals->nelts; i++)
7548     resolve_sal_pc (&sals->sals[i]);
7549 }
7550
7551 /* Fast tracepoints may have restrictions on valid locations.  For
7552    instance, a fast tracepoint using a jump instead of a trap will
7553    likely have to overwrite more bytes than a trap would, and so can
7554    only be placed where the instruction is longer than the jump, or a
7555    multi-instruction sequence does not have a jump into the middle of
7556    it, etc.  */
7557
7558 static void
7559 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
7560                             struct symtabs_and_lines *sals)
7561 {
7562   int i, rslt;
7563   struct symtab_and_line *sal;
7564   char *msg;
7565   struct cleanup *old_chain;
7566
7567   for (i = 0; i < sals->nelts; i++)
7568     {
7569       struct gdbarch *sarch;
7570
7571       sal = &sals->sals[i];
7572
7573       sarch = get_sal_arch (*sal);
7574       /* We fall back to GDBARCH if there is no architecture
7575          associated with SAL.  */
7576       if (sarch == NULL)
7577         sarch = gdbarch;
7578       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
7579                                                NULL, &msg);
7580       old_chain = make_cleanup (xfree, msg);
7581
7582       if (!rslt)
7583         error (_("May not have a fast tracepoint at 0x%s%s"),
7584                paddress (sarch, sal->pc), (msg ? msg : ""));
7585
7586       do_cleanups (old_chain);
7587     }
7588 }
7589
7590 /* Given TOK, a string specification of condition and thread, as
7591    accepted by the 'break' command, extract the condition
7592    string and thread number and set *COND_STRING and *THREAD.
7593    PC identifies the context at which the condition should be parsed.
7594    If no condition is found, *COND_STRING is set to NULL.
7595    If no thread is found, *THREAD is set to -1.  */
7596 static void 
7597 find_condition_and_thread (char *tok, CORE_ADDR pc, 
7598                            char **cond_string, int *thread, int *task)
7599 {
7600   *cond_string = NULL;
7601   *thread = -1;
7602   while (tok && *tok)
7603     {
7604       char *end_tok;
7605       int toklen;
7606       char *cond_start = NULL;
7607       char *cond_end = NULL;
7608
7609       tok = skip_spaces (tok);
7610       
7611       end_tok = skip_to_space (tok);
7612       
7613       toklen = end_tok - tok;
7614       
7615       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
7616         {
7617           struct expression *expr;
7618
7619           tok = cond_start = end_tok + 1;
7620           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
7621           xfree (expr);
7622           cond_end = tok;
7623           *cond_string = savestring (cond_start, 
7624                                      cond_end - cond_start);
7625         }
7626       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
7627         {
7628           char *tmptok;
7629           
7630           tok = end_tok + 1;
7631           tmptok = tok;
7632           *thread = strtol (tok, &tok, 0);
7633           if (tok == tmptok)
7634             error (_("Junk after thread keyword."));
7635           if (!valid_thread_id (*thread))
7636             error (_("Unknown thread %d."), *thread);
7637         }
7638       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
7639         {
7640           char *tmptok;
7641
7642           tok = end_tok + 1;
7643           tmptok = tok;
7644           *task = strtol (tok, &tok, 0);
7645           if (tok == tmptok)
7646             error (_("Junk after task keyword."));
7647           if (!valid_task_id (*task))
7648             error (_("Unknown task %d."), *task);
7649         }
7650       else
7651         error (_("Junk at end of arguments."));
7652     }
7653 }
7654
7655 /* Decode a static tracepoint marker spec.  */
7656
7657 static struct symtabs_and_lines
7658 decode_static_tracepoint_spec (char **arg_p)
7659 {
7660   VEC(static_tracepoint_marker_p) *markers = NULL;
7661   struct symtabs_and_lines sals;
7662   struct symtab_and_line sal;
7663   struct symbol *sym;
7664   struct cleanup *old_chain;
7665   char *p = &(*arg_p)[3];
7666   char *endp;
7667   char *marker_str;
7668   int i;
7669
7670   p = skip_spaces (p);
7671
7672   endp = skip_to_space (p);
7673
7674   marker_str = savestring (p, endp - p);
7675   old_chain = make_cleanup (xfree, marker_str);
7676
7677   markers = target_static_tracepoint_markers_by_strid (marker_str);
7678   if (VEC_empty(static_tracepoint_marker_p, markers))
7679     error (_("No known static tracepoint marker named %s"), marker_str);
7680
7681   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
7682   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
7683
7684   for (i = 0; i < sals.nelts; i++)
7685     {
7686       struct static_tracepoint_marker *marker;
7687
7688       marker = VEC_index (static_tracepoint_marker_p, markers, i);
7689
7690       init_sal (&sals.sals[i]);
7691
7692       sals.sals[i] = find_pc_line (marker->address, 0);
7693       sals.sals[i].pc = marker->address;
7694
7695       release_static_tracepoint_marker (marker);
7696     }
7697
7698   do_cleanups (old_chain);
7699
7700   *arg_p = endp;
7701   return sals;
7702 }
7703
7704 /* Set a breakpoint.  This function is shared between CLI and MI
7705    functions for setting a breakpoint.  This function has two major
7706    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
7707    parameter.  If non-zero, the function will parse arg, extracting
7708    breakpoint location, address and thread.  Otherwise, ARG is just
7709    the location of breakpoint, with condition and thread specified by
7710    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
7711    the breakpoint number will be allocated from the internal
7712    breakpoint count.  Returns true if any breakpoint was created;
7713    false otherwise.  */
7714
7715 int
7716 create_breakpoint (struct gdbarch *gdbarch,
7717                    char *arg, char *cond_string, int thread,
7718                    int parse_condition_and_thread,
7719                    int tempflag, enum bptype type_wanted,
7720                    int ignore_count,
7721                    enum auto_boolean pending_break_support,
7722                    const struct breakpoint_ops *ops,
7723                    int from_tty, int enabled, int internal)
7724 {
7725   volatile struct gdb_exception e;
7726   char *copy_arg = NULL;
7727   char *addr_start = arg;
7728   struct linespec_result canonical;
7729   struct cleanup *old_chain;
7730   struct cleanup *bkpt_chain = NULL;
7731   int i;
7732   int pending = 0;
7733   int task = 0;
7734   int prev_bkpt_count = breakpoint_count;
7735
7736   gdb_assert (ops != NULL);
7737
7738   init_linespec_result (&canonical);
7739
7740   TRY_CATCH (e, RETURN_MASK_ALL)
7741     {
7742       ops->create_sals_from_address (&arg, &canonical, type_wanted,
7743                                      addr_start, &copy_arg);
7744     }
7745
7746   /* If caller is interested in rc value from parse, set value.  */
7747   switch (e.reason)
7748     {
7749     case GDB_NO_ERROR:
7750       if (VEC_empty (linespec_sals, canonical.sals))
7751         return 0;
7752       break;
7753     case RETURN_ERROR:
7754       switch (e.error)
7755         {
7756         case NOT_FOUND_ERROR:
7757
7758           /* If pending breakpoint support is turned off, throw
7759              error.  */
7760
7761           if (pending_break_support == AUTO_BOOLEAN_FALSE)
7762             throw_exception (e);
7763
7764           exception_print (gdb_stderr, e);
7765
7766           /* If pending breakpoint support is auto query and the user
7767              selects no, then simply return the error code.  */
7768           if (pending_break_support == AUTO_BOOLEAN_AUTO
7769               && !nquery (_("Make %s pending on future shared library load? "),
7770                           bptype_string (type_wanted)))
7771             return 0;
7772
7773           /* At this point, either the user was queried about setting
7774              a pending breakpoint and selected yes, or pending
7775              breakpoint behavior is on and thus a pending breakpoint
7776              is defaulted on behalf of the user.  */
7777           {
7778             struct linespec_sals lsal;
7779
7780             copy_arg = xstrdup (addr_start);
7781             lsal.canonical = xstrdup (copy_arg);
7782             lsal.sals.nelts = 1;
7783             lsal.sals.sals = XNEW (struct symtab_and_line);
7784             init_sal (&lsal.sals.sals[0]);
7785             pending = 1;
7786             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
7787           }
7788           break;
7789         default:
7790           throw_exception (e);
7791         }
7792       break;
7793     default:
7794       throw_exception (e);
7795     }
7796
7797   /* Create a chain of things that always need to be cleaned up.  */
7798   old_chain = make_cleanup_destroy_linespec_result (&canonical);
7799
7800   /* ----------------------------- SNIP -----------------------------
7801      Anything added to the cleanup chain beyond this point is assumed
7802      to be part of a breakpoint.  If the breakpoint create succeeds
7803      then the memory is not reclaimed.  */
7804   bkpt_chain = make_cleanup (null_cleanup, 0);
7805
7806   /* Resolve all line numbers to PC's and verify that the addresses
7807      are ok for the target.  */
7808   if (!pending)
7809     {
7810       int ix;
7811       struct linespec_sals *iter;
7812
7813       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
7814         breakpoint_sals_to_pc (&iter->sals);
7815     }
7816
7817   /* Fast tracepoints may have additional restrictions on location.  */
7818   if (!pending && type_wanted == bp_fast_tracepoint)
7819     {
7820       int ix;
7821       struct linespec_sals *iter;
7822
7823       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
7824         check_fast_tracepoint_sals (gdbarch, &iter->sals);
7825     }
7826
7827   /* Verify that condition can be parsed, before setting any
7828      breakpoints.  Allocate a separate condition expression for each
7829      breakpoint.  */
7830   if (!pending)
7831     {
7832       struct linespec_sals *lsal;
7833
7834       lsal = VEC_index (linespec_sals, canonical.sals, 0);
7835
7836       if (parse_condition_and_thread)
7837         {
7838             /* Here we only parse 'arg' to separate condition
7839                from thread number, so parsing in context of first
7840                sal is OK.  When setting the breakpoint we'll 
7841                re-parse it in context of each sal.  */
7842             cond_string = NULL;
7843             thread = -1;
7844             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
7845                                        &thread, &task);
7846             if (cond_string)
7847                 make_cleanup (xfree, cond_string);
7848         }
7849       else
7850         {
7851             /* Create a private copy of condition string.  */
7852             if (cond_string)
7853             {
7854                 cond_string = xstrdup (cond_string);
7855                 make_cleanup (xfree, cond_string);
7856             }
7857         }
7858
7859       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
7860                                    cond_string, type_wanted,
7861                                    tempflag ? disp_del : disp_donttouch,
7862                                    thread, task, ignore_count, ops,
7863                                    from_tty, enabled, internal);
7864     }
7865   else
7866     {
7867       struct breakpoint *b;
7868
7869       make_cleanup (xfree, copy_arg);
7870
7871       if (is_tracepoint_type (type_wanted))
7872         {
7873           struct tracepoint *t;
7874
7875           t = XCNEW (struct tracepoint);
7876           b = &t->base;
7877         }
7878       else
7879         b = XNEW (struct breakpoint);
7880
7881       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
7882
7883       b->addr_string = copy_arg;
7884       b->cond_string = NULL;
7885       b->ignore_count = ignore_count;
7886       b->disposition = tempflag ? disp_del : disp_donttouch;
7887       b->condition_not_parsed = 1;
7888       b->enable_state = enabled ? bp_enabled : bp_disabled;
7889       if ((type_wanted != bp_breakpoint
7890            && type_wanted != bp_hardware_breakpoint) || thread != -1)
7891         b->pspace = current_program_space;
7892
7893       install_breakpoint (internal, b, 0);
7894     }
7895   
7896   if (VEC_length (linespec_sals, canonical.sals) > 1)
7897     {
7898       warning (_("Multiple breakpoints were set.\nUse the "
7899                  "\"delete\" command to delete unwanted breakpoints."));
7900       prev_breakpoint_count = prev_bkpt_count;
7901     }
7902
7903   /* That's it.  Discard the cleanups for data inserted into the
7904      breakpoint.  */
7905   discard_cleanups (bkpt_chain);
7906   /* But cleanup everything else.  */
7907   do_cleanups (old_chain);
7908
7909   /* error call may happen here - have BKPT_CHAIN already discarded.  */
7910   update_global_location_list (1);
7911
7912   return 1;
7913 }
7914
7915 /* Set a breakpoint.
7916    ARG is a string describing breakpoint address,
7917    condition, and thread.
7918    FLAG specifies if a breakpoint is hardware on,
7919    and if breakpoint is temporary, using BP_HARDWARE_FLAG
7920    and BP_TEMPFLAG.  */
7921
7922 static void
7923 break_command_1 (char *arg, int flag, int from_tty)
7924 {
7925   int tempflag = flag & BP_TEMPFLAG;
7926   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
7927                              ? bp_hardware_breakpoint
7928                              : bp_breakpoint);
7929
7930   create_breakpoint (get_current_arch (),
7931                      arg,
7932                      NULL, 0, 1 /* parse arg */,
7933                      tempflag, type_wanted,
7934                      0 /* Ignore count */,
7935                      pending_break_support,
7936                      &bkpt_breakpoint_ops,
7937                      from_tty,
7938                      1 /* enabled */,
7939                      0 /* internal */);
7940 }
7941
7942 /* Helper function for break_command_1 and disassemble_command.  */
7943
7944 void
7945 resolve_sal_pc (struct symtab_and_line *sal)
7946 {
7947   CORE_ADDR pc;
7948
7949   if (sal->pc == 0 && sal->symtab != NULL)
7950     {
7951       if (!find_line_pc (sal->symtab, sal->line, &pc))
7952         error (_("No line %d in file \"%s\"."),
7953                sal->line, sal->symtab->filename);
7954       sal->pc = pc;
7955
7956       /* If this SAL corresponds to a breakpoint inserted using a line
7957          number, then skip the function prologue if necessary.  */
7958       if (sal->explicit_line)
7959         skip_prologue_sal (sal);
7960     }
7961
7962   if (sal->section == 0 && sal->symtab != NULL)
7963     {
7964       struct blockvector *bv;
7965       struct block *b;
7966       struct symbol *sym;
7967
7968       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
7969       if (bv != NULL)
7970         {
7971           sym = block_linkage_function (b);
7972           if (sym != NULL)
7973             {
7974               fixup_symbol_section (sym, sal->symtab->objfile);
7975               sal->section = SYMBOL_OBJ_SECTION (sym);
7976             }
7977           else
7978             {
7979               /* It really is worthwhile to have the section, so we'll
7980                  just have to look harder. This case can be executed
7981                  if we have line numbers but no functions (as can
7982                  happen in assembly source).  */
7983
7984               struct minimal_symbol *msym;
7985               struct cleanup *old_chain = save_current_space_and_thread ();
7986
7987               switch_to_program_space_and_thread (sal->pspace);
7988
7989               msym = lookup_minimal_symbol_by_pc (sal->pc);
7990               if (msym)
7991                 sal->section = SYMBOL_OBJ_SECTION (msym);
7992
7993               do_cleanups (old_chain);
7994             }
7995         }
7996     }
7997 }
7998
7999 void
8000 break_command (char *arg, int from_tty)
8001 {
8002   break_command_1 (arg, 0, from_tty);
8003 }
8004
8005 void
8006 tbreak_command (char *arg, int from_tty)
8007 {
8008   break_command_1 (arg, BP_TEMPFLAG, from_tty);
8009 }
8010
8011 static void
8012 hbreak_command (char *arg, int from_tty)
8013 {
8014   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
8015 }
8016
8017 static void
8018 thbreak_command (char *arg, int from_tty)
8019 {
8020   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
8021 }
8022
8023 static void
8024 stop_command (char *arg, int from_tty)
8025 {
8026   printf_filtered (_("Specify the type of breakpoint to set.\n\
8027 Usage: stop in <function | address>\n\
8028        stop at <line>\n"));
8029 }
8030
8031 static void
8032 stopin_command (char *arg, int from_tty)
8033 {
8034   int badInput = 0;
8035
8036   if (arg == (char *) NULL)
8037     badInput = 1;
8038   else if (*arg != '*')
8039     {
8040       char *argptr = arg;
8041       int hasColon = 0;
8042
8043       /* Look for a ':'.  If this is a line number specification, then
8044          say it is bad, otherwise, it should be an address or
8045          function/method name.  */
8046       while (*argptr && !hasColon)
8047         {
8048           hasColon = (*argptr == ':');
8049           argptr++;
8050         }
8051
8052       if (hasColon)
8053         badInput = (*argptr != ':');    /* Not a class::method */
8054       else
8055         badInput = isdigit (*arg);      /* a simple line number */
8056     }
8057
8058   if (badInput)
8059     printf_filtered (_("Usage: stop in <function | address>\n"));
8060   else
8061     break_command_1 (arg, 0, from_tty);
8062 }
8063
8064 static void
8065 stopat_command (char *arg, int from_tty)
8066 {
8067   int badInput = 0;
8068
8069   if (arg == (char *) NULL || *arg == '*')      /* no line number */
8070     badInput = 1;
8071   else
8072     {
8073       char *argptr = arg;
8074       int hasColon = 0;
8075
8076       /* Look for a ':'.  If there is a '::' then get out, otherwise
8077          it is probably a line number.  */
8078       while (*argptr && !hasColon)
8079         {
8080           hasColon = (*argptr == ':');
8081           argptr++;
8082         }
8083
8084       if (hasColon)
8085         badInput = (*argptr == ':');    /* we have class::method */
8086       else
8087         badInput = !isdigit (*arg);     /* not a line number */
8088     }
8089
8090   if (badInput)
8091     printf_filtered (_("Usage: stop at <line>\n"));
8092   else
8093     break_command_1 (arg, 0, from_tty);
8094 }
8095
8096 /* Implement the "breakpoint_hit" breakpoint_ops method for
8097    ranged breakpoints.  */
8098
8099 static int
8100 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
8101                                   struct address_space *aspace,
8102                                   CORE_ADDR bp_addr)
8103 {
8104   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
8105                                          bl->length, aspace, bp_addr);
8106 }
8107
8108 /* Implement the "resources_needed" breakpoint_ops method for
8109    ranged breakpoints.  */
8110
8111 static int
8112 resources_needed_ranged_breakpoint (const struct bp_location *bl)
8113 {
8114   return target_ranged_break_num_registers ();
8115 }
8116
8117 /* Implement the "print_it" breakpoint_ops method for
8118    ranged breakpoints.  */
8119
8120 static enum print_stop_action
8121 print_it_ranged_breakpoint (bpstat bs)
8122 {
8123   struct breakpoint *b = bs->breakpoint_at;
8124   struct bp_location *bl = b->loc;
8125   struct ui_out *uiout = current_uiout;
8126
8127   gdb_assert (b->type == bp_hardware_breakpoint);
8128
8129   /* Ranged breakpoints have only one location.  */
8130   gdb_assert (bl && bl->next == NULL);
8131
8132   annotate_breakpoint (b->number);
8133   if (b->disposition == disp_del)
8134     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
8135   else
8136     ui_out_text (uiout, "\nRanged breakpoint ");
8137   if (ui_out_is_mi_like_p (uiout))
8138     {
8139       ui_out_field_string (uiout, "reason",
8140                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
8141       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8142     }
8143   ui_out_field_int (uiout, "bkptno", b->number);
8144   ui_out_text (uiout, ", ");
8145
8146   return PRINT_SRC_AND_LOC;
8147 }
8148
8149 /* Implement the "print_one" breakpoint_ops method for
8150    ranged breakpoints.  */
8151
8152 static void
8153 print_one_ranged_breakpoint (struct breakpoint *b,
8154                              struct bp_location **last_loc)
8155 {
8156   struct bp_location *bl = b->loc;
8157   struct value_print_options opts;
8158   struct ui_out *uiout = current_uiout;
8159
8160   /* Ranged breakpoints have only one location.  */
8161   gdb_assert (bl && bl->next == NULL);
8162
8163   get_user_print_options (&opts);
8164
8165   if (opts.addressprint)
8166     /* We don't print the address range here, it will be printed later
8167        by print_one_detail_ranged_breakpoint.  */
8168     ui_out_field_skip (uiout, "addr");
8169   annotate_field (5);
8170   print_breakpoint_location (b, bl);
8171   *last_loc = bl;
8172 }
8173
8174 /* Implement the "print_one_detail" breakpoint_ops method for
8175    ranged breakpoints.  */
8176
8177 static void
8178 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
8179                                     struct ui_out *uiout)
8180 {
8181   CORE_ADDR address_start, address_end;
8182   struct bp_location *bl = b->loc;
8183   struct ui_stream *stb = ui_out_stream_new (uiout);
8184   struct cleanup *cleanup = make_cleanup_ui_out_stream_delete (stb);
8185
8186   gdb_assert (bl);
8187
8188   address_start = bl->address;
8189   address_end = address_start + bl->length - 1;
8190
8191   ui_out_text (uiout, "\taddress range: ");
8192   fprintf_unfiltered (stb->stream, "[%s, %s]",
8193                       print_core_address (bl->gdbarch, address_start),
8194                       print_core_address (bl->gdbarch, address_end));
8195   ui_out_field_stream (uiout, "addr", stb);
8196   ui_out_text (uiout, "\n");
8197
8198   do_cleanups (cleanup);
8199 }
8200
8201 /* Implement the "print_mention" breakpoint_ops method for
8202    ranged breakpoints.  */
8203
8204 static void
8205 print_mention_ranged_breakpoint (struct breakpoint *b)
8206 {
8207   struct bp_location *bl = b->loc;
8208   struct ui_out *uiout = current_uiout;
8209
8210   gdb_assert (bl);
8211   gdb_assert (b->type == bp_hardware_breakpoint);
8212
8213   if (ui_out_is_mi_like_p (uiout))
8214     return;
8215
8216   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
8217                    b->number, paddress (bl->gdbarch, bl->address),
8218                    paddress (bl->gdbarch, bl->address + bl->length - 1));
8219 }
8220
8221 /* Implement the "print_recreate" breakpoint_ops method for
8222    ranged breakpoints.  */
8223
8224 static void
8225 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
8226 {
8227   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
8228                       b->addr_string_range_end);
8229   print_recreate_thread (b, fp);
8230 }
8231
8232 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
8233
8234 static struct breakpoint_ops ranged_breakpoint_ops;
8235
8236 /* Find the address where the end of the breakpoint range should be
8237    placed, given the SAL of the end of the range.  This is so that if
8238    the user provides a line number, the end of the range is set to the
8239    last instruction of the given line.  */
8240
8241 static CORE_ADDR
8242 find_breakpoint_range_end (struct symtab_and_line sal)
8243 {
8244   CORE_ADDR end;
8245
8246   /* If the user provided a PC value, use it.  Otherwise,
8247      find the address of the end of the given location.  */
8248   if (sal.explicit_pc)
8249     end = sal.pc;
8250   else
8251     {
8252       int ret;
8253       CORE_ADDR start;
8254
8255       ret = find_line_pc_range (sal, &start, &end);
8256       if (!ret)
8257         error (_("Could not find location of the end of the range."));
8258
8259       /* find_line_pc_range returns the start of the next line.  */
8260       end--;
8261     }
8262
8263   return end;
8264 }
8265
8266 /* Implement the "break-range" CLI command.  */
8267
8268 static void
8269 break_range_command (char *arg, int from_tty)
8270 {
8271   char *arg_start, *addr_string_start, *addr_string_end;
8272   struct linespec_result canonical_start, canonical_end;
8273   int bp_count, can_use_bp, length;
8274   CORE_ADDR end;
8275   struct breakpoint *b;
8276   struct symtab_and_line sal_start, sal_end;
8277   struct cleanup *cleanup_bkpt;
8278   struct linespec_sals *lsal_start, *lsal_end;
8279
8280   /* We don't support software ranged breakpoints.  */
8281   if (target_ranged_break_num_registers () < 0)
8282     error (_("This target does not support hardware ranged breakpoints."));
8283
8284   bp_count = hw_breakpoint_used_count ();
8285   bp_count += target_ranged_break_num_registers ();
8286   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8287                                                    bp_count, 0);
8288   if (can_use_bp < 0)
8289     error (_("Hardware breakpoints used exceeds limit."));
8290
8291   arg = skip_spaces (arg);
8292   if (arg == NULL || arg[0] == '\0')
8293     error(_("No address range specified."));
8294
8295   init_linespec_result (&canonical_start);
8296
8297   arg_start = arg;
8298   parse_breakpoint_sals (&arg, &canonical_start);
8299
8300   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
8301
8302   if (arg[0] != ',')
8303     error (_("Too few arguments."));
8304   else if (VEC_empty (linespec_sals, canonical_start.sals))
8305     error (_("Could not find location of the beginning of the range."));
8306
8307   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
8308
8309   if (VEC_length (linespec_sals, canonical_start.sals) > 1
8310       || lsal_start->sals.nelts != 1)
8311     error (_("Cannot create a ranged breakpoint with multiple locations."));
8312
8313   sal_start = lsal_start->sals.sals[0];
8314   addr_string_start = savestring (arg_start, arg - arg_start);
8315   make_cleanup (xfree, addr_string_start);
8316
8317   arg++;        /* Skip the comma.  */
8318   arg = skip_spaces (arg);
8319
8320   /* Parse the end location.  */
8321
8322   init_linespec_result (&canonical_end);
8323   arg_start = arg;
8324
8325   /* We call decode_line_full directly here instead of using
8326      parse_breakpoint_sals because we need to specify the start location's
8327      symtab and line as the default symtab and line for the end of the
8328      range.  This makes it possible to have ranges like "foo.c:27, +14",
8329      where +14 means 14 lines from the start location.  */
8330   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
8331                     sal_start.symtab, sal_start.line,
8332                     &canonical_end, NULL, NULL);
8333
8334   make_cleanup_destroy_linespec_result (&canonical_end);
8335
8336   if (VEC_empty (linespec_sals, canonical_end.sals))
8337     error (_("Could not find location of the end of the range."));
8338
8339   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
8340   if (VEC_length (linespec_sals, canonical_end.sals) > 1
8341       || lsal_end->sals.nelts != 1)
8342     error (_("Cannot create a ranged breakpoint with multiple locations."));
8343
8344   sal_end = lsal_end->sals.sals[0];
8345   addr_string_end = savestring (arg_start, arg - arg_start);
8346   make_cleanup (xfree, addr_string_end);
8347
8348   end = find_breakpoint_range_end (sal_end);
8349   if (sal_start.pc > end)
8350     error (_("Invalid address range, end precedes start."));
8351
8352   length = end - sal_start.pc + 1;
8353   if (length < 0)
8354     /* Length overflowed.  */
8355     error (_("Address range too large."));
8356   else if (length == 1)
8357     {
8358       /* This range is simple enough to be handled by
8359          the `hbreak' command.  */
8360       hbreak_command (addr_string_start, 1);
8361
8362       do_cleanups (cleanup_bkpt);
8363
8364       return;
8365     }
8366
8367   /* Now set up the breakpoint.  */
8368   b = set_raw_breakpoint (get_current_arch (), sal_start,
8369                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
8370   set_breakpoint_count (breakpoint_count + 1);
8371   b->number = breakpoint_count;
8372   b->disposition = disp_donttouch;
8373   b->addr_string = xstrdup (addr_string_start);
8374   b->addr_string_range_end = xstrdup (addr_string_end);
8375   b->loc->length = length;
8376
8377   do_cleanups (cleanup_bkpt);
8378
8379   mention (b);
8380   observer_notify_breakpoint_created (b);
8381   update_global_location_list (1);
8382 }
8383
8384 /*  Return non-zero if EXP is verified as constant.  Returned zero
8385     means EXP is variable.  Also the constant detection may fail for
8386     some constant expressions and in such case still falsely return
8387     zero.  */
8388 static int
8389 watchpoint_exp_is_const (const struct expression *exp)
8390 {
8391   int i = exp->nelts;
8392
8393   while (i > 0)
8394     {
8395       int oplenp, argsp;
8396
8397       /* We are only interested in the descriptor of each element.  */
8398       operator_length (exp, i, &oplenp, &argsp);
8399       i -= oplenp;
8400
8401       switch (exp->elts[i].opcode)
8402         {
8403         case BINOP_ADD:
8404         case BINOP_SUB:
8405         case BINOP_MUL:
8406         case BINOP_DIV:
8407         case BINOP_REM:
8408         case BINOP_MOD:
8409         case BINOP_LSH:
8410         case BINOP_RSH:
8411         case BINOP_LOGICAL_AND:
8412         case BINOP_LOGICAL_OR:
8413         case BINOP_BITWISE_AND:
8414         case BINOP_BITWISE_IOR:
8415         case BINOP_BITWISE_XOR:
8416         case BINOP_EQUAL:
8417         case BINOP_NOTEQUAL:
8418         case BINOP_LESS:
8419         case BINOP_GTR:
8420         case BINOP_LEQ:
8421         case BINOP_GEQ:
8422         case BINOP_REPEAT:
8423         case BINOP_COMMA:
8424         case BINOP_EXP:
8425         case BINOP_MIN:
8426         case BINOP_MAX:
8427         case BINOP_INTDIV:
8428         case BINOP_CONCAT:
8429         case BINOP_IN:
8430         case BINOP_RANGE:
8431         case TERNOP_COND:
8432         case TERNOP_SLICE:
8433         case TERNOP_SLICE_COUNT:
8434
8435         case OP_LONG:
8436         case OP_DOUBLE:
8437         case OP_DECFLOAT:
8438         case OP_LAST:
8439         case OP_COMPLEX:
8440         case OP_STRING:
8441         case OP_BITSTRING:
8442         case OP_ARRAY:
8443         case OP_TYPE:
8444         case OP_NAME:
8445         case OP_OBJC_NSSTRING:
8446
8447         case UNOP_NEG:
8448         case UNOP_LOGICAL_NOT:
8449         case UNOP_COMPLEMENT:
8450         case UNOP_ADDR:
8451         case UNOP_HIGH:
8452           /* Unary, binary and ternary operators: We have to check
8453              their operands.  If they are constant, then so is the
8454              result of that operation.  For instance, if A and B are
8455              determined to be constants, then so is "A + B".
8456
8457              UNOP_IND is one exception to the rule above, because the
8458              value of *ADDR is not necessarily a constant, even when
8459              ADDR is.  */
8460           break;
8461
8462         case OP_VAR_VALUE:
8463           /* Check whether the associated symbol is a constant.
8464
8465              We use SYMBOL_CLASS rather than TYPE_CONST because it's
8466              possible that a buggy compiler could mark a variable as
8467              constant even when it is not, and TYPE_CONST would return
8468              true in this case, while SYMBOL_CLASS wouldn't.
8469
8470              We also have to check for function symbols because they
8471              are always constant.  */
8472           {
8473             struct symbol *s = exp->elts[i + 2].symbol;
8474
8475             if (SYMBOL_CLASS (s) != LOC_BLOCK
8476                 && SYMBOL_CLASS (s) != LOC_CONST
8477                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
8478               return 0;
8479             break;
8480           }
8481
8482         /* The default action is to return 0 because we are using
8483            the optimistic approach here: If we don't know something,
8484            then it is not a constant.  */
8485         default:
8486           return 0;
8487         }
8488     }
8489
8490   return 1;
8491 }
8492
8493 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
8494
8495 static void
8496 dtor_watchpoint (struct breakpoint *self)
8497 {
8498   struct watchpoint *w = (struct watchpoint *) self;
8499
8500   xfree (w->cond_exp);
8501   xfree (w->exp);
8502   xfree (w->exp_string);
8503   xfree (w->exp_string_reparse);
8504   value_free (w->val);
8505
8506   base_breakpoint_ops.dtor (self);
8507 }
8508
8509 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
8510
8511 static void
8512 re_set_watchpoint (struct breakpoint *b)
8513 {
8514   struct watchpoint *w = (struct watchpoint *) b;
8515
8516   /* Watchpoint can be either on expression using entirely global
8517      variables, or it can be on local variables.
8518
8519      Watchpoints of the first kind are never auto-deleted, and even
8520      persist across program restarts.  Since they can use variables
8521      from shared libraries, we need to reparse expression as libraries
8522      are loaded and unloaded.
8523
8524      Watchpoints on local variables can also change meaning as result
8525      of solib event.  For example, if a watchpoint uses both a local
8526      and a global variables in expression, it's a local watchpoint,
8527      but unloading of a shared library will make the expression
8528      invalid.  This is not a very common use case, but we still
8529      re-evaluate expression, to avoid surprises to the user.
8530
8531      Note that for local watchpoints, we re-evaluate it only if
8532      watchpoints frame id is still valid.  If it's not, it means the
8533      watchpoint is out of scope and will be deleted soon.  In fact,
8534      I'm not sure we'll ever be called in this case.
8535
8536      If a local watchpoint's frame id is still valid, then
8537      w->exp_valid_block is likewise valid, and we can safely use it.
8538
8539      Don't do anything about disabled watchpoints, since they will be
8540      reevaluated again when enabled.  */
8541   update_watchpoint (w, 1 /* reparse */);
8542 }
8543
8544 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
8545
8546 static int
8547 insert_watchpoint (struct bp_location *bl)
8548 {
8549   struct watchpoint *w = (struct watchpoint *) bl->owner;
8550   int length = w->exact ? 1 : bl->length;
8551
8552   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
8553                                    w->cond_exp);
8554 }
8555
8556 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
8557
8558 static int
8559 remove_watchpoint (struct bp_location *bl)
8560 {
8561   struct watchpoint *w = (struct watchpoint *) bl->owner;
8562   int length = w->exact ? 1 : bl->length;
8563
8564   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
8565                                    w->cond_exp);
8566 }
8567
8568 static int
8569 breakpoint_hit_watchpoint (const struct bp_location *bl,
8570                            struct address_space *aspace, CORE_ADDR bp_addr)
8571 {
8572   struct breakpoint *b = bl->owner;
8573   struct watchpoint *w = (struct watchpoint *) b;
8574
8575   /* Continuable hardware watchpoints are treated as non-existent if the
8576      reason we stopped wasn't a hardware watchpoint (we didn't stop on
8577      some data address).  Otherwise gdb won't stop on a break instruction
8578      in the code (not from a breakpoint) when a hardware watchpoint has
8579      been defined.  Also skip watchpoints which we know did not trigger
8580      (did not match the data address).  */
8581   if (is_hardware_watchpoint (b)
8582       && w->watchpoint_triggered == watch_triggered_no)
8583     return 0;
8584
8585   return 1;
8586 }
8587
8588 static void
8589 check_status_watchpoint (bpstat bs)
8590 {
8591   gdb_assert (is_watchpoint (bs->breakpoint_at));
8592
8593   bpstat_check_watchpoint (bs);
8594 }
8595
8596 /* Implement the "resources_needed" breakpoint_ops method for
8597    hardware watchpoints.  */
8598
8599 static int
8600 resources_needed_watchpoint (const struct bp_location *bl)
8601 {
8602   struct watchpoint *w = (struct watchpoint *) bl->owner;
8603   int length = w->exact? 1 : bl->length;
8604
8605   return target_region_ok_for_hw_watchpoint (bl->address, length);
8606 }
8607
8608 /* Implement the "works_in_software_mode" breakpoint_ops method for
8609    hardware watchpoints.  */
8610
8611 static int
8612 works_in_software_mode_watchpoint (const struct breakpoint *b)
8613 {
8614   /* Read and access watchpoints only work with hardware support.  */
8615   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
8616 }
8617
8618 static enum print_stop_action
8619 print_it_watchpoint (bpstat bs)
8620 {
8621   struct cleanup *old_chain;
8622   struct breakpoint *b;
8623   const struct bp_location *bl;
8624   struct ui_stream *stb;
8625   enum print_stop_action result;
8626   struct watchpoint *w;
8627   struct ui_out *uiout = current_uiout;
8628
8629   gdb_assert (bs->bp_location_at != NULL);
8630
8631   bl = bs->bp_location_at;
8632   b = bs->breakpoint_at;
8633   w = (struct watchpoint *) b;
8634
8635   stb = ui_out_stream_new (uiout);
8636   old_chain = make_cleanup_ui_out_stream_delete (stb);
8637
8638   switch (b->type)
8639     {
8640     case bp_watchpoint:
8641     case bp_hardware_watchpoint:
8642       annotate_watchpoint (b->number);
8643       if (ui_out_is_mi_like_p (uiout))
8644         ui_out_field_string
8645           (uiout, "reason",
8646            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
8647       mention (b);
8648       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
8649       ui_out_text (uiout, "\nOld value = ");
8650       watchpoint_value_print (bs->old_val, stb->stream);
8651       ui_out_field_stream (uiout, "old", stb);
8652       ui_out_text (uiout, "\nNew value = ");
8653       watchpoint_value_print (w->val, stb->stream);
8654       ui_out_field_stream (uiout, "new", stb);
8655       ui_out_text (uiout, "\n");
8656       /* More than one watchpoint may have been triggered.  */
8657       result = PRINT_UNKNOWN;
8658       break;
8659
8660     case bp_read_watchpoint:
8661       if (ui_out_is_mi_like_p (uiout))
8662         ui_out_field_string
8663           (uiout, "reason",
8664            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
8665       mention (b);
8666       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
8667       ui_out_text (uiout, "\nValue = ");
8668       watchpoint_value_print (w->val, stb->stream);
8669       ui_out_field_stream (uiout, "value", stb);
8670       ui_out_text (uiout, "\n");
8671       result = PRINT_UNKNOWN;
8672       break;
8673
8674     case bp_access_watchpoint:
8675       if (bs->old_val != NULL)
8676         {
8677           annotate_watchpoint (b->number);
8678           if (ui_out_is_mi_like_p (uiout))
8679             ui_out_field_string
8680               (uiout, "reason",
8681                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
8682           mention (b);
8683           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
8684           ui_out_text (uiout, "\nOld value = ");
8685           watchpoint_value_print (bs->old_val, stb->stream);
8686           ui_out_field_stream (uiout, "old", stb);
8687           ui_out_text (uiout, "\nNew value = ");
8688         }
8689       else
8690         {
8691           mention (b);
8692           if (ui_out_is_mi_like_p (uiout))
8693             ui_out_field_string
8694               (uiout, "reason",
8695                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
8696           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
8697           ui_out_text (uiout, "\nValue = ");
8698         }
8699       watchpoint_value_print (w->val, stb->stream);
8700       ui_out_field_stream (uiout, "new", stb);
8701       ui_out_text (uiout, "\n");
8702       result = PRINT_UNKNOWN;
8703       break;
8704     default:
8705       result = PRINT_UNKNOWN;
8706     }
8707
8708   do_cleanups (old_chain);
8709   return result;
8710 }
8711
8712 /* Implement the "print_mention" breakpoint_ops method for hardware
8713    watchpoints.  */
8714
8715 static void
8716 print_mention_watchpoint (struct breakpoint *b)
8717 {
8718   struct cleanup *ui_out_chain;
8719   struct watchpoint *w = (struct watchpoint *) b;
8720   struct ui_out *uiout = current_uiout;
8721
8722   switch (b->type)
8723     {
8724     case bp_watchpoint:
8725       ui_out_text (uiout, "Watchpoint ");
8726       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
8727       break;
8728     case bp_hardware_watchpoint:
8729       ui_out_text (uiout, "Hardware watchpoint ");
8730       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
8731       break;
8732     case bp_read_watchpoint:
8733       ui_out_text (uiout, "Hardware read watchpoint ");
8734       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
8735       break;
8736     case bp_access_watchpoint:
8737       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
8738       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
8739       break;
8740     default:
8741       internal_error (__FILE__, __LINE__,
8742                       _("Invalid hardware watchpoint type."));
8743     }
8744
8745   ui_out_field_int (uiout, "number", b->number);
8746   ui_out_text (uiout, ": ");
8747   ui_out_field_string (uiout, "exp", w->exp_string);
8748   do_cleanups (ui_out_chain);
8749 }
8750
8751 /* Implement the "print_recreate" breakpoint_ops method for
8752    watchpoints.  */
8753
8754 static void
8755 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
8756 {
8757   struct watchpoint *w = (struct watchpoint *) b;
8758
8759   switch (b->type)
8760     {
8761     case bp_watchpoint:
8762     case bp_hardware_watchpoint:
8763       fprintf_unfiltered (fp, "watch");
8764       break;
8765     case bp_read_watchpoint:
8766       fprintf_unfiltered (fp, "rwatch");
8767       break;
8768     case bp_access_watchpoint:
8769       fprintf_unfiltered (fp, "awatch");
8770       break;
8771     default:
8772       internal_error (__FILE__, __LINE__,
8773                       _("Invalid watchpoint type."));
8774     }
8775
8776   fprintf_unfiltered (fp, " %s", w->exp_string);
8777   print_recreate_thread (b, fp);
8778 }
8779
8780 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
8781
8782 static struct breakpoint_ops watchpoint_breakpoint_ops;
8783
8784 /* Implement the "insert" breakpoint_ops method for
8785    masked hardware watchpoints.  */
8786
8787 static int
8788 insert_masked_watchpoint (struct bp_location *bl)
8789 {
8790   struct watchpoint *w = (struct watchpoint *) bl->owner;
8791
8792   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
8793                                         bl->watchpoint_type);
8794 }
8795
8796 /* Implement the "remove" breakpoint_ops method for
8797    masked hardware watchpoints.  */
8798
8799 static int
8800 remove_masked_watchpoint (struct bp_location *bl)
8801 {
8802   struct watchpoint *w = (struct watchpoint *) bl->owner;
8803
8804   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
8805                                         bl->watchpoint_type);
8806 }
8807
8808 /* Implement the "resources_needed" breakpoint_ops method for
8809    masked hardware watchpoints.  */
8810
8811 static int
8812 resources_needed_masked_watchpoint (const struct bp_location *bl)
8813 {
8814   struct watchpoint *w = (struct watchpoint *) bl->owner;
8815
8816   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
8817 }
8818
8819 /* Implement the "works_in_software_mode" breakpoint_ops method for
8820    masked hardware watchpoints.  */
8821
8822 static int
8823 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
8824 {
8825   return 0;
8826 }
8827
8828 /* Implement the "print_it" breakpoint_ops method for
8829    masked hardware watchpoints.  */
8830
8831 static enum print_stop_action
8832 print_it_masked_watchpoint (bpstat bs)
8833 {
8834   struct breakpoint *b = bs->breakpoint_at;
8835   struct ui_out *uiout = current_uiout;
8836
8837   /* Masked watchpoints have only one location.  */
8838   gdb_assert (b->loc && b->loc->next == NULL);
8839
8840   switch (b->type)
8841     {
8842     case bp_hardware_watchpoint:
8843       annotate_watchpoint (b->number);
8844       if (ui_out_is_mi_like_p (uiout))
8845         ui_out_field_string
8846           (uiout, "reason",
8847            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
8848       break;
8849
8850     case bp_read_watchpoint:
8851       if (ui_out_is_mi_like_p (uiout))
8852         ui_out_field_string
8853           (uiout, "reason",
8854            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
8855       break;
8856
8857     case bp_access_watchpoint:
8858       if (ui_out_is_mi_like_p (uiout))
8859         ui_out_field_string
8860           (uiout, "reason",
8861            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
8862       break;
8863     default:
8864       internal_error (__FILE__, __LINE__,
8865                       _("Invalid hardware watchpoint type."));
8866     }
8867
8868   mention (b);
8869   ui_out_text (uiout, _("\n\
8870 Check the underlying instruction at PC for the memory\n\
8871 address and value which triggered this watchpoint.\n"));
8872   ui_out_text (uiout, "\n");
8873
8874   /* More than one watchpoint may have been triggered.  */
8875   return PRINT_UNKNOWN;
8876 }
8877
8878 /* Implement the "print_one_detail" breakpoint_ops method for
8879    masked hardware watchpoints.  */
8880
8881 static void
8882 print_one_detail_masked_watchpoint (const struct breakpoint *b,
8883                                     struct ui_out *uiout)
8884 {
8885   struct watchpoint *w = (struct watchpoint *) b;
8886
8887   /* Masked watchpoints have only one location.  */
8888   gdb_assert (b->loc && b->loc->next == NULL);
8889
8890   ui_out_text (uiout, "\tmask ");
8891   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
8892   ui_out_text (uiout, "\n");
8893 }
8894
8895 /* Implement the "print_mention" breakpoint_ops method for
8896    masked hardware watchpoints.  */
8897
8898 static void
8899 print_mention_masked_watchpoint (struct breakpoint *b)
8900 {
8901   struct watchpoint *w = (struct watchpoint *) b;
8902   struct ui_out *uiout = current_uiout;
8903   struct cleanup *ui_out_chain;
8904
8905   switch (b->type)
8906     {
8907     case bp_hardware_watchpoint:
8908       ui_out_text (uiout, "Masked hardware watchpoint ");
8909       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
8910       break;
8911     case bp_read_watchpoint:
8912       ui_out_text (uiout, "Masked hardware read watchpoint ");
8913       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
8914       break;
8915     case bp_access_watchpoint:
8916       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
8917       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
8918       break;
8919     default:
8920       internal_error (__FILE__, __LINE__,
8921                       _("Invalid hardware watchpoint type."));
8922     }
8923
8924   ui_out_field_int (uiout, "number", b->number);
8925   ui_out_text (uiout, ": ");
8926   ui_out_field_string (uiout, "exp", w->exp_string);
8927   do_cleanups (ui_out_chain);
8928 }
8929
8930 /* Implement the "print_recreate" breakpoint_ops method for
8931    masked hardware watchpoints.  */
8932
8933 static void
8934 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
8935 {
8936   struct watchpoint *w = (struct watchpoint *) b;
8937   char tmp[40];
8938
8939   switch (b->type)
8940     {
8941     case bp_hardware_watchpoint:
8942       fprintf_unfiltered (fp, "watch");
8943       break;
8944     case bp_read_watchpoint:
8945       fprintf_unfiltered (fp, "rwatch");
8946       break;
8947     case bp_access_watchpoint:
8948       fprintf_unfiltered (fp, "awatch");
8949       break;
8950     default:
8951       internal_error (__FILE__, __LINE__,
8952                       _("Invalid hardware watchpoint type."));
8953     }
8954
8955   sprintf_vma (tmp, w->hw_wp_mask);
8956   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
8957   print_recreate_thread (b, fp);
8958 }
8959
8960 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
8961
8962 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
8963
8964 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
8965
8966 static int
8967 is_masked_watchpoint (const struct breakpoint *b)
8968 {
8969   return b->ops == &masked_watchpoint_breakpoint_ops;
8970 }
8971
8972 /* accessflag:  hw_write:  watch write, 
8973                 hw_read:   watch read, 
8974                 hw_access: watch access (read or write) */
8975 static void
8976 watch_command_1 (char *arg, int accessflag, int from_tty,
8977                  int just_location, int internal)
8978 {
8979   volatile struct gdb_exception e;
8980   struct breakpoint *b, *scope_breakpoint = NULL;
8981   struct expression *exp;
8982   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
8983   struct value *val, *mark, *result;
8984   struct frame_info *frame;
8985   char *exp_start = NULL;
8986   char *exp_end = NULL;
8987   char *tok, *end_tok;
8988   int toklen = -1;
8989   char *cond_start = NULL;
8990   char *cond_end = NULL;
8991   enum bptype bp_type;
8992   int thread = -1;
8993   int pc = 0;
8994   /* Flag to indicate whether we are going to use masks for
8995      the hardware watchpoint.  */
8996   int use_mask = 0;
8997   CORE_ADDR mask = 0;
8998   struct watchpoint *w;
8999
9000   /* Make sure that we actually have parameters to parse.  */
9001   if (arg != NULL && arg[0] != '\0')
9002     {
9003       char *value_start;
9004
9005       /* Look for "parameter value" pairs at the end
9006          of the arguments string.  */
9007       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
9008         {
9009           /* Skip whitespace at the end of the argument list.  */
9010           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9011             tok--;
9012
9013           /* Find the beginning of the last token.
9014              This is the value of the parameter.  */
9015           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9016             tok--;
9017           value_start = tok + 1;
9018
9019           /* Skip whitespace.  */
9020           while (tok > arg && (*tok == ' ' || *tok == '\t'))
9021             tok--;
9022
9023           end_tok = tok;
9024
9025           /* Find the beginning of the second to last token.
9026              This is the parameter itself.  */
9027           while (tok > arg && (*tok != ' ' && *tok != '\t'))
9028             tok--;
9029           tok++;
9030           toklen = end_tok - tok + 1;
9031
9032           if (toklen == 6 && !strncmp (tok, "thread", 6))
9033             {
9034               /* At this point we've found a "thread" token, which means
9035                  the user is trying to set a watchpoint that triggers
9036                  only in a specific thread.  */
9037               char *endp;
9038
9039               if (thread != -1)
9040                 error(_("You can specify only one thread."));
9041
9042               /* Extract the thread ID from the next token.  */
9043               thread = strtol (value_start, &endp, 0);
9044
9045               /* Check if the user provided a valid numeric value for the
9046                  thread ID.  */
9047               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
9048                 error (_("Invalid thread ID specification %s."), value_start);
9049
9050               /* Check if the thread actually exists.  */
9051               if (!valid_thread_id (thread))
9052                 error (_("Unknown thread %d."), thread);
9053             }
9054           else if (toklen == 4 && !strncmp (tok, "mask", 4))
9055             {
9056               /* We've found a "mask" token, which means the user wants to
9057                  create a hardware watchpoint that is going to have the mask
9058                  facility.  */
9059               struct value *mask_value, *mark;
9060
9061               if (use_mask)
9062                 error(_("You can specify only one mask."));
9063
9064               use_mask = just_location = 1;
9065
9066               mark = value_mark ();
9067               mask_value = parse_to_comma_and_eval (&value_start);
9068               mask = value_as_address (mask_value);
9069               value_free_to_mark (mark);
9070             }
9071           else
9072             /* We didn't recognize what we found.  We should stop here.  */
9073             break;
9074
9075           /* Truncate the string and get rid of the "parameter value" pair before
9076              the arguments string is parsed by the parse_exp_1 function.  */
9077           *tok = '\0';
9078         }
9079     }
9080
9081   /* Parse the rest of the arguments.  */
9082   innermost_block = NULL;
9083   exp_start = arg;
9084   exp = parse_exp_1 (&arg, 0, 0);
9085   exp_end = arg;
9086   /* Remove trailing whitespace from the expression before saving it.
9087      This makes the eventual display of the expression string a bit
9088      prettier.  */
9089   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
9090     --exp_end;
9091
9092   /* Checking if the expression is not constant.  */
9093   if (watchpoint_exp_is_const (exp))
9094     {
9095       int len;
9096
9097       len = exp_end - exp_start;
9098       while (len > 0 && isspace (exp_start[len - 1]))
9099         len--;
9100       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
9101     }
9102
9103   exp_valid_block = innermost_block;
9104   mark = value_mark ();
9105   fetch_subexp_value (exp, &pc, &val, &result, NULL);
9106
9107   if (just_location)
9108     {
9109       int ret;
9110
9111       exp_valid_block = NULL;
9112       val = value_addr (result);
9113       release_value (val);
9114       value_free_to_mark (mark);
9115
9116       if (use_mask)
9117         {
9118           ret = target_masked_watch_num_registers (value_as_address (val),
9119                                                    mask);
9120           if (ret == -1)
9121             error (_("This target does not support masked watchpoints."));
9122           else if (ret == -2)
9123             error (_("Invalid mask or memory region."));
9124         }
9125     }
9126   else if (val != NULL)
9127     release_value (val);
9128
9129   tok = skip_spaces (arg);
9130   end_tok = skip_to_space (tok);
9131
9132   toklen = end_tok - tok;
9133   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
9134     {
9135       struct expression *cond;
9136
9137       innermost_block = NULL;
9138       tok = cond_start = end_tok + 1;
9139       cond = parse_exp_1 (&tok, 0, 0);
9140
9141       /* The watchpoint expression may not be local, but the condition
9142          may still be.  E.g.: `watch global if local > 0'.  */
9143       cond_exp_valid_block = innermost_block;
9144
9145       xfree (cond);
9146       cond_end = tok;
9147     }
9148   if (*tok)
9149     error (_("Junk at end of command."));
9150
9151   if (accessflag == hw_read)
9152     bp_type = bp_read_watchpoint;
9153   else if (accessflag == hw_access)
9154     bp_type = bp_access_watchpoint;
9155   else
9156     bp_type = bp_hardware_watchpoint;
9157
9158   frame = block_innermost_frame (exp_valid_block);
9159
9160   /* If the expression is "local", then set up a "watchpoint scope"
9161      breakpoint at the point where we've left the scope of the watchpoint
9162      expression.  Create the scope breakpoint before the watchpoint, so
9163      that we will encounter it first in bpstat_stop_status.  */
9164   if (exp_valid_block && frame)
9165     {
9166       if (frame_id_p (frame_unwind_caller_id (frame)))
9167         {
9168           scope_breakpoint
9169             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
9170                                           frame_unwind_caller_pc (frame),
9171                                           bp_watchpoint_scope,
9172                                           &momentary_breakpoint_ops);
9173
9174           scope_breakpoint->enable_state = bp_enabled;
9175
9176           /* Automatically delete the breakpoint when it hits.  */
9177           scope_breakpoint->disposition = disp_del;
9178
9179           /* Only break in the proper frame (help with recursion).  */
9180           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
9181
9182           /* Set the address at which we will stop.  */
9183           scope_breakpoint->loc->gdbarch
9184             = frame_unwind_caller_arch (frame);
9185           scope_breakpoint->loc->requested_address
9186             = frame_unwind_caller_pc (frame);
9187           scope_breakpoint->loc->address
9188             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
9189                                          scope_breakpoint->loc->requested_address,
9190                                          scope_breakpoint->type);
9191         }
9192     }
9193
9194   /* Now set up the breakpoint.  */
9195
9196   w = XCNEW (struct watchpoint);
9197   b = &w->base;
9198   if (use_mask)
9199     init_raw_breakpoint_without_location (b, NULL, bp_type,
9200                                           &masked_watchpoint_breakpoint_ops);
9201   else
9202     init_raw_breakpoint_without_location (b, NULL, bp_type,
9203                                           &watchpoint_breakpoint_ops);
9204   b->thread = thread;
9205   b->disposition = disp_donttouch;
9206   b->pspace = current_program_space;
9207   w->exp = exp;
9208   w->exp_valid_block = exp_valid_block;
9209   w->cond_exp_valid_block = cond_exp_valid_block;
9210   if (just_location)
9211     {
9212       struct type *t = value_type (val);
9213       CORE_ADDR addr = value_as_address (val);
9214       char *name;
9215
9216       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
9217       name = type_to_string (t);
9218
9219       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
9220                                           core_addr_to_string (addr));
9221       xfree (name);
9222
9223       w->exp_string = xstrprintf ("-location %.*s",
9224                                   (int) (exp_end - exp_start), exp_start);
9225
9226       /* The above expression is in C.  */
9227       b->language = language_c;
9228     }
9229   else
9230     w->exp_string = savestring (exp_start, exp_end - exp_start);
9231
9232   if (use_mask)
9233     {
9234       w->hw_wp_mask = mask;
9235     }
9236   else
9237     {
9238       w->val = val;
9239       w->val_valid = 1;
9240     }
9241
9242   if (cond_start)
9243     b->cond_string = savestring (cond_start, cond_end - cond_start);
9244   else
9245     b->cond_string = 0;
9246
9247   if (frame)
9248     {
9249       w->watchpoint_frame = get_frame_id (frame);
9250       w->watchpoint_thread = inferior_ptid;
9251     }
9252   else
9253     {
9254       w->watchpoint_frame = null_frame_id;
9255       w->watchpoint_thread = null_ptid;
9256     }
9257
9258   if (scope_breakpoint != NULL)
9259     {
9260       /* The scope breakpoint is related to the watchpoint.  We will
9261          need to act on them together.  */
9262       b->related_breakpoint = scope_breakpoint;
9263       scope_breakpoint->related_breakpoint = b;
9264     }
9265
9266   if (!just_location)
9267     value_free_to_mark (mark);
9268
9269   TRY_CATCH (e, RETURN_MASK_ALL)
9270     {
9271       /* Finally update the new watchpoint.  This creates the locations
9272          that should be inserted.  */
9273       update_watchpoint (w, 1);
9274     }
9275   if (e.reason < 0)
9276     {
9277       delete_breakpoint (b);
9278       throw_exception (e);
9279     }
9280
9281   install_breakpoint (internal, b, 1);
9282 }
9283
9284 /* Return count of debug registers needed to watch the given expression.
9285    If the watchpoint cannot be handled in hardware return zero.  */
9286
9287 static int
9288 can_use_hardware_watchpoint (struct value *v)
9289 {
9290   int found_memory_cnt = 0;
9291   struct value *head = v;
9292
9293   /* Did the user specifically forbid us to use hardware watchpoints? */
9294   if (!can_use_hw_watchpoints)
9295     return 0;
9296
9297   /* Make sure that the value of the expression depends only upon
9298      memory contents, and values computed from them within GDB.  If we
9299      find any register references or function calls, we can't use a
9300      hardware watchpoint.
9301
9302      The idea here is that evaluating an expression generates a series
9303      of values, one holding the value of every subexpression.  (The
9304      expression a*b+c has five subexpressions: a, b, a*b, c, and
9305      a*b+c.)  GDB's values hold almost enough information to establish
9306      the criteria given above --- they identify memory lvalues,
9307      register lvalues, computed values, etcetera.  So we can evaluate
9308      the expression, and then scan the chain of values that leaves
9309      behind to decide whether we can detect any possible change to the
9310      expression's final value using only hardware watchpoints.
9311
9312      However, I don't think that the values returned by inferior
9313      function calls are special in any way.  So this function may not
9314      notice that an expression involving an inferior function call
9315      can't be watched with hardware watchpoints.  FIXME.  */
9316   for (; v; v = value_next (v))
9317     {
9318       if (VALUE_LVAL (v) == lval_memory)
9319         {
9320           if (v != head && value_lazy (v))
9321             /* A lazy memory lvalue in the chain is one that GDB never
9322                needed to fetch; we either just used its address (e.g.,
9323                `a' in `a.b') or we never needed it at all (e.g., `a'
9324                in `a,b').  This doesn't apply to HEAD; if that is
9325                lazy then it was not readable, but watch it anyway.  */
9326             ;
9327           else
9328             {
9329               /* Ahh, memory we actually used!  Check if we can cover
9330                  it with hardware watchpoints.  */
9331               struct type *vtype = check_typedef (value_type (v));
9332
9333               /* We only watch structs and arrays if user asked for it
9334                  explicitly, never if they just happen to appear in a
9335                  middle of some value chain.  */
9336               if (v == head
9337                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
9338                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
9339                 {
9340                   CORE_ADDR vaddr = value_address (v);
9341                   int len;
9342                   int num_regs;
9343
9344                   len = (target_exact_watchpoints
9345                          && is_scalar_type_recursive (vtype))?
9346                     1 : TYPE_LENGTH (value_type (v));
9347
9348                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
9349                   if (!num_regs)
9350                     return 0;
9351                   else
9352                     found_memory_cnt += num_regs;
9353                 }
9354             }
9355         }
9356       else if (VALUE_LVAL (v) != not_lval
9357                && deprecated_value_modifiable (v) == 0)
9358         return 0;       /* These are values from the history (e.g., $1).  */
9359       else if (VALUE_LVAL (v) == lval_register)
9360         return 0;       /* Cannot watch a register with a HW watchpoint.  */
9361     }
9362
9363   /* The expression itself looks suitable for using a hardware
9364      watchpoint, but give the target machine a chance to reject it.  */
9365   return found_memory_cnt;
9366 }
9367
9368 void
9369 watch_command_wrapper (char *arg, int from_tty, int internal)
9370 {
9371   watch_command_1 (arg, hw_write, from_tty, 0, internal);
9372 }
9373
9374 /* A helper function that looks for an argument at the start of a
9375    string.  The argument must also either be at the end of the string,
9376    or be followed by whitespace.  Returns 1 if it finds the argument,
9377    0 otherwise.  If the argument is found, it updates *STR.  */
9378
9379 static int
9380 check_for_argument (char **str, char *arg, int arg_len)
9381 {
9382   if (strncmp (*str, arg, arg_len) == 0
9383       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
9384     {
9385       *str += arg_len;
9386       return 1;
9387     }
9388   return 0;
9389 }
9390
9391 /* A helper function that looks for the "-location" argument and then
9392    calls watch_command_1.  */
9393
9394 static void
9395 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
9396 {
9397   int just_location = 0;
9398
9399   if (arg
9400       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
9401           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
9402     {
9403       arg = skip_spaces (arg);
9404       just_location = 1;
9405     }
9406
9407   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
9408 }
9409
9410 static void
9411 watch_command (char *arg, int from_tty)
9412 {
9413   watch_maybe_just_location (arg, hw_write, from_tty);
9414 }
9415
9416 void
9417 rwatch_command_wrapper (char *arg, int from_tty, int internal)
9418 {
9419   watch_command_1 (arg, hw_read, from_tty, 0, internal);
9420 }
9421
9422 static void
9423 rwatch_command (char *arg, int from_tty)
9424 {
9425   watch_maybe_just_location (arg, hw_read, from_tty);
9426 }
9427
9428 void
9429 awatch_command_wrapper (char *arg, int from_tty, int internal)
9430 {
9431   watch_command_1 (arg, hw_access, from_tty, 0, internal);
9432 }
9433
9434 static void
9435 awatch_command (char *arg, int from_tty)
9436 {
9437   watch_maybe_just_location (arg, hw_access, from_tty);
9438 }
9439 \f
9440
9441 /* Helper routines for the until_command routine in infcmd.c.  Here
9442    because it uses the mechanisms of breakpoints.  */
9443
9444 struct until_break_command_continuation_args
9445 {
9446   struct breakpoint *breakpoint;
9447   struct breakpoint *breakpoint2;
9448   int thread_num;
9449 };
9450
9451 /* This function is called by fetch_inferior_event via the
9452    cmd_continuation pointer, to complete the until command.  It takes
9453    care of cleaning up the temporary breakpoints set up by the until
9454    command.  */
9455 static void
9456 until_break_command_continuation (void *arg, int err)
9457 {
9458   struct until_break_command_continuation_args *a = arg;
9459
9460   delete_breakpoint (a->breakpoint);
9461   if (a->breakpoint2)
9462     delete_breakpoint (a->breakpoint2);
9463   delete_longjmp_breakpoint (a->thread_num);
9464 }
9465
9466 void
9467 until_break_command (char *arg, int from_tty, int anywhere)
9468 {
9469   struct symtabs_and_lines sals;
9470   struct symtab_and_line sal;
9471   struct frame_info *frame = get_selected_frame (NULL);
9472   struct breakpoint *breakpoint;
9473   struct breakpoint *breakpoint2 = NULL;
9474   struct cleanup *old_chain;
9475   int thread;
9476   struct thread_info *tp;
9477
9478   clear_proceed_status ();
9479
9480   /* Set a breakpoint where the user wants it and at return from
9481      this function.  */
9482
9483   if (last_displayed_sal_is_valid ())
9484     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
9485                           get_last_displayed_symtab (),
9486                           get_last_displayed_line ());
9487   else
9488     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
9489                           (struct symtab *) NULL, 0);
9490
9491   if (sals.nelts != 1)
9492     error (_("Couldn't get information on specified line."));
9493
9494   sal = sals.sals[0];
9495   xfree (sals.sals);    /* malloc'd, so freed.  */
9496
9497   if (*arg)
9498     error (_("Junk at end of arguments."));
9499
9500   resolve_sal_pc (&sal);
9501
9502   if (anywhere)
9503     /* If the user told us to continue until a specified location,
9504        we don't specify a frame at which we need to stop.  */
9505     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
9506                                            null_frame_id, bp_until);
9507   else
9508     /* Otherwise, specify the selected frame, because we want to stop
9509        only at the very same frame.  */
9510     breakpoint = set_momentary_breakpoint (get_frame_arch (frame), sal,
9511                                            get_stack_frame_id (frame),
9512                                            bp_until);
9513
9514   old_chain = make_cleanup_delete_breakpoint (breakpoint);
9515
9516   tp = inferior_thread ();
9517   thread = tp->num;
9518
9519   /* Keep within the current frame, or in frames called by the current
9520      one.  */
9521
9522   if (frame_id_p (frame_unwind_caller_id (frame)))
9523     {
9524       sal = find_pc_line (frame_unwind_caller_pc (frame), 0);
9525       sal.pc = frame_unwind_caller_pc (frame);
9526       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
9527                                               sal,
9528                                               frame_unwind_caller_id (frame),
9529                                               bp_until);
9530       make_cleanup_delete_breakpoint (breakpoint2);
9531
9532       set_longjmp_breakpoint (tp, frame_unwind_caller_id (frame));
9533       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
9534     }
9535
9536   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
9537
9538   /* If we are running asynchronously, and proceed call above has
9539      actually managed to start the target, arrange for breakpoints to
9540      be deleted when the target stops.  Otherwise, we're already
9541      stopped and delete breakpoints via cleanup chain.  */
9542
9543   if (target_can_async_p () && is_running (inferior_ptid))
9544     {
9545       struct until_break_command_continuation_args *args;
9546       args = xmalloc (sizeof (*args));
9547
9548       args->breakpoint = breakpoint;
9549       args->breakpoint2 = breakpoint2;
9550       args->thread_num = thread;
9551
9552       discard_cleanups (old_chain);
9553       add_continuation (inferior_thread (),
9554                         until_break_command_continuation, args,
9555                         xfree);
9556     }
9557   else
9558     do_cleanups (old_chain);
9559 }
9560
9561 /* This function attempts to parse an optional "if <cond>" clause
9562    from the arg string.  If one is not found, it returns NULL.
9563
9564    Else, it returns a pointer to the condition string.  (It does not
9565    attempt to evaluate the string against a particular block.)  And,
9566    it updates arg to point to the first character following the parsed
9567    if clause in the arg string.  */
9568
9569 static char *
9570 ep_parse_optional_if_clause (char **arg)
9571 {
9572   char *cond_string;
9573
9574   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
9575     return NULL;
9576
9577   /* Skip the "if" keyword.  */
9578   (*arg) += 2;
9579
9580   /* Skip any extra leading whitespace, and record the start of the
9581      condition string.  */
9582   *arg = skip_spaces (*arg);
9583   cond_string = *arg;
9584
9585   /* Assume that the condition occupies the remainder of the arg
9586      string.  */
9587   (*arg) += strlen (cond_string);
9588
9589   return cond_string;
9590 }
9591
9592 /* Commands to deal with catching events, such as signals, exceptions,
9593    process start/exit, etc.  */
9594
9595 typedef enum
9596 {
9597   catch_fork_temporary, catch_vfork_temporary,
9598   catch_fork_permanent, catch_vfork_permanent
9599 }
9600 catch_fork_kind;
9601
9602 static void
9603 catch_fork_command_1 (char *arg, int from_tty, 
9604                       struct cmd_list_element *command)
9605 {
9606   struct gdbarch *gdbarch = get_current_arch ();
9607   char *cond_string = NULL;
9608   catch_fork_kind fork_kind;
9609   int tempflag;
9610
9611   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
9612   tempflag = (fork_kind == catch_fork_temporary
9613               || fork_kind == catch_vfork_temporary);
9614
9615   if (!arg)
9616     arg = "";
9617   arg = skip_spaces (arg);
9618
9619   /* The allowed syntax is:
9620      catch [v]fork
9621      catch [v]fork if <cond>
9622
9623      First, check if there's an if clause.  */
9624   cond_string = ep_parse_optional_if_clause (&arg);
9625
9626   if ((*arg != '\0') && !isspace (*arg))
9627     error (_("Junk at end of arguments."));
9628
9629   /* If this target supports it, create a fork or vfork catchpoint
9630      and enable reporting of such events.  */
9631   switch (fork_kind)
9632     {
9633     case catch_fork_temporary:
9634     case catch_fork_permanent:
9635       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
9636                                           &catch_fork_breakpoint_ops);
9637       break;
9638     case catch_vfork_temporary:
9639     case catch_vfork_permanent:
9640       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
9641                                           &catch_vfork_breakpoint_ops);
9642       break;
9643     default:
9644       error (_("unsupported or unknown fork kind; cannot catch it"));
9645       break;
9646     }
9647 }
9648
9649 static void
9650 catch_exec_command_1 (char *arg, int from_tty, 
9651                       struct cmd_list_element *command)
9652 {
9653   struct exec_catchpoint *c;
9654   struct gdbarch *gdbarch = get_current_arch ();
9655   int tempflag;
9656   char *cond_string = NULL;
9657
9658   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
9659
9660   if (!arg)
9661     arg = "";
9662   arg = skip_spaces (arg);
9663
9664   /* The allowed syntax is:
9665      catch exec
9666      catch exec if <cond>
9667
9668      First, check if there's an if clause.  */
9669   cond_string = ep_parse_optional_if_clause (&arg);
9670
9671   if ((*arg != '\0') && !isspace (*arg))
9672     error (_("Junk at end of arguments."));
9673
9674   c = XNEW (struct exec_catchpoint);
9675   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
9676                    &catch_exec_breakpoint_ops);
9677   c->exec_pathname = NULL;
9678
9679   install_breakpoint (0, &c->base, 1);
9680 }
9681
9682 static enum print_stop_action
9683 print_it_exception_catchpoint (bpstat bs)
9684 {
9685   struct ui_out *uiout = current_uiout;
9686   struct breakpoint *b = bs->breakpoint_at;
9687   int bp_temp, bp_throw;
9688
9689   annotate_catchpoint (b->number);
9690
9691   bp_throw = strstr (b->addr_string, "throw") != NULL;
9692   if (b->loc->address != b->loc->requested_address)
9693     breakpoint_adjustment_warning (b->loc->requested_address,
9694                                    b->loc->address,
9695                                    b->number, 1);
9696   bp_temp = b->disposition == disp_del;
9697   ui_out_text (uiout, 
9698                bp_temp ? "Temporary catchpoint "
9699                        : "Catchpoint ");
9700   if (!ui_out_is_mi_like_p (uiout))
9701     ui_out_field_int (uiout, "bkptno", b->number);
9702   ui_out_text (uiout,
9703                bp_throw ? " (exception thrown), "
9704                         : " (exception caught), ");
9705   if (ui_out_is_mi_like_p (uiout))
9706     {
9707       ui_out_field_string (uiout, "reason", 
9708                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9709       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9710       ui_out_field_int (uiout, "bkptno", b->number);
9711     }
9712   return PRINT_SRC_AND_LOC;
9713 }
9714
9715 static void
9716 print_one_exception_catchpoint (struct breakpoint *b, 
9717                                 struct bp_location **last_loc)
9718 {
9719   struct value_print_options opts;
9720   struct ui_out *uiout = current_uiout;
9721
9722   get_user_print_options (&opts);
9723   if (opts.addressprint)
9724     {
9725       annotate_field (4);
9726       if (b->loc == NULL || b->loc->shlib_disabled)
9727         ui_out_field_string (uiout, "addr", "<PENDING>");
9728       else
9729         ui_out_field_core_addr (uiout, "addr",
9730                                 b->loc->gdbarch, b->loc->address);
9731     }
9732   annotate_field (5);
9733   if (b->loc)
9734     *last_loc = b->loc;
9735   if (strstr (b->addr_string, "throw") != NULL)
9736     ui_out_field_string (uiout, "what", "exception throw");
9737   else
9738     ui_out_field_string (uiout, "what", "exception catch");
9739 }
9740
9741 static void
9742 print_mention_exception_catchpoint (struct breakpoint *b)
9743 {
9744   struct ui_out *uiout = current_uiout;
9745   int bp_temp;
9746   int bp_throw;
9747
9748   bp_temp = b->disposition == disp_del;
9749   bp_throw = strstr (b->addr_string, "throw") != NULL;
9750   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
9751                               : _("Catchpoint "));
9752   ui_out_field_int (uiout, "bkptno", b->number);
9753   ui_out_text (uiout, bp_throw ? _(" (throw)")
9754                                : _(" (catch)"));
9755 }
9756
9757 /* Implement the "print_recreate" breakpoint_ops method for throw and
9758    catch catchpoints.  */
9759
9760 static void
9761 print_recreate_exception_catchpoint (struct breakpoint *b, 
9762                                      struct ui_file *fp)
9763 {
9764   int bp_temp;
9765   int bp_throw;
9766
9767   bp_temp = b->disposition == disp_del;
9768   bp_throw = strstr (b->addr_string, "throw") != NULL;
9769   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
9770   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
9771   print_recreate_thread (b, fp);
9772 }
9773
9774 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
9775
9776 static int
9777 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
9778                           enum exception_event_kind ex_event, int from_tty)
9779 {
9780   char *trigger_func_name;
9781  
9782   if (ex_event == EX_EVENT_CATCH)
9783     trigger_func_name = "__cxa_begin_catch";
9784   else
9785     trigger_func_name = "__cxa_throw";
9786
9787   create_breakpoint (get_current_arch (),
9788                      trigger_func_name, cond_string, -1,
9789                      0 /* condition and thread are valid.  */,
9790                      tempflag, bp_breakpoint,
9791                      0,
9792                      AUTO_BOOLEAN_TRUE /* pending */,
9793                      &gnu_v3_exception_catchpoint_ops, from_tty,
9794                      1 /* enabled */,
9795                      0 /* internal */);
9796
9797   return 1;
9798 }
9799
9800 /* Deal with "catch catch" and "catch throw" commands.  */
9801
9802 static void
9803 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
9804                            int tempflag, int from_tty)
9805 {
9806   char *cond_string = NULL;
9807
9808   if (!arg)
9809     arg = "";
9810   arg = skip_spaces (arg);
9811
9812   cond_string = ep_parse_optional_if_clause (&arg);
9813
9814   if ((*arg != '\0') && !isspace (*arg))
9815     error (_("Junk at end of arguments."));
9816
9817   if (ex_event != EX_EVENT_THROW
9818       && ex_event != EX_EVENT_CATCH)
9819     error (_("Unsupported or unknown exception event; cannot catch it"));
9820
9821   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
9822     return;
9823
9824   warning (_("Unsupported with this platform/compiler combination."));
9825 }
9826
9827 /* Implementation of "catch catch" command.  */
9828
9829 static void
9830 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
9831 {
9832   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
9833
9834   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
9835 }
9836
9837 /* Implementation of "catch throw" command.  */
9838
9839 static void
9840 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
9841 {
9842   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
9843
9844   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
9845 }
9846
9847 void
9848 init_ada_exception_breakpoint (struct breakpoint *b,
9849                                struct gdbarch *gdbarch,
9850                                struct symtab_and_line sal,
9851                                char *addr_string,
9852                                const struct breakpoint_ops *ops,
9853                                int tempflag,
9854                                int from_tty)
9855 {
9856   if (from_tty)
9857     {
9858       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
9859       if (!loc_gdbarch)
9860         loc_gdbarch = gdbarch;
9861
9862       describe_other_breakpoints (loc_gdbarch,
9863                                   sal.pspace, sal.pc, sal.section, -1);
9864       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
9865          version for exception catchpoints, because two catchpoints
9866          used for different exception names will use the same address.
9867          In this case, a "breakpoint ... also set at..." warning is
9868          unproductive.  Besides, the warning phrasing is also a bit
9869          inappropriate, we should use the word catchpoint, and tell
9870          the user what type of catchpoint it is.  The above is good
9871          enough for now, though.  */
9872     }
9873
9874   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
9875
9876   b->enable_state = bp_enabled;
9877   b->disposition = tempflag ? disp_del : disp_donttouch;
9878   b->addr_string = addr_string;
9879   b->language = language_ada;
9880 }
9881
9882 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
9883    filter list, or NULL if no filtering is required.  */
9884 static VEC(int) *
9885 catch_syscall_split_args (char *arg)
9886 {
9887   VEC(int) *result = NULL;
9888   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
9889
9890   while (*arg != '\0')
9891     {
9892       int i, syscall_number;
9893       char *endptr;
9894       char cur_name[128];
9895       struct syscall s;
9896
9897       /* Skip whitespace.  */
9898       while (isspace (*arg))
9899         arg++;
9900
9901       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
9902         cur_name[i] = arg[i];
9903       cur_name[i] = '\0';
9904       arg += i;
9905
9906       /* Check if the user provided a syscall name or a number.  */
9907       syscall_number = (int) strtol (cur_name, &endptr, 0);
9908       if (*endptr == '\0')
9909         get_syscall_by_number (syscall_number, &s);
9910       else
9911         {
9912           /* We have a name.  Let's check if it's valid and convert it
9913              to a number.  */
9914           get_syscall_by_name (cur_name, &s);
9915
9916           if (s.number == UNKNOWN_SYSCALL)
9917             /* Here we have to issue an error instead of a warning,
9918                because GDB cannot do anything useful if there's no
9919                syscall number to be caught.  */
9920             error (_("Unknown syscall name '%s'."), cur_name);
9921         }
9922
9923       /* Ok, it's valid.  */
9924       VEC_safe_push (int, result, s.number);
9925     }
9926
9927   discard_cleanups (cleanup);
9928   return result;
9929 }
9930
9931 /* Implement the "catch syscall" command.  */
9932
9933 static void
9934 catch_syscall_command_1 (char *arg, int from_tty, 
9935                          struct cmd_list_element *command)
9936 {
9937   int tempflag;
9938   VEC(int) *filter;
9939   struct syscall s;
9940   struct gdbarch *gdbarch = get_current_arch ();
9941
9942   /* Checking if the feature if supported.  */
9943   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
9944     error (_("The feature 'catch syscall' is not supported on \
9945 this architecture yet."));
9946
9947   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
9948
9949   arg = skip_spaces (arg);
9950
9951   /* We need to do this first "dummy" translation in order
9952      to get the syscall XML file loaded or, most important,
9953      to display a warning to the user if there's no XML file
9954      for his/her architecture.  */
9955   get_syscall_by_number (0, &s);
9956
9957   /* The allowed syntax is:
9958      catch syscall
9959      catch syscall <name | number> [<name | number> ... <name | number>]
9960
9961      Let's check if there's a syscall name.  */
9962
9963   if (arg != NULL)
9964     filter = catch_syscall_split_args (arg);
9965   else
9966     filter = NULL;
9967
9968   create_syscall_event_catchpoint (tempflag, filter,
9969                                    &catch_syscall_breakpoint_ops);
9970 }
9971
9972 static void
9973 catch_command (char *arg, int from_tty)
9974 {
9975   error (_("Catch requires an event name."));
9976 }
9977 \f
9978
9979 static void
9980 tcatch_command (char *arg, int from_tty)
9981 {
9982   error (_("Catch requires an event name."));
9983 }
9984
9985 /* A qsort comparison function that sorts breakpoints in order.  */
9986
9987 static int
9988 compare_breakpoints (const void *a, const void *b)
9989 {
9990   const breakpoint_p *ba = a;
9991   uintptr_t ua = (uintptr_t) *ba;
9992   const breakpoint_p *bb = b;
9993   uintptr_t ub = (uintptr_t) *bb;
9994
9995   if ((*ba)->number < (*bb)->number)
9996     return -1;
9997   else if ((*ba)->number > (*bb)->number)
9998     return 1;
9999
10000   /* Now sort by address, in case we see, e..g, two breakpoints with
10001      the number 0.  */
10002   if (ua < ub)
10003     return -1;
10004   return ub > ub ? 1 : 0;
10005 }
10006
10007 /* Delete breakpoints by address or line.  */
10008
10009 static void
10010 clear_command (char *arg, int from_tty)
10011 {
10012   struct breakpoint *b, *prev;
10013   VEC(breakpoint_p) *found = 0;
10014   int ix;
10015   int default_match;
10016   struct symtabs_and_lines sals;
10017   struct symtab_and_line sal;
10018   int i;
10019   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
10020
10021   if (arg)
10022     {
10023       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
10024                                      | DECODE_LINE_LIST_MODE));
10025       default_match = 0;
10026     }
10027   else
10028     {
10029       sals.sals = (struct symtab_and_line *)
10030         xmalloc (sizeof (struct symtab_and_line));
10031       make_cleanup (xfree, sals.sals);
10032       init_sal (&sal);          /* Initialize to zeroes.  */
10033
10034       /* Set sal's line, symtab, pc, and pspace to the values
10035          corresponding to the last call to print_frame_info.  If the
10036          codepoint is not valid, this will set all the fields to 0.  */
10037       get_last_displayed_sal (&sal);
10038       if (sal.symtab == 0)
10039         error (_("No source file specified."));
10040
10041       sals.sals[0] = sal;
10042       sals.nelts = 1;
10043
10044       default_match = 1;
10045     }
10046
10047   /* We don't call resolve_sal_pc here.  That's not as bad as it
10048      seems, because all existing breakpoints typically have both
10049      file/line and pc set.  So, if clear is given file/line, we can
10050      match this to existing breakpoint without obtaining pc at all.
10051
10052      We only support clearing given the address explicitly 
10053      present in breakpoint table.  Say, we've set breakpoint 
10054      at file:line.  There were several PC values for that file:line,
10055      due to optimization, all in one block.
10056
10057      We've picked one PC value.  If "clear" is issued with another
10058      PC corresponding to the same file:line, the breakpoint won't
10059      be cleared.  We probably can still clear the breakpoint, but 
10060      since the other PC value is never presented to user, user
10061      can only find it by guessing, and it does not seem important
10062      to support that.  */
10063
10064   /* For each line spec given, delete bps which correspond to it.  Do
10065      it in two passes, solely to preserve the current behavior that
10066      from_tty is forced true if we delete more than one
10067      breakpoint.  */
10068
10069   found = NULL;
10070   make_cleanup (VEC_cleanup (breakpoint_p), &found);
10071   for (i = 0; i < sals.nelts; i++)
10072     {
10073       int is_abs, sal_name_len;
10074
10075       /* If exact pc given, clear bpts at that pc.
10076          If line given (pc == 0), clear all bpts on specified line.
10077          If defaulting, clear all bpts on default line
10078          or at default pc.
10079
10080          defaulting    sal.pc != 0    tests to do
10081
10082          0              1             pc
10083          1              1             pc _and_ line
10084          0              0             line
10085          1              0             <can't happen> */
10086
10087       sal = sals.sals[i];
10088       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
10089       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
10090
10091       /* Find all matching breakpoints and add them to 'found'.  */
10092       ALL_BREAKPOINTS (b)
10093         {
10094           int match = 0;
10095           /* Are we going to delete b?  */
10096           if (b->type != bp_none && !is_watchpoint (b))
10097             {
10098               struct bp_location *loc = b->loc;
10099               for (; loc; loc = loc->next)
10100                 {
10101                   /* If the user specified file:line, don't allow a PC
10102                      match.  This matches historical gdb behavior.  */
10103                   int pc_match = (!sal.explicit_line
10104                                   && sal.pc
10105                                   && (loc->pspace == sal.pspace)
10106                                   && (loc->address == sal.pc)
10107                                   && (!section_is_overlay (loc->section)
10108                                       || loc->section == sal.section));
10109                   int line_match = 0;
10110
10111                   if ((default_match || sal.explicit_line)
10112                       && loc->source_file != NULL
10113                       && sal.symtab != NULL
10114                       && sal.pspace == loc->pspace
10115                       && loc->line_number == sal.line)
10116                     {
10117                       if (filename_cmp (loc->source_file,
10118                                         sal.symtab->filename) == 0)
10119                         line_match = 1;
10120                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
10121                                && compare_filenames_for_search (loc->source_file,
10122                                                                 sal.symtab->filename,
10123                                                                 sal_name_len))
10124                         line_match = 1;
10125                     }
10126
10127                   if (pc_match || line_match)
10128                     {
10129                       match = 1;
10130                       break;
10131                     }
10132                 }
10133             }
10134
10135           if (match)
10136             VEC_safe_push(breakpoint_p, found, b);
10137         }
10138     }
10139
10140   /* Now go thru the 'found' chain and delete them.  */
10141   if (VEC_empty(breakpoint_p, found))
10142     {
10143       if (arg)
10144         error (_("No breakpoint at %s."), arg);
10145       else
10146         error (_("No breakpoint at this line."));
10147     }
10148
10149   /* Remove duplicates from the vec.  */
10150   qsort (VEC_address (breakpoint_p, found),
10151          VEC_length (breakpoint_p, found),
10152          sizeof (breakpoint_p),
10153          compare_breakpoints);
10154   prev = VEC_index (breakpoint_p, found, 0);
10155   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
10156     {
10157       if (b == prev)
10158         {
10159           VEC_ordered_remove (breakpoint_p, found, ix);
10160           --ix;
10161         }
10162     }
10163
10164   if (VEC_length(breakpoint_p, found) > 1)
10165     from_tty = 1;       /* Always report if deleted more than one.  */
10166   if (from_tty)
10167     {
10168       if (VEC_length(breakpoint_p, found) == 1)
10169         printf_unfiltered (_("Deleted breakpoint "));
10170       else
10171         printf_unfiltered (_("Deleted breakpoints "));
10172     }
10173   breakpoints_changed ();
10174
10175   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
10176     {
10177       if (from_tty)
10178         printf_unfiltered ("%d ", b->number);
10179       delete_breakpoint (b);
10180     }
10181   if (from_tty)
10182     putchar_unfiltered ('\n');
10183
10184   do_cleanups (cleanups);
10185 }
10186 \f
10187 /* Delete breakpoint in BS if they are `delete' breakpoints and
10188    all breakpoints that are marked for deletion, whether hit or not.
10189    This is called after any breakpoint is hit, or after errors.  */
10190
10191 void
10192 breakpoint_auto_delete (bpstat bs)
10193 {
10194   struct breakpoint *b, *b_tmp;
10195
10196   for (; bs; bs = bs->next)
10197     if (bs->breakpoint_at
10198         && bs->breakpoint_at->disposition == disp_del
10199         && bs->stop)
10200       delete_breakpoint (bs->breakpoint_at);
10201
10202   ALL_BREAKPOINTS_SAFE (b, b_tmp)
10203   {
10204     if (b->disposition == disp_del_at_next_stop)
10205       delete_breakpoint (b);
10206   }
10207 }
10208
10209 /* A comparison function for bp_location AP and BP being interfaced to
10210    qsort.  Sort elements primarily by their ADDRESS (no matter what
10211    does breakpoint_address_is_meaningful say for its OWNER),
10212    secondarily by ordering first bp_permanent OWNERed elements and
10213    terciarily just ensuring the array is sorted stable way despite
10214    qsort being an unstable algorithm.  */
10215
10216 static int
10217 bp_location_compare (const void *ap, const void *bp)
10218 {
10219   struct bp_location *a = *(void **) ap;
10220   struct bp_location *b = *(void **) bp;
10221   /* A and B come from existing breakpoints having non-NULL OWNER.  */
10222   int a_perm = a->owner->enable_state == bp_permanent;
10223   int b_perm = b->owner->enable_state == bp_permanent;
10224
10225   if (a->address != b->address)
10226     return (a->address > b->address) - (a->address < b->address);
10227
10228   /* Sort permanent breakpoints first.  */
10229   if (a_perm != b_perm)
10230     return (a_perm < b_perm) - (a_perm > b_perm);
10231
10232   /* Make the user-visible order stable across GDB runs.  Locations of
10233      the same breakpoint can be sorted in arbitrary order.  */
10234
10235   if (a->owner->number != b->owner->number)
10236     return (a->owner->number > b->owner->number)
10237            - (a->owner->number < b->owner->number);
10238
10239   return (a > b) - (a < b);
10240 }
10241
10242 /* Set bp_location_placed_address_before_address_max and
10243    bp_location_shadow_len_after_address_max according to the current
10244    content of the bp_location array.  */
10245
10246 static void
10247 bp_location_target_extensions_update (void)
10248 {
10249   struct bp_location *bl, **blp_tmp;
10250
10251   bp_location_placed_address_before_address_max = 0;
10252   bp_location_shadow_len_after_address_max = 0;
10253
10254   ALL_BP_LOCATIONS (bl, blp_tmp)
10255     {
10256       CORE_ADDR start, end, addr;
10257
10258       if (!bp_location_has_shadow (bl))
10259         continue;
10260
10261       start = bl->target_info.placed_address;
10262       end = start + bl->target_info.shadow_len;
10263
10264       gdb_assert (bl->address >= start);
10265       addr = bl->address - start;
10266       if (addr > bp_location_placed_address_before_address_max)
10267         bp_location_placed_address_before_address_max = addr;
10268
10269       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
10270
10271       gdb_assert (bl->address < end);
10272       addr = end - bl->address;
10273       if (addr > bp_location_shadow_len_after_address_max)
10274         bp_location_shadow_len_after_address_max = addr;
10275     }
10276 }
10277
10278 /* Download tracepoint locations if they haven't been.  */
10279
10280 static void
10281 download_tracepoint_locations (void)
10282 {
10283   struct bp_location *bl, **blp_tmp;
10284   struct cleanup *old_chain;
10285
10286   if (!target_can_download_tracepoint ())
10287     return;
10288
10289   old_chain = save_current_space_and_thread ();
10290
10291   ALL_BP_LOCATIONS (bl, blp_tmp)
10292     {
10293       struct tracepoint *t;
10294
10295       if (!is_tracepoint (bl->owner))
10296         continue;
10297
10298       if ((bl->owner->type == bp_fast_tracepoint
10299            ? !may_insert_fast_tracepoints
10300            : !may_insert_tracepoints))
10301         continue;
10302
10303       /* In tracepoint, locations are _never_ duplicated, so
10304          should_be_inserted is equivalent to
10305          unduplicated_should_be_inserted.  */
10306       if (!should_be_inserted (bl) || bl->inserted)
10307         continue;
10308
10309       switch_to_program_space_and_thread (bl->pspace);
10310
10311       target_download_tracepoint (bl);
10312
10313       bl->inserted = 1;
10314       t = (struct tracepoint *) bl->owner;
10315       t->number_on_target = bl->owner->number;
10316     }
10317
10318   do_cleanups (old_chain);
10319 }
10320
10321 /* Swap the insertion/duplication state between two locations.  */
10322
10323 static void
10324 swap_insertion (struct bp_location *left, struct bp_location *right)
10325 {
10326   const int left_inserted = left->inserted;
10327   const int left_duplicate = left->duplicate;
10328   const struct bp_target_info left_target_info = left->target_info;
10329
10330   /* Locations of tracepoints can never be duplicated.  */
10331   if (is_tracepoint (left->owner))
10332     gdb_assert (!left->duplicate);
10333   if (is_tracepoint (right->owner))
10334     gdb_assert (!right->duplicate);
10335
10336   left->inserted = right->inserted;
10337   left->duplicate = right->duplicate;
10338   left->target_info = right->target_info;
10339   right->inserted = left_inserted;
10340   right->duplicate = left_duplicate;
10341   right->target_info = left_target_info;
10342 }
10343
10344 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
10345    into the inferior, only remove already-inserted locations that no
10346    longer should be inserted.  Functions that delete a breakpoint or
10347    breakpoints should pass false, so that deleting a breakpoint
10348    doesn't have the side effect of inserting the locations of other
10349    breakpoints that are marked not-inserted, but should_be_inserted
10350    returns true on them.
10351
10352    This behaviour is useful is situations close to tear-down -- e.g.,
10353    after an exec, while the target still has execution, but breakpoint
10354    shadows of the previous executable image should *NOT* be restored
10355    to the new image; or before detaching, where the target still has
10356    execution and wants to delete breakpoints from GDB's lists, and all
10357    breakpoints had already been removed from the inferior.  */
10358
10359 static void
10360 update_global_location_list (int should_insert)
10361 {
10362   struct breakpoint *b;
10363   struct bp_location **locp, *loc;
10364   struct cleanup *cleanups;
10365
10366   /* Used in the duplicates detection below.  When iterating over all
10367      bp_locations, points to the first bp_location of a given address.
10368      Breakpoints and watchpoints of different types are never
10369      duplicates of each other.  Keep one pointer for each type of
10370      breakpoint/watchpoint, so we only need to loop over all locations
10371      once.  */
10372   struct bp_location *bp_loc_first;  /* breakpoint */
10373   struct bp_location *wp_loc_first;  /* hardware watchpoint */
10374   struct bp_location *awp_loc_first; /* access watchpoint */
10375   struct bp_location *rwp_loc_first; /* read watchpoint */
10376
10377   /* Saved former bp_location array which we compare against the newly
10378      built bp_location from the current state of ALL_BREAKPOINTS.  */
10379   struct bp_location **old_location, **old_locp;
10380   unsigned old_location_count;
10381
10382   old_location = bp_location;
10383   old_location_count = bp_location_count;
10384   bp_location = NULL;
10385   bp_location_count = 0;
10386   cleanups = make_cleanup (xfree, old_location);
10387
10388   ALL_BREAKPOINTS (b)
10389     for (loc = b->loc; loc; loc = loc->next)
10390       bp_location_count++;
10391
10392   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
10393   locp = bp_location;
10394   ALL_BREAKPOINTS (b)
10395     for (loc = b->loc; loc; loc = loc->next)
10396       *locp++ = loc;
10397   qsort (bp_location, bp_location_count, sizeof (*bp_location),
10398          bp_location_compare);
10399
10400   bp_location_target_extensions_update ();
10401
10402   /* Identify bp_location instances that are no longer present in the
10403      new list, and therefore should be freed.  Note that it's not
10404      necessary that those locations should be removed from inferior --
10405      if there's another location at the same address (previously
10406      marked as duplicate), we don't need to remove/insert the
10407      location.
10408      
10409      LOCP is kept in sync with OLD_LOCP, each pointing to the current
10410      and former bp_location array state respectively.  */
10411
10412   locp = bp_location;
10413   for (old_locp = old_location; old_locp < old_location + old_location_count;
10414        old_locp++)
10415     {
10416       struct bp_location *old_loc = *old_locp;
10417       struct bp_location **loc2p;
10418
10419       /* Tells if 'old_loc' is found among the new locations.  If
10420          not, we have to free it.  */
10421       int found_object = 0;
10422       /* Tells if the location should remain inserted in the target.  */
10423       int keep_in_target = 0;
10424       int removed = 0;
10425
10426       /* Skip LOCP entries which will definitely never be needed.
10427          Stop either at or being the one matching OLD_LOC.  */
10428       while (locp < bp_location + bp_location_count
10429              && (*locp)->address < old_loc->address)
10430         locp++;
10431
10432       for (loc2p = locp;
10433            (loc2p < bp_location + bp_location_count
10434             && (*loc2p)->address == old_loc->address);
10435            loc2p++)
10436         {
10437           if (*loc2p == old_loc)
10438             {
10439               found_object = 1;
10440               break;
10441             }
10442         }
10443
10444       /* If this location is no longer present, and inserted, look if
10445          there's maybe a new location at the same address.  If so,
10446          mark that one inserted, and don't remove this one.  This is
10447          needed so that we don't have a time window where a breakpoint
10448          at certain location is not inserted.  */
10449
10450       if (old_loc->inserted)
10451         {
10452           /* If the location is inserted now, we might have to remove
10453              it.  */
10454
10455           if (found_object && should_be_inserted (old_loc))
10456             {
10457               /* The location is still present in the location list,
10458                  and still should be inserted.  Don't do anything.  */
10459               keep_in_target = 1;
10460             }
10461           else
10462             {
10463               /* The location is either no longer present, or got
10464                  disabled.  See if there's another location at the
10465                  same address, in which case we don't need to remove
10466                  this one from the target.  */
10467
10468               /* OLD_LOC comes from existing struct breakpoint.  */
10469               if (breakpoint_address_is_meaningful (old_loc->owner))
10470                 {
10471                   for (loc2p = locp;
10472                        (loc2p < bp_location + bp_location_count
10473                         && (*loc2p)->address == old_loc->address);
10474                        loc2p++)
10475                     {
10476                       struct bp_location *loc2 = *loc2p;
10477
10478                       if (breakpoint_locations_match (loc2, old_loc))
10479                         {
10480                           /* Read watchpoint locations are switched to
10481                              access watchpoints, if the former are not
10482                              supported, but the latter are.  */
10483                           if (is_hardware_watchpoint (old_loc->owner))
10484                             {
10485                               gdb_assert (is_hardware_watchpoint (loc2->owner));
10486                               loc2->watchpoint_type = old_loc->watchpoint_type;
10487                             }
10488
10489                           /* loc2 is a duplicated location. We need to check
10490                              if it should be inserted in case it will be
10491                              unduplicated.  */
10492                           if (loc2 != old_loc
10493                               && unduplicated_should_be_inserted (loc2))
10494                             {
10495                               swap_insertion (old_loc, loc2);
10496                               keep_in_target = 1;
10497                               break;
10498                             }
10499                         }
10500                     }
10501                 }
10502             }
10503
10504           if (!keep_in_target)
10505             {
10506               if (remove_breakpoint (old_loc, mark_uninserted))
10507                 {
10508                   /* This is just about all we can do.  We could keep
10509                      this location on the global list, and try to
10510                      remove it next time, but there's no particular
10511                      reason why we will succeed next time.
10512                      
10513                      Note that at this point, old_loc->owner is still
10514                      valid, as delete_breakpoint frees the breakpoint
10515                      only after calling us.  */
10516                   printf_filtered (_("warning: Error removing "
10517                                      "breakpoint %d\n"), 
10518                                    old_loc->owner->number);
10519                 }
10520               removed = 1;
10521             }
10522         }
10523
10524       if (!found_object)
10525         {
10526           if (removed && non_stop
10527               && breakpoint_address_is_meaningful (old_loc->owner)
10528               && !is_hardware_watchpoint (old_loc->owner))
10529             {
10530               /* This location was removed from the target.  In
10531                  non-stop mode, a race condition is possible where
10532                  we've removed a breakpoint, but stop events for that
10533                  breakpoint are already queued and will arrive later.
10534                  We apply an heuristic to be able to distinguish such
10535                  SIGTRAPs from other random SIGTRAPs: we keep this
10536                  breakpoint location for a bit, and will retire it
10537                  after we see some number of events.  The theory here
10538                  is that reporting of events should, "on the average",
10539                  be fair, so after a while we'll see events from all
10540                  threads that have anything of interest, and no longer
10541                  need to keep this breakpoint location around.  We
10542                  don't hold locations forever so to reduce chances of
10543                  mistaking a non-breakpoint SIGTRAP for a breakpoint
10544                  SIGTRAP.
10545
10546                  The heuristic failing can be disastrous on
10547                  decr_pc_after_break targets.
10548
10549                  On decr_pc_after_break targets, like e.g., x86-linux,
10550                  if we fail to recognize a late breakpoint SIGTRAP,
10551                  because events_till_retirement has reached 0 too
10552                  soon, we'll fail to do the PC adjustment, and report
10553                  a random SIGTRAP to the user.  When the user resumes
10554                  the inferior, it will most likely immediately crash
10555                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
10556                  corrupted, because of being resumed e.g., in the
10557                  middle of a multi-byte instruction, or skipped a
10558                  one-byte instruction.  This was actually seen happen
10559                  on native x86-linux, and should be less rare on
10560                  targets that do not support new thread events, like
10561                  remote, due to the heuristic depending on
10562                  thread_count.
10563
10564                  Mistaking a random SIGTRAP for a breakpoint trap
10565                  causes similar symptoms (PC adjustment applied when
10566                  it shouldn't), but then again, playing with SIGTRAPs
10567                  behind the debugger's back is asking for trouble.
10568
10569                  Since hardware watchpoint traps are always
10570                  distinguishable from other traps, so we don't need to
10571                  apply keep hardware watchpoint moribund locations
10572                  around.  We simply always ignore hardware watchpoint
10573                  traps we can no longer explain.  */
10574
10575               old_loc->events_till_retirement = 3 * (thread_count () + 1);
10576               old_loc->owner = NULL;
10577
10578               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
10579             }
10580           else
10581             {
10582               old_loc->owner = NULL;
10583               decref_bp_location (&old_loc);
10584             }
10585         }
10586     }
10587
10588   /* Rescan breakpoints at the same address and section, marking the
10589      first one as "first" and any others as "duplicates".  This is so
10590      that the bpt instruction is only inserted once.  If we have a
10591      permanent breakpoint at the same place as BPT, make that one the
10592      official one, and the rest as duplicates.  Permanent breakpoints
10593      are sorted first for the same address.
10594
10595      Do the same for hardware watchpoints, but also considering the
10596      watchpoint's type (regular/access/read) and length.  */
10597
10598   bp_loc_first = NULL;
10599   wp_loc_first = NULL;
10600   awp_loc_first = NULL;
10601   rwp_loc_first = NULL;
10602   ALL_BP_LOCATIONS (loc, locp)
10603     {
10604       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
10605          non-NULL.  */
10606       struct bp_location **loc_first_p;
10607       b = loc->owner;
10608
10609       if (!should_be_inserted (loc)
10610           || !breakpoint_address_is_meaningful (b)
10611           /* Don't detect duplicate for tracepoint locations because they are
10612            never duplicated.  See the comments in field `duplicate' of
10613            `struct bp_location'.  */
10614           || is_tracepoint (b))
10615         continue;
10616
10617       /* Permanent breakpoint should always be inserted.  */
10618       if (b->enable_state == bp_permanent && ! loc->inserted)
10619         internal_error (__FILE__, __LINE__,
10620                         _("allegedly permanent breakpoint is not "
10621                         "actually inserted"));
10622
10623       if (b->type == bp_hardware_watchpoint)
10624         loc_first_p = &wp_loc_first;
10625       else if (b->type == bp_read_watchpoint)
10626         loc_first_p = &rwp_loc_first;
10627       else if (b->type == bp_access_watchpoint)
10628         loc_first_p = &awp_loc_first;
10629       else
10630         loc_first_p = &bp_loc_first;
10631
10632       if (*loc_first_p == NULL
10633           || (overlay_debugging && loc->section != (*loc_first_p)->section)
10634           || !breakpoint_locations_match (loc, *loc_first_p))
10635         {
10636           *loc_first_p = loc;
10637           loc->duplicate = 0;
10638           continue;
10639         }
10640
10641
10642       /* This and the above ensure the invariant that the first location
10643          is not duplicated, and is the inserted one.
10644          All following are marked as duplicated, and are not inserted.  */
10645       if (loc->inserted)
10646         swap_insertion (loc, *loc_first_p);
10647       loc->duplicate = 1;
10648
10649       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
10650           && b->enable_state != bp_permanent)
10651         internal_error (__FILE__, __LINE__,
10652                         _("another breakpoint was inserted on top of "
10653                         "a permanent breakpoint"));
10654     }
10655
10656   if (breakpoints_always_inserted_mode () && should_insert
10657       && (have_live_inferiors ()
10658           || (gdbarch_has_global_breakpoints (target_gdbarch))))
10659     insert_breakpoint_locations ();
10660
10661   if (should_insert)
10662     download_tracepoint_locations ();
10663
10664   do_cleanups (cleanups);
10665 }
10666
10667 void
10668 breakpoint_retire_moribund (void)
10669 {
10670   struct bp_location *loc;
10671   int ix;
10672
10673   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
10674     if (--(loc->events_till_retirement) == 0)
10675       {
10676         decref_bp_location (&loc);
10677         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
10678         --ix;
10679       }
10680 }
10681
10682 static void
10683 update_global_location_list_nothrow (int inserting)
10684 {
10685   volatile struct gdb_exception e;
10686
10687   TRY_CATCH (e, RETURN_MASK_ERROR)
10688     update_global_location_list (inserting);
10689 }
10690
10691 /* Clear BKP from a BPS.  */
10692
10693 static void
10694 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
10695 {
10696   bpstat bs;
10697
10698   for (bs = bps; bs; bs = bs->next)
10699     if (bs->breakpoint_at == bpt)
10700       {
10701         bs->breakpoint_at = NULL;
10702         bs->old_val = NULL;
10703         /* bs->commands will be freed later.  */
10704       }
10705 }
10706
10707 /* Callback for iterate_over_threads.  */
10708 static int
10709 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
10710 {
10711   struct breakpoint *bpt = data;
10712
10713   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
10714   return 0;
10715 }
10716
10717 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
10718    callbacks.  */
10719
10720 static void
10721 say_where (struct breakpoint *b)
10722 {
10723   struct ui_out *uiout = current_uiout;
10724   struct value_print_options opts;
10725
10726   get_user_print_options (&opts);
10727
10728   /* i18n: cagney/2005-02-11: Below needs to be merged into a
10729      single string.  */
10730   if (b->loc == NULL)
10731     {
10732       printf_filtered (_(" (%s) pending."), b->addr_string);
10733     }
10734   else
10735     {
10736       if (opts.addressprint || b->loc->source_file == NULL)
10737         {
10738           printf_filtered (" at ");
10739           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
10740                           gdb_stdout);
10741         }
10742       if (b->loc->source_file)
10743         {
10744           /* If there is a single location, we can print the location
10745              more nicely.  */
10746           if (b->loc->next == NULL)
10747             printf_filtered (": file %s, line %d.",
10748                              b->loc->source_file, b->loc->line_number);
10749           else
10750             /* This is not ideal, but each location may have a
10751                different file name, and this at least reflects the
10752                real situation somewhat.  */
10753             printf_filtered (": %s.", b->addr_string);
10754         }
10755
10756       if (b->loc->next)
10757         {
10758           struct bp_location *loc = b->loc;
10759           int n = 0;
10760           for (; loc; loc = loc->next)
10761             ++n;
10762           printf_filtered (" (%d locations)", n);
10763         }
10764     }
10765 }
10766
10767 /* Default bp_location_ops methods.  */
10768
10769 static void
10770 bp_location_dtor (struct bp_location *self)
10771 {
10772   xfree (self->cond);
10773   xfree (self->function_name);
10774   xfree (self->source_file);
10775 }
10776
10777 static const struct bp_location_ops bp_location_ops =
10778 {
10779   bp_location_dtor
10780 };
10781
10782 /* Default breakpoint_ops methods all breakpoint_ops ultimately
10783    inherit from.  */
10784
10785 static void
10786 base_breakpoint_dtor (struct breakpoint *self)
10787 {
10788   decref_counted_command_line (&self->commands);
10789   xfree (self->cond_string);
10790   xfree (self->addr_string);
10791   xfree (self->filter);
10792   xfree (self->addr_string_range_end);
10793 }
10794
10795 static struct bp_location *
10796 base_breakpoint_allocate_location (struct breakpoint *self)
10797 {
10798   struct bp_location *loc;
10799
10800   loc = XNEW (struct bp_location);
10801   init_bp_location (loc, &bp_location_ops, self);
10802   return loc;
10803 }
10804
10805 static void
10806 base_breakpoint_re_set (struct breakpoint *b)
10807 {
10808   /* Nothing to re-set. */
10809 }
10810
10811 #define internal_error_pure_virtual_called() \
10812   gdb_assert_not_reached ("pure virtual function called")
10813
10814 static int
10815 base_breakpoint_insert_location (struct bp_location *bl)
10816 {
10817   internal_error_pure_virtual_called ();
10818 }
10819
10820 static int
10821 base_breakpoint_remove_location (struct bp_location *bl)
10822 {
10823   internal_error_pure_virtual_called ();
10824 }
10825
10826 static int
10827 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
10828                                 struct address_space *aspace,
10829                                 CORE_ADDR bp_addr)
10830 {
10831   internal_error_pure_virtual_called ();
10832 }
10833
10834 static void
10835 base_breakpoint_check_status (bpstat bs)
10836 {
10837   /* Always stop.   */
10838 }
10839
10840 /* A "works_in_software_mode" breakpoint_ops method that just internal
10841    errors.  */
10842
10843 static int
10844 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
10845 {
10846   internal_error_pure_virtual_called ();
10847 }
10848
10849 /* A "resources_needed" breakpoint_ops method that just internal
10850    errors.  */
10851
10852 static int
10853 base_breakpoint_resources_needed (const struct bp_location *bl)
10854 {
10855   internal_error_pure_virtual_called ();
10856 }
10857
10858 static enum print_stop_action
10859 base_breakpoint_print_it (bpstat bs)
10860 {
10861   internal_error_pure_virtual_called ();
10862 }
10863
10864 static void
10865 base_breakpoint_print_one_detail (const struct breakpoint *self,
10866                                   struct ui_out *uiout)
10867 {
10868   /* nothing */
10869 }
10870
10871 static void
10872 base_breakpoint_print_mention (struct breakpoint *b)
10873 {
10874   internal_error_pure_virtual_called ();
10875 }
10876
10877 static void
10878 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
10879 {
10880   internal_error_pure_virtual_called ();
10881 }
10882
10883 static void
10884 base_breakpoint_create_sals_from_address (char **arg,
10885                                           struct linespec_result *canonical,
10886                                           enum bptype type_wanted,
10887                                           char *addr_start,
10888                                           char **copy_arg)
10889 {
10890   internal_error_pure_virtual_called ();
10891 }
10892
10893 static void
10894 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
10895                                         struct linespec_result *c,
10896                                         struct linespec_sals *lsal,
10897                                         char *cond_string,
10898                                         enum bptype type_wanted,
10899                                         enum bpdisp disposition,
10900                                         int thread,
10901                                         int task, int ignore_count,
10902                                         const struct breakpoint_ops *o,
10903                                         int from_tty, int enabled,
10904                                         int internal)
10905 {
10906   internal_error_pure_virtual_called ();
10907 }
10908
10909 static void
10910 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
10911                                  struct symtabs_and_lines *sals)
10912 {
10913   internal_error_pure_virtual_called ();
10914 }
10915
10916 static struct breakpoint_ops base_breakpoint_ops =
10917 {
10918   base_breakpoint_dtor,
10919   base_breakpoint_allocate_location,
10920   base_breakpoint_re_set,
10921   base_breakpoint_insert_location,
10922   base_breakpoint_remove_location,
10923   base_breakpoint_breakpoint_hit,
10924   base_breakpoint_check_status,
10925   base_breakpoint_resources_needed,
10926   base_breakpoint_works_in_software_mode,
10927   base_breakpoint_print_it,
10928   NULL,
10929   base_breakpoint_print_one_detail,
10930   base_breakpoint_print_mention,
10931   base_breakpoint_print_recreate,
10932   base_breakpoint_create_sals_from_address,
10933   base_breakpoint_create_breakpoints_sal,
10934   base_breakpoint_decode_linespec,
10935 };
10936
10937 /* Default breakpoint_ops methods.  */
10938
10939 static void
10940 bkpt_re_set (struct breakpoint *b)
10941 {
10942   /* FIXME: is this still reachable?  */
10943   if (b->addr_string == NULL)
10944     {
10945       /* Anything without a string can't be re-set.  */
10946       delete_breakpoint (b);
10947       return;
10948     }
10949
10950   breakpoint_re_set_default (b);
10951 }
10952
10953 static int
10954 bkpt_insert_location (struct bp_location *bl)
10955 {
10956   if (bl->loc_type == bp_loc_hardware_breakpoint)
10957     return target_insert_hw_breakpoint (bl->gdbarch,
10958                                         &bl->target_info);
10959   else
10960     return target_insert_breakpoint (bl->gdbarch,
10961                                      &bl->target_info);
10962 }
10963
10964 static int
10965 bkpt_remove_location (struct bp_location *bl)
10966 {
10967   if (bl->loc_type == bp_loc_hardware_breakpoint)
10968     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
10969   else
10970     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
10971 }
10972
10973 static int
10974 bkpt_breakpoint_hit (const struct bp_location *bl,
10975                      struct address_space *aspace, CORE_ADDR bp_addr)
10976 {
10977   struct breakpoint *b = bl->owner;
10978
10979   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
10980                                  aspace, bp_addr))
10981     return 0;
10982
10983   if (overlay_debugging         /* unmapped overlay section */
10984       && section_is_overlay (bl->section)
10985       && !section_is_mapped (bl->section))
10986     return 0;
10987
10988   return 1;
10989 }
10990
10991 static int
10992 bkpt_resources_needed (const struct bp_location *bl)
10993 {
10994   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
10995
10996   return 1;
10997 }
10998
10999 static enum print_stop_action
11000 bkpt_print_it (bpstat bs)
11001 {
11002   struct breakpoint *b;
11003   const struct bp_location *bl;
11004   int bp_temp;
11005   struct ui_out *uiout = current_uiout;
11006
11007   gdb_assert (bs->bp_location_at != NULL);
11008
11009   bl = bs->bp_location_at;
11010   b = bs->breakpoint_at;
11011
11012   bp_temp = b->disposition == disp_del;
11013   if (bl->address != bl->requested_address)
11014     breakpoint_adjustment_warning (bl->requested_address,
11015                                    bl->address,
11016                                    b->number, 1);
11017   annotate_breakpoint (b->number);
11018   if (bp_temp)
11019     ui_out_text (uiout, "\nTemporary breakpoint ");
11020   else
11021     ui_out_text (uiout, "\nBreakpoint ");
11022   if (ui_out_is_mi_like_p (uiout))
11023     {
11024       ui_out_field_string (uiout, "reason",
11025                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11026       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11027     }
11028   ui_out_field_int (uiout, "bkptno", b->number);
11029   ui_out_text (uiout, ", ");
11030
11031   return PRINT_SRC_AND_LOC;
11032 }
11033
11034 static void
11035 bkpt_print_mention (struct breakpoint *b)
11036 {
11037   if (ui_out_is_mi_like_p (current_uiout))
11038     return;
11039
11040   switch (b->type)
11041     {
11042     case bp_breakpoint:
11043     case bp_gnu_ifunc_resolver:
11044       if (b->disposition == disp_del)
11045         printf_filtered (_("Temporary breakpoint"));
11046       else
11047         printf_filtered (_("Breakpoint"));
11048       printf_filtered (_(" %d"), b->number);
11049       if (b->type == bp_gnu_ifunc_resolver)
11050         printf_filtered (_(" at gnu-indirect-function resolver"));
11051       break;
11052     case bp_hardware_breakpoint:
11053       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
11054       break;
11055     }
11056
11057   say_where (b);
11058 }
11059
11060 static void
11061 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
11062 {
11063   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
11064     fprintf_unfiltered (fp, "tbreak");
11065   else if (tp->type == bp_breakpoint)
11066     fprintf_unfiltered (fp, "break");
11067   else if (tp->type == bp_hardware_breakpoint
11068            && tp->disposition == disp_del)
11069     fprintf_unfiltered (fp, "thbreak");
11070   else if (tp->type == bp_hardware_breakpoint)
11071     fprintf_unfiltered (fp, "hbreak");
11072   else
11073     internal_error (__FILE__, __LINE__,
11074                     _("unhandled breakpoint type %d"), (int) tp->type);
11075
11076   fprintf_unfiltered (fp, " %s", tp->addr_string);
11077   print_recreate_thread (tp, fp);
11078 }
11079
11080 static void
11081 bkpt_create_sals_from_address (char **arg,
11082                                struct linespec_result *canonical,
11083                                enum bptype type_wanted,
11084                                char *addr_start, char **copy_arg)
11085 {
11086   create_sals_from_address_default (arg, canonical, type_wanted,
11087                                     addr_start, copy_arg);
11088 }
11089
11090 static void
11091 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
11092                              struct linespec_result *canonical,
11093                              struct linespec_sals *lsal,
11094                              char *cond_string,
11095                              enum bptype type_wanted,
11096                              enum bpdisp disposition,
11097                              int thread,
11098                              int task, int ignore_count,
11099                              const struct breakpoint_ops *ops,
11100                              int from_tty, int enabled,
11101                              int internal)
11102 {
11103   create_breakpoints_sal_default (gdbarch, canonical, lsal,
11104                                   cond_string, type_wanted,
11105                                   disposition, thread, task,
11106                                   ignore_count, ops, from_tty,
11107                                   enabled, internal);
11108 }
11109
11110 static void
11111 bkpt_decode_linespec (struct breakpoint *b, char **s,
11112                       struct symtabs_and_lines *sals)
11113 {
11114   decode_linespec_default (b, s, sals);
11115 }
11116
11117 /* Virtual table for internal breakpoints.  */
11118
11119 static void
11120 internal_bkpt_re_set (struct breakpoint *b)
11121 {
11122   switch (b->type)
11123     {
11124       /* Delete overlay event and longjmp master breakpoints; they
11125          will be reset later by breakpoint_re_set.  */
11126     case bp_overlay_event:
11127     case bp_longjmp_master:
11128     case bp_std_terminate_master:
11129     case bp_exception_master:
11130       delete_breakpoint (b);
11131       break;
11132
11133       /* This breakpoint is special, it's set up when the inferior
11134          starts and we really don't want to touch it.  */
11135     case bp_shlib_event:
11136
11137       /* Like bp_shlib_event, this breakpoint type is special.  Once
11138          it is set up, we do not want to touch it.  */
11139     case bp_thread_event:
11140       break;
11141     }
11142 }
11143
11144 static void
11145 internal_bkpt_check_status (bpstat bs)
11146 {
11147   /* We do not stop for these.  */
11148   bs->stop = 0;
11149 }
11150
11151 static enum print_stop_action
11152 internal_bkpt_print_it (bpstat bs)
11153 {
11154   struct ui_out *uiout = current_uiout;
11155   struct breakpoint *b;
11156
11157   b = bs->breakpoint_at;
11158
11159   switch (b->type)
11160     {
11161     case bp_shlib_event:
11162       /* Did we stop because the user set the stop_on_solib_events
11163          variable?  (If so, we report this as a generic, "Stopped due
11164          to shlib event" message.) */
11165       ui_out_text (uiout, _("Stopped due to shared library event\n"));
11166       if (ui_out_is_mi_like_p (uiout))
11167         ui_out_field_string (uiout, "reason",
11168                              async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
11169       break;
11170
11171     case bp_thread_event:
11172       /* Not sure how we will get here.
11173          GDB should not stop for these breakpoints.  */
11174       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
11175       break;
11176
11177     case bp_overlay_event:
11178       /* By analogy with the thread event, GDB should not stop for these.  */
11179       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
11180       break;
11181
11182     case bp_longjmp_master:
11183       /* These should never be enabled.  */
11184       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
11185       break;
11186
11187     case bp_std_terminate_master:
11188       /* These should never be enabled.  */
11189       printf_filtered (_("std::terminate Master Breakpoint: "
11190                          "gdb should not stop!\n"));
11191       break;
11192
11193     case bp_exception_master:
11194       /* These should never be enabled.  */
11195       printf_filtered (_("Exception Master Breakpoint: "
11196                          "gdb should not stop!\n"));
11197       break;
11198     }
11199
11200   return PRINT_NOTHING;
11201 }
11202
11203 static void
11204 internal_bkpt_print_mention (struct breakpoint *b)
11205 {
11206   /* Nothing to mention.  These breakpoints are internal.  */
11207 }
11208
11209 /* Virtual table for momentary breakpoints  */
11210
11211 static void
11212 momentary_bkpt_re_set (struct breakpoint *b)
11213 {
11214   /* Keep temporary breakpoints, which can be encountered when we step
11215      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
11216      Otherwise these should have been blown away via the cleanup chain
11217      or by breakpoint_init_inferior when we rerun the executable.  */
11218 }
11219
11220 static void
11221 momentary_bkpt_check_status (bpstat bs)
11222 {
11223   /* Nothing.  The point of these breakpoints is causing a stop.  */
11224 }
11225
11226 static enum print_stop_action
11227 momentary_bkpt_print_it (bpstat bs)
11228 {
11229   struct ui_out *uiout = current_uiout;
11230
11231   if (ui_out_is_mi_like_p (uiout))
11232     {
11233       struct breakpoint *b = bs->breakpoint_at;
11234
11235       switch (b->type)
11236         {
11237         case bp_finish:
11238           ui_out_field_string
11239             (uiout, "reason",
11240              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
11241           break;
11242
11243         case bp_until:
11244           ui_out_field_string
11245             (uiout, "reason",
11246              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
11247           break;
11248         }
11249     }
11250
11251   return PRINT_UNKNOWN;
11252 }
11253
11254 static void
11255 momentary_bkpt_print_mention (struct breakpoint *b)
11256 {
11257   /* Nothing to mention.  These breakpoints are internal.  */
11258 }
11259
11260 /* The breakpoint_ops structure to be used in tracepoints.  */
11261
11262 static void
11263 tracepoint_re_set (struct breakpoint *b)
11264 {
11265   breakpoint_re_set_default (b);
11266 }
11267
11268 static int
11269 tracepoint_breakpoint_hit (const struct bp_location *bl,
11270                            struct address_space *aspace, CORE_ADDR bp_addr)
11271 {
11272   /* By definition, the inferior does not report stops at
11273      tracepoints.  */
11274   return 0;
11275 }
11276
11277 static void
11278 tracepoint_print_one_detail (const struct breakpoint *self,
11279                              struct ui_out *uiout)
11280 {
11281   struct tracepoint *tp = (struct tracepoint *) self;
11282   if (tp->static_trace_marker_id)
11283     {
11284       gdb_assert (self->type == bp_static_tracepoint);
11285
11286       ui_out_text (uiout, "\tmarker id is ");
11287       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
11288                            tp->static_trace_marker_id);
11289       ui_out_text (uiout, "\n");
11290     }
11291 }
11292
11293 static void
11294 tracepoint_print_mention (struct breakpoint *b)
11295 {
11296   if (ui_out_is_mi_like_p (current_uiout))
11297     return;
11298
11299   switch (b->type)
11300     {
11301     case bp_tracepoint:
11302       printf_filtered (_("Tracepoint"));
11303       printf_filtered (_(" %d"), b->number);
11304       break;
11305     case bp_fast_tracepoint:
11306       printf_filtered (_("Fast tracepoint"));
11307       printf_filtered (_(" %d"), b->number);
11308       break;
11309     case bp_static_tracepoint:
11310       printf_filtered (_("Static tracepoint"));
11311       printf_filtered (_(" %d"), b->number);
11312       break;
11313     default:
11314       internal_error (__FILE__, __LINE__,
11315                       _("unhandled tracepoint type %d"), (int) b->type);
11316     }
11317
11318   say_where (b);
11319 }
11320
11321 static void
11322 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
11323 {
11324   struct tracepoint *tp = (struct tracepoint *) self;
11325
11326   if (self->type == bp_fast_tracepoint)
11327     fprintf_unfiltered (fp, "ftrace");
11328   if (self->type == bp_static_tracepoint)
11329     fprintf_unfiltered (fp, "strace");
11330   else if (self->type == bp_tracepoint)
11331     fprintf_unfiltered (fp, "trace");
11332   else
11333     internal_error (__FILE__, __LINE__,
11334                     _("unhandled tracepoint type %d"), (int) self->type);
11335
11336   fprintf_unfiltered (fp, " %s", self->addr_string);
11337   print_recreate_thread (self, fp);
11338
11339   if (tp->pass_count)
11340     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
11341 }
11342
11343 static void
11344 tracepoint_create_sals_from_address (char **arg,
11345                                      struct linespec_result *canonical,
11346                                      enum bptype type_wanted,
11347                                      char *addr_start, char **copy_arg)
11348 {
11349   create_sals_from_address_default (arg, canonical, type_wanted,
11350                                     addr_start, copy_arg);
11351 }
11352
11353 static void
11354 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
11355                                    struct linespec_result *canonical,
11356                                    struct linespec_sals *lsal,
11357                                    char *cond_string,
11358                                    enum bptype type_wanted,
11359                                    enum bpdisp disposition,
11360                                    int thread,
11361                                    int task, int ignore_count,
11362                                    const struct breakpoint_ops *ops,
11363                                    int from_tty, int enabled,
11364                                    int internal)
11365 {
11366   create_breakpoints_sal_default (gdbarch, canonical, lsal,
11367                                   cond_string, type_wanted,
11368                                   disposition, thread, task,
11369                                   ignore_count, ops, from_tty,
11370                                   enabled, internal);
11371 }
11372
11373 static void
11374 tracepoint_decode_linespec (struct breakpoint *b, char **s,
11375                             struct symtabs_and_lines *sals)
11376 {
11377   decode_linespec_default (b, s, sals);
11378 }
11379
11380 struct breakpoint_ops tracepoint_breakpoint_ops;
11381
11382 /* The breakpoint_ops structure to be used on static tracepoints with
11383    markers (`-m').  */
11384
11385 static void
11386 strace_marker_create_sals_from_address (char **arg,
11387                                         struct linespec_result *canonical,
11388                                         enum bptype type_wanted,
11389                                         char *addr_start, char **copy_arg)
11390 {
11391   struct linespec_sals lsal;
11392
11393   lsal.sals = decode_static_tracepoint_spec (arg);
11394
11395   *copy_arg = savestring (addr_start, *arg - addr_start);
11396
11397   canonical->addr_string = xstrdup (*copy_arg);
11398   lsal.canonical = xstrdup (*copy_arg);
11399   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
11400 }
11401
11402 static void
11403 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
11404                                       struct linespec_result *canonical,
11405                                       struct linespec_sals *lsal,
11406                                       char *cond_string,
11407                                       enum bptype type_wanted,
11408                                       enum bpdisp disposition,
11409                                       int thread,
11410                                       int task, int ignore_count,
11411                                       const struct breakpoint_ops *ops,
11412                                       int from_tty, int enabled,
11413                                       int internal)
11414 {
11415   int i;
11416
11417   /* If the user is creating a static tracepoint by marker id
11418      (strace -m MARKER_ID), then store the sals index, so that
11419      breakpoint_re_set can try to match up which of the newly
11420      found markers corresponds to this one, and, don't try to
11421      expand multiple locations for each sal, given than SALS
11422      already should contain all sals for MARKER_ID.  */
11423
11424   for (i = 0; i < lsal->sals.nelts; ++i)
11425     {
11426       struct symtabs_and_lines expanded;
11427       struct tracepoint *tp;
11428       struct cleanup *old_chain;
11429       char *addr_string;
11430
11431       expanded.nelts = 1;
11432       expanded.sals = &lsal->sals.sals[i];
11433
11434       addr_string = xstrdup (canonical->addr_string);
11435       old_chain = make_cleanup (xfree, addr_string);
11436
11437       tp = XCNEW (struct tracepoint);
11438       init_breakpoint_sal (&tp->base, gdbarch, expanded,
11439                            addr_string, NULL,
11440                            cond_string, type_wanted, disposition,
11441                            thread, task, ignore_count, ops,
11442                            from_tty, enabled, internal,
11443                            canonical->special_display);
11444       /* Given that its possible to have multiple markers with
11445          the same string id, if the user is creating a static
11446          tracepoint by marker id ("strace -m MARKER_ID"), then
11447          store the sals index, so that breakpoint_re_set can
11448          try to match up which of the newly found markers
11449          corresponds to this one  */
11450       tp->static_trace_marker_id_idx = i;
11451
11452       install_breakpoint (internal, &tp->base, 0);
11453
11454       discard_cleanups (old_chain);
11455     }
11456 }
11457
11458 static void
11459 strace_marker_decode_linespec (struct breakpoint *b, char **s,
11460                                struct symtabs_and_lines *sals)
11461 {
11462   struct tracepoint *tp = (struct tracepoint *) b;
11463
11464   *sals = decode_static_tracepoint_spec (s);
11465   if (sals->nelts > tp->static_trace_marker_id_idx)
11466     {
11467       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
11468       sals->nelts = 1;
11469     }
11470   else
11471     error (_("marker %s not found"), tp->static_trace_marker_id);
11472 }
11473
11474 static struct breakpoint_ops strace_marker_breakpoint_ops;
11475
11476 static int
11477 strace_marker_p (struct breakpoint *b)
11478 {
11479   return b->ops == &strace_marker_breakpoint_ops;
11480 }
11481
11482 /* Delete a breakpoint and clean up all traces of it in the data
11483    structures.  */
11484
11485 void
11486 delete_breakpoint (struct breakpoint *bpt)
11487 {
11488   struct breakpoint *b;
11489
11490   gdb_assert (bpt != NULL);
11491
11492   /* Has this bp already been deleted?  This can happen because
11493      multiple lists can hold pointers to bp's.  bpstat lists are
11494      especial culprits.
11495
11496      One example of this happening is a watchpoint's scope bp.  When
11497      the scope bp triggers, we notice that the watchpoint is out of
11498      scope, and delete it.  We also delete its scope bp.  But the
11499      scope bp is marked "auto-deleting", and is already on a bpstat.
11500      That bpstat is then checked for auto-deleting bp's, which are
11501      deleted.
11502
11503      A real solution to this problem might involve reference counts in
11504      bp's, and/or giving them pointers back to their referencing
11505      bpstat's, and teaching delete_breakpoint to only free a bp's
11506      storage when no more references were extent.  A cheaper bandaid
11507      was chosen.  */
11508   if (bpt->type == bp_none)
11509     return;
11510
11511   /* At least avoid this stale reference until the reference counting
11512      of breakpoints gets resolved.  */
11513   if (bpt->related_breakpoint != bpt)
11514     {
11515       struct breakpoint *related;
11516       struct watchpoint *w;
11517
11518       if (bpt->type == bp_watchpoint_scope)
11519         w = (struct watchpoint *) bpt->related_breakpoint;
11520       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
11521         w = (struct watchpoint *) bpt;
11522       else
11523         w = NULL;
11524       if (w != NULL)
11525         watchpoint_del_at_next_stop (w);
11526
11527       /* Unlink bpt from the bpt->related_breakpoint ring.  */
11528       for (related = bpt; related->related_breakpoint != bpt;
11529            related = related->related_breakpoint);
11530       related->related_breakpoint = bpt->related_breakpoint;
11531       bpt->related_breakpoint = bpt;
11532     }
11533
11534   /* watch_command_1 creates a watchpoint but only sets its number if
11535      update_watchpoint succeeds in creating its bp_locations.  If there's
11536      a problem in that process, we'll be asked to delete the half-created
11537      watchpoint.  In that case, don't announce the deletion.  */
11538   if (bpt->number)
11539     observer_notify_breakpoint_deleted (bpt);
11540
11541   if (breakpoint_chain == bpt)
11542     breakpoint_chain = bpt->next;
11543
11544   ALL_BREAKPOINTS (b)
11545     if (b->next == bpt)
11546     {
11547       b->next = bpt->next;
11548       break;
11549     }
11550
11551   /* Be sure no bpstat's are pointing at the breakpoint after it's
11552      been freed.  */
11553   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
11554      in all threads for now.  Note that we cannot just remove bpstats
11555      pointing at bpt from the stop_bpstat list entirely, as breakpoint
11556      commands are associated with the bpstat; if we remove it here,
11557      then the later call to bpstat_do_actions (&stop_bpstat); in
11558      event-top.c won't do anything, and temporary breakpoints with
11559      commands won't work.  */
11560
11561   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
11562
11563   /* Now that breakpoint is removed from breakpoint list, update the
11564      global location list.  This will remove locations that used to
11565      belong to this breakpoint.  Do this before freeing the breakpoint
11566      itself, since remove_breakpoint looks at location's owner.  It
11567      might be better design to have location completely
11568      self-contained, but it's not the case now.  */
11569   update_global_location_list (0);
11570
11571   bpt->ops->dtor (bpt);
11572   /* On the chance that someone will soon try again to delete this
11573      same bp, we mark it as deleted before freeing its storage.  */
11574   bpt->type = bp_none;
11575   xfree (bpt);
11576 }
11577
11578 static void
11579 do_delete_breakpoint_cleanup (void *b)
11580 {
11581   delete_breakpoint (b);
11582 }
11583
11584 struct cleanup *
11585 make_cleanup_delete_breakpoint (struct breakpoint *b)
11586 {
11587   return make_cleanup (do_delete_breakpoint_cleanup, b);
11588 }
11589
11590 /* Iterator function to call a user-provided callback function once
11591    for each of B and its related breakpoints.  */
11592
11593 static void
11594 iterate_over_related_breakpoints (struct breakpoint *b,
11595                                   void (*function) (struct breakpoint *,
11596                                                     void *),
11597                                   void *data)
11598 {
11599   struct breakpoint *related;
11600
11601   related = b;
11602   do
11603     {
11604       struct breakpoint *next;
11605
11606       /* FUNCTION may delete RELATED.  */
11607       next = related->related_breakpoint;
11608
11609       if (next == related)
11610         {
11611           /* RELATED is the last ring entry.  */
11612           function (related, data);
11613
11614           /* FUNCTION may have deleted it, so we'd never reach back to
11615              B.  There's nothing left to do anyway, so just break
11616              out.  */
11617           break;
11618         }
11619       else
11620         function (related, data);
11621
11622       related = next;
11623     }
11624   while (related != b);
11625 }
11626
11627 static void
11628 do_delete_breakpoint (struct breakpoint *b, void *ignore)
11629 {
11630   delete_breakpoint (b);
11631 }
11632
11633 /* A callback for map_breakpoint_numbers that calls
11634    delete_breakpoint.  */
11635
11636 static void
11637 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
11638 {
11639   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
11640 }
11641
11642 void
11643 delete_command (char *arg, int from_tty)
11644 {
11645   struct breakpoint *b, *b_tmp;
11646
11647   dont_repeat ();
11648
11649   if (arg == 0)
11650     {
11651       int breaks_to_delete = 0;
11652
11653       /* Delete all breakpoints if no argument.  Do not delete
11654          internal breakpoints, these have to be deleted with an
11655          explicit breakpoint number argument.  */
11656       ALL_BREAKPOINTS (b)
11657         if (user_breakpoint_p (b))
11658           {
11659             breaks_to_delete = 1;
11660             break;
11661           }
11662
11663       /* Ask user only if there are some breakpoints to delete.  */
11664       if (!from_tty
11665           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
11666         {
11667           ALL_BREAKPOINTS_SAFE (b, b_tmp)
11668             if (user_breakpoint_p (b))
11669               delete_breakpoint (b);
11670         }
11671     }
11672   else
11673     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
11674 }
11675
11676 static int
11677 all_locations_are_pending (struct bp_location *loc)
11678 {
11679   for (; loc; loc = loc->next)
11680     if (!loc->shlib_disabled
11681         && !loc->pspace->executing_startup)
11682       return 0;
11683   return 1;
11684 }
11685
11686 /* Subroutine of update_breakpoint_locations to simplify it.
11687    Return non-zero if multiple fns in list LOC have the same name.
11688    Null names are ignored.  */
11689
11690 static int
11691 ambiguous_names_p (struct bp_location *loc)
11692 {
11693   struct bp_location *l;
11694   htab_t htab = htab_create_alloc (13, htab_hash_string,
11695                                    (int (*) (const void *, 
11696                                              const void *)) streq,
11697                                    NULL, xcalloc, xfree);
11698
11699   for (l = loc; l != NULL; l = l->next)
11700     {
11701       const char **slot;
11702       const char *name = l->function_name;
11703
11704       /* Allow for some names to be NULL, ignore them.  */
11705       if (name == NULL)
11706         continue;
11707
11708       slot = (const char **) htab_find_slot (htab, (const void *) name,
11709                                              INSERT);
11710       /* NOTE: We can assume slot != NULL here because xcalloc never
11711          returns NULL.  */
11712       if (*slot != NULL)
11713         {
11714           htab_delete (htab);
11715           return 1;
11716         }
11717       *slot = name;
11718     }
11719
11720   htab_delete (htab);
11721   return 0;
11722 }
11723
11724 /* When symbols change, it probably means the sources changed as well,
11725    and it might mean the static tracepoint markers are no longer at
11726    the same address or line numbers they used to be at last we
11727    checked.  Losing your static tracepoints whenever you rebuild is
11728    undesirable.  This function tries to resync/rematch gdb static
11729    tracepoints with the markers on the target, for static tracepoints
11730    that have not been set by marker id.  Static tracepoint that have
11731    been set by marker id are reset by marker id in breakpoint_re_set.
11732    The heuristic is:
11733
11734    1) For a tracepoint set at a specific address, look for a marker at
11735    the old PC.  If one is found there, assume to be the same marker.
11736    If the name / string id of the marker found is different from the
11737    previous known name, assume that means the user renamed the marker
11738    in the sources, and output a warning.
11739
11740    2) For a tracepoint set at a given line number, look for a marker
11741    at the new address of the old line number.  If one is found there,
11742    assume to be the same marker.  If the name / string id of the
11743    marker found is different from the previous known name, assume that
11744    means the user renamed the marker in the sources, and output a
11745    warning.
11746
11747    3) If a marker is no longer found at the same address or line, it
11748    may mean the marker no longer exists.  But it may also just mean
11749    the code changed a bit.  Maybe the user added a few lines of code
11750    that made the marker move up or down (in line number terms).  Ask
11751    the target for info about the marker with the string id as we knew
11752    it.  If found, update line number and address in the matching
11753    static tracepoint.  This will get confused if there's more than one
11754    marker with the same ID (possible in UST, although unadvised
11755    precisely because it confuses tools).  */
11756
11757 static struct symtab_and_line
11758 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
11759 {
11760   struct tracepoint *tp = (struct tracepoint *) b;
11761   struct static_tracepoint_marker marker;
11762   CORE_ADDR pc;
11763   int i;
11764
11765   pc = sal.pc;
11766   if (sal.line)
11767     find_line_pc (sal.symtab, sal.line, &pc);
11768
11769   if (target_static_tracepoint_marker_at (pc, &marker))
11770     {
11771       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
11772         warning (_("static tracepoint %d changed probed marker from %s to %s"),
11773                  b->number,
11774                  tp->static_trace_marker_id, marker.str_id);
11775
11776       xfree (tp->static_trace_marker_id);
11777       tp->static_trace_marker_id = xstrdup (marker.str_id);
11778       release_static_tracepoint_marker (&marker);
11779
11780       return sal;
11781     }
11782
11783   /* Old marker wasn't found on target at lineno.  Try looking it up
11784      by string ID.  */
11785   if (!sal.explicit_pc
11786       && sal.line != 0
11787       && sal.symtab != NULL
11788       && tp->static_trace_marker_id != NULL)
11789     {
11790       VEC(static_tracepoint_marker_p) *markers;
11791
11792       markers
11793         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
11794
11795       if (!VEC_empty(static_tracepoint_marker_p, markers))
11796         {
11797           struct symtab_and_line sal2;
11798           struct symbol *sym;
11799           struct static_tracepoint_marker *tpmarker;
11800           struct ui_out *uiout = current_uiout;
11801
11802           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
11803
11804           xfree (tp->static_trace_marker_id);
11805           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
11806
11807           warning (_("marker for static tracepoint %d (%s) not "
11808                      "found at previous line number"),
11809                    b->number, tp->static_trace_marker_id);
11810
11811           init_sal (&sal2);
11812
11813           sal2.pc = tpmarker->address;
11814
11815           sal2 = find_pc_line (tpmarker->address, 0);
11816           sym = find_pc_sect_function (tpmarker->address, NULL);
11817           ui_out_text (uiout, "Now in ");
11818           if (sym)
11819             {
11820               ui_out_field_string (uiout, "func",
11821                                    SYMBOL_PRINT_NAME (sym));
11822               ui_out_text (uiout, " at ");
11823             }
11824           ui_out_field_string (uiout, "file", sal2.symtab->filename);
11825           ui_out_text (uiout, ":");
11826
11827           if (ui_out_is_mi_like_p (uiout))
11828             {
11829               char *fullname = symtab_to_fullname (sal2.symtab);
11830
11831               if (fullname)
11832                 ui_out_field_string (uiout, "fullname", fullname);
11833             }
11834
11835           ui_out_field_int (uiout, "line", sal2.line);
11836           ui_out_text (uiout, "\n");
11837
11838           b->loc->line_number = sal2.line;
11839
11840           xfree (b->loc->source_file);
11841           if (sym)
11842             b->loc->source_file = xstrdup (sal2.symtab->filename);
11843           else
11844             b->loc->source_file = NULL;
11845
11846           xfree (b->addr_string);
11847           b->addr_string = xstrprintf ("%s:%d",
11848                                        sal2.symtab->filename,
11849                                        b->loc->line_number);
11850
11851           /* Might be nice to check if function changed, and warn if
11852              so.  */
11853
11854           release_static_tracepoint_marker (tpmarker);
11855         }
11856     }
11857   return sal;
11858 }
11859
11860 /* Returns 1 iff locations A and B are sufficiently same that
11861    we don't need to report breakpoint as changed.  */
11862
11863 static int
11864 locations_are_equal (struct bp_location *a, struct bp_location *b)
11865 {
11866   while (a && b)
11867     {
11868       if (a->address != b->address)
11869         return 0;
11870
11871       if (a->shlib_disabled != b->shlib_disabled)
11872         return 0;
11873
11874       if (a->enabled != b->enabled)
11875         return 0;
11876
11877       a = a->next;
11878       b = b->next;
11879     }
11880
11881   if ((a == NULL) != (b == NULL))
11882     return 0;
11883
11884   return 1;
11885 }
11886
11887 /* Create new breakpoint locations for B (a hardware or software breakpoint)
11888    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
11889    a ranged breakpoint.  */
11890
11891 void
11892 update_breakpoint_locations (struct breakpoint *b,
11893                              struct symtabs_and_lines sals,
11894                              struct symtabs_and_lines sals_end)
11895 {
11896   int i;
11897   struct bp_location *existing_locations = b->loc;
11898
11899   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
11900     {
11901       /* Ranged breakpoints have only one start location and one end
11902          location.  */
11903       b->enable_state = bp_disabled;
11904       update_global_location_list (1);
11905       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
11906                            "multiple locations found\n"),
11907                          b->number);
11908       return;
11909     }
11910
11911   /* If there's no new locations, and all existing locations are
11912      pending, don't do anything.  This optimizes the common case where
11913      all locations are in the same shared library, that was unloaded.
11914      We'd like to retain the location, so that when the library is
11915      loaded again, we don't loose the enabled/disabled status of the
11916      individual locations.  */
11917   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
11918     return;
11919
11920   b->loc = NULL;
11921
11922   for (i = 0; i < sals.nelts; ++i)
11923     {
11924       struct bp_location *new_loc;
11925
11926       switch_to_program_space_and_thread (sals.sals[i].pspace);
11927
11928       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
11929
11930       /* Reparse conditions, they might contain references to the
11931          old symtab.  */
11932       if (b->cond_string != NULL)
11933         {
11934           char *s;
11935           volatile struct gdb_exception e;
11936
11937           s = b->cond_string;
11938           TRY_CATCH (e, RETURN_MASK_ERROR)
11939             {
11940               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
11941                                            0);
11942             }
11943           if (e.reason < 0)
11944             {
11945               warning (_("failed to reevaluate condition "
11946                          "for breakpoint %d: %s"), 
11947                        b->number, e.message);
11948               new_loc->enabled = 0;
11949             }
11950         }
11951
11952       if (sals_end.nelts)
11953         {
11954           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
11955
11956           new_loc->length = end - sals.sals[0].pc + 1;
11957         }
11958     }
11959
11960   /* Update locations of permanent breakpoints.  */
11961   if (b->enable_state == bp_permanent)
11962     make_breakpoint_permanent (b);
11963
11964   /* If possible, carry over 'disable' status from existing
11965      breakpoints.  */
11966   {
11967     struct bp_location *e = existing_locations;
11968     /* If there are multiple breakpoints with the same function name,
11969        e.g. for inline functions, comparing function names won't work.
11970        Instead compare pc addresses; this is just a heuristic as things
11971        may have moved, but in practice it gives the correct answer
11972        often enough until a better solution is found.  */
11973     int have_ambiguous_names = ambiguous_names_p (b->loc);
11974
11975     for (; e; e = e->next)
11976       {
11977         if (!e->enabled && e->function_name)
11978           {
11979             struct bp_location *l = b->loc;
11980             if (have_ambiguous_names)
11981               {
11982                 for (; l; l = l->next)
11983                   if (breakpoint_locations_match (e, l))
11984                     {
11985                       l->enabled = 0;
11986                       break;
11987                     }
11988               }
11989             else
11990               {
11991                 for (; l; l = l->next)
11992                   if (l->function_name
11993                       && strcmp (e->function_name, l->function_name) == 0)
11994                     {
11995                       l->enabled = 0;
11996                       break;
11997                     }
11998               }
11999           }
12000       }
12001   }
12002
12003   if (!locations_are_equal (existing_locations, b->loc))
12004     observer_notify_breakpoint_modified (b);
12005
12006   update_global_location_list (1);
12007 }
12008
12009 /* Find the SaL locations corresponding to the given ADDR_STRING.
12010    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
12011
12012 static struct symtabs_and_lines
12013 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
12014 {
12015   char *s;
12016   struct symtabs_and_lines sals = {0};
12017   volatile struct gdb_exception e;
12018
12019   gdb_assert (b->ops != NULL);
12020   s = addr_string;
12021
12022   TRY_CATCH (e, RETURN_MASK_ERROR)
12023     {
12024       b->ops->decode_linespec (b, &s, &sals);
12025     }
12026   if (e.reason < 0)
12027     {
12028       int not_found_and_ok = 0;
12029       /* For pending breakpoints, it's expected that parsing will
12030          fail until the right shared library is loaded.  User has
12031          already told to create pending breakpoints and don't need
12032          extra messages.  If breakpoint is in bp_shlib_disabled
12033          state, then user already saw the message about that
12034          breakpoint being disabled, and don't want to see more
12035          errors.  */
12036       if (e.error == NOT_FOUND_ERROR
12037           && (b->condition_not_parsed 
12038               || (b->loc && b->loc->shlib_disabled)
12039               || (b->loc && b->loc->pspace->executing_startup)
12040               || b->enable_state == bp_disabled))
12041         not_found_and_ok = 1;
12042
12043       if (!not_found_and_ok)
12044         {
12045           /* We surely don't want to warn about the same breakpoint
12046              10 times.  One solution, implemented here, is disable
12047              the breakpoint on error.  Another solution would be to
12048              have separate 'warning emitted' flag.  Since this
12049              happens only when a binary has changed, I don't know
12050              which approach is better.  */
12051           b->enable_state = bp_disabled;
12052           throw_exception (e);
12053         }
12054     }
12055
12056   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
12057     {
12058       int i;
12059
12060       for (i = 0; i < sals.nelts; ++i)
12061         resolve_sal_pc (&sals.sals[i]);
12062       if (b->condition_not_parsed && s && s[0])
12063         {
12064           char *cond_string = 0;
12065           int thread = -1;
12066           int task = 0;
12067
12068           find_condition_and_thread (s, sals.sals[0].pc,
12069                                      &cond_string, &thread, &task);
12070           if (cond_string)
12071             b->cond_string = cond_string;
12072           b->thread = thread;
12073           b->task = task;
12074           b->condition_not_parsed = 0;
12075         }
12076
12077       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
12078         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
12079
12080       *found = 1;
12081     }
12082   else
12083     *found = 0;
12084
12085   return sals;
12086 }
12087
12088 /* The default re_set method, for typical hardware or software
12089    breakpoints.  Reevaluate the breakpoint and recreate its
12090    locations.  */
12091
12092 static void
12093 breakpoint_re_set_default (struct breakpoint *b)
12094 {
12095   int found;
12096   struct symtabs_and_lines sals, sals_end;
12097   struct symtabs_and_lines expanded = {0};
12098   struct symtabs_and_lines expanded_end = {0};
12099
12100   sals = addr_string_to_sals (b, b->addr_string, &found);
12101   if (found)
12102     {
12103       make_cleanup (xfree, sals.sals);
12104       expanded = sals;
12105     }
12106
12107   if (b->addr_string_range_end)
12108     {
12109       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
12110       if (found)
12111         {
12112           make_cleanup (xfree, sals_end.sals);
12113           expanded_end = sals_end;
12114         }
12115     }
12116
12117   update_breakpoint_locations (b, expanded, expanded_end);
12118 }
12119
12120 /* Default method for creating SALs from an address string.  It basically
12121    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
12122
12123 static void
12124 create_sals_from_address_default (char **arg,
12125                                   struct linespec_result *canonical,
12126                                   enum bptype type_wanted,
12127                                   char *addr_start, char **copy_arg)
12128 {
12129   parse_breakpoint_sals (arg, canonical);
12130 }
12131
12132 /* Call create_breakpoints_sal for the given arguments.  This is the default
12133    function for the `create_breakpoints_sal' method of
12134    breakpoint_ops.  */
12135
12136 static void
12137 create_breakpoints_sal_default (struct gdbarch *gdbarch,
12138                                 struct linespec_result *canonical,
12139                                 struct linespec_sals *lsal,
12140                                 char *cond_string,
12141                                 enum bptype type_wanted,
12142                                 enum bpdisp disposition,
12143                                 int thread,
12144                                 int task, int ignore_count,
12145                                 const struct breakpoint_ops *ops,
12146                                 int from_tty, int enabled,
12147                                 int internal)
12148 {
12149   create_breakpoints_sal (gdbarch, canonical, cond_string,
12150                           type_wanted, disposition,
12151                           thread, task, ignore_count, ops, from_tty,
12152                           enabled, internal);
12153 }
12154
12155 /* Decode the line represented by S by calling decode_line_full.  This is the
12156    default function for the `decode_linespec' method of breakpoint_ops.  */
12157
12158 static void
12159 decode_linespec_default (struct breakpoint *b, char **s,
12160                          struct symtabs_and_lines *sals)
12161 {
12162   struct linespec_result canonical;
12163
12164   init_linespec_result (&canonical);
12165   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
12166                     (struct symtab *) NULL, 0,
12167                     &canonical, multiple_symbols_all,
12168                     b->filter);
12169
12170   /* We should get 0 or 1 resulting SALs.  */
12171   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
12172
12173   if (VEC_length (linespec_sals, canonical.sals) > 0)
12174     {
12175       struct linespec_sals *lsal;
12176
12177       lsal = VEC_index (linespec_sals, canonical.sals, 0);
12178       *sals = lsal->sals;
12179       /* Arrange it so the destructor does not free the
12180          contents.  */
12181       lsal->sals.sals = NULL;
12182     }
12183
12184   destroy_linespec_result (&canonical);
12185 }
12186
12187 /* Prepare the global context for a re-set of breakpoint B.  */
12188
12189 static struct cleanup *
12190 prepare_re_set_context (struct breakpoint *b)
12191 {
12192   struct cleanup *cleanups;
12193
12194   input_radix = b->input_radix;
12195   cleanups = save_current_space_and_thread ();
12196   if (b->pspace != NULL)
12197     switch_to_program_space_and_thread (b->pspace);
12198   set_language (b->language);
12199
12200   return cleanups;
12201 }
12202
12203 /* Reset a breakpoint given it's struct breakpoint * BINT.
12204    The value we return ends up being the return value from catch_errors.
12205    Unused in this case.  */
12206
12207 static int
12208 breakpoint_re_set_one (void *bint)
12209 {
12210   /* Get past catch_errs.  */
12211   struct breakpoint *b = (struct breakpoint *) bint;
12212   struct cleanup *cleanups;
12213
12214   cleanups = prepare_re_set_context (b);
12215   b->ops->re_set (b);
12216   do_cleanups (cleanups);
12217   return 0;
12218 }
12219
12220 /* Re-set all breakpoints after symbols have been re-loaded.  */
12221 void
12222 breakpoint_re_set (void)
12223 {
12224   struct breakpoint *b, *b_tmp;
12225   enum language save_language;
12226   int save_input_radix;
12227   struct cleanup *old_chain;
12228
12229   save_language = current_language->la_language;
12230   save_input_radix = input_radix;
12231   old_chain = save_current_program_space ();
12232
12233   ALL_BREAKPOINTS_SAFE (b, b_tmp)
12234   {
12235     /* Format possible error msg.  */
12236     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
12237                                 b->number);
12238     struct cleanup *cleanups = make_cleanup (xfree, message);
12239     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
12240     do_cleanups (cleanups);
12241   }
12242   set_language (save_language);
12243   input_radix = save_input_radix;
12244
12245   jit_breakpoint_re_set ();
12246
12247   do_cleanups (old_chain);
12248
12249   create_overlay_event_breakpoint ();
12250   create_longjmp_master_breakpoint ();
12251   create_std_terminate_master_breakpoint ();
12252   create_exception_master_breakpoint ();
12253
12254   /* While we're at it, reset the skip list too.  */
12255   skip_re_set ();
12256 }
12257 \f
12258 /* Reset the thread number of this breakpoint:
12259
12260    - If the breakpoint is for all threads, leave it as-is.
12261    - Else, reset it to the current thread for inferior_ptid.  */
12262 void
12263 breakpoint_re_set_thread (struct breakpoint *b)
12264 {
12265   if (b->thread != -1)
12266     {
12267       if (in_thread_list (inferior_ptid))
12268         b->thread = pid_to_thread_id (inferior_ptid);
12269
12270       /* We're being called after following a fork.  The new fork is
12271          selected as current, and unless this was a vfork will have a
12272          different program space from the original thread.  Reset that
12273          as well.  */
12274       b->loc->pspace = current_program_space;
12275     }
12276 }
12277
12278 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
12279    If from_tty is nonzero, it prints a message to that effect,
12280    which ends with a period (no newline).  */
12281
12282 void
12283 set_ignore_count (int bptnum, int count, int from_tty)
12284 {
12285   struct breakpoint *b;
12286
12287   if (count < 0)
12288     count = 0;
12289
12290   ALL_BREAKPOINTS (b)
12291     if (b->number == bptnum)
12292     {
12293       if (is_tracepoint (b))
12294         {
12295           if (from_tty && count != 0)
12296             printf_filtered (_("Ignore count ignored for tracepoint %d."),
12297                              bptnum);
12298           return;
12299         }
12300       
12301       b->ignore_count = count;
12302       if (from_tty)
12303         {
12304           if (count == 0)
12305             printf_filtered (_("Will stop next time "
12306                                "breakpoint %d is reached."),
12307                              bptnum);
12308           else if (count == 1)
12309             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
12310                              bptnum);
12311           else
12312             printf_filtered (_("Will ignore next %d "
12313                                "crossings of breakpoint %d."),
12314                              count, bptnum);
12315         }
12316       breakpoints_changed ();
12317       observer_notify_breakpoint_modified (b);
12318       return;
12319     }
12320
12321   error (_("No breakpoint number %d."), bptnum);
12322 }
12323
12324 /* Command to set ignore-count of breakpoint N to COUNT.  */
12325
12326 static void
12327 ignore_command (char *args, int from_tty)
12328 {
12329   char *p = args;
12330   int num;
12331
12332   if (p == 0)
12333     error_no_arg (_("a breakpoint number"));
12334
12335   num = get_number (&p);
12336   if (num == 0)
12337     error (_("bad breakpoint number: '%s'"), args);
12338   if (*p == 0)
12339     error (_("Second argument (specified ignore-count) is missing."));
12340
12341   set_ignore_count (num,
12342                     longest_to_int (value_as_long (parse_and_eval (p))),
12343                     from_tty);
12344   if (from_tty)
12345     printf_filtered ("\n");
12346 }
12347 \f
12348 /* Call FUNCTION on each of the breakpoints
12349    whose numbers are given in ARGS.  */
12350
12351 static void
12352 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
12353                                                       void *),
12354                         void *data)
12355 {
12356   int num;
12357   struct breakpoint *b, *tmp;
12358   int match;
12359   struct get_number_or_range_state state;
12360
12361   if (args == 0)
12362     error_no_arg (_("one or more breakpoint numbers"));
12363
12364   init_number_or_range (&state, args);
12365
12366   while (!state.finished)
12367     {
12368       char *p = state.string;
12369
12370       match = 0;
12371
12372       num = get_number_or_range (&state);
12373       if (num == 0)
12374         {
12375           warning (_("bad breakpoint number at or near '%s'"), p);
12376         }
12377       else
12378         {
12379           ALL_BREAKPOINTS_SAFE (b, tmp)
12380             if (b->number == num)
12381               {
12382                 match = 1;
12383                 function (b, data);
12384                 break;
12385               }
12386           if (match == 0)
12387             printf_unfiltered (_("No breakpoint number %d.\n"), num);
12388         }
12389     }
12390 }
12391
12392 static struct bp_location *
12393 find_location_by_number (char *number)
12394 {
12395   char *dot = strchr (number, '.');
12396   char *p1;
12397   int bp_num;
12398   int loc_num;
12399   struct breakpoint *b;
12400   struct bp_location *loc;  
12401
12402   *dot = '\0';
12403
12404   p1 = number;
12405   bp_num = get_number (&p1);
12406   if (bp_num == 0)
12407     error (_("Bad breakpoint number '%s'"), number);
12408
12409   ALL_BREAKPOINTS (b)
12410     if (b->number == bp_num)
12411       {
12412         break;
12413       }
12414
12415   if (!b || b->number != bp_num)
12416     error (_("Bad breakpoint number '%s'"), number);
12417   
12418   p1 = dot+1;
12419   loc_num = get_number (&p1);
12420   if (loc_num == 0)
12421     error (_("Bad breakpoint location number '%s'"), number);
12422
12423   --loc_num;
12424   loc = b->loc;
12425   for (;loc_num && loc; --loc_num, loc = loc->next)
12426     ;
12427   if (!loc)
12428     error (_("Bad breakpoint location number '%s'"), dot+1);
12429     
12430   return loc;  
12431 }
12432
12433
12434 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
12435    If from_tty is nonzero, it prints a message to that effect,
12436    which ends with a period (no newline).  */
12437
12438 void
12439 disable_breakpoint (struct breakpoint *bpt)
12440 {
12441   /* Never disable a watchpoint scope breakpoint; we want to
12442      hit them when we leave scope so we can delete both the
12443      watchpoint and its scope breakpoint at that time.  */
12444   if (bpt->type == bp_watchpoint_scope)
12445     return;
12446
12447   /* You can't disable permanent breakpoints.  */
12448   if (bpt->enable_state == bp_permanent)
12449     return;
12450
12451   bpt->enable_state = bp_disabled;
12452
12453   if (target_supports_enable_disable_tracepoint ()
12454       && current_trace_status ()->running && is_tracepoint (bpt))
12455     {
12456       struct bp_location *location;
12457      
12458       for (location = bpt->loc; location; location = location->next)
12459         target_disable_tracepoint (location);
12460     }
12461
12462   update_global_location_list (0);
12463
12464   observer_notify_breakpoint_modified (bpt);
12465 }
12466
12467 /* A callback for iterate_over_related_breakpoints.  */
12468
12469 static void
12470 do_disable_breakpoint (struct breakpoint *b, void *ignore)
12471 {
12472   disable_breakpoint (b);
12473 }
12474
12475 /* A callback for map_breakpoint_numbers that calls
12476    disable_breakpoint.  */
12477
12478 static void
12479 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
12480 {
12481   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
12482 }
12483
12484 static void
12485 disable_command (char *args, int from_tty)
12486 {
12487   if (args == 0)
12488     {
12489       struct breakpoint *bpt;
12490
12491       ALL_BREAKPOINTS (bpt)
12492         if (user_breakpoint_p (bpt))
12493           disable_breakpoint (bpt);
12494     }
12495   else if (strchr (args, '.'))
12496     {
12497       struct bp_location *loc = find_location_by_number (args);
12498       if (loc)
12499         {
12500           loc->enabled = 0;
12501           if (target_supports_enable_disable_tracepoint ()
12502               && current_trace_status ()->running && loc->owner
12503               && is_tracepoint (loc->owner))
12504             target_disable_tracepoint (loc);
12505         }
12506       update_global_location_list (0);
12507     }
12508   else
12509     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
12510 }
12511
12512 static void
12513 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition)
12514 {
12515   int target_resources_ok;
12516
12517   if (bpt->type == bp_hardware_breakpoint)
12518     {
12519       int i;
12520       i = hw_breakpoint_used_count ();
12521       target_resources_ok = 
12522         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
12523                                             i + 1, 0);
12524       if (target_resources_ok == 0)
12525         error (_("No hardware breakpoint support in the target."));
12526       else if (target_resources_ok < 0)
12527         error (_("Hardware breakpoints used exceeds limit."));
12528     }
12529
12530   if (is_watchpoint (bpt))
12531     {
12532       /* Initialize it just to avoid a GCC false warning.  */
12533       enum enable_state orig_enable_state = 0;
12534       volatile struct gdb_exception e;
12535
12536       TRY_CATCH (e, RETURN_MASK_ALL)
12537         {
12538           struct watchpoint *w = (struct watchpoint *) bpt;
12539
12540           orig_enable_state = bpt->enable_state;
12541           bpt->enable_state = bp_enabled;
12542           update_watchpoint (w, 1 /* reparse */);
12543         }
12544       if (e.reason < 0)
12545         {
12546           bpt->enable_state = orig_enable_state;
12547           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
12548                              bpt->number);
12549           return;
12550         }
12551     }
12552
12553   if (bpt->enable_state != bp_permanent)
12554     bpt->enable_state = bp_enabled;
12555
12556   if (target_supports_enable_disable_tracepoint ()
12557       && current_trace_status ()->running && is_tracepoint (bpt))
12558     {
12559       struct bp_location *location;
12560
12561       for (location = bpt->loc; location; location = location->next)
12562         target_enable_tracepoint (location);
12563     }
12564
12565   bpt->disposition = disposition;
12566   update_global_location_list (1);
12567   breakpoints_changed ();
12568   
12569   observer_notify_breakpoint_modified (bpt);
12570 }
12571
12572
12573 void
12574 enable_breakpoint (struct breakpoint *bpt)
12575 {
12576   enable_breakpoint_disp (bpt, bpt->disposition);
12577 }
12578
12579 static void
12580 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
12581 {
12582   enable_breakpoint (bpt);
12583 }
12584
12585 /* A callback for map_breakpoint_numbers that calls
12586    enable_breakpoint.  */
12587
12588 static void
12589 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
12590 {
12591   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
12592 }
12593
12594 /* The enable command enables the specified breakpoints (or all defined
12595    breakpoints) so they once again become (or continue to be) effective
12596    in stopping the inferior.  */
12597
12598 static void
12599 enable_command (char *args, int from_tty)
12600 {
12601   if (args == 0)
12602     {
12603       struct breakpoint *bpt;
12604
12605       ALL_BREAKPOINTS (bpt)
12606         if (user_breakpoint_p (bpt))
12607           enable_breakpoint (bpt);
12608     }
12609   else if (strchr (args, '.'))
12610     {
12611       struct bp_location *loc = find_location_by_number (args);
12612       if (loc)
12613         {
12614           loc->enabled = 1;
12615           if (target_supports_enable_disable_tracepoint ()
12616               && current_trace_status ()->running && loc->owner
12617               && is_tracepoint (loc->owner))
12618             target_enable_tracepoint (loc);
12619         }
12620       update_global_location_list (1);
12621     }
12622   else
12623     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
12624 }
12625
12626 static void
12627 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
12628 {
12629   enum bpdisp disp = *(enum bpdisp *) arg;
12630
12631   enable_breakpoint_disp (bpt, disp);
12632 }
12633
12634 static void
12635 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
12636 {
12637   enum bpdisp disp = disp_disable;
12638
12639   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
12640 }
12641
12642 static void
12643 enable_once_command (char *args, int from_tty)
12644 {
12645   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
12646 }
12647
12648 static void
12649 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
12650 {
12651   enum bpdisp disp = disp_del;
12652
12653   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
12654 }
12655
12656 static void
12657 enable_delete_command (char *args, int from_tty)
12658 {
12659   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
12660 }
12661 \f
12662 static void
12663 set_breakpoint_cmd (char *args, int from_tty)
12664 {
12665 }
12666
12667 static void
12668 show_breakpoint_cmd (char *args, int from_tty)
12669 {
12670 }
12671
12672 /* Invalidate last known value of any hardware watchpoint if
12673    the memory which that value represents has been written to by
12674    GDB itself.  */
12675
12676 static void
12677 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
12678                                       const bfd_byte *data)
12679 {
12680   struct breakpoint *bp;
12681
12682   ALL_BREAKPOINTS (bp)
12683     if (bp->enable_state == bp_enabled
12684         && bp->type == bp_hardware_watchpoint)
12685       {
12686         struct watchpoint *wp = (struct watchpoint *) bp;
12687
12688         if (wp->val_valid && wp->val)
12689           {
12690             struct bp_location *loc;
12691
12692             for (loc = bp->loc; loc != NULL; loc = loc->next)
12693               if (loc->loc_type == bp_loc_hardware_watchpoint
12694                   && loc->address + loc->length > addr
12695                   && addr + len > loc->address)
12696                 {
12697                   value_free (wp->val);
12698                   wp->val = NULL;
12699                   wp->val_valid = 0;
12700                 }
12701           }
12702       }
12703 }
12704
12705 /* Use the last displayed codepoint's values, or nothing
12706    if they aren't valid.  */
12707
12708 struct symtabs_and_lines
12709 decode_line_spec_1 (char *string, int flags)
12710 {
12711   struct symtabs_and_lines sals;
12712
12713   if (string == 0)
12714     error (_("Empty line specification."));
12715   if (last_displayed_sal_is_valid ())
12716     sals = decode_line_1 (&string, flags,
12717                           get_last_displayed_symtab (),
12718                           get_last_displayed_line ());
12719   else
12720     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
12721   if (*string)
12722     error (_("Junk at end of line specification: %s"), string);
12723   return sals;
12724 }
12725
12726 /* Create and insert a raw software breakpoint at PC.  Return an
12727    identifier, which should be used to remove the breakpoint later.
12728    In general, places which call this should be using something on the
12729    breakpoint chain instead; this function should be eliminated
12730    someday.  */
12731
12732 void *
12733 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
12734                                   struct address_space *aspace, CORE_ADDR pc)
12735 {
12736   struct bp_target_info *bp_tgt;
12737
12738   bp_tgt = XZALLOC (struct bp_target_info);
12739
12740   bp_tgt->placed_address_space = aspace;
12741   bp_tgt->placed_address = pc;
12742
12743   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
12744     {
12745       /* Could not insert the breakpoint.  */
12746       xfree (bp_tgt);
12747       return NULL;
12748     }
12749
12750   return bp_tgt;
12751 }
12752
12753 /* Remove a breakpoint BP inserted by
12754    deprecated_insert_raw_breakpoint.  */
12755
12756 int
12757 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
12758 {
12759   struct bp_target_info *bp_tgt = bp;
12760   int ret;
12761
12762   ret = target_remove_breakpoint (gdbarch, bp_tgt);
12763   xfree (bp_tgt);
12764
12765   return ret;
12766 }
12767
12768 /* One (or perhaps two) breakpoints used for software single
12769    stepping.  */
12770
12771 static void *single_step_breakpoints[2];
12772 static struct gdbarch *single_step_gdbarch[2];
12773
12774 /* Create and insert a breakpoint for software single step.  */
12775
12776 void
12777 insert_single_step_breakpoint (struct gdbarch *gdbarch,
12778                                struct address_space *aspace, 
12779                                CORE_ADDR next_pc)
12780 {
12781   void **bpt_p;
12782
12783   if (single_step_breakpoints[0] == NULL)
12784     {
12785       bpt_p = &single_step_breakpoints[0];
12786       single_step_gdbarch[0] = gdbarch;
12787     }
12788   else
12789     {
12790       gdb_assert (single_step_breakpoints[1] == NULL);
12791       bpt_p = &single_step_breakpoints[1];
12792       single_step_gdbarch[1] = gdbarch;
12793     }
12794
12795   /* NOTE drow/2006-04-11: A future improvement to this function would
12796      be to only create the breakpoints once, and actually put them on
12797      the breakpoint chain.  That would let us use set_raw_breakpoint.
12798      We could adjust the addresses each time they were needed.  Doing
12799      this requires corresponding changes elsewhere where single step
12800      breakpoints are handled, however.  So, for now, we use this.  */
12801
12802   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
12803   if (*bpt_p == NULL)
12804     error (_("Could not insert single-step breakpoint at %s"),
12805              paddress (gdbarch, next_pc));
12806 }
12807
12808 /* Check if the breakpoints used for software single stepping
12809    were inserted or not.  */
12810
12811 int
12812 single_step_breakpoints_inserted (void)
12813 {
12814   return (single_step_breakpoints[0] != NULL
12815           || single_step_breakpoints[1] != NULL);
12816 }
12817
12818 /* Remove and delete any breakpoints used for software single step.  */
12819
12820 void
12821 remove_single_step_breakpoints (void)
12822 {
12823   gdb_assert (single_step_breakpoints[0] != NULL);
12824
12825   /* See insert_single_step_breakpoint for more about this deprecated
12826      call.  */
12827   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
12828                                     single_step_breakpoints[0]);
12829   single_step_gdbarch[0] = NULL;
12830   single_step_breakpoints[0] = NULL;
12831
12832   if (single_step_breakpoints[1] != NULL)
12833     {
12834       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
12835                                         single_step_breakpoints[1]);
12836       single_step_gdbarch[1] = NULL;
12837       single_step_breakpoints[1] = NULL;
12838     }
12839 }
12840
12841 /* Delete software single step breakpoints without removing them from
12842    the inferior.  This is intended to be used if the inferior's address
12843    space where they were inserted is already gone, e.g. after exit or
12844    exec.  */
12845
12846 void
12847 cancel_single_step_breakpoints (void)
12848 {
12849   int i;
12850
12851   for (i = 0; i < 2; i++)
12852     if (single_step_breakpoints[i])
12853       {
12854         xfree (single_step_breakpoints[i]);
12855         single_step_breakpoints[i] = NULL;
12856         single_step_gdbarch[i] = NULL;
12857       }
12858 }
12859
12860 /* Detach software single-step breakpoints from INFERIOR_PTID without
12861    removing them.  */
12862
12863 static void
12864 detach_single_step_breakpoints (void)
12865 {
12866   int i;
12867
12868   for (i = 0; i < 2; i++)
12869     if (single_step_breakpoints[i])
12870       target_remove_breakpoint (single_step_gdbarch[i],
12871                                 single_step_breakpoints[i]);
12872 }
12873
12874 /* Check whether a software single-step breakpoint is inserted at
12875    PC.  */
12876
12877 static int
12878 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
12879                                         CORE_ADDR pc)
12880 {
12881   int i;
12882
12883   for (i = 0; i < 2; i++)
12884     {
12885       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
12886       if (bp_tgt
12887           && breakpoint_address_match (bp_tgt->placed_address_space,
12888                                        bp_tgt->placed_address,
12889                                        aspace, pc))
12890         return 1;
12891     }
12892
12893   return 0;
12894 }
12895
12896 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
12897    non-zero otherwise.  */
12898 static int
12899 is_syscall_catchpoint_enabled (struct breakpoint *bp)
12900 {
12901   if (syscall_catchpoint_p (bp)
12902       && bp->enable_state != bp_disabled
12903       && bp->enable_state != bp_call_disabled)
12904     return 1;
12905   else
12906     return 0;
12907 }
12908
12909 int
12910 catch_syscall_enabled (void)
12911 {
12912   struct inferior *inf = current_inferior ();
12913
12914   return inf->total_syscalls_count != 0;
12915 }
12916
12917 int
12918 catching_syscall_number (int syscall_number)
12919 {
12920   struct breakpoint *bp;
12921
12922   ALL_BREAKPOINTS (bp)
12923     if (is_syscall_catchpoint_enabled (bp))
12924       {
12925         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
12926
12927         if (c->syscalls_to_be_caught)
12928           {
12929             int i, iter;
12930             for (i = 0;
12931                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
12932                  i++)
12933               if (syscall_number == iter)
12934                 return 1;
12935           }
12936         else
12937           return 1;
12938       }
12939
12940   return 0;
12941 }
12942
12943 /* Complete syscall names.  Used by "catch syscall".  */
12944 static char **
12945 catch_syscall_completer (struct cmd_list_element *cmd,
12946                          char *text, char *word)
12947 {
12948   const char **list = get_syscall_names ();
12949   char **retlist
12950     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
12951
12952   xfree (list);
12953   return retlist;
12954 }
12955
12956 /* Tracepoint-specific operations.  */
12957
12958 /* Set tracepoint count to NUM.  */
12959 static void
12960 set_tracepoint_count (int num)
12961 {
12962   tracepoint_count = num;
12963   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
12964 }
12965
12966 void
12967 trace_command (char *arg, int from_tty)
12968 {
12969   if (create_breakpoint (get_current_arch (),
12970                          arg,
12971                          NULL, 0, 1 /* parse arg */,
12972                          0 /* tempflag */,
12973                          bp_tracepoint /* type_wanted */,
12974                          0 /* Ignore count */,
12975                          pending_break_support,
12976                          &tracepoint_breakpoint_ops,
12977                          from_tty,
12978                          1 /* enabled */,
12979                          0 /* internal */))
12980     set_tracepoint_count (breakpoint_count);
12981 }
12982
12983 void
12984 ftrace_command (char *arg, int from_tty)
12985 {
12986   if (create_breakpoint (get_current_arch (),
12987                          arg,
12988                          NULL, 0, 1 /* parse arg */,
12989                          0 /* tempflag */,
12990                          bp_fast_tracepoint /* type_wanted */,
12991                          0 /* Ignore count */,
12992                          pending_break_support,
12993                          &tracepoint_breakpoint_ops,
12994                          from_tty,
12995                          1 /* enabled */,
12996                          0 /* internal */))
12997     set_tracepoint_count (breakpoint_count);
12998 }
12999
13000 /* strace command implementation.  Creates a static tracepoint.  */
13001
13002 void
13003 strace_command (char *arg, int from_tty)
13004 {
13005   struct breakpoint_ops *ops;
13006
13007   /* Decide if we are dealing with a static tracepoint marker (`-m'),
13008      or with a normal static tracepoint.  */
13009   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
13010     ops = &strace_marker_breakpoint_ops;
13011   else
13012     ops = &tracepoint_breakpoint_ops;
13013
13014   if (create_breakpoint (get_current_arch (),
13015                          arg,
13016                          NULL, 0, 1 /* parse arg */,
13017                          0 /* tempflag */,
13018                          bp_static_tracepoint /* type_wanted */,
13019                          0 /* Ignore count */,
13020                          pending_break_support,
13021                          ops,
13022                          from_tty,
13023                          1 /* enabled */,
13024                          0 /* internal */))
13025     set_tracepoint_count (breakpoint_count);
13026 }
13027
13028 /* Set up a fake reader function that gets command lines from a linked
13029    list that was acquired during tracepoint uploading.  */
13030
13031 static struct uploaded_tp *this_utp;
13032 static int next_cmd;
13033
13034 static char *
13035 read_uploaded_action (void)
13036 {
13037   char *rslt;
13038
13039   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
13040
13041   next_cmd++;
13042
13043   return rslt;
13044 }
13045
13046 /* Given information about a tracepoint as recorded on a target (which
13047    can be either a live system or a trace file), attempt to create an
13048    equivalent GDB tracepoint.  This is not a reliable process, since
13049    the target does not necessarily have all the information used when
13050    the tracepoint was originally defined.  */
13051   
13052 struct tracepoint *
13053 create_tracepoint_from_upload (struct uploaded_tp *utp)
13054 {
13055   char *addr_str, small_buf[100];
13056   struct tracepoint *tp;
13057
13058   if (utp->at_string)
13059     addr_str = utp->at_string;
13060   else
13061     {
13062       /* In the absence of a source location, fall back to raw
13063          address.  Since there is no way to confirm that the address
13064          means the same thing as when the trace was started, warn the
13065          user.  */
13066       warning (_("Uploaded tracepoint %d has no "
13067                  "source location, using raw address"),
13068                utp->number);
13069       sprintf (small_buf, "*%s", hex_string (utp->addr));
13070       addr_str = small_buf;
13071     }
13072
13073   /* There's not much we can do with a sequence of bytecodes.  */
13074   if (utp->cond && !utp->cond_string)
13075     warning (_("Uploaded tracepoint %d condition "
13076                "has no source form, ignoring it"),
13077              utp->number);
13078
13079   if (!create_breakpoint (get_current_arch (),
13080                           addr_str,
13081                           utp->cond_string, -1, 0 /* parse cond/thread */,
13082                           0 /* tempflag */,
13083                           utp->type /* type_wanted */,
13084                           0 /* Ignore count */,
13085                           pending_break_support,
13086                           &tracepoint_breakpoint_ops,
13087                           0 /* from_tty */,
13088                           utp->enabled /* enabled */,
13089                           0 /* internal */))
13090     return NULL;
13091
13092   set_tracepoint_count (breakpoint_count);
13093   
13094   /* Get the tracepoint we just created.  */
13095   tp = get_tracepoint (tracepoint_count);
13096   gdb_assert (tp != NULL);
13097
13098   if (utp->pass > 0)
13099     {
13100       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
13101
13102       trace_pass_command (small_buf, 0);
13103     }
13104
13105   /* If we have uploaded versions of the original commands, set up a
13106      special-purpose "reader" function and call the usual command line
13107      reader, then pass the result to the breakpoint command-setting
13108      function.  */
13109   if (!VEC_empty (char_ptr, utp->cmd_strings))
13110     {
13111       struct command_line *cmd_list;
13112
13113       this_utp = utp;
13114       next_cmd = 0;
13115
13116       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
13117
13118       breakpoint_set_commands (&tp->base, cmd_list);
13119     }
13120   else if (!VEC_empty (char_ptr, utp->actions)
13121            || !VEC_empty (char_ptr, utp->step_actions))
13122     warning (_("Uploaded tracepoint %d actions "
13123                "have no source form, ignoring them"),
13124              utp->number);
13125
13126   /* Copy any status information that might be available.  */
13127   tp->base.hit_count = utp->hit_count;
13128   tp->traceframe_usage = utp->traceframe_usage;
13129
13130   return tp;
13131 }
13132   
13133 /* Print information on tracepoint number TPNUM_EXP, or all if
13134    omitted.  */
13135
13136 static void
13137 tracepoints_info (char *args, int from_tty)
13138 {
13139   struct ui_out *uiout = current_uiout;
13140   int num_printed;
13141
13142   num_printed = breakpoint_1 (args, 0, is_tracepoint);
13143
13144   if (num_printed == 0)
13145     {
13146       if (args == NULL || *args == '\0')
13147         ui_out_message (uiout, 0, "No tracepoints.\n");
13148       else
13149         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
13150     }
13151
13152   default_collect_info ();
13153 }
13154
13155 /* The 'enable trace' command enables tracepoints.
13156    Not supported by all targets.  */
13157 static void
13158 enable_trace_command (char *args, int from_tty)
13159 {
13160   enable_command (args, from_tty);
13161 }
13162
13163 /* The 'disable trace' command disables tracepoints.
13164    Not supported by all targets.  */
13165 static void
13166 disable_trace_command (char *args, int from_tty)
13167 {
13168   disable_command (args, from_tty);
13169 }
13170
13171 /* Remove a tracepoint (or all if no argument).  */
13172 static void
13173 delete_trace_command (char *arg, int from_tty)
13174 {
13175   struct breakpoint *b, *b_tmp;
13176
13177   dont_repeat ();
13178
13179   if (arg == 0)
13180     {
13181       int breaks_to_delete = 0;
13182
13183       /* Delete all breakpoints if no argument.
13184          Do not delete internal or call-dummy breakpoints, these
13185          have to be deleted with an explicit breakpoint number 
13186          argument.  */
13187       ALL_TRACEPOINTS (b)
13188         if (is_tracepoint (b) && user_breakpoint_p (b))
13189           {
13190             breaks_to_delete = 1;
13191             break;
13192           }
13193
13194       /* Ask user only if there are some breakpoints to delete.  */
13195       if (!from_tty
13196           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
13197         {
13198           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13199             if (is_tracepoint (b) && user_breakpoint_p (b))
13200               delete_breakpoint (b);
13201         }
13202     }
13203   else
13204     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13205 }
13206
13207 /* Helper function for trace_pass_command.  */
13208
13209 static void
13210 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
13211 {
13212   tp->pass_count = count;
13213   observer_notify_tracepoint_modified (tp->base.number);
13214   if (from_tty)
13215     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
13216                      tp->base.number, count);
13217 }
13218
13219 /* Set passcount for tracepoint.
13220
13221    First command argument is passcount, second is tracepoint number.
13222    If tracepoint number omitted, apply to most recently defined.
13223    Also accepts special argument "all".  */
13224
13225 static void
13226 trace_pass_command (char *args, int from_tty)
13227 {
13228   struct tracepoint *t1;
13229   unsigned int count;
13230
13231   if (args == 0 || *args == 0)
13232     error (_("passcount command requires an "
13233              "argument (count + optional TP num)"));
13234
13235   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
13236
13237   while (*args && isspace ((int) *args))
13238     args++;
13239
13240   if (*args && strncasecmp (args, "all", 3) == 0)
13241     {
13242       struct breakpoint *b;
13243
13244       args += 3;                        /* Skip special argument "all".  */
13245       if (*args)
13246         error (_("Junk at end of arguments."));
13247
13248       ALL_TRACEPOINTS (b)
13249       {
13250         t1 = (struct tracepoint *) b;
13251         trace_pass_set_count (t1, count, from_tty);
13252       }
13253     }
13254   else if (*args == '\0')
13255     {
13256       t1 = get_tracepoint_by_number (&args, NULL, 1);
13257       if (t1)
13258         trace_pass_set_count (t1, count, from_tty);
13259     }
13260   else
13261     {
13262       struct get_number_or_range_state state;
13263
13264       init_number_or_range (&state, args);
13265       while (!state.finished)
13266         {
13267           t1 = get_tracepoint_by_number (&args, &state, 1);
13268           if (t1)
13269             trace_pass_set_count (t1, count, from_tty);
13270         }
13271     }
13272 }
13273
13274 struct tracepoint *
13275 get_tracepoint (int num)
13276 {
13277   struct breakpoint *t;
13278
13279   ALL_TRACEPOINTS (t)
13280     if (t->number == num)
13281       return (struct tracepoint *) t;
13282
13283   return NULL;
13284 }
13285
13286 /* Find the tracepoint with the given target-side number (which may be
13287    different from the tracepoint number after disconnecting and
13288    reconnecting).  */
13289
13290 struct tracepoint *
13291 get_tracepoint_by_number_on_target (int num)
13292 {
13293   struct breakpoint *b;
13294
13295   ALL_TRACEPOINTS (b)
13296     {
13297       struct tracepoint *t = (struct tracepoint *) b;
13298
13299       if (t->number_on_target == num)
13300         return t;
13301     }
13302
13303   return NULL;
13304 }
13305
13306 /* Utility: parse a tracepoint number and look it up in the list.
13307    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
13308    If OPTIONAL_P is true, then if the argument is missing, the most
13309    recent tracepoint (tracepoint_count) is returned.  */
13310 struct tracepoint *
13311 get_tracepoint_by_number (char **arg,
13312                           struct get_number_or_range_state *state,
13313                           int optional_p)
13314 {
13315   extern int tracepoint_count;
13316   struct breakpoint *t;
13317   int tpnum;
13318   char *instring = arg == NULL ? NULL : *arg;
13319
13320   if (state)
13321     {
13322       gdb_assert (!state->finished);
13323       tpnum = get_number_or_range (state);
13324     }
13325   else if (arg == NULL || *arg == NULL || ! **arg)
13326     {
13327       if (optional_p)
13328         tpnum = tracepoint_count;
13329       else
13330         error_no_arg (_("tracepoint number"));
13331     }
13332   else
13333     tpnum = get_number (arg);
13334
13335   if (tpnum <= 0)
13336     {
13337       if (instring && *instring)
13338         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
13339                          instring);
13340       else
13341         printf_filtered (_("Tracepoint argument missing "
13342                            "and no previous tracepoint\n"));
13343       return NULL;
13344     }
13345
13346   ALL_TRACEPOINTS (t)
13347     if (t->number == tpnum)
13348     {
13349       return (struct tracepoint *) t;
13350     }
13351
13352   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
13353   return NULL;
13354 }
13355
13356 void
13357 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
13358 {
13359   if (b->thread != -1)
13360     fprintf_unfiltered (fp, " thread %d", b->thread);
13361
13362   if (b->task != 0)
13363     fprintf_unfiltered (fp, " task %d", b->task);
13364
13365   fprintf_unfiltered (fp, "\n");
13366 }
13367
13368 /* Save information on user settable breakpoints (watchpoints, etc) to
13369    a new script file named FILENAME.  If FILTER is non-NULL, call it
13370    on each breakpoint and only include the ones for which it returns
13371    non-zero.  */
13372
13373 static void
13374 save_breakpoints (char *filename, int from_tty,
13375                   int (*filter) (const struct breakpoint *))
13376 {
13377   struct breakpoint *tp;
13378   int any = 0;
13379   char *pathname;
13380   struct cleanup *cleanup;
13381   struct ui_file *fp;
13382   int extra_trace_bits = 0;
13383
13384   if (filename == 0 || *filename == 0)
13385     error (_("Argument required (file name in which to save)"));
13386
13387   /* See if we have anything to save.  */
13388   ALL_BREAKPOINTS (tp)
13389   {
13390     /* Skip internal and momentary breakpoints.  */
13391     if (!user_breakpoint_p (tp))
13392       continue;
13393
13394     /* If we have a filter, only save the breakpoints it accepts.  */
13395     if (filter && !filter (tp))
13396       continue;
13397
13398     any = 1;
13399
13400     if (is_tracepoint (tp))
13401       {
13402         extra_trace_bits = 1;
13403
13404         /* We can stop searching.  */
13405         break;
13406       }
13407   }
13408
13409   if (!any)
13410     {
13411       warning (_("Nothing to save."));
13412       return;
13413     }
13414
13415   pathname = tilde_expand (filename);
13416   cleanup = make_cleanup (xfree, pathname);
13417   fp = gdb_fopen (pathname, "w");
13418   if (!fp)
13419     error (_("Unable to open file '%s' for saving (%s)"),
13420            filename, safe_strerror (errno));
13421   make_cleanup_ui_file_delete (fp);
13422
13423   if (extra_trace_bits)
13424     save_trace_state_variables (fp);
13425
13426   ALL_BREAKPOINTS (tp)
13427   {
13428     /* Skip internal and momentary breakpoints.  */
13429     if (!user_breakpoint_p (tp))
13430       continue;
13431
13432     /* If we have a filter, only save the breakpoints it accepts.  */
13433     if (filter && !filter (tp))
13434       continue;
13435
13436     tp->ops->print_recreate (tp, fp);
13437
13438     /* Note, we can't rely on tp->number for anything, as we can't
13439        assume the recreated breakpoint numbers will match.  Use $bpnum
13440        instead.  */
13441
13442     if (tp->cond_string)
13443       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
13444
13445     if (tp->ignore_count)
13446       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
13447
13448     if (tp->commands)
13449       {
13450         volatile struct gdb_exception ex;       
13451
13452         fprintf_unfiltered (fp, "  commands\n");
13453         
13454         ui_out_redirect (current_uiout, fp);
13455         TRY_CATCH (ex, RETURN_MASK_ALL)
13456           {
13457             print_command_lines (current_uiout, tp->commands->commands, 2);
13458           }
13459         ui_out_redirect (current_uiout, NULL);
13460
13461         if (ex.reason < 0)
13462           throw_exception (ex);
13463
13464         fprintf_unfiltered (fp, "  end\n");
13465       }
13466
13467     if (tp->enable_state == bp_disabled)
13468       fprintf_unfiltered (fp, "disable\n");
13469
13470     /* If this is a multi-location breakpoint, check if the locations
13471        should be individually disabled.  Watchpoint locations are
13472        special, and not user visible.  */
13473     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
13474       {
13475         struct bp_location *loc;
13476         int n = 1;
13477
13478         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
13479           if (!loc->enabled)
13480             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
13481       }
13482   }
13483
13484   if (extra_trace_bits && *default_collect)
13485     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
13486
13487   do_cleanups (cleanup);
13488   if (from_tty)
13489     printf_filtered (_("Saved to file '%s'.\n"), filename);
13490 }
13491
13492 /* The `save breakpoints' command.  */
13493
13494 static void
13495 save_breakpoints_command (char *args, int from_tty)
13496 {
13497   save_breakpoints (args, from_tty, NULL);
13498 }
13499
13500 /* The `save tracepoints' command.  */
13501
13502 static void
13503 save_tracepoints_command (char *args, int from_tty)
13504 {
13505   save_breakpoints (args, from_tty, is_tracepoint);
13506 }
13507
13508 /* Create a vector of all tracepoints.  */
13509
13510 VEC(breakpoint_p) *
13511 all_tracepoints (void)
13512 {
13513   VEC(breakpoint_p) *tp_vec = 0;
13514   struct breakpoint *tp;
13515
13516   ALL_TRACEPOINTS (tp)
13517   {
13518     VEC_safe_push (breakpoint_p, tp_vec, tp);
13519   }
13520
13521   return tp_vec;
13522 }
13523
13524 \f
13525 /* This help string is used for the break, hbreak, tbreak and thbreak
13526    commands.  It is defined as a macro to prevent duplication.
13527    COMMAND should be a string constant containing the name of the
13528    command.  */
13529 #define BREAK_ARGS_HELP(command) \
13530 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
13531 LOCATION may be a line number, function name, or \"*\" and an address.\n\
13532 If a line number is specified, break at start of code for that line.\n\
13533 If a function is specified, break at start of code for that function.\n\
13534 If an address is specified, break at that exact address.\n\
13535 With no LOCATION, uses current execution address of the selected\n\
13536 stack frame.  This is useful for breaking on return to a stack frame.\n\
13537 \n\
13538 THREADNUM is the number from \"info threads\".\n\
13539 CONDITION is a boolean expression.\n\
13540 \n\
13541 Multiple breakpoints at one place are permitted, and useful if their\n\
13542 conditions are different.\n\
13543 \n\
13544 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
13545
13546 /* List of subcommands for "catch".  */
13547 static struct cmd_list_element *catch_cmdlist;
13548
13549 /* List of subcommands for "tcatch".  */
13550 static struct cmd_list_element *tcatch_cmdlist;
13551
13552 void
13553 add_catch_command (char *name, char *docstring,
13554                    void (*sfunc) (char *args, int from_tty,
13555                                   struct cmd_list_element *command),
13556                    char **(*completer) (struct cmd_list_element *cmd,
13557                                          char *text, char *word),
13558                    void *user_data_catch,
13559                    void *user_data_tcatch)
13560 {
13561   struct cmd_list_element *command;
13562
13563   command = add_cmd (name, class_breakpoint, NULL, docstring,
13564                      &catch_cmdlist);
13565   set_cmd_sfunc (command, sfunc);
13566   set_cmd_context (command, user_data_catch);
13567   set_cmd_completer (command, completer);
13568
13569   command = add_cmd (name, class_breakpoint, NULL, docstring,
13570                      &tcatch_cmdlist);
13571   set_cmd_sfunc (command, sfunc);
13572   set_cmd_context (command, user_data_tcatch);
13573   set_cmd_completer (command, completer);
13574 }
13575
13576 static void
13577 clear_syscall_counts (struct inferior *inf)
13578 {
13579   inf->total_syscalls_count = 0;
13580   inf->any_syscall_count = 0;
13581   VEC_free (int, inf->syscalls_counts);
13582 }
13583
13584 static void
13585 save_command (char *arg, int from_tty)
13586 {
13587   printf_unfiltered (_("\"save\" must be followed by "
13588                        "the name of a save subcommand.\n"));
13589   help_list (save_cmdlist, "save ", -1, gdb_stdout);
13590 }
13591
13592 struct breakpoint *
13593 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
13594                           void *data)
13595 {
13596   struct breakpoint *b, *b_tmp;
13597
13598   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13599     {
13600       if ((*callback) (b, data))
13601         return b;
13602     }
13603
13604   return NULL;
13605 }
13606
13607 /* Zero if any of the breakpoint's locations could be a location where
13608    functions have been inlined, nonzero otherwise.  */
13609
13610 static int
13611 is_non_inline_function (struct breakpoint *b)
13612 {
13613   /* The shared library event breakpoint is set on the address of a
13614      non-inline function.  */
13615   if (b->type == bp_shlib_event)
13616     return 1;
13617
13618   return 0;
13619 }
13620
13621 /* Nonzero if the specified PC cannot be a location where functions
13622    have been inlined.  */
13623
13624 int
13625 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc)
13626 {
13627   struct breakpoint *b;
13628   struct bp_location *bl;
13629
13630   ALL_BREAKPOINTS (b)
13631     {
13632       if (!is_non_inline_function (b))
13633         continue;
13634
13635       for (bl = b->loc; bl != NULL; bl = bl->next)
13636         {
13637           if (!bl->shlib_disabled
13638               && bpstat_check_location (bl, aspace, pc))
13639             return 1;
13640         }
13641     }
13642
13643   return 0;
13644 }
13645
13646 void
13647 initialize_breakpoint_ops (void)
13648 {
13649   static int initialized = 0;
13650
13651   struct breakpoint_ops *ops;
13652
13653   if (initialized)
13654     return;
13655   initialized = 1;
13656
13657   /* The breakpoint_ops structure to be inherit by all kinds of
13658      breakpoints (real breakpoints, i.e., user "break" breakpoints,
13659      internal and momentary breakpoints, etc.).  */
13660   ops = &bkpt_base_breakpoint_ops;
13661   *ops = base_breakpoint_ops;
13662   ops->re_set = bkpt_re_set;
13663   ops->insert_location = bkpt_insert_location;
13664   ops->remove_location = bkpt_remove_location;
13665   ops->breakpoint_hit = bkpt_breakpoint_hit;
13666   ops->create_sals_from_address = bkpt_create_sals_from_address;
13667   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
13668   ops->decode_linespec = bkpt_decode_linespec;
13669
13670   /* The breakpoint_ops structure to be used in regular breakpoints.  */
13671   ops = &bkpt_breakpoint_ops;
13672   *ops = bkpt_base_breakpoint_ops;
13673   ops->re_set = bkpt_re_set;
13674   ops->resources_needed = bkpt_resources_needed;
13675   ops->print_it = bkpt_print_it;
13676   ops->print_mention = bkpt_print_mention;
13677   ops->print_recreate = bkpt_print_recreate;
13678
13679   /* Ranged breakpoints.  */
13680   ops = &ranged_breakpoint_ops;
13681   *ops = bkpt_breakpoint_ops;
13682   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
13683   ops->resources_needed = resources_needed_ranged_breakpoint;
13684   ops->print_it = print_it_ranged_breakpoint;
13685   ops->print_one = print_one_ranged_breakpoint;
13686   ops->print_one_detail = print_one_detail_ranged_breakpoint;
13687   ops->print_mention = print_mention_ranged_breakpoint;
13688   ops->print_recreate = print_recreate_ranged_breakpoint;
13689
13690   /* Internal breakpoints.  */
13691   ops = &internal_breakpoint_ops;
13692   *ops = bkpt_base_breakpoint_ops;
13693   ops->re_set = internal_bkpt_re_set;
13694   ops->check_status = internal_bkpt_check_status;
13695   ops->print_it = internal_bkpt_print_it;
13696   ops->print_mention = internal_bkpt_print_mention;
13697
13698   /* Momentary breakpoints.  */
13699   ops = &momentary_breakpoint_ops;
13700   *ops = bkpt_base_breakpoint_ops;
13701   ops->re_set = momentary_bkpt_re_set;
13702   ops->check_status = momentary_bkpt_check_status;
13703   ops->print_it = momentary_bkpt_print_it;
13704   ops->print_mention = momentary_bkpt_print_mention;
13705
13706   /* GNU v3 exception catchpoints.  */
13707   ops = &gnu_v3_exception_catchpoint_ops;
13708   *ops = bkpt_breakpoint_ops;
13709   ops->print_it = print_it_exception_catchpoint;
13710   ops->print_one = print_one_exception_catchpoint;
13711   ops->print_mention = print_mention_exception_catchpoint;
13712   ops->print_recreate = print_recreate_exception_catchpoint;
13713
13714   /* Watchpoints.  */
13715   ops = &watchpoint_breakpoint_ops;
13716   *ops = base_breakpoint_ops;
13717   ops->dtor = dtor_watchpoint;
13718   ops->re_set = re_set_watchpoint;
13719   ops->insert_location = insert_watchpoint;
13720   ops->remove_location = remove_watchpoint;
13721   ops->breakpoint_hit = breakpoint_hit_watchpoint;
13722   ops->check_status = check_status_watchpoint;
13723   ops->resources_needed = resources_needed_watchpoint;
13724   ops->works_in_software_mode = works_in_software_mode_watchpoint;
13725   ops->print_it = print_it_watchpoint;
13726   ops->print_mention = print_mention_watchpoint;
13727   ops->print_recreate = print_recreate_watchpoint;
13728
13729   /* Masked watchpoints.  */
13730   ops = &masked_watchpoint_breakpoint_ops;
13731   *ops = watchpoint_breakpoint_ops;
13732   ops->insert_location = insert_masked_watchpoint;
13733   ops->remove_location = remove_masked_watchpoint;
13734   ops->resources_needed = resources_needed_masked_watchpoint;
13735   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
13736   ops->print_it = print_it_masked_watchpoint;
13737   ops->print_one_detail = print_one_detail_masked_watchpoint;
13738   ops->print_mention = print_mention_masked_watchpoint;
13739   ops->print_recreate = print_recreate_masked_watchpoint;
13740
13741   /* Tracepoints.  */
13742   ops = &tracepoint_breakpoint_ops;
13743   *ops = base_breakpoint_ops;
13744   ops->re_set = tracepoint_re_set;
13745   ops->breakpoint_hit = tracepoint_breakpoint_hit;
13746   ops->print_one_detail = tracepoint_print_one_detail;
13747   ops->print_mention = tracepoint_print_mention;
13748   ops->print_recreate = tracepoint_print_recreate;
13749   ops->create_sals_from_address = tracepoint_create_sals_from_address;
13750   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
13751   ops->decode_linespec = tracepoint_decode_linespec;
13752
13753   /* Static tracepoints with marker (`-m').  */
13754   ops = &strace_marker_breakpoint_ops;
13755   *ops = tracepoint_breakpoint_ops;
13756   ops->create_sals_from_address = strace_marker_create_sals_from_address;
13757   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
13758   ops->decode_linespec = strace_marker_decode_linespec;
13759
13760   /* Fork catchpoints.  */
13761   ops = &catch_fork_breakpoint_ops;
13762   *ops = base_breakpoint_ops;
13763   ops->insert_location = insert_catch_fork;
13764   ops->remove_location = remove_catch_fork;
13765   ops->breakpoint_hit = breakpoint_hit_catch_fork;
13766   ops->print_it = print_it_catch_fork;
13767   ops->print_one = print_one_catch_fork;
13768   ops->print_mention = print_mention_catch_fork;
13769   ops->print_recreate = print_recreate_catch_fork;
13770
13771   /* Vfork catchpoints.  */
13772   ops = &catch_vfork_breakpoint_ops;
13773   *ops = base_breakpoint_ops;
13774   ops->insert_location = insert_catch_vfork;
13775   ops->remove_location = remove_catch_vfork;
13776   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
13777   ops->print_it = print_it_catch_vfork;
13778   ops->print_one = print_one_catch_vfork;
13779   ops->print_mention = print_mention_catch_vfork;
13780   ops->print_recreate = print_recreate_catch_vfork;
13781
13782   /* Exec catchpoints.  */
13783   ops = &catch_exec_breakpoint_ops;
13784   *ops = base_breakpoint_ops;
13785   ops->dtor = dtor_catch_exec;
13786   ops->insert_location = insert_catch_exec;
13787   ops->remove_location = remove_catch_exec;
13788   ops->breakpoint_hit = breakpoint_hit_catch_exec;
13789   ops->print_it = print_it_catch_exec;
13790   ops->print_one = print_one_catch_exec;
13791   ops->print_mention = print_mention_catch_exec;
13792   ops->print_recreate = print_recreate_catch_exec;
13793
13794   /* Syscall catchpoints.  */
13795   ops = &catch_syscall_breakpoint_ops;
13796   *ops = base_breakpoint_ops;
13797   ops->dtor = dtor_catch_syscall;
13798   ops->insert_location = insert_catch_syscall;
13799   ops->remove_location = remove_catch_syscall;
13800   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
13801   ops->print_it = print_it_catch_syscall;
13802   ops->print_one = print_one_catch_syscall;
13803   ops->print_mention = print_mention_catch_syscall;
13804   ops->print_recreate = print_recreate_catch_syscall;
13805 }
13806
13807 void
13808 _initialize_breakpoint (void)
13809 {
13810   struct cmd_list_element *c;
13811
13812   initialize_breakpoint_ops ();
13813
13814   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
13815   observer_attach_inferior_exit (clear_syscall_counts);
13816   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
13817
13818   breakpoint_objfile_key = register_objfile_data ();
13819
13820   breakpoint_chain = 0;
13821   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
13822      before a breakpoint is set.  */
13823   breakpoint_count = 0;
13824
13825   tracepoint_count = 0;
13826
13827   add_com ("ignore", class_breakpoint, ignore_command, _("\
13828 Set ignore-count of breakpoint number N to COUNT.\n\
13829 Usage is `ignore N COUNT'."));
13830   if (xdb_commands)
13831     add_com_alias ("bc", "ignore", class_breakpoint, 1);
13832
13833   add_com ("commands", class_breakpoint, commands_command, _("\
13834 Set commands to be executed when a breakpoint is hit.\n\
13835 Give breakpoint number as argument after \"commands\".\n\
13836 With no argument, the targeted breakpoint is the last one set.\n\
13837 The commands themselves follow starting on the next line.\n\
13838 Type a line containing \"end\" to indicate the end of them.\n\
13839 Give \"silent\" as the first line to make the breakpoint silent;\n\
13840 then no output is printed when it is hit, except what the commands print."));
13841
13842   add_com ("condition", class_breakpoint, condition_command, _("\
13843 Specify breakpoint number N to break only if COND is true.\n\
13844 Usage is `condition N COND', where N is an integer and COND is an\n\
13845 expression to be evaluated whenever breakpoint N is reached."));
13846
13847   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
13848 Set a temporary breakpoint.\n\
13849 Like \"break\" except the breakpoint is only temporary,\n\
13850 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
13851 by using \"enable delete\" on the breakpoint number.\n\
13852 \n"
13853 BREAK_ARGS_HELP ("tbreak")));
13854   set_cmd_completer (c, location_completer);
13855
13856   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
13857 Set a hardware assisted breakpoint.\n\
13858 Like \"break\" except the breakpoint requires hardware support,\n\
13859 some target hardware may not have this support.\n\
13860 \n"
13861 BREAK_ARGS_HELP ("hbreak")));
13862   set_cmd_completer (c, location_completer);
13863
13864   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
13865 Set a temporary hardware assisted breakpoint.\n\
13866 Like \"hbreak\" except the breakpoint is only temporary,\n\
13867 so it will be deleted when hit.\n\
13868 \n"
13869 BREAK_ARGS_HELP ("thbreak")));
13870   set_cmd_completer (c, location_completer);
13871
13872   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
13873 Enable some breakpoints.\n\
13874 Give breakpoint numbers (separated by spaces) as arguments.\n\
13875 With no subcommand, breakpoints are enabled until you command otherwise.\n\
13876 This is used to cancel the effect of the \"disable\" command.\n\
13877 With a subcommand you can enable temporarily."),
13878                   &enablelist, "enable ", 1, &cmdlist);
13879   if (xdb_commands)
13880     add_com ("ab", class_breakpoint, enable_command, _("\
13881 Enable some breakpoints.\n\
13882 Give breakpoint numbers (separated by spaces) as arguments.\n\
13883 With no subcommand, breakpoints are enabled until you command otherwise.\n\
13884 This is used to cancel the effect of the \"disable\" command.\n\
13885 With a subcommand you can enable temporarily."));
13886
13887   add_com_alias ("en", "enable", class_breakpoint, 1);
13888
13889   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
13890 Enable some breakpoints.\n\
13891 Give breakpoint numbers (separated by spaces) as arguments.\n\
13892 This is used to cancel the effect of the \"disable\" command.\n\
13893 May be abbreviated to simply \"enable\".\n"),
13894                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
13895
13896   add_cmd ("once", no_class, enable_once_command, _("\
13897 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
13898 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
13899            &enablebreaklist);
13900
13901   add_cmd ("delete", no_class, enable_delete_command, _("\
13902 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
13903 If a breakpoint is hit while enabled in this fashion, it is deleted."),
13904            &enablebreaklist);
13905
13906   add_cmd ("delete", no_class, enable_delete_command, _("\
13907 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
13908 If a breakpoint is hit while enabled in this fashion, it is deleted."),
13909            &enablelist);
13910
13911   add_cmd ("once", no_class, enable_once_command, _("\
13912 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
13913 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
13914            &enablelist);
13915
13916   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
13917 Disable some breakpoints.\n\
13918 Arguments are breakpoint numbers with spaces in between.\n\
13919 To disable all breakpoints, give no argument.\n\
13920 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
13921                   &disablelist, "disable ", 1, &cmdlist);
13922   add_com_alias ("dis", "disable", class_breakpoint, 1);
13923   add_com_alias ("disa", "disable", class_breakpoint, 1);
13924   if (xdb_commands)
13925     add_com ("sb", class_breakpoint, disable_command, _("\
13926 Disable some breakpoints.\n\
13927 Arguments are breakpoint numbers with spaces in between.\n\
13928 To disable all breakpoints, give no argument.\n\
13929 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
13930
13931   add_cmd ("breakpoints", class_alias, disable_command, _("\
13932 Disable some breakpoints.\n\
13933 Arguments are breakpoint numbers with spaces in between.\n\
13934 To disable all breakpoints, give no argument.\n\
13935 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
13936 This command may be abbreviated \"disable\"."),
13937            &disablelist);
13938
13939   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
13940 Delete some breakpoints or auto-display expressions.\n\
13941 Arguments are breakpoint numbers with spaces in between.\n\
13942 To delete all breakpoints, give no argument.\n\
13943 \n\
13944 Also a prefix command for deletion of other GDB objects.\n\
13945 The \"unset\" command is also an alias for \"delete\"."),
13946                   &deletelist, "delete ", 1, &cmdlist);
13947   add_com_alias ("d", "delete", class_breakpoint, 1);
13948   add_com_alias ("del", "delete", class_breakpoint, 1);
13949   if (xdb_commands)
13950     add_com ("db", class_breakpoint, delete_command, _("\
13951 Delete some breakpoints.\n\
13952 Arguments are breakpoint numbers with spaces in between.\n\
13953 To delete all breakpoints, give no argument.\n"));
13954
13955   add_cmd ("breakpoints", class_alias, delete_command, _("\
13956 Delete some breakpoints or auto-display expressions.\n\
13957 Arguments are breakpoint numbers with spaces in between.\n\
13958 To delete all breakpoints, give no argument.\n\
13959 This command may be abbreviated \"delete\"."),
13960            &deletelist);
13961
13962   add_com ("clear", class_breakpoint, clear_command, _("\
13963 Clear breakpoint at specified line or function.\n\
13964 Argument may be line number, function name, or \"*\" and an address.\n\
13965 If line number is specified, all breakpoints in that line are cleared.\n\
13966 If function is specified, breakpoints at beginning of function are cleared.\n\
13967 If an address is specified, breakpoints at that address are cleared.\n\
13968 \n\
13969 With no argument, clears all breakpoints in the line that the selected frame\n\
13970 is executing in.\n\
13971 \n\
13972 See also the \"delete\" command which clears breakpoints by number."));
13973   add_com_alias ("cl", "clear", class_breakpoint, 1);
13974
13975   c = add_com ("break", class_breakpoint, break_command, _("\
13976 Set breakpoint at specified line or function.\n"
13977 BREAK_ARGS_HELP ("break")));
13978   set_cmd_completer (c, location_completer);
13979
13980   add_com_alias ("b", "break", class_run, 1);
13981   add_com_alias ("br", "break", class_run, 1);
13982   add_com_alias ("bre", "break", class_run, 1);
13983   add_com_alias ("brea", "break", class_run, 1);
13984
13985   if (xdb_commands)
13986    add_com_alias ("ba", "break", class_breakpoint, 1);
13987
13988   if (dbx_commands)
13989     {
13990       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
13991 Break in function/address or break at a line in the current file."),
13992                              &stoplist, "stop ", 1, &cmdlist);
13993       add_cmd ("in", class_breakpoint, stopin_command,
13994                _("Break in function or address."), &stoplist);
13995       add_cmd ("at", class_breakpoint, stopat_command,
13996                _("Break at a line in the current file."), &stoplist);
13997       add_com ("status", class_info, breakpoints_info, _("\
13998 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
13999 The \"Type\" column indicates one of:\n\
14000 \tbreakpoint     - normal breakpoint\n\
14001 \twatchpoint     - watchpoint\n\
14002 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14003 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14004 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14005 address and file/line number respectively.\n\
14006 \n\
14007 Convenience variable \"$_\" and default examine address for \"x\"\n\
14008 are set to the address of the last breakpoint listed unless the command\n\
14009 is prefixed with \"server \".\n\n\
14010 Convenience variable \"$bpnum\" contains the number of the last\n\
14011 breakpoint set."));
14012     }
14013
14014   add_info ("breakpoints", breakpoints_info, _("\
14015 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
14016 The \"Type\" column indicates one of:\n\
14017 \tbreakpoint     - normal breakpoint\n\
14018 \twatchpoint     - watchpoint\n\
14019 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14020 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14021 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14022 address and file/line number respectively.\n\
14023 \n\
14024 Convenience variable \"$_\" and default examine address for \"x\"\n\
14025 are set to the address of the last breakpoint listed unless the command\n\
14026 is prefixed with \"server \".\n\n\
14027 Convenience variable \"$bpnum\" contains the number of the last\n\
14028 breakpoint set."));
14029
14030   add_info_alias ("b", "breakpoints", 1);
14031
14032   if (xdb_commands)
14033     add_com ("lb", class_breakpoint, breakpoints_info, _("\
14034 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
14035 The \"Type\" column indicates one of:\n\
14036 \tbreakpoint     - normal breakpoint\n\
14037 \twatchpoint     - watchpoint\n\
14038 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14039 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14040 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14041 address and file/line number respectively.\n\
14042 \n\
14043 Convenience variable \"$_\" and default examine address for \"x\"\n\
14044 are set to the address of the last breakpoint listed unless the command\n\
14045 is prefixed with \"server \".\n\n\
14046 Convenience variable \"$bpnum\" contains the number of the last\n\
14047 breakpoint set."));
14048
14049   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
14050 Status of all breakpoints, or breakpoint number NUMBER.\n\
14051 The \"Type\" column indicates one of:\n\
14052 \tbreakpoint     - normal breakpoint\n\
14053 \twatchpoint     - watchpoint\n\
14054 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
14055 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
14056 \tuntil          - internal breakpoint used by the \"until\" command\n\
14057 \tfinish         - internal breakpoint used by the \"finish\" command\n\
14058 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
14059 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
14060 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
14061 address and file/line number respectively.\n\
14062 \n\
14063 Convenience variable \"$_\" and default examine address for \"x\"\n\
14064 are set to the address of the last breakpoint listed unless the command\n\
14065 is prefixed with \"server \".\n\n\
14066 Convenience variable \"$bpnum\" contains the number of the last\n\
14067 breakpoint set."),
14068            &maintenanceinfolist);
14069
14070   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
14071 Set catchpoints to catch events."),
14072                   &catch_cmdlist, "catch ",
14073                   0/*allow-unknown*/, &cmdlist);
14074
14075   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
14076 Set temporary catchpoints to catch events."),
14077                   &tcatch_cmdlist, "tcatch ",
14078                   0/*allow-unknown*/, &cmdlist);
14079
14080   /* Add catch and tcatch sub-commands.  */
14081   add_catch_command ("catch", _("\
14082 Catch an exception, when caught."),
14083                      catch_catch_command,
14084                      NULL,
14085                      CATCH_PERMANENT,
14086                      CATCH_TEMPORARY);
14087   add_catch_command ("throw", _("\
14088 Catch an exception, when thrown."),
14089                      catch_throw_command,
14090                      NULL,
14091                      CATCH_PERMANENT,
14092                      CATCH_TEMPORARY);
14093   add_catch_command ("fork", _("Catch calls to fork."),
14094                      catch_fork_command_1,
14095                      NULL,
14096                      (void *) (uintptr_t) catch_fork_permanent,
14097                      (void *) (uintptr_t) catch_fork_temporary);
14098   add_catch_command ("vfork", _("Catch calls to vfork."),
14099                      catch_fork_command_1,
14100                      NULL,
14101                      (void *) (uintptr_t) catch_vfork_permanent,
14102                      (void *) (uintptr_t) catch_vfork_temporary);
14103   add_catch_command ("exec", _("Catch calls to exec."),
14104                      catch_exec_command_1,
14105                      NULL,
14106                      CATCH_PERMANENT,
14107                      CATCH_TEMPORARY);
14108   add_catch_command ("syscall", _("\
14109 Catch system calls by their names and/or numbers.\n\
14110 Arguments say which system calls to catch.  If no arguments\n\
14111 are given, every system call will be caught.\n\
14112 Arguments, if given, should be one or more system call names\n\
14113 (if your system supports that), or system call numbers."),
14114                      catch_syscall_command_1,
14115                      catch_syscall_completer,
14116                      CATCH_PERMANENT,
14117                      CATCH_TEMPORARY);
14118
14119   c = add_com ("watch", class_breakpoint, watch_command, _("\
14120 Set a watchpoint for an expression.\n\
14121 Usage: watch [-l|-location] EXPRESSION\n\
14122 A watchpoint stops execution of your program whenever the value of\n\
14123 an expression changes.\n\
14124 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14125 the memory to which it refers."));
14126   set_cmd_completer (c, expression_completer);
14127
14128   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
14129 Set a read watchpoint for an expression.\n\
14130 Usage: rwatch [-l|-location] EXPRESSION\n\
14131 A watchpoint stops execution of your program whenever the value of\n\
14132 an expression is read.\n\
14133 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14134 the memory to which it refers."));
14135   set_cmd_completer (c, expression_completer);
14136
14137   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
14138 Set a watchpoint for an expression.\n\
14139 Usage: awatch [-l|-location] EXPRESSION\n\
14140 A watchpoint stops execution of your program whenever the value of\n\
14141 an expression is either read or written.\n\
14142 If -l or -location is given, this evaluates EXPRESSION and watches\n\
14143 the memory to which it refers."));
14144   set_cmd_completer (c, expression_completer);
14145
14146   add_info ("watchpoints", watchpoints_info, _("\
14147 Status of specified watchpoints (all watchpoints if no argument)."));
14148
14149   /* XXX: cagney/2005-02-23: This should be a boolean, and should
14150      respond to changes - contrary to the description.  */
14151   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
14152                             &can_use_hw_watchpoints, _("\
14153 Set debugger's willingness to use watchpoint hardware."), _("\
14154 Show debugger's willingness to use watchpoint hardware."), _("\
14155 If zero, gdb will not use hardware for new watchpoints, even if\n\
14156 such is available.  (However, any hardware watchpoints that were\n\
14157 created before setting this to nonzero, will continue to use watchpoint\n\
14158 hardware.)"),
14159                             NULL,
14160                             show_can_use_hw_watchpoints,
14161                             &setlist, &showlist);
14162
14163   can_use_hw_watchpoints = 1;
14164
14165   /* Tracepoint manipulation commands.  */
14166
14167   c = add_com ("trace", class_breakpoint, trace_command, _("\
14168 Set a tracepoint at specified line or function.\n\
14169 \n"
14170 BREAK_ARGS_HELP ("trace") "\n\
14171 Do \"help tracepoints\" for info on other tracepoint commands."));
14172   set_cmd_completer (c, location_completer);
14173
14174   add_com_alias ("tp", "trace", class_alias, 0);
14175   add_com_alias ("tr", "trace", class_alias, 1);
14176   add_com_alias ("tra", "trace", class_alias, 1);
14177   add_com_alias ("trac", "trace", class_alias, 1);
14178
14179   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
14180 Set a fast tracepoint at specified line or function.\n\
14181 \n"
14182 BREAK_ARGS_HELP ("ftrace") "\n\
14183 Do \"help tracepoints\" for info on other tracepoint commands."));
14184   set_cmd_completer (c, location_completer);
14185
14186   c = add_com ("strace", class_breakpoint, strace_command, _("\
14187 Set a static tracepoint at specified line, function or marker.\n\
14188 \n\
14189 strace [LOCATION] [if CONDITION]\n\
14190 LOCATION may be a line number, function name, \"*\" and an address,\n\
14191 or -m MARKER_ID.\n\
14192 If a line number is specified, probe the marker at start of code\n\
14193 for that line.  If a function is specified, probe the marker at start\n\
14194 of code for that function.  If an address is specified, probe the marker\n\
14195 at that exact address.  If a marker id is specified, probe the marker\n\
14196 with that name.  With no LOCATION, uses current execution address of\n\
14197 the selected stack frame.\n\
14198 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
14199 This collects arbitrary user data passed in the probe point call to the\n\
14200 tracing library.  You can inspect it when analyzing the trace buffer,\n\
14201 by printing the $_sdata variable like any other convenience variable.\n\
14202 \n\
14203 CONDITION is a boolean expression.\n\
14204 \n\
14205 Multiple tracepoints at one place are permitted, and useful if their\n\
14206 conditions are different.\n\
14207 \n\
14208 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
14209 Do \"help tracepoints\" for info on other tracepoint commands."));
14210   set_cmd_completer (c, location_completer);
14211
14212   add_info ("tracepoints", tracepoints_info, _("\
14213 Status of specified tracepoints (all tracepoints if no argument).\n\
14214 Convenience variable \"$tpnum\" contains the number of the\n\
14215 last tracepoint set."));
14216
14217   add_info_alias ("tp", "tracepoints", 1);
14218
14219   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
14220 Delete specified tracepoints.\n\
14221 Arguments are tracepoint numbers, separated by spaces.\n\
14222 No argument means delete all tracepoints."),
14223            &deletelist);
14224
14225   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
14226 Disable specified tracepoints.\n\
14227 Arguments are tracepoint numbers, separated by spaces.\n\
14228 No argument means disable all tracepoints."),
14229            &disablelist);
14230   deprecate_cmd (c, "disable");
14231
14232   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
14233 Enable specified tracepoints.\n\
14234 Arguments are tracepoint numbers, separated by spaces.\n\
14235 No argument means enable all tracepoints."),
14236            &enablelist);
14237   deprecate_cmd (c, "enable");
14238
14239   add_com ("passcount", class_trace, trace_pass_command, _("\
14240 Set the passcount for a tracepoint.\n\
14241 The trace will end when the tracepoint has been passed 'count' times.\n\
14242 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
14243 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
14244
14245   add_prefix_cmd ("save", class_breakpoint, save_command,
14246                   _("Save breakpoint definitions as a script."),
14247                   &save_cmdlist, "save ",
14248                   0/*allow-unknown*/, &cmdlist);
14249
14250   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
14251 Save current breakpoint definitions as a script.\n\
14252 This includes all types of breakpoints (breakpoints, watchpoints,\n\
14253 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
14254 session to restore them."),
14255                &save_cmdlist);
14256   set_cmd_completer (c, filename_completer);
14257
14258   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
14259 Save current tracepoint definitions as a script.\n\
14260 Use the 'source' command in another debug session to restore them."),
14261                &save_cmdlist);
14262   set_cmd_completer (c, filename_completer);
14263
14264   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
14265   deprecate_cmd (c, "save tracepoints");
14266
14267   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
14268 Breakpoint specific settings\n\
14269 Configure various breakpoint-specific variables such as\n\
14270 pending breakpoint behavior"),
14271                   &breakpoint_set_cmdlist, "set breakpoint ",
14272                   0/*allow-unknown*/, &setlist);
14273   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
14274 Breakpoint specific settings\n\
14275 Configure various breakpoint-specific variables such as\n\
14276 pending breakpoint behavior"),
14277                   &breakpoint_show_cmdlist, "show breakpoint ",
14278                   0/*allow-unknown*/, &showlist);
14279
14280   add_setshow_auto_boolean_cmd ("pending", no_class,
14281                                 &pending_break_support, _("\
14282 Set debugger's behavior regarding pending breakpoints."), _("\
14283 Show debugger's behavior regarding pending breakpoints."), _("\
14284 If on, an unrecognized breakpoint location will cause gdb to create a\n\
14285 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
14286 an error.  If auto, an unrecognized breakpoint location results in a\n\
14287 user-query to see if a pending breakpoint should be created."),
14288                                 NULL,
14289                                 show_pending_break_support,
14290                                 &breakpoint_set_cmdlist,
14291                                 &breakpoint_show_cmdlist);
14292
14293   pending_break_support = AUTO_BOOLEAN_AUTO;
14294
14295   add_setshow_boolean_cmd ("auto-hw", no_class,
14296                            &automatic_hardware_breakpoints, _("\
14297 Set automatic usage of hardware breakpoints."), _("\
14298 Show automatic usage of hardware breakpoints."), _("\
14299 If set, the debugger will automatically use hardware breakpoints for\n\
14300 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
14301 a warning will be emitted for such breakpoints."),
14302                            NULL,
14303                            show_automatic_hardware_breakpoints,
14304                            &breakpoint_set_cmdlist,
14305                            &breakpoint_show_cmdlist);
14306
14307   add_setshow_enum_cmd ("always-inserted", class_support,
14308                         always_inserted_enums, &always_inserted_mode, _("\
14309 Set mode for inserting breakpoints."), _("\
14310 Show mode for inserting breakpoints."), _("\
14311 When this mode is off, breakpoints are inserted in inferior when it is\n\
14312 resumed, and removed when execution stops.  When this mode is on,\n\
14313 breakpoints are inserted immediately and removed only when the user\n\
14314 deletes the breakpoint.  When this mode is auto (which is the default),\n\
14315 the behaviour depends on the non-stop setting (see help set non-stop).\n\
14316 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
14317 behaves as if always-inserted mode is on; if gdb is controlling the\n\
14318 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
14319                            NULL,
14320                            &show_always_inserted_mode,
14321                            &breakpoint_set_cmdlist,
14322                            &breakpoint_show_cmdlist);
14323
14324   add_com ("break-range", class_breakpoint, break_range_command, _("\
14325 Set a breakpoint for an address range.\n\
14326 break-range START-LOCATION, END-LOCATION\n\
14327 where START-LOCATION and END-LOCATION can be one of the following:\n\
14328   LINENUM, for that line in the current file,\n\
14329   FILE:LINENUM, for that line in that file,\n\
14330   +OFFSET, for that number of lines after the current line\n\
14331            or the start of the range\n\
14332   FUNCTION, for the first line in that function,\n\
14333   FILE:FUNCTION, to distinguish among like-named static functions.\n\
14334   *ADDRESS, for the instruction at that address.\n\
14335 \n\
14336 The breakpoint will stop execution of the inferior whenever it executes\n\
14337 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
14338 range (including START-LOCATION and END-LOCATION)."));
14339
14340   automatic_hardware_breakpoints = 1;
14341
14342   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
14343 }