Minor style fixes in breakpoint.c:find_condition_and_thread
[external/binutils.git] / gdb / breakpoint.c
1 /* Everything about breakpoints, for GDB.
2
3    Copyright (C) 1986-2012 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include <ctype.h>
23 #include "hashtab.h"
24 #include "symtab.h"
25 #include "frame.h"
26 #include "breakpoint.h"
27 #include "tracepoint.h"
28 #include "gdbtypes.h"
29 #include "expression.h"
30 #include "gdbcore.h"
31 #include "gdbcmd.h"
32 #include "value.h"
33 #include "command.h"
34 #include "inferior.h"
35 #include "gdbthread.h"
36 #include "target.h"
37 #include "language.h"
38 #include "gdb_string.h"
39 #include "gdb-demangle.h"
40 #include "filenames.h"
41 #include "annotate.h"
42 #include "symfile.h"
43 #include "objfiles.h"
44 #include "source.h"
45 #include "linespec.h"
46 #include "completer.h"
47 #include "gdb.h"
48 #include "ui-out.h"
49 #include "cli/cli-script.h"
50 #include "gdb_assert.h"
51 #include "block.h"
52 #include "solib.h"
53 #include "solist.h"
54 #include "observer.h"
55 #include "exceptions.h"
56 #include "memattr.h"
57 #include "ada-lang.h"
58 #include "top.h"
59 #include "valprint.h"
60 #include "jit.h"
61 #include "xml-syscall.h"
62 #include "parser-defs.h"
63 #include "gdb_regex.h"
64 #include "probe.h"
65 #include "cli/cli-utils.h"
66 #include "continuations.h"
67 #include "stack.h"
68 #include "skip.h"
69 #include "gdb_regex.h"
70 #include "ax-gdb.h"
71
72 /* readline include files */
73 #include "readline/readline.h"
74 #include "readline/history.h"
75
76 /* readline defines this.  */
77 #undef savestring
78
79 #include "mi/mi-common.h"
80 #include "python/python.h"
81
82 /* Prototypes for local functions.  */
83
84 static void enable_delete_command (char *, int);
85
86 static void enable_once_command (char *, int);
87
88 static void enable_count_command (char *, int);
89
90 static void disable_command (char *, int);
91
92 static void enable_command (char *, int);
93
94 static void map_breakpoint_numbers (char *, void (*) (struct breakpoint *,
95                                                       void *),
96                                     void *);
97
98 static void ignore_command (char *, int);
99
100 static int breakpoint_re_set_one (void *);
101
102 static void breakpoint_re_set_default (struct breakpoint *);
103
104 static void create_sals_from_address_default (char **,
105                                               struct linespec_result *,
106                                               enum bptype, char *,
107                                               char **);
108
109 static void create_breakpoints_sal_default (struct gdbarch *,
110                                             struct linespec_result *,
111                                             struct linespec_sals *,
112                                             char *, char *, enum bptype,
113                                             enum bpdisp, int, int,
114                                             int,
115                                             const struct breakpoint_ops *,
116                                             int, int, int, unsigned);
117
118 static void decode_linespec_default (struct breakpoint *, char **,
119                                      struct symtabs_and_lines *);
120
121 static void clear_command (char *, int);
122
123 static void catch_command (char *, int);
124
125 static int can_use_hardware_watchpoint (struct value *);
126
127 static void break_command_1 (char *, int, int);
128
129 static void mention (struct breakpoint *);
130
131 static struct breakpoint *set_raw_breakpoint_without_location (struct gdbarch *,
132                                                                enum bptype,
133                                                                const struct breakpoint_ops *);
134 static struct bp_location *add_location_to_breakpoint (struct breakpoint *,
135                                                        const struct symtab_and_line *);
136
137 /* This function is used in gdbtk sources and thus can not be made
138    static.  */
139 struct breakpoint *set_raw_breakpoint (struct gdbarch *gdbarch,
140                                        struct symtab_and_line,
141                                        enum bptype,
142                                        const struct breakpoint_ops *);
143
144 static struct breakpoint *
145   momentary_breakpoint_from_master (struct breakpoint *orig,
146                                     enum bptype type,
147                                     const struct breakpoint_ops *ops);
148
149 static void breakpoint_adjustment_warning (CORE_ADDR, CORE_ADDR, int, int);
150
151 static CORE_ADDR adjust_breakpoint_address (struct gdbarch *gdbarch,
152                                             CORE_ADDR bpaddr,
153                                             enum bptype bptype);
154
155 static void describe_other_breakpoints (struct gdbarch *,
156                                         struct program_space *, CORE_ADDR,
157                                         struct obj_section *, int);
158
159 static int breakpoint_address_match (struct address_space *aspace1,
160                                      CORE_ADDR addr1,
161                                      struct address_space *aspace2,
162                                      CORE_ADDR addr2);
163
164 static int watchpoint_locations_match (struct bp_location *loc1,
165                                        struct bp_location *loc2);
166
167 static int breakpoint_location_address_match (struct bp_location *bl,
168                                               struct address_space *aspace,
169                                               CORE_ADDR addr);
170
171 static void breakpoints_info (char *, int);
172
173 static void watchpoints_info (char *, int);
174
175 static int breakpoint_1 (char *, int, 
176                          int (*) (const struct breakpoint *));
177
178 static int breakpoint_cond_eval (void *);
179
180 static void cleanup_executing_breakpoints (void *);
181
182 static void commands_command (char *, int);
183
184 static void condition_command (char *, int);
185
186 typedef enum
187   {
188     mark_inserted,
189     mark_uninserted
190   }
191 insertion_state_t;
192
193 static int remove_breakpoint (struct bp_location *, insertion_state_t);
194 static int remove_breakpoint_1 (struct bp_location *, insertion_state_t);
195
196 static enum print_stop_action print_bp_stop_message (bpstat bs);
197
198 static int watchpoint_check (void *);
199
200 static void maintenance_info_breakpoints (char *, int);
201
202 static int hw_breakpoint_used_count (void);
203
204 static int hw_watchpoint_use_count (struct breakpoint *);
205
206 static int hw_watchpoint_used_count_others (struct breakpoint *except,
207                                             enum bptype type,
208                                             int *other_type_used);
209
210 static void hbreak_command (char *, int);
211
212 static void thbreak_command (char *, int);
213
214 static void enable_breakpoint_disp (struct breakpoint *, enum bpdisp,
215                                     int count);
216
217 static void stop_command (char *arg, int from_tty);
218
219 static void stopin_command (char *arg, int from_tty);
220
221 static void stopat_command (char *arg, int from_tty);
222
223 static char *ep_parse_optional_if_clause (char **arg);
224
225 static void catch_exception_command_1 (enum exception_event_kind ex_event, 
226                                        char *arg, int tempflag, int from_tty);
227
228 static void tcatch_command (char *arg, int from_tty);
229
230 static void detach_single_step_breakpoints (void);
231
232 static int single_step_breakpoint_inserted_here_p (struct address_space *,
233                                                    CORE_ADDR pc);
234
235 static void free_bp_location (struct bp_location *loc);
236 static void incref_bp_location (struct bp_location *loc);
237 static void decref_bp_location (struct bp_location **loc);
238
239 static struct bp_location *allocate_bp_location (struct breakpoint *bpt);
240
241 static void update_global_location_list (int);
242
243 static void update_global_location_list_nothrow (int);
244
245 static int is_hardware_watchpoint (const struct breakpoint *bpt);
246
247 static void insert_breakpoint_locations (void);
248
249 static int syscall_catchpoint_p (struct breakpoint *b);
250
251 static void tracepoints_info (char *, int);
252
253 static void delete_trace_command (char *, int);
254
255 static void enable_trace_command (char *, int);
256
257 static void disable_trace_command (char *, int);
258
259 static void trace_pass_command (char *, int);
260
261 static int is_masked_watchpoint (const struct breakpoint *b);
262
263 static struct bp_location **get_first_locp_gte_addr (CORE_ADDR address);
264
265 /* Return 1 if B refers to a static tracepoint set by marker ("-m"), zero
266    otherwise.  */
267
268 static int strace_marker_p (struct breakpoint *b);
269
270 static void init_catchpoint (struct breakpoint *b,
271                              struct gdbarch *gdbarch, int tempflag,
272                              char *cond_string,
273                              const struct breakpoint_ops *ops);
274
275 /* The abstract base class all breakpoint_ops structures inherit
276    from.  */
277 static struct breakpoint_ops base_breakpoint_ops;
278
279 /* The breakpoint_ops structure to be inherited by all breakpoint_ops
280    that are implemented on top of software or hardware breakpoints
281    (user breakpoints, internal and momentary breakpoints, etc.).  */
282 static struct breakpoint_ops bkpt_base_breakpoint_ops;
283
284 /* Internal breakpoints class type.  */
285 static struct breakpoint_ops internal_breakpoint_ops;
286
287 /* Momentary breakpoints class type.  */
288 static struct breakpoint_ops momentary_breakpoint_ops;
289
290 /* The breakpoint_ops structure to be used in regular user created
291    breakpoints.  */
292 struct breakpoint_ops bkpt_breakpoint_ops;
293
294 /* Breakpoints set on probes.  */
295 static struct breakpoint_ops bkpt_probe_breakpoint_ops;
296
297 /* Dynamic printf class type.  */
298 static struct breakpoint_ops dprintf_breakpoint_ops;
299
300 /* A reference-counted struct command_line.  This lets multiple
301    breakpoints share a single command list.  */
302 struct counted_command_line
303 {
304   /* The reference count.  */
305   int refc;
306
307   /* The command list.  */
308   struct command_line *commands;
309 };
310
311 struct command_line *
312 breakpoint_commands (struct breakpoint *b)
313 {
314   return b->commands ? b->commands->commands : NULL;
315 }
316
317 /* Flag indicating that a command has proceeded the inferior past the
318    current breakpoint.  */
319
320 static int breakpoint_proceeded;
321
322 const char *
323 bpdisp_text (enum bpdisp disp)
324 {
325   /* NOTE: the following values are a part of MI protocol and
326      represent values of 'disp' field returned when inferior stops at
327      a breakpoint.  */
328   static const char * const bpdisps[] = {"del", "dstp", "dis", "keep"};
329
330   return bpdisps[(int) disp];
331 }
332
333 /* Prototypes for exported functions.  */
334 /* If FALSE, gdb will not use hardware support for watchpoints, even
335    if such is available.  */
336 static int can_use_hw_watchpoints;
337
338 static void
339 show_can_use_hw_watchpoints (struct ui_file *file, int from_tty,
340                              struct cmd_list_element *c,
341                              const char *value)
342 {
343   fprintf_filtered (file,
344                     _("Debugger's willingness to use "
345                       "watchpoint hardware is %s.\n"),
346                     value);
347 }
348
349 /* If AUTO_BOOLEAN_FALSE, gdb will not attempt to create pending breakpoints.
350    If AUTO_BOOLEAN_TRUE, gdb will automatically create pending breakpoints
351    for unrecognized breakpoint locations.
352    If AUTO_BOOLEAN_AUTO, gdb will query when breakpoints are unrecognized.  */
353 static enum auto_boolean pending_break_support;
354 static void
355 show_pending_break_support (struct ui_file *file, int from_tty,
356                             struct cmd_list_element *c,
357                             const char *value)
358 {
359   fprintf_filtered (file,
360                     _("Debugger's behavior regarding "
361                       "pending breakpoints is %s.\n"),
362                     value);
363 }
364
365 /* If 1, gdb will automatically use hardware breakpoints for breakpoints
366    set with "break" but falling in read-only memory.
367    If 0, gdb will warn about such breakpoints, but won't automatically
368    use hardware breakpoints.  */
369 static int automatic_hardware_breakpoints;
370 static void
371 show_automatic_hardware_breakpoints (struct ui_file *file, int from_tty,
372                                      struct cmd_list_element *c,
373                                      const char *value)
374 {
375   fprintf_filtered (file,
376                     _("Automatic usage of hardware breakpoints is %s.\n"),
377                     value);
378 }
379
380 /* If on, gdb will keep breakpoints inserted even as inferior is
381    stopped, and immediately insert any new breakpoints.  If off, gdb
382    will insert breakpoints into inferior only when resuming it, and
383    will remove breakpoints upon stop.  If auto, GDB will behave as ON
384    if in non-stop mode, and as OFF if all-stop mode.*/
385
386 static const char always_inserted_auto[] = "auto";
387 static const char always_inserted_on[] = "on";
388 static const char always_inserted_off[] = "off";
389 static const char *const always_inserted_enums[] = {
390   always_inserted_auto,
391   always_inserted_off,
392   always_inserted_on,
393   NULL
394 };
395 static const char *always_inserted_mode = always_inserted_auto;
396 static void
397 show_always_inserted_mode (struct ui_file *file, int from_tty,
398                      struct cmd_list_element *c, const char *value)
399 {
400   if (always_inserted_mode == always_inserted_auto)
401     fprintf_filtered (file,
402                       _("Always inserted breakpoint "
403                         "mode is %s (currently %s).\n"),
404                       value,
405                       breakpoints_always_inserted_mode () ? "on" : "off");
406   else
407     fprintf_filtered (file, _("Always inserted breakpoint mode is %s.\n"),
408                       value);
409 }
410
411 int
412 breakpoints_always_inserted_mode (void)
413 {
414   return (always_inserted_mode == always_inserted_on
415           || (always_inserted_mode == always_inserted_auto && non_stop));
416 }
417
418 static const char condition_evaluation_both[] = "host or target";
419
420 /* Modes for breakpoint condition evaluation.  */
421 static const char condition_evaluation_auto[] = "auto";
422 static const char condition_evaluation_host[] = "host";
423 static const char condition_evaluation_target[] = "target";
424 static const char *const condition_evaluation_enums[] = {
425   condition_evaluation_auto,
426   condition_evaluation_host,
427   condition_evaluation_target,
428   NULL
429 };
430
431 /* Global that holds the current mode for breakpoint condition evaluation.  */
432 static const char *condition_evaluation_mode_1 = condition_evaluation_auto;
433
434 /* Global that we use to display information to the user (gets its value from
435    condition_evaluation_mode_1.  */
436 static const char *condition_evaluation_mode = condition_evaluation_auto;
437
438 /* Translate a condition evaluation mode MODE into either "host"
439    or "target".  This is used mostly to translate from "auto" to the
440    real setting that is being used.  It returns the translated
441    evaluation mode.  */
442
443 static const char *
444 translate_condition_evaluation_mode (const char *mode)
445 {
446   if (mode == condition_evaluation_auto)
447     {
448       if (target_supports_evaluation_of_breakpoint_conditions ())
449         return condition_evaluation_target;
450       else
451         return condition_evaluation_host;
452     }
453   else
454     return mode;
455 }
456
457 /* Discovers what condition_evaluation_auto translates to.  */
458
459 static const char *
460 breakpoint_condition_evaluation_mode (void)
461 {
462   return translate_condition_evaluation_mode (condition_evaluation_mode);
463 }
464
465 /* Return true if GDB should evaluate breakpoint conditions or false
466    otherwise.  */
467
468 static int
469 gdb_evaluates_breakpoint_condition_p (void)
470 {
471   const char *mode = breakpoint_condition_evaluation_mode ();
472
473   return (mode == condition_evaluation_host);
474 }
475
476 void _initialize_breakpoint (void);
477
478 /* Are we executing breakpoint commands?  */
479 static int executing_breakpoint_commands;
480
481 /* Are overlay event breakpoints enabled? */
482 static int overlay_events_enabled;
483
484 /* See description in breakpoint.h. */
485 int target_exact_watchpoints = 0;
486
487 /* Walk the following statement or block through all breakpoints.
488    ALL_BREAKPOINTS_SAFE does so even if the statement deletes the
489    current breakpoint.  */
490
491 #define ALL_BREAKPOINTS(B)  for (B = breakpoint_chain; B; B = B->next)
492
493 #define ALL_BREAKPOINTS_SAFE(B,TMP)     \
494         for (B = breakpoint_chain;      \
495              B ? (TMP=B->next, 1): 0;   \
496              B = TMP)
497
498 /* Similar iterator for the low-level breakpoints.  SAFE variant is
499    not provided so update_global_location_list must not be called
500    while executing the block of ALL_BP_LOCATIONS.  */
501
502 #define ALL_BP_LOCATIONS(B,BP_TMP)                                      \
503         for (BP_TMP = bp_location;                                      \
504              BP_TMP < bp_location + bp_location_count && (B = *BP_TMP); \
505              BP_TMP++)
506
507 /* Iterates through locations with address ADDRESS for the currently selected
508    program space.  BP_LOCP_TMP points to each object.  BP_LOCP_START points
509    to where the loop should start from.
510    If BP_LOCP_START is a NULL pointer, the macro automatically seeks the
511    appropriate location to start with.  */
512
513 #define ALL_BP_LOCATIONS_AT_ADDR(BP_LOCP_TMP, BP_LOCP_START, ADDRESS)   \
514         for (BP_LOCP_START = BP_LOCP_START == NULL ? get_first_locp_gte_addr (ADDRESS) : BP_LOCP_START, \
515              BP_LOCP_TMP = BP_LOCP_START;                               \
516              BP_LOCP_START                                              \
517              && (BP_LOCP_TMP < bp_location + bp_location_count          \
518              && (*BP_LOCP_TMP)->address == ADDRESS);                    \
519              BP_LOCP_TMP++)
520
521 /* Iterator for tracepoints only.  */
522
523 #define ALL_TRACEPOINTS(B)  \
524   for (B = breakpoint_chain; B; B = B->next)  \
525     if (is_tracepoint (B))
526
527 /* Chains of all breakpoints defined.  */
528
529 struct breakpoint *breakpoint_chain;
530
531 /* Array is sorted by bp_location_compare - primarily by the ADDRESS.  */
532
533 static struct bp_location **bp_location;
534
535 /* Number of elements of BP_LOCATION.  */
536
537 static unsigned bp_location_count;
538
539 /* Maximum alignment offset between bp_target_info.PLACED_ADDRESS and
540    ADDRESS for the current elements of BP_LOCATION which get a valid
541    result from bp_location_has_shadow.  You can use it for roughly
542    limiting the subrange of BP_LOCATION to scan for shadow bytes for
543    an address you need to read.  */
544
545 static CORE_ADDR bp_location_placed_address_before_address_max;
546
547 /* Maximum offset plus alignment between bp_target_info.PLACED_ADDRESS
548    + bp_target_info.SHADOW_LEN and ADDRESS for the current elements of
549    BP_LOCATION which get a valid result from bp_location_has_shadow.
550    You can use it for roughly limiting the subrange of BP_LOCATION to
551    scan for shadow bytes for an address you need to read.  */
552
553 static CORE_ADDR bp_location_shadow_len_after_address_max;
554
555 /* The locations that no longer correspond to any breakpoint, unlinked
556    from bp_location array, but for which a hit may still be reported
557    by a target.  */
558 VEC(bp_location_p) *moribund_locations = NULL;
559
560 /* Number of last breakpoint made.  */
561
562 static int breakpoint_count;
563
564 /* The value of `breakpoint_count' before the last command that
565    created breakpoints.  If the last (break-like) command created more
566    than one breakpoint, then the difference between BREAKPOINT_COUNT
567    and PREV_BREAKPOINT_COUNT is more than one.  */
568 static int prev_breakpoint_count;
569
570 /* Number of last tracepoint made.  */
571
572 static int tracepoint_count;
573
574 static struct cmd_list_element *breakpoint_set_cmdlist;
575 static struct cmd_list_element *breakpoint_show_cmdlist;
576 struct cmd_list_element *save_cmdlist;
577
578 /* Return whether a breakpoint is an active enabled breakpoint.  */
579 static int
580 breakpoint_enabled (struct breakpoint *b)
581 {
582   return (b->enable_state == bp_enabled);
583 }
584
585 /* Set breakpoint count to NUM.  */
586
587 static void
588 set_breakpoint_count (int num)
589 {
590   prev_breakpoint_count = breakpoint_count;
591   breakpoint_count = num;
592   set_internalvar_integer (lookup_internalvar ("bpnum"), num);
593 }
594
595 /* Used by `start_rbreak_breakpoints' below, to record the current
596    breakpoint count before "rbreak" creates any breakpoint.  */
597 static int rbreak_start_breakpoint_count;
598
599 /* Called at the start an "rbreak" command to record the first
600    breakpoint made.  */
601
602 void
603 start_rbreak_breakpoints (void)
604 {
605   rbreak_start_breakpoint_count = breakpoint_count;
606 }
607
608 /* Called at the end of an "rbreak" command to record the last
609    breakpoint made.  */
610
611 void
612 end_rbreak_breakpoints (void)
613 {
614   prev_breakpoint_count = rbreak_start_breakpoint_count;
615 }
616
617 /* Used in run_command to zero the hit count when a new run starts.  */
618
619 void
620 clear_breakpoint_hit_counts (void)
621 {
622   struct breakpoint *b;
623
624   ALL_BREAKPOINTS (b)
625     b->hit_count = 0;
626 }
627
628 /* Allocate a new counted_command_line with reference count of 1.
629    The new structure owns COMMANDS.  */
630
631 static struct counted_command_line *
632 alloc_counted_command_line (struct command_line *commands)
633 {
634   struct counted_command_line *result
635     = xmalloc (sizeof (struct counted_command_line));
636
637   result->refc = 1;
638   result->commands = commands;
639   return result;
640 }
641
642 /* Increment reference count.  This does nothing if CMD is NULL.  */
643
644 static void
645 incref_counted_command_line (struct counted_command_line *cmd)
646 {
647   if (cmd)
648     ++cmd->refc;
649 }
650
651 /* Decrement reference count.  If the reference count reaches 0,
652    destroy the counted_command_line.  Sets *CMDP to NULL.  This does
653    nothing if *CMDP is NULL.  */
654
655 static void
656 decref_counted_command_line (struct counted_command_line **cmdp)
657 {
658   if (*cmdp)
659     {
660       if (--(*cmdp)->refc == 0)
661         {
662           free_command_lines (&(*cmdp)->commands);
663           xfree (*cmdp);
664         }
665       *cmdp = NULL;
666     }
667 }
668
669 /* A cleanup function that calls decref_counted_command_line.  */
670
671 static void
672 do_cleanup_counted_command_line (void *arg)
673 {
674   decref_counted_command_line (arg);
675 }
676
677 /* Create a cleanup that calls decref_counted_command_line on the
678    argument.  */
679
680 static struct cleanup *
681 make_cleanup_decref_counted_command_line (struct counted_command_line **cmdp)
682 {
683   return make_cleanup (do_cleanup_counted_command_line, cmdp);
684 }
685
686 \f
687 /* Return the breakpoint with the specified number, or NULL
688    if the number does not refer to an existing breakpoint.  */
689
690 struct breakpoint *
691 get_breakpoint (int num)
692 {
693   struct breakpoint *b;
694
695   ALL_BREAKPOINTS (b)
696     if (b->number == num)
697       return b;
698   
699   return NULL;
700 }
701
702 \f
703
704 /* Mark locations as "conditions have changed" in case the target supports
705    evaluating conditions on its side.  */
706
707 static void
708 mark_breakpoint_modified (struct breakpoint *b)
709 {
710   struct bp_location *loc;
711
712   /* This is only meaningful if the target is
713      evaluating conditions and if the user has
714      opted for condition evaluation on the target's
715      side.  */
716   if (gdb_evaluates_breakpoint_condition_p ()
717       || !target_supports_evaluation_of_breakpoint_conditions ())
718     return;
719
720   if (!is_breakpoint (b))
721     return;
722
723   for (loc = b->loc; loc; loc = loc->next)
724     loc->condition_changed = condition_modified;
725 }
726
727 /* Mark location as "conditions have changed" in case the target supports
728    evaluating conditions on its side.  */
729
730 static void
731 mark_breakpoint_location_modified (struct bp_location *loc)
732 {
733   /* This is only meaningful if the target is
734      evaluating conditions and if the user has
735      opted for condition evaluation on the target's
736      side.  */
737   if (gdb_evaluates_breakpoint_condition_p ()
738       || !target_supports_evaluation_of_breakpoint_conditions ())
739
740     return;
741
742   if (!is_breakpoint (loc->owner))
743     return;
744
745   loc->condition_changed = condition_modified;
746 }
747
748 /* Sets the condition-evaluation mode using the static global
749    condition_evaluation_mode.  */
750
751 static void
752 set_condition_evaluation_mode (char *args, int from_tty,
753                                struct cmd_list_element *c)
754 {
755   struct breakpoint *b;
756   const char *old_mode, *new_mode;
757
758   if ((condition_evaluation_mode_1 == condition_evaluation_target)
759       && !target_supports_evaluation_of_breakpoint_conditions ())
760     {
761       condition_evaluation_mode_1 = condition_evaluation_mode;
762       warning (_("Target does not support breakpoint condition evaluation.\n"
763                  "Using host evaluation mode instead."));
764       return;
765     }
766
767   new_mode = translate_condition_evaluation_mode (condition_evaluation_mode_1);
768   old_mode = translate_condition_evaluation_mode (condition_evaluation_mode);
769
770   /* Flip the switch.  Flip it even if OLD_MODE == NEW_MODE as one of the
771      settings was "auto".  */
772   condition_evaluation_mode = condition_evaluation_mode_1;
773
774   /* Only update the mode if the user picked a different one.  */
775   if (new_mode != old_mode)
776     {
777       struct bp_location *loc, **loc_tmp;
778       /* If the user switched to a different evaluation mode, we
779          need to synch the changes with the target as follows:
780
781          "host" -> "target": Send all (valid) conditions to the target.
782          "target" -> "host": Remove all the conditions from the target.
783       */
784
785       if (new_mode == condition_evaluation_target)
786         {
787           /* Mark everything modified and synch conditions with the
788              target.  */
789           ALL_BP_LOCATIONS (loc, loc_tmp)
790             mark_breakpoint_location_modified (loc);
791         }
792       else
793         {
794           /* Manually mark non-duplicate locations to synch conditions
795              with the target.  We do this to remove all the conditions the
796              target knows about.  */
797           ALL_BP_LOCATIONS (loc, loc_tmp)
798             if (is_breakpoint (loc->owner) && loc->inserted)
799               loc->needs_update = 1;
800         }
801
802       /* Do the update.  */
803       update_global_location_list (1);
804     }
805
806   return;
807 }
808
809 /* Shows the current mode of breakpoint condition evaluation.  Explicitly shows
810    what "auto" is translating to.  */
811
812 static void
813 show_condition_evaluation_mode (struct ui_file *file, int from_tty,
814                                 struct cmd_list_element *c, const char *value)
815 {
816   if (condition_evaluation_mode == condition_evaluation_auto)
817     fprintf_filtered (file,
818                       _("Breakpoint condition evaluation "
819                         "mode is %s (currently %s).\n"),
820                       value,
821                       breakpoint_condition_evaluation_mode ());
822   else
823     fprintf_filtered (file, _("Breakpoint condition evaluation mode is %s.\n"),
824                       value);
825 }
826
827 /* A comparison function for bp_location AP and BP that is used by
828    bsearch.  This comparison function only cares about addresses, unlike
829    the more general bp_location_compare function.  */
830
831 static int
832 bp_location_compare_addrs (const void *ap, const void *bp)
833 {
834   struct bp_location *a = *(void **) ap;
835   struct bp_location *b = *(void **) bp;
836
837   if (a->address == b->address)
838     return 0;
839   else
840     return ((a->address > b->address) - (a->address < b->address));
841 }
842
843 /* Helper function to skip all bp_locations with addresses
844    less than ADDRESS.  It returns the first bp_location that
845    is greater than or equal to ADDRESS.  If none is found, just
846    return NULL.  */
847
848 static struct bp_location **
849 get_first_locp_gte_addr (CORE_ADDR address)
850 {
851   struct bp_location dummy_loc;
852   struct bp_location *dummy_locp = &dummy_loc;
853   struct bp_location **locp_found = NULL;
854
855   /* Initialize the dummy location's address field.  */
856   memset (&dummy_loc, 0, sizeof (struct bp_location));
857   dummy_loc.address = address;
858
859   /* Find a close match to the first location at ADDRESS.  */
860   locp_found = bsearch (&dummy_locp, bp_location, bp_location_count,
861                         sizeof (struct bp_location **),
862                         bp_location_compare_addrs);
863
864   /* Nothing was found, nothing left to do.  */
865   if (locp_found == NULL)
866     return NULL;
867
868   /* We may have found a location that is at ADDRESS but is not the first in the
869      location's list.  Go backwards (if possible) and locate the first one.  */
870   while ((locp_found - 1) >= bp_location
871          && (*(locp_found - 1))->address == address)
872     locp_found--;
873
874   return locp_found;
875 }
876
877 void
878 set_breakpoint_condition (struct breakpoint *b, char *exp,
879                           int from_tty)
880 {
881   xfree (b->cond_string);
882   b->cond_string = NULL;
883
884   if (is_watchpoint (b))
885     {
886       struct watchpoint *w = (struct watchpoint *) b;
887
888       xfree (w->cond_exp);
889       w->cond_exp = NULL;
890     }
891   else
892     {
893       struct bp_location *loc;
894
895       for (loc = b->loc; loc; loc = loc->next)
896         {
897           xfree (loc->cond);
898           loc->cond = NULL;
899
900           /* No need to free the condition agent expression
901              bytecode (if we have one).  We will handle this
902              when we go through update_global_location_list.  */
903         }
904     }
905
906   if (*exp == 0)
907     {
908       if (from_tty)
909         printf_filtered (_("Breakpoint %d now unconditional.\n"), b->number);
910     }
911   else
912     {
913       char *arg = exp;
914
915       /* I don't know if it matters whether this is the string the user
916          typed in or the decompiled expression.  */
917       b->cond_string = xstrdup (arg);
918       b->condition_not_parsed = 0;
919
920       if (is_watchpoint (b))
921         {
922           struct watchpoint *w = (struct watchpoint *) b;
923
924           innermost_block = NULL;
925           arg = exp;
926           w->cond_exp = parse_exp_1 (&arg, 0, 0);
927           if (*arg)
928             error (_("Junk at end of expression"));
929           w->cond_exp_valid_block = innermost_block;
930         }
931       else
932         {
933           struct bp_location *loc;
934
935           for (loc = b->loc; loc; loc = loc->next)
936             {
937               arg = exp;
938               loc->cond =
939                 parse_exp_1 (&arg, block_for_pc (loc->address), 0);
940               if (*arg)
941                 error (_("Junk at end of expression"));
942             }
943         }
944     }
945   mark_breakpoint_modified (b);
946
947   breakpoints_changed ();
948   observer_notify_breakpoint_modified (b);
949 }
950
951 /* condition N EXP -- set break condition of breakpoint N to EXP.  */
952
953 static void
954 condition_command (char *arg, int from_tty)
955 {
956   struct breakpoint *b;
957   char *p;
958   int bnum;
959
960   if (arg == 0)
961     error_no_arg (_("breakpoint number"));
962
963   p = arg;
964   bnum = get_number (&p);
965   if (bnum == 0)
966     error (_("Bad breakpoint argument: '%s'"), arg);
967
968   ALL_BREAKPOINTS (b)
969     if (b->number == bnum)
970       {
971         /* Check if this breakpoint has a Python object assigned to
972            it, and if it has a definition of the "stop"
973            method.  This method and conditions entered into GDB from
974            the CLI are mutually exclusive.  */
975         if (b->py_bp_object
976             && gdbpy_breakpoint_has_py_cond (b->py_bp_object))
977           error (_("Cannot set a condition where a Python 'stop' "
978                    "method has been defined in the breakpoint."));
979         set_breakpoint_condition (b, p, from_tty);
980
981         if (is_breakpoint (b))
982           update_global_location_list (1);
983
984         return;
985       }
986
987   error (_("No breakpoint number %d."), bnum);
988 }
989
990 /* Check that COMMAND do not contain commands that are suitable
991    only for tracepoints and not suitable for ordinary breakpoints.
992    Throw if any such commands is found.  */
993
994 static void
995 check_no_tracepoint_commands (struct command_line *commands)
996 {
997   struct command_line *c;
998
999   for (c = commands; c; c = c->next)
1000     {
1001       int i;
1002
1003       if (c->control_type == while_stepping_control)
1004         error (_("The 'while-stepping' command can "
1005                  "only be used for tracepoints"));
1006
1007       for (i = 0; i < c->body_count; ++i)
1008         check_no_tracepoint_commands ((c->body_list)[i]);
1009
1010       /* Not that command parsing removes leading whitespace and comment
1011          lines and also empty lines.  So, we only need to check for
1012          command directly.  */
1013       if (strstr (c->line, "collect ") == c->line)
1014         error (_("The 'collect' command can only be used for tracepoints"));
1015
1016       if (strstr (c->line, "teval ") == c->line)
1017         error (_("The 'teval' command can only be used for tracepoints"));
1018     }
1019 }
1020
1021 /* Encapsulate tests for different types of tracepoints.  */
1022
1023 static int
1024 is_tracepoint_type (enum bptype type)
1025 {
1026   return (type == bp_tracepoint
1027           || type == bp_fast_tracepoint
1028           || type == bp_static_tracepoint);
1029 }
1030
1031 int
1032 is_tracepoint (const struct breakpoint *b)
1033 {
1034   return is_tracepoint_type (b->type);
1035 }
1036
1037 /* A helper function that validates that COMMANDS are valid for a
1038    breakpoint.  This function will throw an exception if a problem is
1039    found.  */
1040
1041 static void
1042 validate_commands_for_breakpoint (struct breakpoint *b,
1043                                   struct command_line *commands)
1044 {
1045   if (is_tracepoint (b))
1046     {
1047       /* We need to verify that each top-level element of commands is
1048          valid for tracepoints, that there's at most one
1049          while-stepping element, and that while-stepping's body has
1050          valid tracing commands excluding nested while-stepping.  */
1051       struct command_line *c;
1052       struct command_line *while_stepping = 0;
1053       for (c = commands; c; c = c->next)
1054         {
1055           if (c->control_type == while_stepping_control)
1056             {
1057               if (b->type == bp_fast_tracepoint)
1058                 error (_("The 'while-stepping' command "
1059                          "cannot be used for fast tracepoint"));
1060               else if (b->type == bp_static_tracepoint)
1061                 error (_("The 'while-stepping' command "
1062                          "cannot be used for static tracepoint"));
1063
1064               if (while_stepping)
1065                 error (_("The 'while-stepping' command "
1066                          "can be used only once"));
1067               else
1068                 while_stepping = c;
1069             }
1070         }
1071       if (while_stepping)
1072         {
1073           struct command_line *c2;
1074
1075           gdb_assert (while_stepping->body_count == 1);
1076           c2 = while_stepping->body_list[0];
1077           for (; c2; c2 = c2->next)
1078             {
1079               if (c2->control_type == while_stepping_control)
1080                 error (_("The 'while-stepping' command cannot be nested"));
1081             }
1082         }
1083     }
1084   else
1085     {
1086       check_no_tracepoint_commands (commands);
1087     }
1088 }
1089
1090 /* Return a vector of all the static tracepoints set at ADDR.  The
1091    caller is responsible for releasing the vector.  */
1092
1093 VEC(breakpoint_p) *
1094 static_tracepoints_here (CORE_ADDR addr)
1095 {
1096   struct breakpoint *b;
1097   VEC(breakpoint_p) *found = 0;
1098   struct bp_location *loc;
1099
1100   ALL_BREAKPOINTS (b)
1101     if (b->type == bp_static_tracepoint)
1102       {
1103         for (loc = b->loc; loc; loc = loc->next)
1104           if (loc->address == addr)
1105             VEC_safe_push(breakpoint_p, found, b);
1106       }
1107
1108   return found;
1109 }
1110
1111 /* Set the command list of B to COMMANDS.  If breakpoint is tracepoint,
1112    validate that only allowed commands are included.  */
1113
1114 void
1115 breakpoint_set_commands (struct breakpoint *b, 
1116                          struct command_line *commands)
1117 {
1118   validate_commands_for_breakpoint (b, commands);
1119
1120   decref_counted_command_line (&b->commands);
1121   b->commands = alloc_counted_command_line (commands);
1122   breakpoints_changed ();
1123   observer_notify_breakpoint_modified (b);
1124 }
1125
1126 /* Set the internal `silent' flag on the breakpoint.  Note that this
1127    is not the same as the "silent" that may appear in the breakpoint's
1128    commands.  */
1129
1130 void
1131 breakpoint_set_silent (struct breakpoint *b, int silent)
1132 {
1133   int old_silent = b->silent;
1134
1135   b->silent = silent;
1136   if (old_silent != silent)
1137     observer_notify_breakpoint_modified (b);
1138 }
1139
1140 /* Set the thread for this breakpoint.  If THREAD is -1, make the
1141    breakpoint work for any thread.  */
1142
1143 void
1144 breakpoint_set_thread (struct breakpoint *b, int thread)
1145 {
1146   int old_thread = b->thread;
1147
1148   b->thread = thread;
1149   if (old_thread != thread)
1150     observer_notify_breakpoint_modified (b);
1151 }
1152
1153 /* Set the task for this breakpoint.  If TASK is 0, make the
1154    breakpoint work for any task.  */
1155
1156 void
1157 breakpoint_set_task (struct breakpoint *b, int task)
1158 {
1159   int old_task = b->task;
1160
1161   b->task = task;
1162   if (old_task != task)
1163     observer_notify_breakpoint_modified (b);
1164 }
1165
1166 void
1167 check_tracepoint_command (char *line, void *closure)
1168 {
1169   struct breakpoint *b = closure;
1170
1171   validate_actionline (&line, b);
1172 }
1173
1174 /* A structure used to pass information through
1175    map_breakpoint_numbers.  */
1176
1177 struct commands_info
1178 {
1179   /* True if the command was typed at a tty.  */
1180   int from_tty;
1181
1182   /* The breakpoint range spec.  */
1183   char *arg;
1184
1185   /* Non-NULL if the body of the commands are being read from this
1186      already-parsed command.  */
1187   struct command_line *control;
1188
1189   /* The command lines read from the user, or NULL if they have not
1190      yet been read.  */
1191   struct counted_command_line *cmd;
1192 };
1193
1194 /* A callback for map_breakpoint_numbers that sets the commands for
1195    commands_command.  */
1196
1197 static void
1198 do_map_commands_command (struct breakpoint *b, void *data)
1199 {
1200   struct commands_info *info = data;
1201
1202   if (info->cmd == NULL)
1203     {
1204       struct command_line *l;
1205
1206       if (info->control != NULL)
1207         l = copy_command_lines (info->control->body_list[0]);
1208       else
1209         {
1210           struct cleanup *old_chain;
1211           char *str;
1212
1213           str = xstrprintf (_("Type commands for breakpoint(s) "
1214                               "%s, one per line."),
1215                             info->arg);
1216
1217           old_chain = make_cleanup (xfree, str);
1218
1219           l = read_command_lines (str,
1220                                   info->from_tty, 1,
1221                                   (is_tracepoint (b)
1222                                    ? check_tracepoint_command : 0),
1223                                   b);
1224
1225           do_cleanups (old_chain);
1226         }
1227
1228       info->cmd = alloc_counted_command_line (l);
1229     }
1230
1231   /* If a breakpoint was on the list more than once, we don't need to
1232      do anything.  */
1233   if (b->commands != info->cmd)
1234     {
1235       validate_commands_for_breakpoint (b, info->cmd->commands);
1236       incref_counted_command_line (info->cmd);
1237       decref_counted_command_line (&b->commands);
1238       b->commands = info->cmd;
1239       breakpoints_changed ();
1240       observer_notify_breakpoint_modified (b);
1241     }
1242 }
1243
1244 static void
1245 commands_command_1 (char *arg, int from_tty, 
1246                     struct command_line *control)
1247 {
1248   struct cleanup *cleanups;
1249   struct commands_info info;
1250
1251   info.from_tty = from_tty;
1252   info.control = control;
1253   info.cmd = NULL;
1254   /* If we read command lines from the user, then `info' will hold an
1255      extra reference to the commands that we must clean up.  */
1256   cleanups = make_cleanup_decref_counted_command_line (&info.cmd);
1257
1258   if (arg == NULL || !*arg)
1259     {
1260       if (breakpoint_count - prev_breakpoint_count > 1)
1261         arg = xstrprintf ("%d-%d", prev_breakpoint_count + 1, 
1262                           breakpoint_count);
1263       else if (breakpoint_count > 0)
1264         arg = xstrprintf ("%d", breakpoint_count);
1265       else
1266         {
1267           /* So that we don't try to free the incoming non-NULL
1268              argument in the cleanup below.  Mapping breakpoint
1269              numbers will fail in this case.  */
1270           arg = NULL;
1271         }
1272     }
1273   else
1274     /* The command loop has some static state, so we need to preserve
1275        our argument.  */
1276     arg = xstrdup (arg);
1277
1278   if (arg != NULL)
1279     make_cleanup (xfree, arg);
1280
1281   info.arg = arg;
1282
1283   map_breakpoint_numbers (arg, do_map_commands_command, &info);
1284
1285   if (info.cmd == NULL)
1286     error (_("No breakpoints specified."));
1287
1288   do_cleanups (cleanups);
1289 }
1290
1291 static void
1292 commands_command (char *arg, int from_tty)
1293 {
1294   commands_command_1 (arg, from_tty, NULL);
1295 }
1296
1297 /* Like commands_command, but instead of reading the commands from
1298    input stream, takes them from an already parsed command structure.
1299
1300    This is used by cli-script.c to DTRT with breakpoint commands
1301    that are part of if and while bodies.  */
1302 enum command_control_type
1303 commands_from_control_command (char *arg, struct command_line *cmd)
1304 {
1305   commands_command_1 (arg, 0, cmd);
1306   return simple_control;
1307 }
1308
1309 /* Return non-zero if BL->TARGET_INFO contains valid information.  */
1310
1311 static int
1312 bp_location_has_shadow (struct bp_location *bl)
1313 {
1314   if (bl->loc_type != bp_loc_software_breakpoint)
1315     return 0;
1316   if (!bl->inserted)
1317     return 0;
1318   if (bl->target_info.shadow_len == 0)
1319     /* BL isn't valid, or doesn't shadow memory.  */
1320     return 0;
1321   return 1;
1322 }
1323
1324 /* Update BUF, which is LEN bytes read from the target address MEMADDR,
1325    by replacing any memory breakpoints with their shadowed contents.
1326
1327    If READBUF is not NULL, this buffer must not overlap with any of
1328    the breakpoint location's shadow_contents buffers.  Otherwise,
1329    a failed assertion internal error will be raised.
1330
1331    The range of shadowed area by each bp_location is:
1332      bl->address - bp_location_placed_address_before_address_max
1333      up to bl->address + bp_location_shadow_len_after_address_max
1334    The range we were requested to resolve shadows for is:
1335      memaddr ... memaddr + len
1336    Thus the safe cutoff boundaries for performance optimization are
1337      memaddr + len <= (bl->address
1338                        - bp_location_placed_address_before_address_max)
1339    and:
1340      bl->address + bp_location_shadow_len_after_address_max <= memaddr  */
1341
1342 void
1343 breakpoint_xfer_memory (gdb_byte *readbuf, gdb_byte *writebuf,
1344                         const gdb_byte *writebuf_org,
1345                         ULONGEST memaddr, LONGEST len)
1346 {
1347   /* Left boundary, right boundary and median element of our binary
1348      search.  */
1349   unsigned bc_l, bc_r, bc;
1350
1351   /* Find BC_L which is a leftmost element which may affect BUF
1352      content.  It is safe to report lower value but a failure to
1353      report higher one.  */
1354
1355   bc_l = 0;
1356   bc_r = bp_location_count;
1357   while (bc_l + 1 < bc_r)
1358     {
1359       struct bp_location *bl;
1360
1361       bc = (bc_l + bc_r) / 2;
1362       bl = bp_location[bc];
1363
1364       /* Check first BL->ADDRESS will not overflow due to the added
1365          constant.  Then advance the left boundary only if we are sure
1366          the BC element can in no way affect the BUF content (MEMADDR
1367          to MEMADDR + LEN range).
1368
1369          Use the BP_LOCATION_SHADOW_LEN_AFTER_ADDRESS_MAX safety
1370          offset so that we cannot miss a breakpoint with its shadow
1371          range tail still reaching MEMADDR.  */
1372
1373       if ((bl->address + bp_location_shadow_len_after_address_max
1374            >= bl->address)
1375           && (bl->address + bp_location_shadow_len_after_address_max
1376               <= memaddr))
1377         bc_l = bc;
1378       else
1379         bc_r = bc;
1380     }
1381
1382   /* Due to the binary search above, we need to make sure we pick the
1383      first location that's at BC_L's address.  E.g., if there are
1384      multiple locations at the same address, BC_L may end up pointing
1385      at a duplicate location, and miss the "master"/"inserted"
1386      location.  Say, given locations L1, L2 and L3 at addresses A and
1387      B:
1388
1389       L1@A, L2@A, L3@B, ...
1390
1391      BC_L could end up pointing at location L2, while the "master"
1392      location could be L1.  Since the `loc->inserted' flag is only set
1393      on "master" locations, we'd forget to restore the shadow of L1
1394      and L2.  */
1395   while (bc_l > 0
1396          && bp_location[bc_l]->address == bp_location[bc_l - 1]->address)
1397     bc_l--;
1398
1399   /* Now do full processing of the found relevant range of elements.  */
1400
1401   for (bc = bc_l; bc < bp_location_count; bc++)
1402   {
1403     struct bp_location *bl = bp_location[bc];
1404     CORE_ADDR bp_addr = 0;
1405     int bp_size = 0;
1406     int bptoffset = 0;
1407
1408     /* bp_location array has BL->OWNER always non-NULL.  */
1409     if (bl->owner->type == bp_none)
1410       warning (_("reading through apparently deleted breakpoint #%d?"),
1411                bl->owner->number);
1412
1413     /* Performance optimization: any further element can no longer affect BUF
1414        content.  */
1415
1416     if (bl->address >= bp_location_placed_address_before_address_max
1417         && memaddr + len <= (bl->address
1418                              - bp_location_placed_address_before_address_max))
1419       break;
1420
1421     if (!bp_location_has_shadow (bl))
1422       continue;
1423     if (!breakpoint_address_match (bl->target_info.placed_address_space, 0,
1424                                    current_program_space->aspace, 0))
1425       continue;
1426
1427     /* Addresses and length of the part of the breakpoint that
1428        we need to copy.  */
1429     bp_addr = bl->target_info.placed_address;
1430     bp_size = bl->target_info.shadow_len;
1431
1432     if (bp_addr + bp_size <= memaddr)
1433       /* The breakpoint is entirely before the chunk of memory we
1434          are reading.  */
1435       continue;
1436
1437     if (bp_addr >= memaddr + len)
1438       /* The breakpoint is entirely after the chunk of memory we are
1439          reading.  */
1440       continue;
1441
1442     /* Offset within shadow_contents.  */
1443     if (bp_addr < memaddr)
1444       {
1445         /* Only copy the second part of the breakpoint.  */
1446         bp_size -= memaddr - bp_addr;
1447         bptoffset = memaddr - bp_addr;
1448         bp_addr = memaddr;
1449       }
1450
1451     if (bp_addr + bp_size > memaddr + len)
1452       {
1453         /* Only copy the first part of the breakpoint.  */
1454         bp_size -= (bp_addr + bp_size) - (memaddr + len);
1455       }
1456
1457     if (readbuf != NULL)
1458       {
1459         /* Verify that the readbuf buffer does not overlap with
1460            the shadow_contents buffer.  */
1461         gdb_assert (bl->target_info.shadow_contents >= readbuf + len
1462                     || readbuf >= (bl->target_info.shadow_contents
1463                                    + bl->target_info.shadow_len));
1464
1465         /* Update the read buffer with this inserted breakpoint's
1466            shadow.  */
1467         memcpy (readbuf + bp_addr - memaddr,
1468                 bl->target_info.shadow_contents + bptoffset, bp_size);
1469       }
1470     else
1471       {
1472         struct gdbarch *gdbarch = bl->gdbarch;
1473         const unsigned char *bp;
1474         CORE_ADDR placed_address = bl->target_info.placed_address;
1475         unsigned placed_size = bl->target_info.placed_size;
1476
1477         /* Update the shadow with what we want to write to memory.  */
1478         memcpy (bl->target_info.shadow_contents + bptoffset,
1479                 writebuf_org + bp_addr - memaddr, bp_size);
1480
1481         /* Determine appropriate breakpoint contents and size for this
1482            address.  */
1483         bp = gdbarch_breakpoint_from_pc (gdbarch, &placed_address, &placed_size);
1484
1485         /* Update the final write buffer with this inserted
1486            breakpoint's INSN.  */
1487         memcpy (writebuf + bp_addr - memaddr, bp + bptoffset, bp_size);
1488       }
1489   }
1490 }
1491 \f
1492
1493 /* Return true if BPT is either a software breakpoint or a hardware
1494    breakpoint.  */
1495
1496 int
1497 is_breakpoint (const struct breakpoint *bpt)
1498 {
1499   return (bpt->type == bp_breakpoint
1500           || bpt->type == bp_hardware_breakpoint
1501           || bpt->type == bp_dprintf);
1502 }
1503
1504 /* Return true if BPT is of any hardware watchpoint kind.  */
1505
1506 static int
1507 is_hardware_watchpoint (const struct breakpoint *bpt)
1508 {
1509   return (bpt->type == bp_hardware_watchpoint
1510           || bpt->type == bp_read_watchpoint
1511           || bpt->type == bp_access_watchpoint);
1512 }
1513
1514 /* Return true if BPT is of any watchpoint kind, hardware or
1515    software.  */
1516
1517 int
1518 is_watchpoint (const struct breakpoint *bpt)
1519 {
1520   return (is_hardware_watchpoint (bpt)
1521           || bpt->type == bp_watchpoint);
1522 }
1523
1524 /* Returns true if the current thread and its running state are safe
1525    to evaluate or update watchpoint B.  Watchpoints on local
1526    expressions need to be evaluated in the context of the thread that
1527    was current when the watchpoint was created, and, that thread needs
1528    to be stopped to be able to select the correct frame context.
1529    Watchpoints on global expressions can be evaluated on any thread,
1530    and in any state.  It is presently left to the target allowing
1531    memory accesses when threads are running.  */
1532
1533 static int
1534 watchpoint_in_thread_scope (struct watchpoint *b)
1535 {
1536   return (b->base.pspace == current_program_space
1537           && (ptid_equal (b->watchpoint_thread, null_ptid)
1538               || (ptid_equal (inferior_ptid, b->watchpoint_thread)
1539                   && !is_executing (inferior_ptid))));
1540 }
1541
1542 /* Set watchpoint B to disp_del_at_next_stop, even including its possible
1543    associated bp_watchpoint_scope breakpoint.  */
1544
1545 static void
1546 watchpoint_del_at_next_stop (struct watchpoint *w)
1547 {
1548   struct breakpoint *b = &w->base;
1549
1550   if (b->related_breakpoint != b)
1551     {
1552       gdb_assert (b->related_breakpoint->type == bp_watchpoint_scope);
1553       gdb_assert (b->related_breakpoint->related_breakpoint == b);
1554       b->related_breakpoint->disposition = disp_del_at_next_stop;
1555       b->related_breakpoint->related_breakpoint = b->related_breakpoint;
1556       b->related_breakpoint = b;
1557     }
1558   b->disposition = disp_del_at_next_stop;
1559 }
1560
1561 /* Assuming that B is a watchpoint:
1562    - Reparse watchpoint expression, if REPARSE is non-zero
1563    - Evaluate expression and store the result in B->val
1564    - Evaluate the condition if there is one, and store the result
1565      in b->loc->cond.
1566    - Update the list of values that must be watched in B->loc.
1567
1568    If the watchpoint disposition is disp_del_at_next_stop, then do
1569    nothing.  If this is local watchpoint that is out of scope, delete
1570    it.
1571
1572    Even with `set breakpoint always-inserted on' the watchpoints are
1573    removed + inserted on each stop here.  Normal breakpoints must
1574    never be removed because they might be missed by a running thread
1575    when debugging in non-stop mode.  On the other hand, hardware
1576    watchpoints (is_hardware_watchpoint; processed here) are specific
1577    to each LWP since they are stored in each LWP's hardware debug
1578    registers.  Therefore, such LWP must be stopped first in order to
1579    be able to modify its hardware watchpoints.
1580
1581    Hardware watchpoints must be reset exactly once after being
1582    presented to the user.  It cannot be done sooner, because it would
1583    reset the data used to present the watchpoint hit to the user.  And
1584    it must not be done later because it could display the same single
1585    watchpoint hit during multiple GDB stops.  Note that the latter is
1586    relevant only to the hardware watchpoint types bp_read_watchpoint
1587    and bp_access_watchpoint.  False hit by bp_hardware_watchpoint is
1588    not user-visible - its hit is suppressed if the memory content has
1589    not changed.
1590
1591    The following constraints influence the location where we can reset
1592    hardware watchpoints:
1593
1594    * target_stopped_by_watchpoint and target_stopped_data_address are
1595      called several times when GDB stops.
1596
1597    [linux] 
1598    * Multiple hardware watchpoints can be hit at the same time,
1599      causing GDB to stop.  GDB only presents one hardware watchpoint
1600      hit at a time as the reason for stopping, and all the other hits
1601      are presented later, one after the other, each time the user
1602      requests the execution to be resumed.  Execution is not resumed
1603      for the threads still having pending hit event stored in
1604      LWP_INFO->STATUS.  While the watchpoint is already removed from
1605      the inferior on the first stop the thread hit event is kept being
1606      reported from its cached value by linux_nat_stopped_data_address
1607      until the real thread resume happens after the watchpoint gets
1608      presented and thus its LWP_INFO->STATUS gets reset.
1609
1610    Therefore the hardware watchpoint hit can get safely reset on the
1611    watchpoint removal from inferior.  */
1612
1613 static void
1614 update_watchpoint (struct watchpoint *b, int reparse)
1615 {
1616   int within_current_scope;
1617   struct frame_id saved_frame_id;
1618   int frame_saved;
1619
1620   /* If this is a local watchpoint, we only want to check if the
1621      watchpoint frame is in scope if the current thread is the thread
1622      that was used to create the watchpoint.  */
1623   if (!watchpoint_in_thread_scope (b))
1624     return;
1625
1626   if (b->base.disposition == disp_del_at_next_stop)
1627     return;
1628  
1629   frame_saved = 0;
1630
1631   /* Determine if the watchpoint is within scope.  */
1632   if (b->exp_valid_block == NULL)
1633     within_current_scope = 1;
1634   else
1635     {
1636       struct frame_info *fi = get_current_frame ();
1637       struct gdbarch *frame_arch = get_frame_arch (fi);
1638       CORE_ADDR frame_pc = get_frame_pc (fi);
1639
1640       /* If we're in a function epilogue, unwinding may not work
1641          properly, so do not attempt to recreate locations at this
1642          point.  See similar comments in watchpoint_check.  */
1643       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
1644         return;
1645
1646       /* Save the current frame's ID so we can restore it after
1647          evaluating the watchpoint expression on its own frame.  */
1648       /* FIXME drow/2003-09-09: It would be nice if evaluate_expression
1649          took a frame parameter, so that we didn't have to change the
1650          selected frame.  */
1651       frame_saved = 1;
1652       saved_frame_id = get_frame_id (get_selected_frame (NULL));
1653
1654       fi = frame_find_by_id (b->watchpoint_frame);
1655       within_current_scope = (fi != NULL);
1656       if (within_current_scope)
1657         select_frame (fi);
1658     }
1659
1660   /* We don't free locations.  They are stored in the bp_location array
1661      and update_global_location_list will eventually delete them and
1662      remove breakpoints if needed.  */
1663   b->base.loc = NULL;
1664
1665   if (within_current_scope && reparse)
1666     {
1667       char *s;
1668
1669       if (b->exp)
1670         {
1671           xfree (b->exp);
1672           b->exp = NULL;
1673         }
1674       s = b->exp_string_reparse ? b->exp_string_reparse : b->exp_string;
1675       b->exp = parse_exp_1 (&s, b->exp_valid_block, 0);
1676       /* If the meaning of expression itself changed, the old value is
1677          no longer relevant.  We don't want to report a watchpoint hit
1678          to the user when the old value and the new value may actually
1679          be completely different objects.  */
1680       value_free (b->val);
1681       b->val = NULL;
1682       b->val_valid = 0;
1683
1684       /* Note that unlike with breakpoints, the watchpoint's condition
1685          expression is stored in the breakpoint object, not in the
1686          locations (re)created below.  */
1687       if (b->base.cond_string != NULL)
1688         {
1689           if (b->cond_exp != NULL)
1690             {
1691               xfree (b->cond_exp);
1692               b->cond_exp = NULL;
1693             }
1694
1695           s = b->base.cond_string;
1696           b->cond_exp = parse_exp_1 (&s, b->cond_exp_valid_block, 0);
1697         }
1698     }
1699
1700   /* If we failed to parse the expression, for example because
1701      it refers to a global variable in a not-yet-loaded shared library,
1702      don't try to insert watchpoint.  We don't automatically delete
1703      such watchpoint, though, since failure to parse expression
1704      is different from out-of-scope watchpoint.  */
1705   if ( !target_has_execution)
1706     {
1707       /* Without execution, memory can't change.  No use to try and
1708          set watchpoint locations.  The watchpoint will be reset when
1709          the target gains execution, through breakpoint_re_set.  */
1710     }
1711   else if (within_current_scope && b->exp)
1712     {
1713       int pc = 0;
1714       struct value *val_chain, *v, *result, *next;
1715       struct program_space *frame_pspace;
1716
1717       fetch_subexp_value (b->exp, &pc, &v, &result, &val_chain);
1718
1719       /* Avoid setting b->val if it's already set.  The meaning of
1720          b->val is 'the last value' user saw, and we should update
1721          it only if we reported that last value to user.  As it
1722          happens, the code that reports it updates b->val directly.
1723          We don't keep track of the memory value for masked
1724          watchpoints.  */
1725       if (!b->val_valid && !is_masked_watchpoint (&b->base))
1726         {
1727           b->val = v;
1728           b->val_valid = 1;
1729         }
1730
1731       frame_pspace = get_frame_program_space (get_selected_frame (NULL));
1732
1733       /* Look at each value on the value chain.  */
1734       for (v = val_chain; v; v = value_next (v))
1735         {
1736           /* If it's a memory location, and GDB actually needed
1737              its contents to evaluate the expression, then we
1738              must watch it.  If the first value returned is
1739              still lazy, that means an error occurred reading it;
1740              watch it anyway in case it becomes readable.  */
1741           if (VALUE_LVAL (v) == lval_memory
1742               && (v == val_chain || ! value_lazy (v)))
1743             {
1744               struct type *vtype = check_typedef (value_type (v));
1745
1746               /* We only watch structs and arrays if user asked
1747                  for it explicitly, never if they just happen to
1748                  appear in the middle of some value chain.  */
1749               if (v == result
1750                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
1751                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
1752                 {
1753                   CORE_ADDR addr;
1754                   int len, type;
1755                   struct bp_location *loc, **tmp;
1756
1757                   addr = value_address (v);
1758                   len = TYPE_LENGTH (value_type (v));
1759                   type = hw_write;
1760                   if (b->base.type == bp_read_watchpoint)
1761                     type = hw_read;
1762                   else if (b->base.type == bp_access_watchpoint)
1763                     type = hw_access;
1764
1765                   loc = allocate_bp_location (&b->base);
1766                   for (tmp = &(b->base.loc); *tmp != NULL; tmp = &((*tmp)->next))
1767                     ;
1768                   *tmp = loc;
1769                   loc->gdbarch = get_type_arch (value_type (v));
1770
1771                   loc->pspace = frame_pspace;
1772                   loc->address = addr;
1773                   loc->length = len;
1774                   loc->watchpoint_type = type;
1775                 }
1776             }
1777         }
1778
1779       /* Change the type of breakpoint between hardware assisted or
1780          an ordinary watchpoint depending on the hardware support
1781          and free hardware slots.  REPARSE is set when the inferior
1782          is started.  */
1783       if (reparse)
1784         {
1785           int reg_cnt;
1786           enum bp_loc_type loc_type;
1787           struct bp_location *bl;
1788
1789           reg_cnt = can_use_hardware_watchpoint (val_chain);
1790
1791           if (reg_cnt)
1792             {
1793               int i, target_resources_ok, other_type_used;
1794               enum bptype type;
1795
1796               /* Use an exact watchpoint when there's only one memory region to be
1797                  watched, and only one debug register is needed to watch it.  */
1798               b->exact = target_exact_watchpoints && reg_cnt == 1;
1799
1800               /* We need to determine how many resources are already
1801                  used for all other hardware watchpoints plus this one
1802                  to see if we still have enough resources to also fit
1803                  this watchpoint in as well.  */
1804
1805               /* If this is a software watchpoint, we try to turn it
1806                  to a hardware one -- count resources as if B was of
1807                  hardware watchpoint type.  */
1808               type = b->base.type;
1809               if (type == bp_watchpoint)
1810                 type = bp_hardware_watchpoint;
1811
1812               /* This watchpoint may or may not have been placed on
1813                  the list yet at this point (it won't be in the list
1814                  if we're trying to create it for the first time,
1815                  through watch_command), so always account for it
1816                  manually.  */
1817
1818               /* Count resources used by all watchpoints except B.  */
1819               i = hw_watchpoint_used_count_others (&b->base, type, &other_type_used);
1820
1821               /* Add in the resources needed for B.  */
1822               i += hw_watchpoint_use_count (&b->base);
1823
1824               target_resources_ok
1825                 = target_can_use_hardware_watchpoint (type, i, other_type_used);
1826               if (target_resources_ok <= 0)
1827                 {
1828                   int sw_mode = b->base.ops->works_in_software_mode (&b->base);
1829
1830                   if (target_resources_ok == 0 && !sw_mode)
1831                     error (_("Target does not support this type of "
1832                              "hardware watchpoint."));
1833                   else if (target_resources_ok < 0 && !sw_mode)
1834                     error (_("There are not enough available hardware "
1835                              "resources for this watchpoint."));
1836
1837                   /* Downgrade to software watchpoint.  */
1838                   b->base.type = bp_watchpoint;
1839                 }
1840               else
1841                 {
1842                   /* If this was a software watchpoint, we've just
1843                      found we have enough resources to turn it to a
1844                      hardware watchpoint.  Otherwise, this is a
1845                      nop.  */
1846                   b->base.type = type;
1847                 }
1848             }
1849           else if (!b->base.ops->works_in_software_mode (&b->base))
1850             error (_("Expression cannot be implemented with "
1851                      "read/access watchpoint."));
1852           else
1853             b->base.type = bp_watchpoint;
1854
1855           loc_type = (b->base.type == bp_watchpoint? bp_loc_other
1856                       : bp_loc_hardware_watchpoint);
1857           for (bl = b->base.loc; bl; bl = bl->next)
1858             bl->loc_type = loc_type;
1859         }
1860
1861       for (v = val_chain; v; v = next)
1862         {
1863           next = value_next (v);
1864           if (v != b->val)
1865             value_free (v);
1866         }
1867
1868       /* If a software watchpoint is not watching any memory, then the
1869          above left it without any location set up.  But,
1870          bpstat_stop_status requires a location to be able to report
1871          stops, so make sure there's at least a dummy one.  */
1872       if (b->base.type == bp_watchpoint && b->base.loc == NULL)
1873         {
1874           struct breakpoint *base = &b->base;
1875           base->loc = allocate_bp_location (base);
1876           base->loc->pspace = frame_pspace;
1877           base->loc->address = -1;
1878           base->loc->length = -1;
1879           base->loc->watchpoint_type = -1;
1880         }
1881     }
1882   else if (!within_current_scope)
1883     {
1884       printf_filtered (_("\
1885 Watchpoint %d deleted because the program has left the block\n\
1886 in which its expression is valid.\n"),
1887                        b->base.number);
1888       watchpoint_del_at_next_stop (b);
1889     }
1890
1891   /* Restore the selected frame.  */
1892   if (frame_saved)
1893     select_frame (frame_find_by_id (saved_frame_id));
1894 }
1895
1896
1897 /* Returns 1 iff breakpoint location should be
1898    inserted in the inferior.  We don't differentiate the type of BL's owner
1899    (breakpoint vs. tracepoint), although insert_location in tracepoint's
1900    breakpoint_ops is not defined, because in insert_bp_location,
1901    tracepoint's insert_location will not be called.  */
1902 static int
1903 should_be_inserted (struct bp_location *bl)
1904 {
1905   if (bl->owner == NULL || !breakpoint_enabled (bl->owner))
1906     return 0;
1907
1908   if (bl->owner->disposition == disp_del_at_next_stop)
1909     return 0;
1910
1911   if (!bl->enabled || bl->shlib_disabled || bl->duplicate)
1912     return 0;
1913
1914   if (user_breakpoint_p (bl->owner) && bl->pspace->executing_startup)
1915     return 0;
1916
1917   /* This is set for example, when we're attached to the parent of a
1918      vfork, and have detached from the child.  The child is running
1919      free, and we expect it to do an exec or exit, at which point the
1920      OS makes the parent schedulable again (and the target reports
1921      that the vfork is done).  Until the child is done with the shared
1922      memory region, do not insert breakpoints in the parent, otherwise
1923      the child could still trip on the parent's breakpoints.  Since
1924      the parent is blocked anyway, it won't miss any breakpoint.  */
1925   if (bl->pspace->breakpoints_not_allowed)
1926     return 0;
1927
1928   return 1;
1929 }
1930
1931 /* Same as should_be_inserted but does the check assuming
1932    that the location is not duplicated.  */
1933
1934 static int
1935 unduplicated_should_be_inserted (struct bp_location *bl)
1936 {
1937   int result;
1938   const int save_duplicate = bl->duplicate;
1939
1940   bl->duplicate = 0;
1941   result = should_be_inserted (bl);
1942   bl->duplicate = save_duplicate;
1943   return result;
1944 }
1945
1946 /* Parses a conditional described by an expression COND into an
1947    agent expression bytecode suitable for evaluation
1948    by the bytecode interpreter.  Return NULL if there was
1949    any error during parsing.  */
1950
1951 static struct agent_expr *
1952 parse_cond_to_aexpr (CORE_ADDR scope, struct expression *cond)
1953 {
1954   struct agent_expr *aexpr = NULL;
1955   struct cleanup *old_chain = NULL;
1956   volatile struct gdb_exception ex;
1957
1958   if (!cond)
1959     return NULL;
1960
1961   /* We don't want to stop processing, so catch any errors
1962      that may show up.  */
1963   TRY_CATCH (ex, RETURN_MASK_ERROR)
1964     {
1965       aexpr = gen_eval_for_expr (scope, cond);
1966     }
1967
1968   if (ex.reason < 0)
1969     {
1970       /* If we got here, it means the condition could not be parsed to a valid
1971          bytecode expression and thus can't be evaluated on the target's side.
1972          It's no use iterating through the conditions.  */
1973       return NULL;
1974     }
1975
1976   /* We have a valid agent expression.  */
1977   return aexpr;
1978 }
1979
1980 /* Based on location BL, create a list of breakpoint conditions to be
1981    passed on to the target.  If we have duplicated locations with different
1982    conditions, we will add such conditions to the list.  The idea is that the
1983    target will evaluate the list of conditions and will only notify GDB when
1984    one of them is true.  */
1985
1986 static void
1987 build_target_condition_list (struct bp_location *bl)
1988 {
1989   struct bp_location **locp = NULL, **loc2p;
1990   int null_condition_or_parse_error = 0;
1991   int modified = bl->needs_update;
1992   struct bp_location *loc;
1993
1994   /* This is only meaningful if the target is
1995      evaluating conditions and if the user has
1996      opted for condition evaluation on the target's
1997      side.  */
1998   if (gdb_evaluates_breakpoint_condition_p ()
1999       || !target_supports_evaluation_of_breakpoint_conditions ())
2000     return;
2001
2002   /* Do a first pass to check for locations with no assigned
2003      conditions or conditions that fail to parse to a valid agent expression
2004      bytecode.  If any of these happen, then it's no use to send conditions
2005      to the target since this location will always trigger and generate a
2006      response back to GDB.  */
2007   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2008     {
2009       loc = (*loc2p);
2010       if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2011         {
2012           if (modified)
2013             {
2014               struct agent_expr *aexpr;
2015
2016               /* Re-parse the conditions since something changed.  In that
2017                  case we already freed the condition bytecodes (see
2018                  force_breakpoint_reinsertion).  We just
2019                  need to parse the condition to bytecodes again.  */
2020               aexpr = parse_cond_to_aexpr (bl->address, loc->cond);
2021               loc->cond_bytecode = aexpr;
2022
2023               /* Check if we managed to parse the conditional expression
2024                  correctly.  If not, we will not send this condition
2025                  to the target.  */
2026               if (aexpr)
2027                 continue;
2028             }
2029
2030           /* If we have a NULL bytecode expression, it means something
2031              went wrong or we have a null condition expression.  */
2032           if (!loc->cond_bytecode)
2033             {
2034               null_condition_or_parse_error = 1;
2035               break;
2036             }
2037         }
2038     }
2039
2040   /* If any of these happened, it means we will have to evaluate the conditions
2041      for the location's address on gdb's side.  It is no use keeping bytecodes
2042      for all the other duplicate locations, thus we free all of them here.
2043
2044      This is so we have a finer control over which locations' conditions are
2045      being evaluated by GDB or the remote stub.  */
2046   if (null_condition_or_parse_error)
2047     {
2048       ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2049         {
2050           loc = (*loc2p);
2051           if (is_breakpoint (loc->owner) && loc->pspace->num == bl->pspace->num)
2052             {
2053               /* Only go as far as the first NULL bytecode is
2054                  located.  */
2055               if (!loc->cond_bytecode)
2056                 return;
2057
2058               free_agent_expr (loc->cond_bytecode);
2059               loc->cond_bytecode = NULL;
2060             }
2061         }
2062     }
2063
2064   /* No NULL conditions or failed bytecode generation.  Build a condition list
2065      for this location's address.  */
2066   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, bl->address)
2067     {
2068       loc = (*loc2p);
2069       if (loc->cond
2070           && is_breakpoint (loc->owner)
2071           && loc->pspace->num == bl->pspace->num
2072           && loc->owner->enable_state == bp_enabled
2073           && loc->enabled)
2074         /* Add the condition to the vector.  This will be used later to send the
2075            conditions to the target.  */
2076         VEC_safe_push (agent_expr_p, bl->target_info.conditions,
2077                        loc->cond_bytecode);
2078     }
2079
2080   return;
2081 }
2082
2083 /* Insert a low-level "breakpoint" of some type.  BL is the breakpoint
2084    location.  Any error messages are printed to TMP_ERROR_STREAM; and
2085    DISABLED_BREAKS, and HW_BREAKPOINT_ERROR are used to report problems.
2086    Returns 0 for success, 1 if the bp_location type is not supported or
2087    -1 for failure.
2088
2089    NOTE drow/2003-09-09: This routine could be broken down to an
2090    object-style method for each breakpoint or catchpoint type.  */
2091 static int
2092 insert_bp_location (struct bp_location *bl,
2093                     struct ui_file *tmp_error_stream,
2094                     int *disabled_breaks,
2095                     int *hw_breakpoint_error)
2096 {
2097   int val = 0;
2098
2099   if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2100     return 0;
2101
2102   /* Note we don't initialize bl->target_info, as that wipes out
2103      the breakpoint location's shadow_contents if the breakpoint
2104      is still inserted at that location.  This in turn breaks
2105      target_read_memory which depends on these buffers when
2106      a memory read is requested at the breakpoint location:
2107      Once the target_info has been wiped, we fail to see that
2108      we have a breakpoint inserted at that address and thus
2109      read the breakpoint instead of returning the data saved in
2110      the breakpoint location's shadow contents.  */
2111   bl->target_info.placed_address = bl->address;
2112   bl->target_info.placed_address_space = bl->pspace->aspace;
2113   bl->target_info.length = bl->length;
2114
2115   /* When working with target-side conditions, we must pass all the conditions
2116      for the same breakpoint address down to the target since GDB will not
2117      insert those locations.  With a list of breakpoint conditions, the target
2118      can decide when to stop and notify GDB.  */
2119
2120   if (is_breakpoint (bl->owner))
2121     {
2122       build_target_condition_list (bl);
2123       /* Reset the condition modification marker.  */
2124       bl->needs_update = 0;
2125     }
2126
2127   if (bl->loc_type == bp_loc_software_breakpoint
2128       || bl->loc_type == bp_loc_hardware_breakpoint)
2129     {
2130       if (bl->owner->type != bp_hardware_breakpoint)
2131         {
2132           /* If the explicitly specified breakpoint type
2133              is not hardware breakpoint, check the memory map to see
2134              if the breakpoint address is in read only memory or not.
2135
2136              Two important cases are:
2137              - location type is not hardware breakpoint, memory
2138              is readonly.  We change the type of the location to
2139              hardware breakpoint.
2140              - location type is hardware breakpoint, memory is
2141              read-write.  This means we've previously made the
2142              location hardware one, but then the memory map changed,
2143              so we undo.
2144              
2145              When breakpoints are removed, remove_breakpoints will use
2146              location types we've just set here, the only possible
2147              problem is that memory map has changed during running
2148              program, but it's not going to work anyway with current
2149              gdb.  */
2150           struct mem_region *mr 
2151             = lookup_mem_region (bl->target_info.placed_address);
2152           
2153           if (mr)
2154             {
2155               if (automatic_hardware_breakpoints)
2156                 {
2157                   enum bp_loc_type new_type;
2158                   
2159                   if (mr->attrib.mode != MEM_RW)
2160                     new_type = bp_loc_hardware_breakpoint;
2161                   else 
2162                     new_type = bp_loc_software_breakpoint;
2163                   
2164                   if (new_type != bl->loc_type)
2165                     {
2166                       static int said = 0;
2167
2168                       bl->loc_type = new_type;
2169                       if (!said)
2170                         {
2171                           fprintf_filtered (gdb_stdout,
2172                                             _("Note: automatically using "
2173                                               "hardware breakpoints for "
2174                                               "read-only addresses.\n"));
2175                           said = 1;
2176                         }
2177                     }
2178                 }
2179               else if (bl->loc_type == bp_loc_software_breakpoint
2180                        && mr->attrib.mode != MEM_RW)        
2181                 warning (_("cannot set software breakpoint "
2182                            "at readonly address %s"),
2183                          paddress (bl->gdbarch, bl->address));
2184             }
2185         }
2186         
2187       /* First check to see if we have to handle an overlay.  */
2188       if (overlay_debugging == ovly_off
2189           || bl->section == NULL
2190           || !(section_is_overlay (bl->section)))
2191         {
2192           /* No overlay handling: just set the breakpoint.  */
2193
2194           val = bl->owner->ops->insert_location (bl);
2195         }
2196       else
2197         {
2198           /* This breakpoint is in an overlay section.
2199              Shall we set a breakpoint at the LMA?  */
2200           if (!overlay_events_enabled)
2201             {
2202               /* Yes -- overlay event support is not active, 
2203                  so we must try to set a breakpoint at the LMA.
2204                  This will not work for a hardware breakpoint.  */
2205               if (bl->loc_type == bp_loc_hardware_breakpoint)
2206                 warning (_("hardware breakpoint %d not supported in overlay!"),
2207                          bl->owner->number);
2208               else
2209                 {
2210                   CORE_ADDR addr = overlay_unmapped_address (bl->address,
2211                                                              bl->section);
2212                   /* Set a software (trap) breakpoint at the LMA.  */
2213                   bl->overlay_target_info = bl->target_info;
2214                   bl->overlay_target_info.placed_address = addr;
2215                   val = target_insert_breakpoint (bl->gdbarch,
2216                                                   &bl->overlay_target_info);
2217                   if (val != 0)
2218                     fprintf_unfiltered (tmp_error_stream,
2219                                         "Overlay breakpoint %d "
2220                                         "failed: in ROM?\n",
2221                                         bl->owner->number);
2222                 }
2223             }
2224           /* Shall we set a breakpoint at the VMA? */
2225           if (section_is_mapped (bl->section))
2226             {
2227               /* Yes.  This overlay section is mapped into memory.  */
2228               val = bl->owner->ops->insert_location (bl);
2229             }
2230           else
2231             {
2232               /* No.  This breakpoint will not be inserted.  
2233                  No error, but do not mark the bp as 'inserted'.  */
2234               return 0;
2235             }
2236         }
2237
2238       if (val)
2239         {
2240           /* Can't set the breakpoint.  */
2241           if (solib_name_from_address (bl->pspace, bl->address))
2242             {
2243               /* See also: disable_breakpoints_in_shlibs.  */
2244               val = 0;
2245               bl->shlib_disabled = 1;
2246               observer_notify_breakpoint_modified (bl->owner);
2247               if (!*disabled_breaks)
2248                 {
2249                   fprintf_unfiltered (tmp_error_stream, 
2250                                       "Cannot insert breakpoint %d.\n", 
2251                                       bl->owner->number);
2252                   fprintf_unfiltered (tmp_error_stream, 
2253                                       "Temporarily disabling shared "
2254                                       "library breakpoints:\n");
2255                 }
2256               *disabled_breaks = 1;
2257               fprintf_unfiltered (tmp_error_stream,
2258                                   "breakpoint #%d\n", bl->owner->number);
2259             }
2260           else
2261             {
2262               if (bl->loc_type == bp_loc_hardware_breakpoint)
2263                 {
2264                   *hw_breakpoint_error = 1;
2265                   fprintf_unfiltered (tmp_error_stream,
2266                                       "Cannot insert hardware "
2267                                       "breakpoint %d.\n",
2268                                       bl->owner->number);
2269                 }
2270               else
2271                 {
2272                   fprintf_unfiltered (tmp_error_stream, 
2273                                       "Cannot insert breakpoint %d.\n", 
2274                                       bl->owner->number);
2275                   fprintf_filtered (tmp_error_stream, 
2276                                     "Error accessing memory address ");
2277                   fputs_filtered (paddress (bl->gdbarch, bl->address),
2278                                   tmp_error_stream);
2279                   fprintf_filtered (tmp_error_stream, ": %s.\n",
2280                                     safe_strerror (val));
2281                 }
2282
2283             }
2284         }
2285       else
2286         bl->inserted = 1;
2287
2288       return val;
2289     }
2290
2291   else if (bl->loc_type == bp_loc_hardware_watchpoint
2292            /* NOTE drow/2003-09-08: This state only exists for removing
2293               watchpoints.  It's not clear that it's necessary...  */
2294            && bl->owner->disposition != disp_del_at_next_stop)
2295     {
2296       gdb_assert (bl->owner->ops != NULL
2297                   && bl->owner->ops->insert_location != NULL);
2298
2299       val = bl->owner->ops->insert_location (bl);
2300
2301       /* If trying to set a read-watchpoint, and it turns out it's not
2302          supported, try emulating one with an access watchpoint.  */
2303       if (val == 1 && bl->watchpoint_type == hw_read)
2304         {
2305           struct bp_location *loc, **loc_temp;
2306
2307           /* But don't try to insert it, if there's already another
2308              hw_access location that would be considered a duplicate
2309              of this one.  */
2310           ALL_BP_LOCATIONS (loc, loc_temp)
2311             if (loc != bl
2312                 && loc->watchpoint_type == hw_access
2313                 && watchpoint_locations_match (bl, loc))
2314               {
2315                 bl->duplicate = 1;
2316                 bl->inserted = 1;
2317                 bl->target_info = loc->target_info;
2318                 bl->watchpoint_type = hw_access;
2319                 val = 0;
2320                 break;
2321               }
2322
2323           if (val == 1)
2324             {
2325               bl->watchpoint_type = hw_access;
2326               val = bl->owner->ops->insert_location (bl);
2327
2328               if (val)
2329                 /* Back to the original value.  */
2330                 bl->watchpoint_type = hw_read;
2331             }
2332         }
2333
2334       bl->inserted = (val == 0);
2335     }
2336
2337   else if (bl->owner->type == bp_catchpoint)
2338     {
2339       gdb_assert (bl->owner->ops != NULL
2340                   && bl->owner->ops->insert_location != NULL);
2341
2342       val = bl->owner->ops->insert_location (bl);
2343       if (val)
2344         {
2345           bl->owner->enable_state = bp_disabled;
2346
2347           if (val == 1)
2348             warning (_("\
2349 Error inserting catchpoint %d: Your system does not support this type\n\
2350 of catchpoint."), bl->owner->number);
2351           else
2352             warning (_("Error inserting catchpoint %d."), bl->owner->number);
2353         }
2354
2355       bl->inserted = (val == 0);
2356
2357       /* We've already printed an error message if there was a problem
2358          inserting this catchpoint, and we've disabled the catchpoint,
2359          so just return success.  */
2360       return 0;
2361     }
2362
2363   return 0;
2364 }
2365
2366 /* This function is called when program space PSPACE is about to be
2367    deleted.  It takes care of updating breakpoints to not reference
2368    PSPACE anymore.  */
2369
2370 void
2371 breakpoint_program_space_exit (struct program_space *pspace)
2372 {
2373   struct breakpoint *b, *b_temp;
2374   struct bp_location *loc, **loc_temp;
2375
2376   /* Remove any breakpoint that was set through this program space.  */
2377   ALL_BREAKPOINTS_SAFE (b, b_temp)
2378     {
2379       if (b->pspace == pspace)
2380         delete_breakpoint (b);
2381     }
2382
2383   /* Breakpoints set through other program spaces could have locations
2384      bound to PSPACE as well.  Remove those.  */
2385   ALL_BP_LOCATIONS (loc, loc_temp)
2386     {
2387       struct bp_location *tmp;
2388
2389       if (loc->pspace == pspace)
2390         {
2391           /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
2392           if (loc->owner->loc == loc)
2393             loc->owner->loc = loc->next;
2394           else
2395             for (tmp = loc->owner->loc; tmp->next != NULL; tmp = tmp->next)
2396               if (tmp->next == loc)
2397                 {
2398                   tmp->next = loc->next;
2399                   break;
2400                 }
2401         }
2402     }
2403
2404   /* Now update the global location list to permanently delete the
2405      removed locations above.  */
2406   update_global_location_list (0);
2407 }
2408
2409 /* Make sure all breakpoints are inserted in inferior.
2410    Throws exception on any error.
2411    A breakpoint that is already inserted won't be inserted
2412    again, so calling this function twice is safe.  */
2413 void
2414 insert_breakpoints (void)
2415 {
2416   struct breakpoint *bpt;
2417
2418   ALL_BREAKPOINTS (bpt)
2419     if (is_hardware_watchpoint (bpt))
2420       {
2421         struct watchpoint *w = (struct watchpoint *) bpt;
2422
2423         update_watchpoint (w, 0 /* don't reparse.  */);
2424       }
2425
2426   update_global_location_list (1);
2427
2428   /* update_global_location_list does not insert breakpoints when
2429      always_inserted_mode is not enabled.  Explicitly insert them
2430      now.  */
2431   if (!breakpoints_always_inserted_mode ())
2432     insert_breakpoint_locations ();
2433 }
2434
2435 /* Invoke CALLBACK for each of bp_location.  */
2436
2437 void
2438 iterate_over_bp_locations (walk_bp_location_callback callback)
2439 {
2440   struct bp_location *loc, **loc_tmp;
2441
2442   ALL_BP_LOCATIONS (loc, loc_tmp)
2443     {
2444       callback (loc, NULL);
2445     }
2446 }
2447
2448 /* This is used when we need to synch breakpoint conditions between GDB and the
2449    target.  It is the case with deleting and disabling of breakpoints when using
2450    always-inserted mode.  */
2451
2452 static void
2453 update_inserted_breakpoint_locations (void)
2454 {
2455   struct bp_location *bl, **blp_tmp;
2456   int error_flag = 0;
2457   int val = 0;
2458   int disabled_breaks = 0;
2459   int hw_breakpoint_error = 0;
2460
2461   struct ui_file *tmp_error_stream = mem_fileopen ();
2462   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2463
2464   /* Explicitly mark the warning -- this will only be printed if
2465      there was an error.  */
2466   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2467
2468   save_current_space_and_thread ();
2469
2470   ALL_BP_LOCATIONS (bl, blp_tmp)
2471     {
2472       /* We only want to update software breakpoints and hardware
2473          breakpoints.  */
2474       if (!is_breakpoint (bl->owner))
2475         continue;
2476
2477       /* We only want to update locations that are already inserted
2478          and need updating.  This is to avoid unwanted insertion during
2479          deletion of breakpoints.  */
2480       if (!bl->inserted || (bl->inserted && !bl->needs_update))
2481         continue;
2482
2483       switch_to_program_space_and_thread (bl->pspace);
2484
2485       /* For targets that support global breakpoints, there's no need
2486          to select an inferior to insert breakpoint to.  In fact, even
2487          if we aren't attached to any process yet, we should still
2488          insert breakpoints.  */
2489       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2490           && ptid_equal (inferior_ptid, null_ptid))
2491         continue;
2492
2493       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2494                                     &hw_breakpoint_error);
2495       if (val)
2496         error_flag = val;
2497     }
2498
2499   if (error_flag)
2500     {
2501       target_terminal_ours_for_output ();
2502       error_stream (tmp_error_stream);
2503     }
2504
2505   do_cleanups (cleanups);
2506 }
2507
2508 /* Used when starting or continuing the program.  */
2509
2510 static void
2511 insert_breakpoint_locations (void)
2512 {
2513   struct breakpoint *bpt;
2514   struct bp_location *bl, **blp_tmp;
2515   int error_flag = 0;
2516   int val = 0;
2517   int disabled_breaks = 0;
2518   int hw_breakpoint_error = 0;
2519
2520   struct ui_file *tmp_error_stream = mem_fileopen ();
2521   struct cleanup *cleanups = make_cleanup_ui_file_delete (tmp_error_stream);
2522   
2523   /* Explicitly mark the warning -- this will only be printed if
2524      there was an error.  */
2525   fprintf_unfiltered (tmp_error_stream, "Warning:\n");
2526
2527   save_current_space_and_thread ();
2528
2529   ALL_BP_LOCATIONS (bl, blp_tmp)
2530     {
2531       if (!should_be_inserted (bl) || (bl->inserted && !bl->needs_update))
2532         continue;
2533
2534       /* There is no point inserting thread-specific breakpoints if
2535          the thread no longer exists.  ALL_BP_LOCATIONS bp_location
2536          has BL->OWNER always non-NULL.  */
2537       if (bl->owner->thread != -1
2538           && !valid_thread_id (bl->owner->thread))
2539         continue;
2540
2541       switch_to_program_space_and_thread (bl->pspace);
2542
2543       /* For targets that support global breakpoints, there's no need
2544          to select an inferior to insert breakpoint to.  In fact, even
2545          if we aren't attached to any process yet, we should still
2546          insert breakpoints.  */
2547       if (!gdbarch_has_global_breakpoints (target_gdbarch)
2548           && ptid_equal (inferior_ptid, null_ptid))
2549         continue;
2550
2551       val = insert_bp_location (bl, tmp_error_stream, &disabled_breaks,
2552                                     &hw_breakpoint_error);
2553       if (val)
2554         error_flag = val;
2555     }
2556
2557   /* If we failed to insert all locations of a watchpoint, remove
2558      them, as half-inserted watchpoint is of limited use.  */
2559   ALL_BREAKPOINTS (bpt)  
2560     {
2561       int some_failed = 0;
2562       struct bp_location *loc;
2563
2564       if (!is_hardware_watchpoint (bpt))
2565         continue;
2566
2567       if (!breakpoint_enabled (bpt))
2568         continue;
2569
2570       if (bpt->disposition == disp_del_at_next_stop)
2571         continue;
2572       
2573       for (loc = bpt->loc; loc; loc = loc->next)
2574         if (!loc->inserted && should_be_inserted (loc))
2575           {
2576             some_failed = 1;
2577             break;
2578           }
2579       if (some_failed)
2580         {
2581           for (loc = bpt->loc; loc; loc = loc->next)
2582             if (loc->inserted)
2583               remove_breakpoint (loc, mark_uninserted);
2584
2585           hw_breakpoint_error = 1;
2586           fprintf_unfiltered (tmp_error_stream,
2587                               "Could not insert hardware watchpoint %d.\n", 
2588                               bpt->number);
2589           error_flag = -1;
2590         }
2591     }
2592
2593   if (error_flag)
2594     {
2595       /* If a hardware breakpoint or watchpoint was inserted, add a
2596          message about possibly exhausted resources.  */
2597       if (hw_breakpoint_error)
2598         {
2599           fprintf_unfiltered (tmp_error_stream, 
2600                               "Could not insert hardware breakpoints:\n\
2601 You may have requested too many hardware breakpoints/watchpoints.\n");
2602         }
2603       target_terminal_ours_for_output ();
2604       error_stream (tmp_error_stream);
2605     }
2606
2607   do_cleanups (cleanups);
2608 }
2609
2610 /* Used when the program stops.
2611    Returns zero if successful, or non-zero if there was a problem
2612    removing a breakpoint location.  */
2613
2614 int
2615 remove_breakpoints (void)
2616 {
2617   struct bp_location *bl, **blp_tmp;
2618   int val = 0;
2619
2620   ALL_BP_LOCATIONS (bl, blp_tmp)
2621   {
2622     if (bl->inserted && !is_tracepoint (bl->owner))
2623       val |= remove_breakpoint (bl, mark_uninserted);
2624   }
2625   return val;
2626 }
2627
2628 /* Remove breakpoints of process PID.  */
2629
2630 int
2631 remove_breakpoints_pid (int pid)
2632 {
2633   struct bp_location *bl, **blp_tmp;
2634   int val;
2635   struct inferior *inf = find_inferior_pid (pid);
2636
2637   ALL_BP_LOCATIONS (bl, blp_tmp)
2638   {
2639     if (bl->pspace != inf->pspace)
2640       continue;
2641
2642     if (bl->inserted)
2643       {
2644         val = remove_breakpoint (bl, mark_uninserted);
2645         if (val != 0)
2646           return val;
2647       }
2648   }
2649   return 0;
2650 }
2651
2652 int
2653 reattach_breakpoints (int pid)
2654 {
2655   struct cleanup *old_chain;
2656   struct bp_location *bl, **blp_tmp;
2657   int val;
2658   struct ui_file *tmp_error_stream;
2659   int dummy1 = 0, dummy2 = 0;
2660   struct inferior *inf;
2661   struct thread_info *tp;
2662
2663   tp = any_live_thread_of_process (pid);
2664   if (tp == NULL)
2665     return 1;
2666
2667   inf = find_inferior_pid (pid);
2668   old_chain = save_inferior_ptid ();
2669
2670   inferior_ptid = tp->ptid;
2671
2672   tmp_error_stream = mem_fileopen ();
2673   make_cleanup_ui_file_delete (tmp_error_stream);
2674
2675   ALL_BP_LOCATIONS (bl, blp_tmp)
2676   {
2677     if (bl->pspace != inf->pspace)
2678       continue;
2679
2680     if (bl->inserted)
2681       {
2682         bl->inserted = 0;
2683         val = insert_bp_location (bl, tmp_error_stream, &dummy1, &dummy2);
2684         if (val != 0)
2685           {
2686             do_cleanups (old_chain);
2687             return val;
2688           }
2689       }
2690   }
2691   do_cleanups (old_chain);
2692   return 0;
2693 }
2694
2695 static int internal_breakpoint_number = -1;
2696
2697 /* Set the breakpoint number of B, depending on the value of INTERNAL.
2698    If INTERNAL is non-zero, the breakpoint number will be populated
2699    from internal_breakpoint_number and that variable decremented.
2700    Otherwise the breakpoint number will be populated from
2701    breakpoint_count and that value incremented.  Internal breakpoints
2702    do not set the internal var bpnum.  */
2703 static void
2704 set_breakpoint_number (int internal, struct breakpoint *b)
2705 {
2706   if (internal)
2707     b->number = internal_breakpoint_number--;
2708   else
2709     {
2710       set_breakpoint_count (breakpoint_count + 1);
2711       b->number = breakpoint_count;
2712     }
2713 }
2714
2715 static struct breakpoint *
2716 create_internal_breakpoint (struct gdbarch *gdbarch,
2717                             CORE_ADDR address, enum bptype type,
2718                             const struct breakpoint_ops *ops)
2719 {
2720   struct symtab_and_line sal;
2721   struct breakpoint *b;
2722
2723   init_sal (&sal);              /* Initialize to zeroes.  */
2724
2725   sal.pc = address;
2726   sal.section = find_pc_overlay (sal.pc);
2727   sal.pspace = current_program_space;
2728
2729   b = set_raw_breakpoint (gdbarch, sal, type, ops);
2730   b->number = internal_breakpoint_number--;
2731   b->disposition = disp_donttouch;
2732
2733   return b;
2734 }
2735
2736 static const char *const longjmp_names[] =
2737   {
2738     "longjmp", "_longjmp", "siglongjmp", "_siglongjmp"
2739   };
2740 #define NUM_LONGJMP_NAMES ARRAY_SIZE(longjmp_names)
2741
2742 /* Per-objfile data private to breakpoint.c.  */
2743 struct breakpoint_objfile_data
2744 {
2745   /* Minimal symbol for "_ovly_debug_event" (if any).  */
2746   struct minimal_symbol *overlay_msym;
2747
2748   /* Minimal symbol(s) for "longjmp", "siglongjmp", etc. (if any).  */
2749   struct minimal_symbol *longjmp_msym[NUM_LONGJMP_NAMES];
2750
2751   /* True if we have looked for longjmp probes.  */
2752   int longjmp_searched;
2753
2754   /* SystemTap probe points for longjmp (if any).  */
2755   VEC (probe_p) *longjmp_probes;
2756
2757   /* Minimal symbol for "std::terminate()" (if any).  */
2758   struct minimal_symbol *terminate_msym;
2759
2760   /* Minimal symbol for "_Unwind_DebugHook" (if any).  */
2761   struct minimal_symbol *exception_msym;
2762
2763   /* True if we have looked for exception probes.  */
2764   int exception_searched;
2765
2766   /* SystemTap probe points for unwinding (if any).  */
2767   VEC (probe_p) *exception_probes;
2768 };
2769
2770 static const struct objfile_data *breakpoint_objfile_key;
2771
2772 /* Minimal symbol not found sentinel.  */
2773 static struct minimal_symbol msym_not_found;
2774
2775 /* Returns TRUE if MSYM point to the "not found" sentinel.  */
2776
2777 static int
2778 msym_not_found_p (const struct minimal_symbol *msym)
2779 {
2780   return msym == &msym_not_found;
2781 }
2782
2783 /* Return per-objfile data needed by breakpoint.c.
2784    Allocate the data if necessary.  */
2785
2786 static struct breakpoint_objfile_data *
2787 get_breakpoint_objfile_data (struct objfile *objfile)
2788 {
2789   struct breakpoint_objfile_data *bp_objfile_data;
2790
2791   bp_objfile_data = objfile_data (objfile, breakpoint_objfile_key);
2792   if (bp_objfile_data == NULL)
2793     {
2794       bp_objfile_data = obstack_alloc (&objfile->objfile_obstack,
2795                                        sizeof (*bp_objfile_data));
2796
2797       memset (bp_objfile_data, 0, sizeof (*bp_objfile_data));
2798       set_objfile_data (objfile, breakpoint_objfile_key, bp_objfile_data);
2799     }
2800   return bp_objfile_data;
2801 }
2802
2803 static void
2804 free_breakpoint_probes (struct objfile *obj, void *data)
2805 {
2806   struct breakpoint_objfile_data *bp_objfile_data = data;
2807
2808   VEC_free (probe_p, bp_objfile_data->longjmp_probes);
2809   VEC_free (probe_p, bp_objfile_data->exception_probes);
2810 }
2811
2812 static void
2813 create_overlay_event_breakpoint (void)
2814 {
2815   struct objfile *objfile;
2816   const char *const func_name = "_ovly_debug_event";
2817
2818   ALL_OBJFILES (objfile)
2819     {
2820       struct breakpoint *b;
2821       struct breakpoint_objfile_data *bp_objfile_data;
2822       CORE_ADDR addr;
2823
2824       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2825
2826       if (msym_not_found_p (bp_objfile_data->overlay_msym))
2827         continue;
2828
2829       if (bp_objfile_data->overlay_msym == NULL)
2830         {
2831           struct minimal_symbol *m;
2832
2833           m = lookup_minimal_symbol_text (func_name, objfile);
2834           if (m == NULL)
2835             {
2836               /* Avoid future lookups in this objfile.  */
2837               bp_objfile_data->overlay_msym = &msym_not_found;
2838               continue;
2839             }
2840           bp_objfile_data->overlay_msym = m;
2841         }
2842
2843       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->overlay_msym);
2844       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
2845                                       bp_overlay_event,
2846                                       &internal_breakpoint_ops);
2847       b->addr_string = xstrdup (func_name);
2848
2849       if (overlay_debugging == ovly_auto)
2850         {
2851           b->enable_state = bp_enabled;
2852           overlay_events_enabled = 1;
2853         }
2854       else
2855        {
2856          b->enable_state = bp_disabled;
2857          overlay_events_enabled = 0;
2858        }
2859     }
2860   update_global_location_list (1);
2861 }
2862
2863 static void
2864 create_longjmp_master_breakpoint (void)
2865 {
2866   struct program_space *pspace;
2867   struct cleanup *old_chain;
2868
2869   old_chain = save_current_program_space ();
2870
2871   ALL_PSPACES (pspace)
2872   {
2873     struct objfile *objfile;
2874
2875     set_current_program_space (pspace);
2876
2877     ALL_OBJFILES (objfile)
2878     {
2879       int i;
2880       struct gdbarch *gdbarch;
2881       struct breakpoint_objfile_data *bp_objfile_data;
2882
2883       gdbarch = get_objfile_arch (objfile);
2884       if (!gdbarch_get_longjmp_target_p (gdbarch))
2885         continue;
2886
2887       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2888
2889       if (!bp_objfile_data->longjmp_searched)
2890         {
2891           bp_objfile_data->longjmp_probes
2892             = find_probes_in_objfile (objfile, "libc", "longjmp");
2893           bp_objfile_data->longjmp_searched = 1;
2894         }
2895
2896       if (bp_objfile_data->longjmp_probes != NULL)
2897         {
2898           int i;
2899           struct probe *probe;
2900           struct gdbarch *gdbarch = get_objfile_arch (objfile);
2901
2902           for (i = 0;
2903                VEC_iterate (probe_p,
2904                             bp_objfile_data->longjmp_probes,
2905                             i, probe);
2906                ++i)
2907             {
2908               struct breakpoint *b;
2909
2910               b = create_internal_breakpoint (gdbarch, probe->address,
2911                                               bp_longjmp_master,
2912                                               &internal_breakpoint_ops);
2913               b->addr_string = xstrdup ("-probe-stap libc:longjmp");
2914               b->enable_state = bp_disabled;
2915             }
2916
2917           continue;
2918         }
2919
2920       for (i = 0; i < NUM_LONGJMP_NAMES; i++)
2921         {
2922           struct breakpoint *b;
2923           const char *func_name;
2924           CORE_ADDR addr;
2925
2926           if (msym_not_found_p (bp_objfile_data->longjmp_msym[i]))
2927             continue;
2928
2929           func_name = longjmp_names[i];
2930           if (bp_objfile_data->longjmp_msym[i] == NULL)
2931             {
2932               struct minimal_symbol *m;
2933
2934               m = lookup_minimal_symbol_text (func_name, objfile);
2935               if (m == NULL)
2936                 {
2937                   /* Prevent future lookups in this objfile.  */
2938                   bp_objfile_data->longjmp_msym[i] = &msym_not_found;
2939                   continue;
2940                 }
2941               bp_objfile_data->longjmp_msym[i] = m;
2942             }
2943
2944           addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->longjmp_msym[i]);
2945           b = create_internal_breakpoint (gdbarch, addr, bp_longjmp_master,
2946                                           &internal_breakpoint_ops);
2947           b->addr_string = xstrdup (func_name);
2948           b->enable_state = bp_disabled;
2949         }
2950     }
2951   }
2952   update_global_location_list (1);
2953
2954   do_cleanups (old_chain);
2955 }
2956
2957 /* Create a master std::terminate breakpoint.  */
2958 static void
2959 create_std_terminate_master_breakpoint (void)
2960 {
2961   struct program_space *pspace;
2962   struct cleanup *old_chain;
2963   const char *const func_name = "std::terminate()";
2964
2965   old_chain = save_current_program_space ();
2966
2967   ALL_PSPACES (pspace)
2968   {
2969     struct objfile *objfile;
2970     CORE_ADDR addr;
2971
2972     set_current_program_space (pspace);
2973
2974     ALL_OBJFILES (objfile)
2975     {
2976       struct breakpoint *b;
2977       struct breakpoint_objfile_data *bp_objfile_data;
2978
2979       bp_objfile_data = get_breakpoint_objfile_data (objfile);
2980
2981       if (msym_not_found_p (bp_objfile_data->terminate_msym))
2982         continue;
2983
2984       if (bp_objfile_data->terminate_msym == NULL)
2985         {
2986           struct minimal_symbol *m;
2987
2988           m = lookup_minimal_symbol (func_name, NULL, objfile);
2989           if (m == NULL || (MSYMBOL_TYPE (m) != mst_text
2990                             && MSYMBOL_TYPE (m) != mst_file_text))
2991             {
2992               /* Prevent future lookups in this objfile.  */
2993               bp_objfile_data->terminate_msym = &msym_not_found;
2994               continue;
2995             }
2996           bp_objfile_data->terminate_msym = m;
2997         }
2998
2999       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->terminate_msym);
3000       b = create_internal_breakpoint (get_objfile_arch (objfile), addr,
3001                                       bp_std_terminate_master,
3002                                       &internal_breakpoint_ops);
3003       b->addr_string = xstrdup (func_name);
3004       b->enable_state = bp_disabled;
3005     }
3006   }
3007
3008   update_global_location_list (1);
3009
3010   do_cleanups (old_chain);
3011 }
3012
3013 /* Install a master breakpoint on the unwinder's debug hook.  */
3014
3015 static void
3016 create_exception_master_breakpoint (void)
3017 {
3018   struct objfile *objfile;
3019   const char *const func_name = "_Unwind_DebugHook";
3020
3021   ALL_OBJFILES (objfile)
3022     {
3023       struct breakpoint *b;
3024       struct gdbarch *gdbarch;
3025       struct breakpoint_objfile_data *bp_objfile_data;
3026       CORE_ADDR addr;
3027
3028       bp_objfile_data = get_breakpoint_objfile_data (objfile);
3029
3030       /* We prefer the SystemTap probe point if it exists.  */
3031       if (!bp_objfile_data->exception_searched)
3032         {
3033           bp_objfile_data->exception_probes
3034             = find_probes_in_objfile (objfile, "libgcc", "unwind");
3035           bp_objfile_data->exception_searched = 1;
3036         }
3037
3038       if (bp_objfile_data->exception_probes != NULL)
3039         {
3040           struct gdbarch *gdbarch = get_objfile_arch (objfile);
3041           int i;
3042           struct probe *probe;
3043
3044           for (i = 0;
3045                VEC_iterate (probe_p,
3046                             bp_objfile_data->exception_probes,
3047                             i, probe);
3048                ++i)
3049             {
3050               struct breakpoint *b;
3051
3052               b = create_internal_breakpoint (gdbarch, probe->address,
3053                                               bp_exception_master,
3054                                               &internal_breakpoint_ops);
3055               b->addr_string = xstrdup ("-probe-stap libgcc:unwind");
3056               b->enable_state = bp_disabled;
3057             }
3058
3059           continue;
3060         }
3061
3062       /* Otherwise, try the hook function.  */
3063
3064       if (msym_not_found_p (bp_objfile_data->exception_msym))
3065         continue;
3066
3067       gdbarch = get_objfile_arch (objfile);
3068
3069       if (bp_objfile_data->exception_msym == NULL)
3070         {
3071           struct minimal_symbol *debug_hook;
3072
3073           debug_hook = lookup_minimal_symbol (func_name, NULL, objfile);
3074           if (debug_hook == NULL)
3075             {
3076               bp_objfile_data->exception_msym = &msym_not_found;
3077               continue;
3078             }
3079
3080           bp_objfile_data->exception_msym = debug_hook;
3081         }
3082
3083       addr = SYMBOL_VALUE_ADDRESS (bp_objfile_data->exception_msym);
3084       addr = gdbarch_convert_from_func_ptr_addr (gdbarch, addr,
3085                                                  &current_target);
3086       b = create_internal_breakpoint (gdbarch, addr, bp_exception_master,
3087                                       &internal_breakpoint_ops);
3088       b->addr_string = xstrdup (func_name);
3089       b->enable_state = bp_disabled;
3090     }
3091
3092   update_global_location_list (1);
3093 }
3094
3095 void
3096 update_breakpoints_after_exec (void)
3097 {
3098   struct breakpoint *b, *b_tmp;
3099   struct bp_location *bploc, **bplocp_tmp;
3100
3101   /* We're about to delete breakpoints from GDB's lists.  If the
3102      INSERTED flag is true, GDB will try to lift the breakpoints by
3103      writing the breakpoints' "shadow contents" back into memory.  The
3104      "shadow contents" are NOT valid after an exec, so GDB should not
3105      do that.  Instead, the target is responsible from marking
3106      breakpoints out as soon as it detects an exec.  We don't do that
3107      here instead, because there may be other attempts to delete
3108      breakpoints after detecting an exec and before reaching here.  */
3109   ALL_BP_LOCATIONS (bploc, bplocp_tmp)
3110     if (bploc->pspace == current_program_space)
3111       gdb_assert (!bploc->inserted);
3112
3113   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3114   {
3115     if (b->pspace != current_program_space)
3116       continue;
3117
3118     /* Solib breakpoints must be explicitly reset after an exec().  */
3119     if (b->type == bp_shlib_event)
3120       {
3121         delete_breakpoint (b);
3122         continue;
3123       }
3124
3125     /* JIT breakpoints must be explicitly reset after an exec().  */
3126     if (b->type == bp_jit_event)
3127       {
3128         delete_breakpoint (b);
3129         continue;
3130       }
3131
3132     /* Thread event breakpoints must be set anew after an exec(),
3133        as must overlay event and longjmp master breakpoints.  */
3134     if (b->type == bp_thread_event || b->type == bp_overlay_event
3135         || b->type == bp_longjmp_master || b->type == bp_std_terminate_master
3136         || b->type == bp_exception_master)
3137       {
3138         delete_breakpoint (b);
3139         continue;
3140       }
3141
3142     /* Step-resume breakpoints are meaningless after an exec().  */
3143     if (b->type == bp_step_resume || b->type == bp_hp_step_resume)
3144       {
3145         delete_breakpoint (b);
3146         continue;
3147       }
3148
3149     /* Longjmp and longjmp-resume breakpoints are also meaningless
3150        after an exec.  */
3151     if (b->type == bp_longjmp || b->type == bp_longjmp_resume
3152         || b->type == bp_exception || b->type == bp_exception_resume)
3153       {
3154         delete_breakpoint (b);
3155         continue;
3156       }
3157
3158     if (b->type == bp_catchpoint)
3159       {
3160         /* For now, none of the bp_catchpoint breakpoints need to
3161            do anything at this point.  In the future, if some of
3162            the catchpoints need to something, we will need to add
3163            a new method, and call this method from here.  */
3164         continue;
3165       }
3166
3167     /* bp_finish is a special case.  The only way we ought to be able
3168        to see one of these when an exec() has happened, is if the user
3169        caught a vfork, and then said "finish".  Ordinarily a finish just
3170        carries them to the call-site of the current callee, by setting
3171        a temporary bp there and resuming.  But in this case, the finish
3172        will carry them entirely through the vfork & exec.
3173
3174        We don't want to allow a bp_finish to remain inserted now.  But
3175        we can't safely delete it, 'cause finish_command has a handle to
3176        the bp on a bpstat, and will later want to delete it.  There's a
3177        chance (and I've seen it happen) that if we delete the bp_finish
3178        here, that its storage will get reused by the time finish_command
3179        gets 'round to deleting the "use to be a bp_finish" breakpoint.
3180        We really must allow finish_command to delete a bp_finish.
3181
3182        In the absence of a general solution for the "how do we know
3183        it's safe to delete something others may have handles to?"
3184        problem, what we'll do here is just uninsert the bp_finish, and
3185        let finish_command delete it.
3186
3187        (We know the bp_finish is "doomed" in the sense that it's
3188        momentary, and will be deleted as soon as finish_command sees
3189        the inferior stopped.  So it doesn't matter that the bp's
3190        address is probably bogus in the new a.out, unlike e.g., the
3191        solib breakpoints.)  */
3192
3193     if (b->type == bp_finish)
3194       {
3195         continue;
3196       }
3197
3198     /* Without a symbolic address, we have little hope of the
3199        pre-exec() address meaning the same thing in the post-exec()
3200        a.out.  */
3201     if (b->addr_string == NULL)
3202       {
3203         delete_breakpoint (b);
3204         continue;
3205       }
3206   }
3207   /* FIXME what about longjmp breakpoints?  Re-create them here?  */
3208   create_overlay_event_breakpoint ();
3209   create_longjmp_master_breakpoint ();
3210   create_std_terminate_master_breakpoint ();
3211   create_exception_master_breakpoint ();
3212 }
3213
3214 int
3215 detach_breakpoints (int pid)
3216 {
3217   struct bp_location *bl, **blp_tmp;
3218   int val = 0;
3219   struct cleanup *old_chain = save_inferior_ptid ();
3220   struct inferior *inf = current_inferior ();
3221
3222   if (pid == PIDGET (inferior_ptid))
3223     error (_("Cannot detach breakpoints of inferior_ptid"));
3224
3225   /* Set inferior_ptid; remove_breakpoint_1 uses this global.  */
3226   inferior_ptid = pid_to_ptid (pid);
3227   ALL_BP_LOCATIONS (bl, blp_tmp)
3228   {
3229     if (bl->pspace != inf->pspace)
3230       continue;
3231
3232     if (bl->inserted)
3233       val |= remove_breakpoint_1 (bl, mark_inserted);
3234   }
3235
3236   /* Detach single-step breakpoints as well.  */
3237   detach_single_step_breakpoints ();
3238
3239   do_cleanups (old_chain);
3240   return val;
3241 }
3242
3243 /* Remove the breakpoint location BL from the current address space.
3244    Note that this is used to detach breakpoints from a child fork.
3245    When we get here, the child isn't in the inferior list, and neither
3246    do we have objects to represent its address space --- we should
3247    *not* look at bl->pspace->aspace here.  */
3248
3249 static int
3250 remove_breakpoint_1 (struct bp_location *bl, insertion_state_t is)
3251 {
3252   int val;
3253
3254   /* BL is never in moribund_locations by our callers.  */
3255   gdb_assert (bl->owner != NULL);
3256
3257   if (bl->owner->enable_state == bp_permanent)
3258     /* Permanent breakpoints cannot be inserted or removed.  */
3259     return 0;
3260
3261   /* The type of none suggests that owner is actually deleted.
3262      This should not ever happen.  */
3263   gdb_assert (bl->owner->type != bp_none);
3264
3265   if (bl->loc_type == bp_loc_software_breakpoint
3266       || bl->loc_type == bp_loc_hardware_breakpoint)
3267     {
3268       /* "Normal" instruction breakpoint: either the standard
3269          trap-instruction bp (bp_breakpoint), or a
3270          bp_hardware_breakpoint.  */
3271
3272       /* First check to see if we have to handle an overlay.  */
3273       if (overlay_debugging == ovly_off
3274           || bl->section == NULL
3275           || !(section_is_overlay (bl->section)))
3276         {
3277           /* No overlay handling: just remove the breakpoint.  */
3278           val = bl->owner->ops->remove_location (bl);
3279         }
3280       else
3281         {
3282           /* This breakpoint is in an overlay section.
3283              Did we set a breakpoint at the LMA?  */
3284           if (!overlay_events_enabled)
3285               {
3286                 /* Yes -- overlay event support is not active, so we
3287                    should have set a breakpoint at the LMA.  Remove it.  
3288                 */
3289                 /* Ignore any failures: if the LMA is in ROM, we will
3290                    have already warned when we failed to insert it.  */
3291                 if (bl->loc_type == bp_loc_hardware_breakpoint)
3292                   target_remove_hw_breakpoint (bl->gdbarch,
3293                                                &bl->overlay_target_info);
3294                 else
3295                   target_remove_breakpoint (bl->gdbarch,
3296                                             &bl->overlay_target_info);
3297               }
3298           /* Did we set a breakpoint at the VMA? 
3299              If so, we will have marked the breakpoint 'inserted'.  */
3300           if (bl->inserted)
3301             {
3302               /* Yes -- remove it.  Previously we did not bother to
3303                  remove the breakpoint if the section had been
3304                  unmapped, but let's not rely on that being safe.  We
3305                  don't know what the overlay manager might do.  */
3306
3307               /* However, we should remove *software* breakpoints only
3308                  if the section is still mapped, or else we overwrite
3309                  wrong code with the saved shadow contents.  */
3310               if (bl->loc_type == bp_loc_hardware_breakpoint
3311                   || section_is_mapped (bl->section))
3312                 val = bl->owner->ops->remove_location (bl);
3313               else
3314                 val = 0;
3315             }
3316           else
3317             {
3318               /* No -- not inserted, so no need to remove.  No error.  */
3319               val = 0;
3320             }
3321         }
3322
3323       /* In some cases, we might not be able to remove a breakpoint
3324          in a shared library that has already been removed, but we
3325          have not yet processed the shlib unload event.  */
3326       if (val && solib_name_from_address (bl->pspace, bl->address))
3327         val = 0;
3328
3329       if (val)
3330         return val;
3331       bl->inserted = (is == mark_inserted);
3332     }
3333   else if (bl->loc_type == bp_loc_hardware_watchpoint)
3334     {
3335       gdb_assert (bl->owner->ops != NULL
3336                   && bl->owner->ops->remove_location != NULL);
3337
3338       bl->inserted = (is == mark_inserted);
3339       bl->owner->ops->remove_location (bl);
3340
3341       /* Failure to remove any of the hardware watchpoints comes here.  */
3342       if ((is == mark_uninserted) && (bl->inserted))
3343         warning (_("Could not remove hardware watchpoint %d."),
3344                  bl->owner->number);
3345     }
3346   else if (bl->owner->type == bp_catchpoint
3347            && breakpoint_enabled (bl->owner)
3348            && !bl->duplicate)
3349     {
3350       gdb_assert (bl->owner->ops != NULL
3351                   && bl->owner->ops->remove_location != NULL);
3352
3353       val = bl->owner->ops->remove_location (bl);
3354       if (val)
3355         return val;
3356
3357       bl->inserted = (is == mark_inserted);
3358     }
3359
3360   return 0;
3361 }
3362
3363 static int
3364 remove_breakpoint (struct bp_location *bl, insertion_state_t is)
3365 {
3366   int ret;
3367   struct cleanup *old_chain;
3368
3369   /* BL is never in moribund_locations by our callers.  */
3370   gdb_assert (bl->owner != NULL);
3371
3372   if (bl->owner->enable_state == bp_permanent)
3373     /* Permanent breakpoints cannot be inserted or removed.  */
3374     return 0;
3375
3376   /* The type of none suggests that owner is actually deleted.
3377      This should not ever happen.  */
3378   gdb_assert (bl->owner->type != bp_none);
3379
3380   old_chain = save_current_space_and_thread ();
3381
3382   switch_to_program_space_and_thread (bl->pspace);
3383
3384   ret = remove_breakpoint_1 (bl, is);
3385
3386   do_cleanups (old_chain);
3387   return ret;
3388 }
3389
3390 /* Clear the "inserted" flag in all breakpoints.  */
3391
3392 void
3393 mark_breakpoints_out (void)
3394 {
3395   struct bp_location *bl, **blp_tmp;
3396
3397   ALL_BP_LOCATIONS (bl, blp_tmp)
3398     if (bl->pspace == current_program_space)
3399       bl->inserted = 0;
3400 }
3401
3402 /* Clear the "inserted" flag in all breakpoints and delete any
3403    breakpoints which should go away between runs of the program.
3404
3405    Plus other such housekeeping that has to be done for breakpoints
3406    between runs.
3407
3408    Note: this function gets called at the end of a run (by
3409    generic_mourn_inferior) and when a run begins (by
3410    init_wait_for_inferior).  */
3411
3412
3413
3414 void
3415 breakpoint_init_inferior (enum inf_context context)
3416 {
3417   struct breakpoint *b, *b_tmp;
3418   struct bp_location *bl, **blp_tmp;
3419   int ix;
3420   struct program_space *pspace = current_program_space;
3421
3422   /* If breakpoint locations are shared across processes, then there's
3423      nothing to do.  */
3424   if (gdbarch_has_global_breakpoints (target_gdbarch))
3425     return;
3426
3427   ALL_BP_LOCATIONS (bl, blp_tmp)
3428   {
3429     /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3430     if (bl->pspace == pspace
3431         && bl->owner->enable_state != bp_permanent)
3432       bl->inserted = 0;
3433   }
3434
3435   ALL_BREAKPOINTS_SAFE (b, b_tmp)
3436   {
3437     if (b->loc && b->loc->pspace != pspace)
3438       continue;
3439
3440     switch (b->type)
3441       {
3442       case bp_call_dummy:
3443
3444         /* If the call dummy breakpoint is at the entry point it will
3445            cause problems when the inferior is rerun, so we better get
3446            rid of it.  */
3447
3448       case bp_watchpoint_scope:
3449
3450         /* Also get rid of scope breakpoints.  */
3451
3452       case bp_shlib_event:
3453
3454         /* Also remove solib event breakpoints.  Their addresses may
3455            have changed since the last time we ran the program.
3456            Actually we may now be debugging against different target;
3457            and so the solib backend that installed this breakpoint may
3458            not be used in by the target.  E.g.,
3459
3460            (gdb) file prog-linux
3461            (gdb) run               # native linux target
3462            ...
3463            (gdb) kill
3464            (gdb) file prog-win.exe
3465            (gdb) tar rem :9999     # remote Windows gdbserver.
3466         */
3467
3468       case bp_step_resume:
3469
3470         /* Also remove step-resume breakpoints.  */
3471
3472         delete_breakpoint (b);
3473         break;
3474
3475       case bp_watchpoint:
3476       case bp_hardware_watchpoint:
3477       case bp_read_watchpoint:
3478       case bp_access_watchpoint:
3479         {
3480           struct watchpoint *w = (struct watchpoint *) b;
3481
3482           /* Likewise for watchpoints on local expressions.  */
3483           if (w->exp_valid_block != NULL)
3484             delete_breakpoint (b);
3485           else if (context == inf_starting)
3486             {
3487               /* Reset val field to force reread of starting value in
3488                  insert_breakpoints.  */
3489               if (w->val)
3490                 value_free (w->val);
3491               w->val = NULL;
3492               w->val_valid = 0;
3493           }
3494         }
3495         break;
3496       default:
3497         break;
3498       }
3499   }
3500
3501   /* Get rid of the moribund locations.  */
3502   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, bl); ++ix)
3503     decref_bp_location (&bl);
3504   VEC_free (bp_location_p, moribund_locations);
3505 }
3506
3507 /* These functions concern about actual breakpoints inserted in the
3508    target --- to e.g. check if we need to do decr_pc adjustment or if
3509    we need to hop over the bkpt --- so we check for address space
3510    match, not program space.  */
3511
3512 /* breakpoint_here_p (PC) returns non-zero if an enabled breakpoint
3513    exists at PC.  It returns ordinary_breakpoint_here if it's an
3514    ordinary breakpoint, or permanent_breakpoint_here if it's a
3515    permanent breakpoint.
3516    - When continuing from a location with an ordinary breakpoint, we
3517      actually single step once before calling insert_breakpoints.
3518    - When continuing from a location with a permanent breakpoint, we
3519      need to use the `SKIP_PERMANENT_BREAKPOINT' macro, provided by
3520      the target, to advance the PC past the breakpoint.  */
3521
3522 enum breakpoint_here
3523 breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3524 {
3525   struct bp_location *bl, **blp_tmp;
3526   int any_breakpoint_here = 0;
3527
3528   ALL_BP_LOCATIONS (bl, blp_tmp)
3529     {
3530       if (bl->loc_type != bp_loc_software_breakpoint
3531           && bl->loc_type != bp_loc_hardware_breakpoint)
3532         continue;
3533
3534       /* ALL_BP_LOCATIONS bp_location has BL->OWNER always non-NULL.  */
3535       if ((breakpoint_enabled (bl->owner)
3536            || bl->owner->enable_state == bp_permanent)
3537           && breakpoint_location_address_match (bl, aspace, pc))
3538         {
3539           if (overlay_debugging 
3540               && section_is_overlay (bl->section)
3541               && !section_is_mapped (bl->section))
3542             continue;           /* unmapped overlay -- can't be a match */
3543           else if (bl->owner->enable_state == bp_permanent)
3544             return permanent_breakpoint_here;
3545           else
3546             any_breakpoint_here = 1;
3547         }
3548     }
3549
3550   return any_breakpoint_here ? ordinary_breakpoint_here : 0;
3551 }
3552
3553 /* Return true if there's a moribund breakpoint at PC.  */
3554
3555 int
3556 moribund_breakpoint_here_p (struct address_space *aspace, CORE_ADDR pc)
3557 {
3558   struct bp_location *loc;
3559   int ix;
3560
3561   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
3562     if (breakpoint_location_address_match (loc, aspace, pc))
3563       return 1;
3564
3565   return 0;
3566 }
3567
3568 /* Returns non-zero if there's a breakpoint inserted at PC, which is
3569    inserted using regular breakpoint_chain / bp_location array
3570    mechanism.  This does not check for single-step breakpoints, which
3571    are inserted and removed using direct target manipulation.  */
3572
3573 int
3574 regular_breakpoint_inserted_here_p (struct address_space *aspace, 
3575                                     CORE_ADDR pc)
3576 {
3577   struct bp_location *bl, **blp_tmp;
3578
3579   ALL_BP_LOCATIONS (bl, blp_tmp)
3580     {
3581       if (bl->loc_type != bp_loc_software_breakpoint
3582           && bl->loc_type != bp_loc_hardware_breakpoint)
3583         continue;
3584
3585       if (bl->inserted
3586           && breakpoint_location_address_match (bl, aspace, pc))
3587         {
3588           if (overlay_debugging 
3589               && section_is_overlay (bl->section)
3590               && !section_is_mapped (bl->section))
3591             continue;           /* unmapped overlay -- can't be a match */
3592           else
3593             return 1;
3594         }
3595     }
3596   return 0;
3597 }
3598
3599 /* Returns non-zero iff there's either regular breakpoint
3600    or a single step breakpoint inserted at PC.  */
3601
3602 int
3603 breakpoint_inserted_here_p (struct address_space *aspace, CORE_ADDR pc)
3604 {
3605   if (regular_breakpoint_inserted_here_p (aspace, pc))
3606     return 1;
3607
3608   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3609     return 1;
3610
3611   return 0;
3612 }
3613
3614 /* This function returns non-zero iff there is a software breakpoint
3615    inserted at PC.  */
3616
3617 int
3618 software_breakpoint_inserted_here_p (struct address_space *aspace,
3619                                      CORE_ADDR pc)
3620 {
3621   struct bp_location *bl, **blp_tmp;
3622
3623   ALL_BP_LOCATIONS (bl, blp_tmp)
3624     {
3625       if (bl->loc_type != bp_loc_software_breakpoint)
3626         continue;
3627
3628       if (bl->inserted
3629           && breakpoint_address_match (bl->pspace->aspace, bl->address,
3630                                        aspace, pc))
3631         {
3632           if (overlay_debugging 
3633               && section_is_overlay (bl->section)
3634               && !section_is_mapped (bl->section))
3635             continue;           /* unmapped overlay -- can't be a match */
3636           else
3637             return 1;
3638         }
3639     }
3640
3641   /* Also check for software single-step breakpoints.  */
3642   if (single_step_breakpoint_inserted_here_p (aspace, pc))
3643     return 1;
3644
3645   return 0;
3646 }
3647
3648 int
3649 hardware_watchpoint_inserted_in_range (struct address_space *aspace,
3650                                        CORE_ADDR addr, ULONGEST len)
3651 {
3652   struct breakpoint *bpt;
3653
3654   ALL_BREAKPOINTS (bpt)
3655     {
3656       struct bp_location *loc;
3657
3658       if (bpt->type != bp_hardware_watchpoint
3659           && bpt->type != bp_access_watchpoint)
3660         continue;
3661
3662       if (!breakpoint_enabled (bpt))
3663         continue;
3664
3665       for (loc = bpt->loc; loc; loc = loc->next)
3666         if (loc->pspace->aspace == aspace && loc->inserted)
3667           {
3668             CORE_ADDR l, h;
3669
3670             /* Check for intersection.  */
3671             l = max (loc->address, addr);
3672             h = min (loc->address + loc->length, addr + len);
3673             if (l < h)
3674               return 1;
3675           }
3676     }
3677   return 0;
3678 }
3679
3680 /* breakpoint_thread_match (PC, PTID) returns true if the breakpoint at
3681    PC is valid for process/thread PTID.  */
3682
3683 int
3684 breakpoint_thread_match (struct address_space *aspace, CORE_ADDR pc,
3685                          ptid_t ptid)
3686 {
3687   struct bp_location *bl, **blp_tmp;
3688   /* The thread and task IDs associated to PTID, computed lazily.  */
3689   int thread = -1;
3690   int task = 0;
3691   
3692   ALL_BP_LOCATIONS (bl, blp_tmp)
3693     {
3694       if (bl->loc_type != bp_loc_software_breakpoint
3695           && bl->loc_type != bp_loc_hardware_breakpoint)
3696         continue;
3697
3698       /* ALL_BP_LOCATIONS bp_location has bl->OWNER always non-NULL.  */
3699       if (!breakpoint_enabled (bl->owner)
3700           && bl->owner->enable_state != bp_permanent)
3701         continue;
3702
3703       if (!breakpoint_location_address_match (bl, aspace, pc))
3704         continue;
3705
3706       if (bl->owner->thread != -1)
3707         {
3708           /* This is a thread-specific breakpoint.  Check that ptid
3709              matches that thread.  If thread hasn't been computed yet,
3710              it is now time to do so.  */
3711           if (thread == -1)
3712             thread = pid_to_thread_id (ptid);
3713           if (bl->owner->thread != thread)
3714             continue;
3715         }
3716
3717       if (bl->owner->task != 0)
3718         {
3719           /* This is a task-specific breakpoint.  Check that ptid
3720              matches that task.  If task hasn't been computed yet,
3721              it is now time to do so.  */
3722           if (task == 0)
3723             task = ada_get_task_number (ptid);
3724           if (bl->owner->task != task)
3725             continue;
3726         }
3727
3728       if (overlay_debugging 
3729           && section_is_overlay (bl->section)
3730           && !section_is_mapped (bl->section))
3731         continue;           /* unmapped overlay -- can't be a match */
3732
3733       return 1;
3734     }
3735
3736   return 0;
3737 }
3738 \f
3739
3740 /* bpstat stuff.  External routines' interfaces are documented
3741    in breakpoint.h.  */
3742
3743 int
3744 is_catchpoint (struct breakpoint *ep)
3745 {
3746   return (ep->type == bp_catchpoint);
3747 }
3748
3749 /* Frees any storage that is part of a bpstat.  Does not walk the
3750    'next' chain.  */
3751
3752 static void
3753 bpstat_free (bpstat bs)
3754 {
3755   if (bs->old_val != NULL)
3756     value_free (bs->old_val);
3757   decref_counted_command_line (&bs->commands);
3758   decref_bp_location (&bs->bp_location_at);
3759   xfree (bs);
3760 }
3761
3762 /* Clear a bpstat so that it says we are not at any breakpoint.
3763    Also free any storage that is part of a bpstat.  */
3764
3765 void
3766 bpstat_clear (bpstat *bsp)
3767 {
3768   bpstat p;
3769   bpstat q;
3770
3771   if (bsp == 0)
3772     return;
3773   p = *bsp;
3774   while (p != NULL)
3775     {
3776       q = p->next;
3777       bpstat_free (p);
3778       p = q;
3779     }
3780   *bsp = NULL;
3781 }
3782
3783 /* Return a copy of a bpstat.  Like "bs1 = bs2" but all storage that
3784    is part of the bpstat is copied as well.  */
3785
3786 bpstat
3787 bpstat_copy (bpstat bs)
3788 {
3789   bpstat p = NULL;
3790   bpstat tmp;
3791   bpstat retval = NULL;
3792
3793   if (bs == NULL)
3794     return bs;
3795
3796   for (; bs != NULL; bs = bs->next)
3797     {
3798       tmp = (bpstat) xmalloc (sizeof (*tmp));
3799       memcpy (tmp, bs, sizeof (*tmp));
3800       incref_counted_command_line (tmp->commands);
3801       incref_bp_location (tmp->bp_location_at);
3802       if (bs->old_val != NULL)
3803         {
3804           tmp->old_val = value_copy (bs->old_val);
3805           release_value (tmp->old_val);
3806         }
3807
3808       if (p == NULL)
3809         /* This is the first thing in the chain.  */
3810         retval = tmp;
3811       else
3812         p->next = tmp;
3813       p = tmp;
3814     }
3815   p->next = NULL;
3816   return retval;
3817 }
3818
3819 /* Find the bpstat associated with this breakpoint.  */
3820
3821 bpstat
3822 bpstat_find_breakpoint (bpstat bsp, struct breakpoint *breakpoint)
3823 {
3824   if (bsp == NULL)
3825     return NULL;
3826
3827   for (; bsp != NULL; bsp = bsp->next)
3828     {
3829       if (bsp->breakpoint_at == breakpoint)
3830         return bsp;
3831     }
3832   return NULL;
3833 }
3834
3835 /* Put in *NUM the breakpoint number of the first breakpoint we are
3836    stopped at.  *BSP upon return is a bpstat which points to the
3837    remaining breakpoints stopped at (but which is not guaranteed to be
3838    good for anything but further calls to bpstat_num).
3839
3840    Return 0 if passed a bpstat which does not indicate any breakpoints.
3841    Return -1 if stopped at a breakpoint that has been deleted since
3842    we set it.
3843    Return 1 otherwise.  */
3844
3845 int
3846 bpstat_num (bpstat *bsp, int *num)
3847 {
3848   struct breakpoint *b;
3849
3850   if ((*bsp) == NULL)
3851     return 0;                   /* No more breakpoint values */
3852
3853   /* We assume we'll never have several bpstats that correspond to a
3854      single breakpoint -- otherwise, this function might return the
3855      same number more than once and this will look ugly.  */
3856   b = (*bsp)->breakpoint_at;
3857   *bsp = (*bsp)->next;
3858   if (b == NULL)
3859     return -1;                  /* breakpoint that's been deleted since */
3860
3861   *num = b->number;             /* We have its number */
3862   return 1;
3863 }
3864
3865 /* See breakpoint.h.  */
3866
3867 void
3868 bpstat_clear_actions (void)
3869 {
3870   struct thread_info *tp;
3871   bpstat bs;
3872
3873   if (ptid_equal (inferior_ptid, null_ptid))
3874     return;
3875
3876   tp = find_thread_ptid (inferior_ptid);
3877   if (tp == NULL)
3878     return;
3879
3880   for (bs = tp->control.stop_bpstat; bs != NULL; bs = bs->next)
3881     {
3882       decref_counted_command_line (&bs->commands);
3883
3884       if (bs->old_val != NULL)
3885         {
3886           value_free (bs->old_val);
3887           bs->old_val = NULL;
3888         }
3889     }
3890 }
3891
3892 /* Called when a command is about to proceed the inferior.  */
3893
3894 static void
3895 breakpoint_about_to_proceed (void)
3896 {
3897   if (!ptid_equal (inferior_ptid, null_ptid))
3898     {
3899       struct thread_info *tp = inferior_thread ();
3900
3901       /* Allow inferior function calls in breakpoint commands to not
3902          interrupt the command list.  When the call finishes
3903          successfully, the inferior will be standing at the same
3904          breakpoint as if nothing happened.  */
3905       if (tp->control.in_infcall)
3906         return;
3907     }
3908
3909   breakpoint_proceeded = 1;
3910 }
3911
3912 /* Stub for cleaning up our state if we error-out of a breakpoint
3913    command.  */
3914 static void
3915 cleanup_executing_breakpoints (void *ignore)
3916 {
3917   executing_breakpoint_commands = 0;
3918 }
3919
3920 /* Return non-zero iff CMD as the first line of a command sequence is `silent'
3921    or its equivalent.  */
3922
3923 static int
3924 command_line_is_silent (struct command_line *cmd)
3925 {
3926   return cmd && (strcmp ("silent", cmd->line) == 0
3927                  || (xdb_commands && strcmp ("Q", cmd->line) == 0));
3928 }
3929
3930 /* Execute all the commands associated with all the breakpoints at
3931    this location.  Any of these commands could cause the process to
3932    proceed beyond this point, etc.  We look out for such changes by
3933    checking the global "breakpoint_proceeded" after each command.
3934
3935    Returns true if a breakpoint command resumed the inferior.  In that
3936    case, it is the caller's responsibility to recall it again with the
3937    bpstat of the current thread.  */
3938
3939 static int
3940 bpstat_do_actions_1 (bpstat *bsp)
3941 {
3942   bpstat bs;
3943   struct cleanup *old_chain;
3944   int again = 0;
3945
3946   /* Avoid endless recursion if a `source' command is contained
3947      in bs->commands.  */
3948   if (executing_breakpoint_commands)
3949     return 0;
3950
3951   executing_breakpoint_commands = 1;
3952   old_chain = make_cleanup (cleanup_executing_breakpoints, 0);
3953
3954   prevent_dont_repeat ();
3955
3956   /* This pointer will iterate over the list of bpstat's.  */
3957   bs = *bsp;
3958
3959   breakpoint_proceeded = 0;
3960   for (; bs != NULL; bs = bs->next)
3961     {
3962       struct counted_command_line *ccmd;
3963       struct command_line *cmd;
3964       struct cleanup *this_cmd_tree_chain;
3965
3966       /* Take ownership of the BSP's command tree, if it has one.
3967
3968          The command tree could legitimately contain commands like
3969          'step' and 'next', which call clear_proceed_status, which
3970          frees stop_bpstat's command tree.  To make sure this doesn't
3971          free the tree we're executing out from under us, we need to
3972          take ownership of the tree ourselves.  Since a given bpstat's
3973          commands are only executed once, we don't need to copy it; we
3974          can clear the pointer in the bpstat, and make sure we free
3975          the tree when we're done.  */
3976       ccmd = bs->commands;
3977       bs->commands = NULL;
3978       this_cmd_tree_chain = make_cleanup_decref_counted_command_line (&ccmd);
3979       cmd = ccmd ? ccmd->commands : NULL;
3980       if (command_line_is_silent (cmd))
3981         {
3982           /* The action has been already done by bpstat_stop_status.  */
3983           cmd = cmd->next;
3984         }
3985
3986       while (cmd != NULL)
3987         {
3988           execute_control_command (cmd);
3989
3990           if (breakpoint_proceeded)
3991             break;
3992           else
3993             cmd = cmd->next;
3994         }
3995
3996       /* We can free this command tree now.  */
3997       do_cleanups (this_cmd_tree_chain);
3998
3999       if (breakpoint_proceeded)
4000         {
4001           if (target_can_async_p ())
4002             /* If we are in async mode, then the target might be still
4003                running, not stopped at any breakpoint, so nothing for
4004                us to do here -- just return to the event loop.  */
4005             ;
4006           else
4007             /* In sync mode, when execute_control_command returns
4008                we're already standing on the next breakpoint.
4009                Breakpoint commands for that stop were not run, since
4010                execute_command does not run breakpoint commands --
4011                only command_line_handler does, but that one is not
4012                involved in execution of breakpoint commands.  So, we
4013                can now execute breakpoint commands.  It should be
4014                noted that making execute_command do bpstat actions is
4015                not an option -- in this case we'll have recursive
4016                invocation of bpstat for each breakpoint with a
4017                command, and can easily blow up GDB stack.  Instead, we
4018                return true, which will trigger the caller to recall us
4019                with the new stop_bpstat.  */
4020             again = 1;
4021           break;
4022         }
4023     }
4024   do_cleanups (old_chain);
4025   return again;
4026 }
4027
4028 void
4029 bpstat_do_actions (void)
4030 {
4031   struct cleanup *cleanup_if_error = make_bpstat_clear_actions_cleanup ();
4032
4033   /* Do any commands attached to breakpoint we are stopped at.  */
4034   while (!ptid_equal (inferior_ptid, null_ptid)
4035          && target_has_execution
4036          && !is_exited (inferior_ptid)
4037          && !is_executing (inferior_ptid))
4038     /* Since in sync mode, bpstat_do_actions may resume the inferior,
4039        and only return when it is stopped at the next breakpoint, we
4040        keep doing breakpoint actions until it returns false to
4041        indicate the inferior was not resumed.  */
4042     if (!bpstat_do_actions_1 (&inferior_thread ()->control.stop_bpstat))
4043       break;
4044
4045   discard_cleanups (cleanup_if_error);
4046 }
4047
4048 /* Print out the (old or new) value associated with a watchpoint.  */
4049
4050 static void
4051 watchpoint_value_print (struct value *val, struct ui_file *stream)
4052 {
4053   if (val == NULL)
4054     fprintf_unfiltered (stream, _("<unreadable>"));
4055   else
4056     {
4057       struct value_print_options opts;
4058       get_user_print_options (&opts);
4059       value_print (val, stream, &opts);
4060     }
4061 }
4062
4063 /* Generic routine for printing messages indicating why we
4064    stopped.  The behavior of this function depends on the value
4065    'print_it' in the bpstat structure.  Under some circumstances we
4066    may decide not to print anything here and delegate the task to
4067    normal_stop().  */
4068
4069 static enum print_stop_action
4070 print_bp_stop_message (bpstat bs)
4071 {
4072   switch (bs->print_it)
4073     {
4074     case print_it_noop:
4075       /* Nothing should be printed for this bpstat entry.  */
4076       return PRINT_UNKNOWN;
4077       break;
4078
4079     case print_it_done:
4080       /* We still want to print the frame, but we already printed the
4081          relevant messages.  */
4082       return PRINT_SRC_AND_LOC;
4083       break;
4084
4085     case print_it_normal:
4086       {
4087         struct breakpoint *b = bs->breakpoint_at;
4088
4089         /* bs->breakpoint_at can be NULL if it was a momentary breakpoint
4090            which has since been deleted.  */
4091         if (b == NULL)
4092           return PRINT_UNKNOWN;
4093
4094         /* Normal case.  Call the breakpoint's print_it method.  */
4095         return b->ops->print_it (bs);
4096       }
4097       break;
4098
4099     default:
4100       internal_error (__FILE__, __LINE__,
4101                       _("print_bp_stop_message: unrecognized enum value"));
4102       break;
4103     }
4104 }
4105
4106 /* A helper function that prints a shared library stopped event.  */
4107
4108 static void
4109 print_solib_event (int is_catchpoint)
4110 {
4111   int any_deleted
4112     = !VEC_empty (char_ptr, current_program_space->deleted_solibs);
4113   int any_added
4114     = !VEC_empty (so_list_ptr, current_program_space->added_solibs);
4115
4116   if (!is_catchpoint)
4117     {
4118       if (any_added || any_deleted)
4119         ui_out_text (current_uiout,
4120                      _("Stopped due to shared library event:\n"));
4121       else
4122         ui_out_text (current_uiout,
4123                      _("Stopped due to shared library event (no "
4124                        "libraries added or removed)\n"));
4125     }
4126
4127   if (ui_out_is_mi_like_p (current_uiout))
4128     ui_out_field_string (current_uiout, "reason",
4129                          async_reason_lookup (EXEC_ASYNC_SOLIB_EVENT));
4130
4131   if (any_deleted)
4132     {
4133       struct cleanup *cleanup;
4134       char *name;
4135       int ix;
4136
4137       ui_out_text (current_uiout, _("  Inferior unloaded "));
4138       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4139                                                     "removed");
4140       for (ix = 0;
4141            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
4142                         ix, name);
4143            ++ix)
4144         {
4145           if (ix > 0)
4146             ui_out_text (current_uiout, "    ");
4147           ui_out_field_string (current_uiout, "library", name);
4148           ui_out_text (current_uiout, "\n");
4149         }
4150
4151       do_cleanups (cleanup);
4152     }
4153
4154   if (any_added)
4155     {
4156       struct so_list *iter;
4157       int ix;
4158       struct cleanup *cleanup;
4159
4160       ui_out_text (current_uiout, _("  Inferior loaded "));
4161       cleanup = make_cleanup_ui_out_list_begin_end (current_uiout,
4162                                                     "added");
4163       for (ix = 0;
4164            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
4165                         ix, iter);
4166            ++ix)
4167         {
4168           if (ix > 0)
4169             ui_out_text (current_uiout, "    ");
4170           ui_out_field_string (current_uiout, "library", iter->so_name);
4171           ui_out_text (current_uiout, "\n");
4172         }
4173
4174       do_cleanups (cleanup);
4175     }
4176 }
4177
4178 /* Print a message indicating what happened.  This is called from
4179    normal_stop().  The input to this routine is the head of the bpstat
4180    list - a list of the eventpoints that caused this stop.  KIND is
4181    the target_waitkind for the stopping event.  This
4182    routine calls the generic print routine for printing a message
4183    about reasons for stopping.  This will print (for example) the
4184    "Breakpoint n," part of the output.  The return value of this
4185    routine is one of:
4186
4187    PRINT_UNKNOWN: Means we printed nothing.
4188    PRINT_SRC_AND_LOC: Means we printed something, and expect subsequent
4189    code to print the location.  An example is 
4190    "Breakpoint 1, " which should be followed by
4191    the location.
4192    PRINT_SRC_ONLY: Means we printed something, but there is no need
4193    to also print the location part of the message.
4194    An example is the catch/throw messages, which
4195    don't require a location appended to the end.
4196    PRINT_NOTHING: We have done some printing and we don't need any 
4197    further info to be printed.  */
4198
4199 enum print_stop_action
4200 bpstat_print (bpstat bs, int kind)
4201 {
4202   int val;
4203
4204   /* Maybe another breakpoint in the chain caused us to stop.
4205      (Currently all watchpoints go on the bpstat whether hit or not.
4206      That probably could (should) be changed, provided care is taken
4207      with respect to bpstat_explains_signal).  */
4208   for (; bs; bs = bs->next)
4209     {
4210       val = print_bp_stop_message (bs);
4211       if (val == PRINT_SRC_ONLY 
4212           || val == PRINT_SRC_AND_LOC 
4213           || val == PRINT_NOTHING)
4214         return val;
4215     }
4216
4217   /* If we had hit a shared library event breakpoint,
4218      print_bp_stop_message would print out this message.  If we hit an
4219      OS-level shared library event, do the same thing.  */
4220   if (kind == TARGET_WAITKIND_LOADED)
4221     {
4222       print_solib_event (0);
4223       return PRINT_NOTHING;
4224     }
4225
4226   /* We reached the end of the chain, or we got a null BS to start
4227      with and nothing was printed.  */
4228   return PRINT_UNKNOWN;
4229 }
4230
4231 /* Evaluate the expression EXP and return 1 if value is zero.  This is
4232    used inside a catch_errors to evaluate the breakpoint condition.
4233    The argument is a "struct expression *" that has been cast to a
4234    "char *" to make it pass through catch_errors.  */
4235
4236 static int
4237 breakpoint_cond_eval (void *exp)
4238 {
4239   struct value *mark = value_mark ();
4240   int i = !value_true (evaluate_expression ((struct expression *) exp));
4241
4242   value_free_to_mark (mark);
4243   return i;
4244 }
4245
4246 /* Allocate a new bpstat.  Link it to the FIFO list by BS_LINK_POINTER.  */
4247
4248 static bpstat
4249 bpstat_alloc (struct bp_location *bl, bpstat **bs_link_pointer)
4250 {
4251   bpstat bs;
4252
4253   bs = (bpstat) xmalloc (sizeof (*bs));
4254   bs->next = NULL;
4255   **bs_link_pointer = bs;
4256   *bs_link_pointer = &bs->next;
4257   bs->breakpoint_at = bl->owner;
4258   bs->bp_location_at = bl;
4259   incref_bp_location (bl);
4260   /* If the condition is false, etc., don't do the commands.  */
4261   bs->commands = NULL;
4262   bs->old_val = NULL;
4263   bs->print_it = print_it_normal;
4264   return bs;
4265 }
4266 \f
4267 /* The target has stopped with waitstatus WS.  Check if any hardware
4268    watchpoints have triggered, according to the target.  */
4269
4270 int
4271 watchpoints_triggered (struct target_waitstatus *ws)
4272 {
4273   int stopped_by_watchpoint = target_stopped_by_watchpoint ();
4274   CORE_ADDR addr;
4275   struct breakpoint *b;
4276
4277   if (!stopped_by_watchpoint)
4278     {
4279       /* We were not stopped by a watchpoint.  Mark all watchpoints
4280          as not triggered.  */
4281       ALL_BREAKPOINTS (b)
4282         if (is_hardware_watchpoint (b))
4283           {
4284             struct watchpoint *w = (struct watchpoint *) b;
4285
4286             w->watchpoint_triggered = watch_triggered_no;
4287           }
4288
4289       return 0;
4290     }
4291
4292   if (!target_stopped_data_address (&current_target, &addr))
4293     {
4294       /* We were stopped by a watchpoint, but we don't know where.
4295          Mark all watchpoints as unknown.  */
4296       ALL_BREAKPOINTS (b)
4297         if (is_hardware_watchpoint (b))
4298           {
4299             struct watchpoint *w = (struct watchpoint *) b;
4300
4301             w->watchpoint_triggered = watch_triggered_unknown;
4302           }
4303
4304       return stopped_by_watchpoint;
4305     }
4306
4307   /* The target could report the data address.  Mark watchpoints
4308      affected by this data address as triggered, and all others as not
4309      triggered.  */
4310
4311   ALL_BREAKPOINTS (b)
4312     if (is_hardware_watchpoint (b))
4313       {
4314         struct watchpoint *w = (struct watchpoint *) b;
4315         struct bp_location *loc;
4316
4317         w->watchpoint_triggered = watch_triggered_no;
4318         for (loc = b->loc; loc; loc = loc->next)
4319           {
4320             if (is_masked_watchpoint (b))
4321               {
4322                 CORE_ADDR newaddr = addr & w->hw_wp_mask;
4323                 CORE_ADDR start = loc->address & w->hw_wp_mask;
4324
4325                 if (newaddr == start)
4326                   {
4327                     w->watchpoint_triggered = watch_triggered_yes;
4328                     break;
4329                   }
4330               }
4331             /* Exact match not required.  Within range is sufficient.  */
4332             else if (target_watchpoint_addr_within_range (&current_target,
4333                                                          addr, loc->address,
4334                                                          loc->length))
4335               {
4336                 w->watchpoint_triggered = watch_triggered_yes;
4337                 break;
4338               }
4339           }
4340       }
4341
4342   return 1;
4343 }
4344
4345 /* Possible return values for watchpoint_check (this can't be an enum
4346    because of check_errors).  */
4347 /* The watchpoint has been deleted.  */
4348 #define WP_DELETED 1
4349 /* The value has changed.  */
4350 #define WP_VALUE_CHANGED 2
4351 /* The value has not changed.  */
4352 #define WP_VALUE_NOT_CHANGED 3
4353 /* Ignore this watchpoint, no matter if the value changed or not.  */
4354 #define WP_IGNORE 4
4355
4356 #define BP_TEMPFLAG 1
4357 #define BP_HARDWAREFLAG 2
4358
4359 /* Evaluate watchpoint condition expression and check if its value
4360    changed.
4361
4362    P should be a pointer to struct bpstat, but is defined as a void *
4363    in order for this function to be usable with catch_errors.  */
4364
4365 static int
4366 watchpoint_check (void *p)
4367 {
4368   bpstat bs = (bpstat) p;
4369   struct watchpoint *b;
4370   struct frame_info *fr;
4371   int within_current_scope;
4372
4373   /* BS is built from an existing struct breakpoint.  */
4374   gdb_assert (bs->breakpoint_at != NULL);
4375   b = (struct watchpoint *) bs->breakpoint_at;
4376
4377   /* If this is a local watchpoint, we only want to check if the
4378      watchpoint frame is in scope if the current thread is the thread
4379      that was used to create the watchpoint.  */
4380   if (!watchpoint_in_thread_scope (b))
4381     return WP_IGNORE;
4382
4383   if (b->exp_valid_block == NULL)
4384     within_current_scope = 1;
4385   else
4386     {
4387       struct frame_info *frame = get_current_frame ();
4388       struct gdbarch *frame_arch = get_frame_arch (frame);
4389       CORE_ADDR frame_pc = get_frame_pc (frame);
4390
4391       /* in_function_epilogue_p() returns a non-zero value if we're
4392          still in the function but the stack frame has already been
4393          invalidated.  Since we can't rely on the values of local
4394          variables after the stack has been destroyed, we are treating
4395          the watchpoint in that state as `not changed' without further
4396          checking.  Don't mark watchpoints as changed if the current
4397          frame is in an epilogue - even if they are in some other
4398          frame, our view of the stack is likely to be wrong and
4399          frame_find_by_id could error out.  */
4400       if (gdbarch_in_function_epilogue_p (frame_arch, frame_pc))
4401         return WP_IGNORE;
4402
4403       fr = frame_find_by_id (b->watchpoint_frame);
4404       within_current_scope = (fr != NULL);
4405
4406       /* If we've gotten confused in the unwinder, we might have
4407          returned a frame that can't describe this variable.  */
4408       if (within_current_scope)
4409         {
4410           struct symbol *function;
4411
4412           function = get_frame_function (fr);
4413           if (function == NULL
4414               || !contained_in (b->exp_valid_block,
4415                                 SYMBOL_BLOCK_VALUE (function)))
4416             within_current_scope = 0;
4417         }
4418
4419       if (within_current_scope)
4420         /* If we end up stopping, the current frame will get selected
4421            in normal_stop.  So this call to select_frame won't affect
4422            the user.  */
4423         select_frame (fr);
4424     }
4425
4426   if (within_current_scope)
4427     {
4428       /* We use value_{,free_to_}mark because it could be a *long*
4429          time before we return to the command level and call
4430          free_all_values.  We can't call free_all_values because we
4431          might be in the middle of evaluating a function call.  */
4432
4433       int pc = 0;
4434       struct value *mark;
4435       struct value *new_val;
4436
4437       if (is_masked_watchpoint (&b->base))
4438         /* Since we don't know the exact trigger address (from
4439            stopped_data_address), just tell the user we've triggered
4440            a mask watchpoint.  */
4441         return WP_VALUE_CHANGED;
4442
4443       mark = value_mark ();
4444       fetch_subexp_value (b->exp, &pc, &new_val, NULL, NULL);
4445
4446       /* We use value_equal_contents instead of value_equal because
4447          the latter coerces an array to a pointer, thus comparing just
4448          the address of the array instead of its contents.  This is
4449          not what we want.  */
4450       if ((b->val != NULL) != (new_val != NULL)
4451           || (b->val != NULL && !value_equal_contents (b->val, new_val)))
4452         {
4453           if (new_val != NULL)
4454             {
4455               release_value (new_val);
4456               value_free_to_mark (mark);
4457             }
4458           bs->old_val = b->val;
4459           b->val = new_val;
4460           b->val_valid = 1;
4461           return WP_VALUE_CHANGED;
4462         }
4463       else
4464         {
4465           /* Nothing changed.  */
4466           value_free_to_mark (mark);
4467           return WP_VALUE_NOT_CHANGED;
4468         }
4469     }
4470   else
4471     {
4472       struct ui_out *uiout = current_uiout;
4473
4474       /* This seems like the only logical thing to do because
4475          if we temporarily ignored the watchpoint, then when
4476          we reenter the block in which it is valid it contains
4477          garbage (in the case of a function, it may have two
4478          garbage values, one before and one after the prologue).
4479          So we can't even detect the first assignment to it and
4480          watch after that (since the garbage may or may not equal
4481          the first value assigned).  */
4482       /* We print all the stop information in
4483          breakpoint_ops->print_it, but in this case, by the time we
4484          call breakpoint_ops->print_it this bp will be deleted
4485          already.  So we have no choice but print the information
4486          here.  */
4487       if (ui_out_is_mi_like_p (uiout))
4488         ui_out_field_string
4489           (uiout, "reason", async_reason_lookup (EXEC_ASYNC_WATCHPOINT_SCOPE));
4490       ui_out_text (uiout, "\nWatchpoint ");
4491       ui_out_field_int (uiout, "wpnum", b->base.number);
4492       ui_out_text (uiout,
4493                    " deleted because the program has left the block in\n\
4494 which its expression is valid.\n");     
4495
4496       /* Make sure the watchpoint's commands aren't executed.  */
4497       decref_counted_command_line (&b->base.commands);
4498       watchpoint_del_at_next_stop (b);
4499
4500       return WP_DELETED;
4501     }
4502 }
4503
4504 /* Return true if it looks like target has stopped due to hitting
4505    breakpoint location BL.  This function does not check if we should
4506    stop, only if BL explains the stop.  */
4507
4508 static int
4509 bpstat_check_location (const struct bp_location *bl,
4510                        struct address_space *aspace, CORE_ADDR bp_addr,
4511                        const struct target_waitstatus *ws)
4512 {
4513   struct breakpoint *b = bl->owner;
4514
4515   /* BL is from an existing breakpoint.  */
4516   gdb_assert (b != NULL);
4517
4518   return b->ops->breakpoint_hit (bl, aspace, bp_addr, ws);
4519 }
4520
4521 /* Determine if the watched values have actually changed, and we
4522    should stop.  If not, set BS->stop to 0.  */
4523
4524 static void
4525 bpstat_check_watchpoint (bpstat bs)
4526 {
4527   const struct bp_location *bl;
4528   struct watchpoint *b;
4529
4530   /* BS is built for existing struct breakpoint.  */
4531   bl = bs->bp_location_at;
4532   gdb_assert (bl != NULL);
4533   b = (struct watchpoint *) bs->breakpoint_at;
4534   gdb_assert (b != NULL);
4535
4536     {
4537       int must_check_value = 0;
4538       
4539       if (b->base.type == bp_watchpoint)
4540         /* For a software watchpoint, we must always check the
4541            watched value.  */
4542         must_check_value = 1;
4543       else if (b->watchpoint_triggered == watch_triggered_yes)
4544         /* We have a hardware watchpoint (read, write, or access)
4545            and the target earlier reported an address watched by
4546            this watchpoint.  */
4547         must_check_value = 1;
4548       else if (b->watchpoint_triggered == watch_triggered_unknown
4549                && b->base.type == bp_hardware_watchpoint)
4550         /* We were stopped by a hardware watchpoint, but the target could
4551            not report the data address.  We must check the watchpoint's
4552            value.  Access and read watchpoints are out of luck; without
4553            a data address, we can't figure it out.  */
4554         must_check_value = 1;
4555
4556       if (must_check_value)
4557         {
4558           char *message
4559             = xstrprintf ("Error evaluating expression for watchpoint %d\n",
4560                           b->base.number);
4561           struct cleanup *cleanups = make_cleanup (xfree, message);
4562           int e = catch_errors (watchpoint_check, bs, message,
4563                                 RETURN_MASK_ALL);
4564           do_cleanups (cleanups);
4565           switch (e)
4566             {
4567             case WP_DELETED:
4568               /* We've already printed what needs to be printed.  */
4569               bs->print_it = print_it_done;
4570               /* Stop.  */
4571               break;
4572             case WP_IGNORE:
4573               bs->print_it = print_it_noop;
4574               bs->stop = 0;
4575               break;
4576             case WP_VALUE_CHANGED:
4577               if (b->base.type == bp_read_watchpoint)
4578                 {
4579                   /* There are two cases to consider here:
4580
4581                      1. We're watching the triggered memory for reads.
4582                      In that case, trust the target, and always report
4583                      the watchpoint hit to the user.  Even though
4584                      reads don't cause value changes, the value may
4585                      have changed since the last time it was read, and
4586                      since we're not trapping writes, we will not see
4587                      those, and as such we should ignore our notion of
4588                      old value.
4589
4590                      2. We're watching the triggered memory for both
4591                      reads and writes.  There are two ways this may
4592                      happen:
4593
4594                      2.1. This is a target that can't break on data
4595                      reads only, but can break on accesses (reads or
4596                      writes), such as e.g., x86.  We detect this case
4597                      at the time we try to insert read watchpoints.
4598
4599                      2.2. Otherwise, the target supports read
4600                      watchpoints, but, the user set an access or write
4601                      watchpoint watching the same memory as this read
4602                      watchpoint.
4603
4604                      If we're watching memory writes as well as reads,
4605                      ignore watchpoint hits when we find that the
4606                      value hasn't changed, as reads don't cause
4607                      changes.  This still gives false positives when
4608                      the program writes the same value to memory as
4609                      what there was already in memory (we will confuse
4610                      it for a read), but it's much better than
4611                      nothing.  */
4612
4613                   int other_write_watchpoint = 0;
4614
4615                   if (bl->watchpoint_type == hw_read)
4616                     {
4617                       struct breakpoint *other_b;
4618
4619                       ALL_BREAKPOINTS (other_b)
4620                         if (other_b->type == bp_hardware_watchpoint
4621                             || other_b->type == bp_access_watchpoint)
4622                           {
4623                             struct watchpoint *other_w =
4624                               (struct watchpoint *) other_b;
4625
4626                             if (other_w->watchpoint_triggered
4627                                 == watch_triggered_yes)
4628                               {
4629                                 other_write_watchpoint = 1;
4630                                 break;
4631                               }
4632                           }
4633                     }
4634
4635                   if (other_write_watchpoint
4636                       || bl->watchpoint_type == hw_access)
4637                     {
4638                       /* We're watching the same memory for writes,
4639                          and the value changed since the last time we
4640                          updated it, so this trap must be for a write.
4641                          Ignore it.  */
4642                       bs->print_it = print_it_noop;
4643                       bs->stop = 0;
4644                     }
4645                 }
4646               break;
4647             case WP_VALUE_NOT_CHANGED:
4648               if (b->base.type == bp_hardware_watchpoint
4649                   || b->base.type == bp_watchpoint)
4650                 {
4651                   /* Don't stop: write watchpoints shouldn't fire if
4652                      the value hasn't changed.  */
4653                   bs->print_it = print_it_noop;
4654                   bs->stop = 0;
4655                 }
4656               /* Stop.  */
4657               break;
4658             default:
4659               /* Can't happen.  */
4660             case 0:
4661               /* Error from catch_errors.  */
4662               printf_filtered (_("Watchpoint %d deleted.\n"), b->base.number);
4663               watchpoint_del_at_next_stop (b);
4664               /* We've already printed what needs to be printed.  */
4665               bs->print_it = print_it_done;
4666               break;
4667             }
4668         }
4669       else      /* must_check_value == 0 */
4670         {
4671           /* This is a case where some watchpoint(s) triggered, but
4672              not at the address of this watchpoint, or else no
4673              watchpoint triggered after all.  So don't print
4674              anything for this watchpoint.  */
4675           bs->print_it = print_it_noop;
4676           bs->stop = 0;
4677         }
4678     }
4679 }
4680
4681
4682 /* Check conditions (condition proper, frame, thread and ignore count)
4683    of breakpoint referred to by BS.  If we should not stop for this
4684    breakpoint, set BS->stop to 0.  */
4685
4686 static void
4687 bpstat_check_breakpoint_conditions (bpstat bs, ptid_t ptid)
4688 {
4689   int thread_id = pid_to_thread_id (ptid);
4690   const struct bp_location *bl;
4691   struct breakpoint *b;
4692
4693   /* BS is built for existing struct breakpoint.  */
4694   bl = bs->bp_location_at;
4695   gdb_assert (bl != NULL);
4696   b = bs->breakpoint_at;
4697   gdb_assert (b != NULL);
4698
4699   /* Even if the target evaluated the condition on its end and notified GDB, we
4700      need to do so again since GDB does not know if we stopped due to a
4701      breakpoint or a single step breakpoint.  */
4702
4703   if (frame_id_p (b->frame_id)
4704       && !frame_id_eq (b->frame_id, get_stack_frame_id (get_current_frame ())))
4705     bs->stop = 0;
4706   else if (bs->stop)
4707     {
4708       int value_is_zero = 0;
4709       struct expression *cond;
4710
4711       /* Evaluate Python breakpoints that have a "stop"
4712          method implemented.  */
4713       if (b->py_bp_object)
4714         bs->stop = gdbpy_should_stop (b->py_bp_object);
4715
4716       if (is_watchpoint (b))
4717         {
4718           struct watchpoint *w = (struct watchpoint *) b;
4719
4720           cond = w->cond_exp;
4721         }
4722       else
4723         cond = bl->cond;
4724
4725       if (cond && b->disposition != disp_del_at_next_stop)
4726         {
4727           int within_current_scope = 1;
4728           struct watchpoint * w;
4729
4730           /* We use value_mark and value_free_to_mark because it could
4731              be a long time before we return to the command level and
4732              call free_all_values.  We can't call free_all_values
4733              because we might be in the middle of evaluating a
4734              function call.  */
4735           struct value *mark = value_mark ();
4736
4737           if (is_watchpoint (b))
4738             w = (struct watchpoint *) b;
4739           else
4740             w = NULL;
4741
4742           /* Need to select the frame, with all that implies so that
4743              the conditions will have the right context.  Because we
4744              use the frame, we will not see an inlined function's
4745              variables when we arrive at a breakpoint at the start
4746              of the inlined function; the current frame will be the
4747              call site.  */
4748           if (w == NULL || w->cond_exp_valid_block == NULL)
4749             select_frame (get_current_frame ());
4750           else
4751             {
4752               struct frame_info *frame;
4753
4754               /* For local watchpoint expressions, which particular
4755                  instance of a local is being watched matters, so we
4756                  keep track of the frame to evaluate the expression
4757                  in.  To evaluate the condition however, it doesn't
4758                  really matter which instantiation of the function
4759                  where the condition makes sense triggers the
4760                  watchpoint.  This allows an expression like "watch
4761                  global if q > 10" set in `func', catch writes to
4762                  global on all threads that call `func', or catch
4763                  writes on all recursive calls of `func' by a single
4764                  thread.  We simply always evaluate the condition in
4765                  the innermost frame that's executing where it makes
4766                  sense to evaluate the condition.  It seems
4767                  intuitive.  */
4768               frame = block_innermost_frame (w->cond_exp_valid_block);
4769               if (frame != NULL)
4770                 select_frame (frame);
4771               else
4772                 within_current_scope = 0;
4773             }
4774           if (within_current_scope)
4775             value_is_zero
4776               = catch_errors (breakpoint_cond_eval, cond,
4777                               "Error in testing breakpoint condition:\n",
4778                               RETURN_MASK_ALL);
4779           else
4780             {
4781               warning (_("Watchpoint condition cannot be tested "
4782                          "in the current scope"));
4783               /* If we failed to set the right context for this
4784                  watchpoint, unconditionally report it.  */
4785               value_is_zero = 0;
4786             }
4787           /* FIXME-someday, should give breakpoint #.  */
4788           value_free_to_mark (mark);
4789         }
4790
4791       if (cond && value_is_zero)
4792         {
4793           bs->stop = 0;
4794         }
4795       else if (b->thread != -1 && b->thread != thread_id)
4796         {
4797           bs->stop = 0;
4798         }
4799       else if (b->ignore_count > 0)
4800         {
4801           b->ignore_count--;
4802           annotate_ignore_count_change ();
4803           bs->stop = 0;
4804           /* Increase the hit count even though we don't stop.  */
4805           ++(b->hit_count);
4806           observer_notify_breakpoint_modified (b);
4807         }       
4808     }
4809 }
4810
4811
4812 /* Get a bpstat associated with having just stopped at address
4813    BP_ADDR in thread PTID.
4814
4815    Determine whether we stopped at a breakpoint, etc, or whether we
4816    don't understand this stop.  Result is a chain of bpstat's such
4817    that:
4818
4819    if we don't understand the stop, the result is a null pointer.
4820
4821    if we understand why we stopped, the result is not null.
4822
4823    Each element of the chain refers to a particular breakpoint or
4824    watchpoint at which we have stopped.  (We may have stopped for
4825    several reasons concurrently.)
4826
4827    Each element of the chain has valid next, breakpoint_at,
4828    commands, FIXME??? fields.  */
4829
4830 bpstat
4831 bpstat_stop_status (struct address_space *aspace,
4832                     CORE_ADDR bp_addr, ptid_t ptid,
4833                     const struct target_waitstatus *ws)
4834 {
4835   struct breakpoint *b = NULL;
4836   struct bp_location *bl;
4837   struct bp_location *loc;
4838   /* First item of allocated bpstat's.  */
4839   bpstat bs_head = NULL, *bs_link = &bs_head;
4840   /* Pointer to the last thing in the chain currently.  */
4841   bpstat bs;
4842   int ix;
4843   int need_remove_insert;
4844   int removed_any;
4845
4846   /* First, build the bpstat chain with locations that explain a
4847      target stop, while being careful to not set the target running,
4848      as that may invalidate locations (in particular watchpoint
4849      locations are recreated).  Resuming will happen here with
4850      breakpoint conditions or watchpoint expressions that include
4851      inferior function calls.  */
4852
4853   ALL_BREAKPOINTS (b)
4854     {
4855       if (!breakpoint_enabled (b) && b->enable_state != bp_permanent)
4856         continue;
4857
4858       for (bl = b->loc; bl != NULL; bl = bl->next)
4859         {
4860           /* For hardware watchpoints, we look only at the first
4861              location.  The watchpoint_check function will work on the
4862              entire expression, not the individual locations.  For
4863              read watchpoints, the watchpoints_triggered function has
4864              checked all locations already.  */
4865           if (b->type == bp_hardware_watchpoint && bl != b->loc)
4866             break;
4867
4868           if (bl->shlib_disabled)
4869             continue;
4870
4871           if (!bpstat_check_location (bl, aspace, bp_addr, ws))
4872             continue;
4873
4874           /* Come here if it's a watchpoint, or if the break address
4875              matches.  */
4876
4877           bs = bpstat_alloc (bl, &bs_link);     /* Alloc a bpstat to
4878                                                    explain stop.  */
4879
4880           /* Assume we stop.  Should we find a watchpoint that is not
4881              actually triggered, or if the condition of the breakpoint
4882              evaluates as false, we'll reset 'stop' to 0.  */
4883           bs->stop = 1;
4884           bs->print = 1;
4885
4886           /* If this is a scope breakpoint, mark the associated
4887              watchpoint as triggered so that we will handle the
4888              out-of-scope event.  We'll get to the watchpoint next
4889              iteration.  */
4890           if (b->type == bp_watchpoint_scope && b->related_breakpoint != b)
4891             {
4892               struct watchpoint *w = (struct watchpoint *) b->related_breakpoint;
4893
4894               w->watchpoint_triggered = watch_triggered_yes;
4895             }
4896         }
4897     }
4898
4899   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
4900     {
4901       if (breakpoint_location_address_match (loc, aspace, bp_addr))
4902         {
4903           bs = bpstat_alloc (loc, &bs_link);
4904           /* For hits of moribund locations, we should just proceed.  */
4905           bs->stop = 0;
4906           bs->print = 0;
4907           bs->print_it = print_it_noop;
4908         }
4909     }
4910
4911   /* A bit of special processing for shlib breakpoints.  We need to
4912      process solib loading here, so that the lists of loaded and
4913      unloaded libraries are correct before we handle "catch load" and
4914      "catch unload".  */
4915   for (bs = bs_head; bs != NULL; bs = bs->next)
4916     {
4917       if (bs->breakpoint_at && bs->breakpoint_at->type == bp_shlib_event)
4918         {
4919           handle_solib_event ();
4920           break;
4921         }
4922     }
4923
4924   /* Now go through the locations that caused the target to stop, and
4925      check whether we're interested in reporting this stop to higher
4926      layers, or whether we should resume the target transparently.  */
4927
4928   removed_any = 0;
4929
4930   for (bs = bs_head; bs != NULL; bs = bs->next)
4931     {
4932       if (!bs->stop)
4933         continue;
4934
4935       b = bs->breakpoint_at;
4936       b->ops->check_status (bs);
4937       if (bs->stop)
4938         {
4939           bpstat_check_breakpoint_conditions (bs, ptid);
4940
4941           if (bs->stop)
4942             {
4943               ++(b->hit_count);
4944               observer_notify_breakpoint_modified (b);
4945
4946               /* We will stop here.  */
4947               if (b->disposition == disp_disable)
4948                 {
4949                   --(b->enable_count);
4950                   if (b->enable_count <= 0
4951                       && b->enable_state != bp_permanent)
4952                     b->enable_state = bp_disabled;
4953                   removed_any = 1;
4954                 }
4955               if (b->silent)
4956                 bs->print = 0;
4957               bs->commands = b->commands;
4958               incref_counted_command_line (bs->commands);
4959               if (command_line_is_silent (bs->commands
4960                                           ? bs->commands->commands : NULL))
4961                 bs->print = 0;
4962             }
4963
4964         }
4965
4966       /* Print nothing for this entry if we don't stop or don't
4967          print.  */
4968       if (!bs->stop || !bs->print)
4969         bs->print_it = print_it_noop;
4970     }
4971
4972   /* If we aren't stopping, the value of some hardware watchpoint may
4973      not have changed, but the intermediate memory locations we are
4974      watching may have.  Don't bother if we're stopping; this will get
4975      done later.  */
4976   need_remove_insert = 0;
4977   if (! bpstat_causes_stop (bs_head))
4978     for (bs = bs_head; bs != NULL; bs = bs->next)
4979       if (!bs->stop
4980           && bs->breakpoint_at
4981           && is_hardware_watchpoint (bs->breakpoint_at))
4982         {
4983           struct watchpoint *w = (struct watchpoint *) bs->breakpoint_at;
4984
4985           update_watchpoint (w, 0 /* don't reparse.  */);
4986           need_remove_insert = 1;
4987         }
4988
4989   if (need_remove_insert)
4990     update_global_location_list (1);
4991   else if (removed_any)
4992     update_global_location_list (0);
4993
4994   return bs_head;
4995 }
4996
4997 static void
4998 handle_jit_event (void)
4999 {
5000   struct frame_info *frame;
5001   struct gdbarch *gdbarch;
5002
5003   /* Switch terminal for any messages produced by
5004      breakpoint_re_set.  */
5005   target_terminal_ours_for_output ();
5006
5007   frame = get_current_frame ();
5008   gdbarch = get_frame_arch (frame);
5009
5010   jit_event_handler (gdbarch);
5011
5012   target_terminal_inferior ();
5013 }
5014
5015 /* Handle an solib event by calling solib_add.  */
5016
5017 void
5018 handle_solib_event (void)
5019 {
5020   clear_program_space_solib_cache (current_inferior ()->pspace);
5021
5022   /* Check for any newly added shared libraries if we're supposed to
5023      be adding them automatically.  Switch terminal for any messages
5024      produced by breakpoint_re_set.  */
5025   target_terminal_ours_for_output ();
5026 #ifdef SOLIB_ADD
5027   SOLIB_ADD (NULL, 0, &current_target, auto_solib_add);
5028 #else
5029   solib_add (NULL, 0, &current_target, auto_solib_add);
5030 #endif
5031   target_terminal_inferior ();
5032 }
5033
5034 /* Prepare WHAT final decision for infrun.  */
5035
5036 /* Decide what infrun needs to do with this bpstat.  */
5037
5038 struct bpstat_what
5039 bpstat_what (bpstat bs_head)
5040 {
5041   struct bpstat_what retval;
5042   int jit_event = 0;
5043   bpstat bs;
5044
5045   retval.main_action = BPSTAT_WHAT_KEEP_CHECKING;
5046   retval.call_dummy = STOP_NONE;
5047   retval.is_longjmp = 0;
5048
5049   for (bs = bs_head; bs != NULL; bs = bs->next)
5050     {
5051       /* Extract this BS's action.  After processing each BS, we check
5052          if its action overrides all we've seem so far.  */
5053       enum bpstat_what_main_action this_action = BPSTAT_WHAT_KEEP_CHECKING;
5054       enum bptype bptype;
5055
5056       if (bs->breakpoint_at == NULL)
5057         {
5058           /* I suspect this can happen if it was a momentary
5059              breakpoint which has since been deleted.  */
5060           bptype = bp_none;
5061         }
5062       else
5063         bptype = bs->breakpoint_at->type;
5064
5065       switch (bptype)
5066         {
5067         case bp_none:
5068           break;
5069         case bp_breakpoint:
5070         case bp_hardware_breakpoint:
5071         case bp_until:
5072         case bp_finish:
5073         case bp_shlib_event:
5074           if (bs->stop)
5075             {
5076               if (bs->print)
5077                 this_action = BPSTAT_WHAT_STOP_NOISY;
5078               else
5079                 this_action = BPSTAT_WHAT_STOP_SILENT;
5080             }
5081           else
5082             this_action = BPSTAT_WHAT_SINGLE;
5083           break;
5084         case bp_watchpoint:
5085         case bp_hardware_watchpoint:
5086         case bp_read_watchpoint:
5087         case bp_access_watchpoint:
5088           if (bs->stop)
5089             {
5090               if (bs->print)
5091                 this_action = BPSTAT_WHAT_STOP_NOISY;
5092               else
5093                 this_action = BPSTAT_WHAT_STOP_SILENT;
5094             }
5095           else
5096             {
5097               /* There was a watchpoint, but we're not stopping.
5098                  This requires no further action.  */
5099             }
5100           break;
5101         case bp_longjmp:
5102         case bp_exception:
5103           this_action = BPSTAT_WHAT_SET_LONGJMP_RESUME;
5104           retval.is_longjmp = bptype == bp_longjmp;
5105           break;
5106         case bp_longjmp_resume:
5107         case bp_exception_resume:
5108           this_action = BPSTAT_WHAT_CLEAR_LONGJMP_RESUME;
5109           retval.is_longjmp = bptype == bp_longjmp_resume;
5110           break;
5111         case bp_step_resume:
5112           if (bs->stop)
5113             this_action = BPSTAT_WHAT_STEP_RESUME;
5114           else
5115             {
5116               /* It is for the wrong frame.  */
5117               this_action = BPSTAT_WHAT_SINGLE;
5118             }
5119           break;
5120         case bp_hp_step_resume:
5121           if (bs->stop)
5122             this_action = BPSTAT_WHAT_HP_STEP_RESUME;
5123           else
5124             {
5125               /* It is for the wrong frame.  */
5126               this_action = BPSTAT_WHAT_SINGLE;
5127             }
5128           break;
5129         case bp_watchpoint_scope:
5130         case bp_thread_event:
5131         case bp_overlay_event:
5132         case bp_longjmp_master:
5133         case bp_std_terminate_master:
5134         case bp_exception_master:
5135           this_action = BPSTAT_WHAT_SINGLE;
5136           break;
5137         case bp_catchpoint:
5138           if (bs->stop)
5139             {
5140               if (bs->print)
5141                 this_action = BPSTAT_WHAT_STOP_NOISY;
5142               else
5143                 this_action = BPSTAT_WHAT_STOP_SILENT;
5144             }
5145           else
5146             {
5147               /* There was a catchpoint, but we're not stopping.
5148                  This requires no further action.  */
5149             }
5150           break;
5151         case bp_jit_event:
5152           jit_event = 1;
5153           this_action = BPSTAT_WHAT_SINGLE;
5154           break;
5155         case bp_call_dummy:
5156           /* Make sure the action is stop (silent or noisy),
5157              so infrun.c pops the dummy frame.  */
5158           retval.call_dummy = STOP_STACK_DUMMY;
5159           this_action = BPSTAT_WHAT_STOP_SILENT;
5160           break;
5161         case bp_std_terminate:
5162           /* Make sure the action is stop (silent or noisy),
5163              so infrun.c pops the dummy frame.  */
5164           retval.call_dummy = STOP_STD_TERMINATE;
5165           this_action = BPSTAT_WHAT_STOP_SILENT;
5166           break;
5167         case bp_tracepoint:
5168         case bp_fast_tracepoint:
5169         case bp_static_tracepoint:
5170           /* Tracepoint hits should not be reported back to GDB, and
5171              if one got through somehow, it should have been filtered
5172              out already.  */
5173           internal_error (__FILE__, __LINE__,
5174                           _("bpstat_what: tracepoint encountered"));
5175           break;
5176         case bp_gnu_ifunc_resolver:
5177           /* Step over it (and insert bp_gnu_ifunc_resolver_return).  */
5178           this_action = BPSTAT_WHAT_SINGLE;
5179           break;
5180         case bp_gnu_ifunc_resolver_return:
5181           /* The breakpoint will be removed, execution will restart from the
5182              PC of the former breakpoint.  */
5183           this_action = BPSTAT_WHAT_KEEP_CHECKING;
5184           break;
5185
5186         case bp_dprintf:
5187           this_action = BPSTAT_WHAT_STOP_SILENT;
5188           break;
5189
5190         default:
5191           internal_error (__FILE__, __LINE__,
5192                           _("bpstat_what: unhandled bptype %d"), (int) bptype);
5193         }
5194
5195       retval.main_action = max (retval.main_action, this_action);
5196     }
5197
5198   /* These operations may affect the bs->breakpoint_at state so they are
5199      delayed after MAIN_ACTION is decided above.  */
5200
5201   if (jit_event)
5202     {
5203       if (debug_infrun)
5204         fprintf_unfiltered (gdb_stdlog, "bpstat_what: bp_jit_event\n");
5205
5206       handle_jit_event ();
5207     }
5208
5209   for (bs = bs_head; bs != NULL; bs = bs->next)
5210     {
5211       struct breakpoint *b = bs->breakpoint_at;
5212
5213       if (b == NULL)
5214         continue;
5215       switch (b->type)
5216         {
5217         case bp_gnu_ifunc_resolver:
5218           gnu_ifunc_resolver_stop (b);
5219           break;
5220         case bp_gnu_ifunc_resolver_return:
5221           gnu_ifunc_resolver_return_stop (b);
5222           break;
5223         }
5224     }
5225
5226   return retval;
5227 }
5228
5229 /* Nonzero if we should step constantly (e.g. watchpoints on machines
5230    without hardware support).  This isn't related to a specific bpstat,
5231    just to things like whether watchpoints are set.  */
5232
5233 int
5234 bpstat_should_step (void)
5235 {
5236   struct breakpoint *b;
5237
5238   ALL_BREAKPOINTS (b)
5239     if (breakpoint_enabled (b) && b->type == bp_watchpoint && b->loc != NULL)
5240       return 1;
5241   return 0;
5242 }
5243
5244 int
5245 bpstat_causes_stop (bpstat bs)
5246 {
5247   for (; bs != NULL; bs = bs->next)
5248     if (bs->stop)
5249       return 1;
5250
5251   return 0;
5252 }
5253
5254 \f
5255
5256 /* Compute a string of spaces suitable to indent the next line
5257    so it starts at the position corresponding to the table column
5258    named COL_NAME in the currently active table of UIOUT.  */
5259
5260 static char *
5261 wrap_indent_at_field (struct ui_out *uiout, const char *col_name)
5262 {
5263   static char wrap_indent[80];
5264   int i, total_width, width, align;
5265   char *text;
5266
5267   total_width = 0;
5268   for (i = 1; ui_out_query_field (uiout, i, &width, &align, &text); i++)
5269     {
5270       if (strcmp (text, col_name) == 0)
5271         {
5272           gdb_assert (total_width < sizeof wrap_indent);
5273           memset (wrap_indent, ' ', total_width);
5274           wrap_indent[total_width] = 0;
5275
5276           return wrap_indent;
5277         }
5278
5279       total_width += width + 1;
5280     }
5281
5282   return NULL;
5283 }
5284
5285 /* Determine if the locations of this breakpoint will have their conditions
5286    evaluated by the target, host or a mix of both.  Returns the following:
5287
5288     "host": Host evals condition.
5289     "host or target": Host or Target evals condition.
5290     "target": Target evals condition.
5291 */
5292
5293 static const char *
5294 bp_condition_evaluator (struct breakpoint *b)
5295 {
5296   struct bp_location *bl;
5297   char host_evals = 0;
5298   char target_evals = 0;
5299
5300   if (!b)
5301     return NULL;
5302
5303   if (!is_breakpoint (b))
5304     return NULL;
5305
5306   if (gdb_evaluates_breakpoint_condition_p ()
5307       || !target_supports_evaluation_of_breakpoint_conditions ())
5308     return condition_evaluation_host;
5309
5310   for (bl = b->loc; bl; bl = bl->next)
5311     {
5312       if (bl->cond_bytecode)
5313         target_evals++;
5314       else
5315         host_evals++;
5316     }
5317
5318   if (host_evals && target_evals)
5319     return condition_evaluation_both;
5320   else if (target_evals)
5321     return condition_evaluation_target;
5322   else
5323     return condition_evaluation_host;
5324 }
5325
5326 /* Determine the breakpoint location's condition evaluator.  This is
5327    similar to bp_condition_evaluator, but for locations.  */
5328
5329 static const char *
5330 bp_location_condition_evaluator (struct bp_location *bl)
5331 {
5332   if (bl && !is_breakpoint (bl->owner))
5333     return NULL;
5334
5335   if (gdb_evaluates_breakpoint_condition_p ()
5336       || !target_supports_evaluation_of_breakpoint_conditions ())
5337     return condition_evaluation_host;
5338
5339   if (bl && bl->cond_bytecode)
5340     return condition_evaluation_target;
5341   else
5342     return condition_evaluation_host;
5343 }
5344
5345 /* Print the LOC location out of the list of B->LOC locations.  */
5346
5347 static void
5348 print_breakpoint_location (struct breakpoint *b,
5349                            struct bp_location *loc)
5350 {
5351   struct ui_out *uiout = current_uiout;
5352   struct cleanup *old_chain = save_current_program_space ();
5353
5354   if (loc != NULL && loc->shlib_disabled)
5355     loc = NULL;
5356
5357   if (loc != NULL)
5358     set_current_program_space (loc->pspace);
5359
5360   if (b->display_canonical)
5361     ui_out_field_string (uiout, "what", b->addr_string);
5362   else if (loc && loc->source_file)
5363     {
5364       struct symbol *sym 
5365         = find_pc_sect_function (loc->address, loc->section);
5366       if (sym)
5367         {
5368           ui_out_text (uiout, "in ");
5369           ui_out_field_string (uiout, "func",
5370                                SYMBOL_PRINT_NAME (sym));
5371           ui_out_text (uiout, " ");
5372           ui_out_wrap_hint (uiout, wrap_indent_at_field (uiout, "what"));
5373           ui_out_text (uiout, "at ");
5374         }
5375       ui_out_field_string (uiout, "file", loc->source_file);
5376       ui_out_text (uiout, ":");
5377       
5378       if (ui_out_is_mi_like_p (uiout))
5379         {
5380           struct symtab_and_line sal = find_pc_line (loc->address, 0);
5381           char *fullname = symtab_to_fullname (sal.symtab);
5382           
5383           if (fullname)
5384             ui_out_field_string (uiout, "fullname", fullname);
5385         }
5386       
5387       ui_out_field_int (uiout, "line", loc->line_number);
5388     }
5389   else if (loc)
5390     {
5391       struct ui_file *stb = mem_fileopen ();
5392       struct cleanup *stb_chain = make_cleanup_ui_file_delete (stb);
5393
5394       print_address_symbolic (loc->gdbarch, loc->address, stb,
5395                               demangle, "");
5396       ui_out_field_stream (uiout, "at", stb);
5397
5398       do_cleanups (stb_chain);
5399     }
5400   else
5401     ui_out_field_string (uiout, "pending", b->addr_string);
5402
5403   if (loc && is_breakpoint (b)
5404       && breakpoint_condition_evaluation_mode () == condition_evaluation_target
5405       && bp_condition_evaluator (b) == condition_evaluation_both)
5406     {
5407       ui_out_text (uiout, " (");
5408       ui_out_field_string (uiout, "evaluated-by",
5409                            bp_location_condition_evaluator (loc));
5410       ui_out_text (uiout, ")");
5411     }
5412
5413   do_cleanups (old_chain);
5414 }
5415
5416 static const char *
5417 bptype_string (enum bptype type)
5418 {
5419   struct ep_type_description
5420     {
5421       enum bptype type;
5422       char *description;
5423     };
5424   static struct ep_type_description bptypes[] =
5425   {
5426     {bp_none, "?deleted?"},
5427     {bp_breakpoint, "breakpoint"},
5428     {bp_hardware_breakpoint, "hw breakpoint"},
5429     {bp_until, "until"},
5430     {bp_finish, "finish"},
5431     {bp_watchpoint, "watchpoint"},
5432     {bp_hardware_watchpoint, "hw watchpoint"},
5433     {bp_read_watchpoint, "read watchpoint"},
5434     {bp_access_watchpoint, "acc watchpoint"},
5435     {bp_longjmp, "longjmp"},
5436     {bp_longjmp_resume, "longjmp resume"},
5437     {bp_exception, "exception"},
5438     {bp_exception_resume, "exception resume"},
5439     {bp_step_resume, "step resume"},
5440     {bp_hp_step_resume, "high-priority step resume"},
5441     {bp_watchpoint_scope, "watchpoint scope"},
5442     {bp_call_dummy, "call dummy"},
5443     {bp_std_terminate, "std::terminate"},
5444     {bp_shlib_event, "shlib events"},
5445     {bp_thread_event, "thread events"},
5446     {bp_overlay_event, "overlay events"},
5447     {bp_longjmp_master, "longjmp master"},
5448     {bp_std_terminate_master, "std::terminate master"},
5449     {bp_exception_master, "exception master"},
5450     {bp_catchpoint, "catchpoint"},
5451     {bp_tracepoint, "tracepoint"},
5452     {bp_fast_tracepoint, "fast tracepoint"},
5453     {bp_static_tracepoint, "static tracepoint"},
5454     {bp_dprintf, "dprintf"},
5455     {bp_jit_event, "jit events"},
5456     {bp_gnu_ifunc_resolver, "STT_GNU_IFUNC resolver"},
5457     {bp_gnu_ifunc_resolver_return, "STT_GNU_IFUNC resolver return"},
5458   };
5459
5460   if (((int) type >= (sizeof (bptypes) / sizeof (bptypes[0])))
5461       || ((int) type != bptypes[(int) type].type))
5462     internal_error (__FILE__, __LINE__,
5463                     _("bptypes table does not describe type #%d."),
5464                     (int) type);
5465
5466   return bptypes[(int) type].description;
5467 }
5468
5469 /* Print B to gdb_stdout.  */
5470
5471 static void
5472 print_one_breakpoint_location (struct breakpoint *b,
5473                                struct bp_location *loc,
5474                                int loc_number,
5475                                struct bp_location **last_loc,
5476                                int allflag)
5477 {
5478   struct command_line *l;
5479   static char bpenables[] = "nynny";
5480
5481   struct ui_out *uiout = current_uiout;
5482   int header_of_multiple = 0;
5483   int part_of_multiple = (loc != NULL);
5484   struct value_print_options opts;
5485
5486   get_user_print_options (&opts);
5487
5488   gdb_assert (!loc || loc_number != 0);
5489   /* See comment in print_one_breakpoint concerning treatment of
5490      breakpoints with single disabled location.  */
5491   if (loc == NULL 
5492       && (b->loc != NULL 
5493           && (b->loc->next != NULL || !b->loc->enabled)))
5494     header_of_multiple = 1;
5495   if (loc == NULL)
5496     loc = b->loc;
5497
5498   annotate_record ();
5499
5500   /* 1 */
5501   annotate_field (0);
5502   if (part_of_multiple)
5503     {
5504       char *formatted;
5505       formatted = xstrprintf ("%d.%d", b->number, loc_number);
5506       ui_out_field_string (uiout, "number", formatted);
5507       xfree (formatted);
5508     }
5509   else
5510     {
5511       ui_out_field_int (uiout, "number", b->number);
5512     }
5513
5514   /* 2 */
5515   annotate_field (1);
5516   if (part_of_multiple)
5517     ui_out_field_skip (uiout, "type");
5518   else
5519     ui_out_field_string (uiout, "type", bptype_string (b->type));
5520
5521   /* 3 */
5522   annotate_field (2);
5523   if (part_of_multiple)
5524     ui_out_field_skip (uiout, "disp");
5525   else
5526     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
5527
5528
5529   /* 4 */
5530   annotate_field (3);
5531   if (part_of_multiple)
5532     ui_out_field_string (uiout, "enabled", loc->enabled ? "y" : "n");
5533   else
5534     ui_out_field_fmt (uiout, "enabled", "%c", 
5535                       bpenables[(int) b->enable_state]);
5536   ui_out_spaces (uiout, 2);
5537
5538   
5539   /* 5 and 6 */
5540   if (b->ops != NULL && b->ops->print_one != NULL)
5541     {
5542       /* Although the print_one can possibly print all locations,
5543          calling it here is not likely to get any nice result.  So,
5544          make sure there's just one location.  */
5545       gdb_assert (b->loc == NULL || b->loc->next == NULL);
5546       b->ops->print_one (b, last_loc);
5547     }
5548   else
5549     switch (b->type)
5550       {
5551       case bp_none:
5552         internal_error (__FILE__, __LINE__,
5553                         _("print_one_breakpoint: bp_none encountered\n"));
5554         break;
5555
5556       case bp_watchpoint:
5557       case bp_hardware_watchpoint:
5558       case bp_read_watchpoint:
5559       case bp_access_watchpoint:
5560         {
5561           struct watchpoint *w = (struct watchpoint *) b;
5562
5563           /* Field 4, the address, is omitted (which makes the columns
5564              not line up too nicely with the headers, but the effect
5565              is relatively readable).  */
5566           if (opts.addressprint)
5567             ui_out_field_skip (uiout, "addr");
5568           annotate_field (5);
5569           ui_out_field_string (uiout, "what", w->exp_string);
5570         }
5571         break;
5572
5573       case bp_breakpoint:
5574       case bp_hardware_breakpoint:
5575       case bp_until:
5576       case bp_finish:
5577       case bp_longjmp:
5578       case bp_longjmp_resume:
5579       case bp_exception:
5580       case bp_exception_resume:
5581       case bp_step_resume:
5582       case bp_hp_step_resume:
5583       case bp_watchpoint_scope:
5584       case bp_call_dummy:
5585       case bp_std_terminate:
5586       case bp_shlib_event:
5587       case bp_thread_event:
5588       case bp_overlay_event:
5589       case bp_longjmp_master:
5590       case bp_std_terminate_master:
5591       case bp_exception_master:
5592       case bp_tracepoint:
5593       case bp_fast_tracepoint:
5594       case bp_static_tracepoint:
5595       case bp_dprintf:
5596       case bp_jit_event:
5597       case bp_gnu_ifunc_resolver:
5598       case bp_gnu_ifunc_resolver_return:
5599         if (opts.addressprint)
5600           {
5601             annotate_field (4);
5602             if (header_of_multiple)
5603               ui_out_field_string (uiout, "addr", "<MULTIPLE>");
5604             else if (b->loc == NULL || loc->shlib_disabled)
5605               ui_out_field_string (uiout, "addr", "<PENDING>");
5606             else
5607               ui_out_field_core_addr (uiout, "addr",
5608                                       loc->gdbarch, loc->address);
5609           }
5610         annotate_field (5);
5611         if (!header_of_multiple)
5612           print_breakpoint_location (b, loc);
5613         if (b->loc)
5614           *last_loc = b->loc;
5615         break;
5616       }
5617
5618
5619   /* For backward compatibility, don't display inferiors unless there
5620      are several.  */
5621   if (loc != NULL
5622       && !header_of_multiple
5623       && (allflag
5624           || (!gdbarch_has_global_breakpoints (target_gdbarch)
5625               && (number_of_program_spaces () > 1
5626                   || number_of_inferiors () > 1)
5627               /* LOC is for existing B, it cannot be in
5628                  moribund_locations and thus having NULL OWNER.  */
5629               && loc->owner->type != bp_catchpoint)))
5630     {
5631       struct inferior *inf;
5632       int first = 1;
5633
5634       for (inf = inferior_list; inf != NULL; inf = inf->next)
5635         {
5636           if (inf->pspace == loc->pspace)
5637             {
5638               if (first)
5639                 {
5640                   first = 0;
5641                   ui_out_text (uiout, " inf ");
5642                 }
5643               else
5644                 ui_out_text (uiout, ", ");
5645               ui_out_text (uiout, plongest (inf->num));
5646             }
5647         }
5648     }
5649
5650   if (!part_of_multiple)
5651     {
5652       if (b->thread != -1)
5653         {
5654           /* FIXME: This seems to be redundant and lost here; see the
5655              "stop only in" line a little further down.  */
5656           ui_out_text (uiout, " thread ");
5657           ui_out_field_int (uiout, "thread", b->thread);
5658         }
5659       else if (b->task != 0)
5660         {
5661           ui_out_text (uiout, " task ");
5662           ui_out_field_int (uiout, "task", b->task);
5663         }
5664     }
5665
5666   ui_out_text (uiout, "\n");
5667
5668   if (!part_of_multiple)
5669     b->ops->print_one_detail (b, uiout);
5670
5671   if (part_of_multiple && frame_id_p (b->frame_id))
5672     {
5673       annotate_field (6);
5674       ui_out_text (uiout, "\tstop only in stack frame at ");
5675       /* FIXME: cagney/2002-12-01: Shouldn't be poking around inside
5676          the frame ID.  */
5677       ui_out_field_core_addr (uiout, "frame",
5678                               b->gdbarch, b->frame_id.stack_addr);
5679       ui_out_text (uiout, "\n");
5680     }
5681   
5682   if (!part_of_multiple && b->cond_string)
5683     {
5684       annotate_field (7);
5685       if (is_tracepoint (b))
5686         ui_out_text (uiout, "\ttrace only if ");
5687       else
5688         ui_out_text (uiout, "\tstop only if ");
5689       ui_out_field_string (uiout, "cond", b->cond_string);
5690
5691       /* Print whether the target is doing the breakpoint's condition
5692          evaluation.  If GDB is doing the evaluation, don't print anything.  */
5693       if (is_breakpoint (b)
5694           && breakpoint_condition_evaluation_mode ()
5695           == condition_evaluation_target)
5696         {
5697           ui_out_text (uiout, " (");
5698           ui_out_field_string (uiout, "evaluated-by",
5699                                bp_condition_evaluator (b));
5700           ui_out_text (uiout, " evals)");
5701         }
5702       ui_out_text (uiout, "\n");
5703     }
5704
5705   if (!part_of_multiple && b->thread != -1)
5706     {
5707       /* FIXME should make an annotation for this.  */
5708       ui_out_text (uiout, "\tstop only in thread ");
5709       ui_out_field_int (uiout, "thread", b->thread);
5710       ui_out_text (uiout, "\n");
5711     }
5712   
5713   if (!part_of_multiple && b->hit_count)
5714     {
5715       /* FIXME should make an annotation for this.  */
5716       if (is_catchpoint (b))
5717         ui_out_text (uiout, "\tcatchpoint");
5718       else if (is_tracepoint (b))
5719         ui_out_text (uiout, "\ttracepoint");
5720       else
5721         ui_out_text (uiout, "\tbreakpoint");
5722       ui_out_text (uiout, " already hit ");
5723       ui_out_field_int (uiout, "times", b->hit_count);
5724       if (b->hit_count == 1)
5725         ui_out_text (uiout, " time\n");
5726       else
5727         ui_out_text (uiout, " times\n");
5728     }
5729   
5730   /* Output the count also if it is zero, but only if this is mi.
5731      FIXME: Should have a better test for this.  */
5732   if (ui_out_is_mi_like_p (uiout))
5733     if (!part_of_multiple && b->hit_count == 0)
5734       ui_out_field_int (uiout, "times", b->hit_count);
5735
5736   if (!part_of_multiple && b->ignore_count)
5737     {
5738       annotate_field (8);
5739       ui_out_text (uiout, "\tignore next ");
5740       ui_out_field_int (uiout, "ignore", b->ignore_count);
5741       ui_out_text (uiout, " hits\n");
5742     }
5743
5744   /* Note that an enable count of 1 corresponds to "enable once"
5745      behavior, which is reported by the combination of enablement and
5746      disposition, so we don't need to mention it here.  */
5747   if (!part_of_multiple && b->enable_count > 1)
5748     {
5749       annotate_field (8);
5750       ui_out_text (uiout, "\tdisable after ");
5751       /* Tweak the wording to clarify that ignore and enable counts
5752          are distinct, and have additive effect.  */
5753       if (b->ignore_count)
5754         ui_out_text (uiout, "additional ");
5755       else
5756         ui_out_text (uiout, "next ");
5757       ui_out_field_int (uiout, "enable", b->enable_count);
5758       ui_out_text (uiout, " hits\n");
5759     }
5760
5761   if (!part_of_multiple && is_tracepoint (b))
5762     {
5763       struct tracepoint *tp = (struct tracepoint *) b;
5764
5765       if (tp->traceframe_usage)
5766         {
5767           ui_out_text (uiout, "\ttrace buffer usage ");
5768           ui_out_field_int (uiout, "traceframe-usage", tp->traceframe_usage);
5769           ui_out_text (uiout, " bytes\n");
5770         }
5771     }
5772   
5773   l = b->commands ? b->commands->commands : NULL;
5774   if (!part_of_multiple && l)
5775     {
5776       struct cleanup *script_chain;
5777
5778       annotate_field (9);
5779       script_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "script");
5780       print_command_lines (uiout, l, 4);
5781       do_cleanups (script_chain);
5782     }
5783
5784   if (is_tracepoint (b))
5785     {
5786       struct tracepoint *t = (struct tracepoint *) b;
5787
5788       if (!part_of_multiple && t->pass_count)
5789         {
5790           annotate_field (10);
5791           ui_out_text (uiout, "\tpass count ");
5792           ui_out_field_int (uiout, "pass", t->pass_count);
5793           ui_out_text (uiout, " \n");
5794         }
5795     }
5796
5797   if (ui_out_is_mi_like_p (uiout) && !part_of_multiple)
5798     {
5799       if (is_watchpoint (b))
5800         {
5801           struct watchpoint *w = (struct watchpoint *) b;
5802
5803           ui_out_field_string (uiout, "original-location", w->exp_string);
5804         }
5805       else if (b->addr_string)
5806         ui_out_field_string (uiout, "original-location", b->addr_string);
5807     }
5808 }
5809
5810 static void
5811 print_one_breakpoint (struct breakpoint *b,
5812                       struct bp_location **last_loc, 
5813                       int allflag)
5814 {
5815   struct cleanup *bkpt_chain;
5816   struct ui_out *uiout = current_uiout;
5817
5818   bkpt_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "bkpt");
5819
5820   print_one_breakpoint_location (b, NULL, 0, last_loc, allflag);
5821   do_cleanups (bkpt_chain);
5822
5823   /* If this breakpoint has custom print function,
5824      it's already printed.  Otherwise, print individual
5825      locations, if any.  */
5826   if (b->ops == NULL || b->ops->print_one == NULL)
5827     {
5828       /* If breakpoint has a single location that is disabled, we
5829          print it as if it had several locations, since otherwise it's
5830          hard to represent "breakpoint enabled, location disabled"
5831          situation.
5832
5833          Note that while hardware watchpoints have several locations
5834          internally, that's not a property exposed to user.  */
5835       if (b->loc 
5836           && !is_hardware_watchpoint (b)
5837           && (b->loc->next || !b->loc->enabled))
5838         {
5839           struct bp_location *loc;
5840           int n = 1;
5841
5842           for (loc = b->loc; loc; loc = loc->next, ++n)
5843             {
5844               struct cleanup *inner2 =
5845                 make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
5846               print_one_breakpoint_location (b, loc, n, last_loc, allflag);
5847               do_cleanups (inner2);
5848             }
5849         }
5850     }
5851 }
5852
5853 static int
5854 breakpoint_address_bits (struct breakpoint *b)
5855 {
5856   int print_address_bits = 0;
5857   struct bp_location *loc;
5858
5859   for (loc = b->loc; loc; loc = loc->next)
5860     {
5861       int addr_bit;
5862
5863       /* Software watchpoints that aren't watching memory don't have
5864          an address to print.  */
5865       if (b->type == bp_watchpoint && loc->watchpoint_type == -1)
5866         continue;
5867
5868       addr_bit = gdbarch_addr_bit (loc->gdbarch);
5869       if (addr_bit > print_address_bits)
5870         print_address_bits = addr_bit;
5871     }
5872
5873   return print_address_bits;
5874 }
5875
5876 struct captured_breakpoint_query_args
5877   {
5878     int bnum;
5879   };
5880
5881 static int
5882 do_captured_breakpoint_query (struct ui_out *uiout, void *data)
5883 {
5884   struct captured_breakpoint_query_args *args = data;
5885   struct breakpoint *b;
5886   struct bp_location *dummy_loc = NULL;
5887
5888   ALL_BREAKPOINTS (b)
5889     {
5890       if (args->bnum == b->number)
5891         {
5892           print_one_breakpoint (b, &dummy_loc, 0);
5893           return GDB_RC_OK;
5894         }
5895     }
5896   return GDB_RC_NONE;
5897 }
5898
5899 enum gdb_rc
5900 gdb_breakpoint_query (struct ui_out *uiout, int bnum, 
5901                       char **error_message)
5902 {
5903   struct captured_breakpoint_query_args args;
5904
5905   args.bnum = bnum;
5906   /* For the moment we don't trust print_one_breakpoint() to not throw
5907      an error.  */
5908   if (catch_exceptions_with_msg (uiout, do_captured_breakpoint_query, &args,
5909                                  error_message, RETURN_MASK_ALL) < 0)
5910     return GDB_RC_FAIL;
5911   else
5912     return GDB_RC_OK;
5913 }
5914
5915 /* Return true if this breakpoint was set by the user, false if it is
5916    internal or momentary.  */
5917
5918 int
5919 user_breakpoint_p (struct breakpoint *b)
5920 {
5921   return b->number > 0;
5922 }
5923
5924 /* Print information on user settable breakpoint (watchpoint, etc)
5925    number BNUM.  If BNUM is -1 print all user-settable breakpoints.
5926    If ALLFLAG is non-zero, include non-user-settable breakpoints.  If
5927    FILTER is non-NULL, call it on each breakpoint and only include the
5928    ones for which it returns non-zero.  Return the total number of
5929    breakpoints listed.  */
5930
5931 static int
5932 breakpoint_1 (char *args, int allflag, 
5933               int (*filter) (const struct breakpoint *))
5934 {
5935   struct breakpoint *b;
5936   struct bp_location *last_loc = NULL;
5937   int nr_printable_breakpoints;
5938   struct cleanup *bkpttbl_chain;
5939   struct value_print_options opts;
5940   int print_address_bits = 0;
5941   int print_type_col_width = 14;
5942   struct ui_out *uiout = current_uiout;
5943
5944   get_user_print_options (&opts);
5945
5946   /* Compute the number of rows in the table, as well as the size
5947      required for address fields.  */
5948   nr_printable_breakpoints = 0;
5949   ALL_BREAKPOINTS (b)
5950     {
5951       /* If we have a filter, only list the breakpoints it accepts.  */
5952       if (filter && !filter (b))
5953         continue;
5954
5955       /* If we have an "args" string, it is a list of breakpoints to 
5956          accept.  Skip the others.  */
5957       if (args != NULL && *args != '\0')
5958         {
5959           if (allflag && parse_and_eval_long (args) != b->number)
5960             continue;
5961           if (!allflag && !number_is_in_list (args, b->number))
5962             continue;
5963         }
5964
5965       if (allflag || user_breakpoint_p (b))
5966         {
5967           int addr_bit, type_len;
5968
5969           addr_bit = breakpoint_address_bits (b);
5970           if (addr_bit > print_address_bits)
5971             print_address_bits = addr_bit;
5972
5973           type_len = strlen (bptype_string (b->type));
5974           if (type_len > print_type_col_width)
5975             print_type_col_width = type_len;
5976
5977           nr_printable_breakpoints++;
5978         }
5979     }
5980
5981   if (opts.addressprint)
5982     bkpttbl_chain 
5983       = make_cleanup_ui_out_table_begin_end (uiout, 6,
5984                                              nr_printable_breakpoints,
5985                                              "BreakpointTable");
5986   else
5987     bkpttbl_chain 
5988       = make_cleanup_ui_out_table_begin_end (uiout, 5,
5989                                              nr_printable_breakpoints,
5990                                              "BreakpointTable");
5991
5992   if (nr_printable_breakpoints > 0)
5993     annotate_breakpoints_headers ();
5994   if (nr_printable_breakpoints > 0)
5995     annotate_field (0);
5996   ui_out_table_header (uiout, 7, ui_left, "number", "Num");     /* 1 */
5997   if (nr_printable_breakpoints > 0)
5998     annotate_field (1);
5999   ui_out_table_header (uiout, print_type_col_width, ui_left,
6000                        "type", "Type");                         /* 2 */
6001   if (nr_printable_breakpoints > 0)
6002     annotate_field (2);
6003   ui_out_table_header (uiout, 4, ui_left, "disp", "Disp");      /* 3 */
6004   if (nr_printable_breakpoints > 0)
6005     annotate_field (3);
6006   ui_out_table_header (uiout, 3, ui_left, "enabled", "Enb");    /* 4 */
6007   if (opts.addressprint)
6008     {
6009       if (nr_printable_breakpoints > 0)
6010         annotate_field (4);
6011       if (print_address_bits <= 32)
6012         ui_out_table_header (uiout, 10, ui_left, 
6013                              "addr", "Address");                /* 5 */
6014       else
6015         ui_out_table_header (uiout, 18, ui_left, 
6016                              "addr", "Address");                /* 5 */
6017     }
6018   if (nr_printable_breakpoints > 0)
6019     annotate_field (5);
6020   ui_out_table_header (uiout, 40, ui_noalign, "what", "What");  /* 6 */
6021   ui_out_table_body (uiout);
6022   if (nr_printable_breakpoints > 0)
6023     annotate_breakpoints_table ();
6024
6025   ALL_BREAKPOINTS (b)
6026     {
6027       QUIT;
6028       /* If we have a filter, only list the breakpoints it accepts.  */
6029       if (filter && !filter (b))
6030         continue;
6031
6032       /* If we have an "args" string, it is a list of breakpoints to 
6033          accept.  Skip the others.  */
6034
6035       if (args != NULL && *args != '\0')
6036         {
6037           if (allflag)  /* maintenance info breakpoint */
6038             {
6039               if (parse_and_eval_long (args) != b->number)
6040                 continue;
6041             }
6042           else          /* all others */
6043             {
6044               if (!number_is_in_list (args, b->number))
6045                 continue;
6046             }
6047         }
6048       /* We only print out user settable breakpoints unless the
6049          allflag is set.  */
6050       if (allflag || user_breakpoint_p (b))
6051         print_one_breakpoint (b, &last_loc, allflag);
6052     }
6053
6054   do_cleanups (bkpttbl_chain);
6055
6056   if (nr_printable_breakpoints == 0)
6057     {
6058       /* If there's a filter, let the caller decide how to report
6059          empty list.  */
6060       if (!filter)
6061         {
6062           if (args == NULL || *args == '\0')
6063             ui_out_message (uiout, 0, "No breakpoints or watchpoints.\n");
6064           else
6065             ui_out_message (uiout, 0, 
6066                             "No breakpoint or watchpoint matching '%s'.\n",
6067                             args);
6068         }
6069     }
6070   else
6071     {
6072       if (last_loc && !server_command)
6073         set_next_address (last_loc->gdbarch, last_loc->address);
6074     }
6075
6076   /* FIXME?  Should this be moved up so that it is only called when
6077      there have been breakpoints? */
6078   annotate_breakpoints_table_end ();
6079
6080   return nr_printable_breakpoints;
6081 }
6082
6083 /* Display the value of default-collect in a way that is generally
6084    compatible with the breakpoint list.  */
6085
6086 static void
6087 default_collect_info (void)
6088 {
6089   struct ui_out *uiout = current_uiout;
6090
6091   /* If it has no value (which is frequently the case), say nothing; a
6092      message like "No default-collect." gets in user's face when it's
6093      not wanted.  */
6094   if (!*default_collect)
6095     return;
6096
6097   /* The following phrase lines up nicely with per-tracepoint collect
6098      actions.  */
6099   ui_out_text (uiout, "default collect ");
6100   ui_out_field_string (uiout, "default-collect", default_collect);
6101   ui_out_text (uiout, " \n");
6102 }
6103   
6104 static void
6105 breakpoints_info (char *args, int from_tty)
6106 {
6107   breakpoint_1 (args, 0, NULL);
6108
6109   default_collect_info ();
6110 }
6111
6112 static void
6113 watchpoints_info (char *args, int from_tty)
6114 {
6115   int num_printed = breakpoint_1 (args, 0, is_watchpoint);
6116   struct ui_out *uiout = current_uiout;
6117
6118   if (num_printed == 0)
6119     {
6120       if (args == NULL || *args == '\0')
6121         ui_out_message (uiout, 0, "No watchpoints.\n");
6122       else
6123         ui_out_message (uiout, 0, "No watchpoint matching '%s'.\n", args);
6124     }
6125 }
6126
6127 static void
6128 maintenance_info_breakpoints (char *args, int from_tty)
6129 {
6130   breakpoint_1 (args, 1, NULL);
6131
6132   default_collect_info ();
6133 }
6134
6135 static int
6136 breakpoint_has_pc (struct breakpoint *b,
6137                    struct program_space *pspace,
6138                    CORE_ADDR pc, struct obj_section *section)
6139 {
6140   struct bp_location *bl = b->loc;
6141
6142   for (; bl; bl = bl->next)
6143     {
6144       if (bl->pspace == pspace
6145           && bl->address == pc
6146           && (!overlay_debugging || bl->section == section))
6147         return 1;         
6148     }
6149   return 0;
6150 }
6151
6152 /* Print a message describing any user-breakpoints set at PC.  This
6153    concerns with logical breakpoints, so we match program spaces, not
6154    address spaces.  */
6155
6156 static void
6157 describe_other_breakpoints (struct gdbarch *gdbarch,
6158                             struct program_space *pspace, CORE_ADDR pc,
6159                             struct obj_section *section, int thread)
6160 {
6161   int others = 0;
6162   struct breakpoint *b;
6163
6164   ALL_BREAKPOINTS (b)
6165     others += (user_breakpoint_p (b)
6166                && breakpoint_has_pc (b, pspace, pc, section));
6167   if (others > 0)
6168     {
6169       if (others == 1)
6170         printf_filtered (_("Note: breakpoint "));
6171       else /* if (others == ???) */
6172         printf_filtered (_("Note: breakpoints "));
6173       ALL_BREAKPOINTS (b)
6174         if (user_breakpoint_p (b) && breakpoint_has_pc (b, pspace, pc, section))
6175           {
6176             others--;
6177             printf_filtered ("%d", b->number);
6178             if (b->thread == -1 && thread != -1)
6179               printf_filtered (" (all threads)");
6180             else if (b->thread != -1)
6181               printf_filtered (" (thread %d)", b->thread);
6182             printf_filtered ("%s%s ",
6183                              ((b->enable_state == bp_disabled
6184                                || b->enable_state == bp_call_disabled)
6185                               ? " (disabled)"
6186                               : b->enable_state == bp_permanent 
6187                               ? " (permanent)"
6188                               : ""),
6189                              (others > 1) ? "," 
6190                              : ((others == 1) ? " and" : ""));
6191           }
6192       printf_filtered (_("also set at pc "));
6193       fputs_filtered (paddress (gdbarch, pc), gdb_stdout);
6194       printf_filtered (".\n");
6195     }
6196 }
6197 \f
6198
6199 /* Return true iff it is meaningful to use the address member of
6200    BPT.  For some breakpoint types, the address member is irrelevant
6201    and it makes no sense to attempt to compare it to other addresses
6202    (or use it for any other purpose either).
6203
6204    More specifically, each of the following breakpoint types will
6205    always have a zero valued address and we don't want to mark
6206    breakpoints of any of these types to be a duplicate of an actual
6207    breakpoint at address zero:
6208
6209       bp_watchpoint
6210       bp_catchpoint
6211
6212 */
6213
6214 static int
6215 breakpoint_address_is_meaningful (struct breakpoint *bpt)
6216 {
6217   enum bptype type = bpt->type;
6218
6219   return (type != bp_watchpoint && type != bp_catchpoint);
6220 }
6221
6222 /* Assuming LOC1 and LOC2's owners are hardware watchpoints, returns
6223    true if LOC1 and LOC2 represent the same watchpoint location.  */
6224
6225 static int
6226 watchpoint_locations_match (struct bp_location *loc1, 
6227                             struct bp_location *loc2)
6228 {
6229   struct watchpoint *w1 = (struct watchpoint *) loc1->owner;
6230   struct watchpoint *w2 = (struct watchpoint *) loc2->owner;
6231
6232   /* Both of them must exist.  */
6233   gdb_assert (w1 != NULL);
6234   gdb_assert (w2 != NULL);
6235
6236   /* If the target can evaluate the condition expression in hardware,
6237      then we we need to insert both watchpoints even if they are at
6238      the same place.  Otherwise the watchpoint will only trigger when
6239      the condition of whichever watchpoint was inserted evaluates to
6240      true, not giving a chance for GDB to check the condition of the
6241      other watchpoint.  */
6242   if ((w1->cond_exp
6243        && target_can_accel_watchpoint_condition (loc1->address, 
6244                                                  loc1->length,
6245                                                  loc1->watchpoint_type,
6246                                                  w1->cond_exp))
6247       || (w2->cond_exp
6248           && target_can_accel_watchpoint_condition (loc2->address, 
6249                                                     loc2->length,
6250                                                     loc2->watchpoint_type,
6251                                                     w2->cond_exp)))
6252     return 0;
6253
6254   /* Note that this checks the owner's type, not the location's.  In
6255      case the target does not support read watchpoints, but does
6256      support access watchpoints, we'll have bp_read_watchpoint
6257      watchpoints with hw_access locations.  Those should be considered
6258      duplicates of hw_read locations.  The hw_read locations will
6259      become hw_access locations later.  */
6260   return (loc1->owner->type == loc2->owner->type
6261           && loc1->pspace->aspace == loc2->pspace->aspace
6262           && loc1->address == loc2->address
6263           && loc1->length == loc2->length);
6264 }
6265
6266 /* Returns true if {ASPACE1,ADDR1} and {ASPACE2,ADDR2} represent the
6267    same breakpoint location.  In most targets, this can only be true
6268    if ASPACE1 matches ASPACE2.  On targets that have global
6269    breakpoints, the address space doesn't really matter.  */
6270
6271 static int
6272 breakpoint_address_match (struct address_space *aspace1, CORE_ADDR addr1,
6273                           struct address_space *aspace2, CORE_ADDR addr2)
6274 {
6275   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6276            || aspace1 == aspace2)
6277           && addr1 == addr2);
6278 }
6279
6280 /* Returns true if {ASPACE2,ADDR2} falls within the range determined by
6281    {ASPACE1,ADDR1,LEN1}.  In most targets, this can only be true if ASPACE1
6282    matches ASPACE2.  On targets that have global breakpoints, the address
6283    space doesn't really matter.  */
6284
6285 static int
6286 breakpoint_address_match_range (struct address_space *aspace1, CORE_ADDR addr1,
6287                                 int len1, struct address_space *aspace2,
6288                                 CORE_ADDR addr2)
6289 {
6290   return ((gdbarch_has_global_breakpoints (target_gdbarch)
6291            || aspace1 == aspace2)
6292           && addr2 >= addr1 && addr2 < addr1 + len1);
6293 }
6294
6295 /* Returns true if {ASPACE,ADDR} matches the breakpoint BL.  BL may be
6296    a ranged breakpoint.  In most targets, a match happens only if ASPACE
6297    matches the breakpoint's address space.  On targets that have global
6298    breakpoints, the address space doesn't really matter.  */
6299
6300 static int
6301 breakpoint_location_address_match (struct bp_location *bl,
6302                                    struct address_space *aspace,
6303                                    CORE_ADDR addr)
6304 {
6305   return (breakpoint_address_match (bl->pspace->aspace, bl->address,
6306                                     aspace, addr)
6307           || (bl->length
6308               && breakpoint_address_match_range (bl->pspace->aspace,
6309                                                  bl->address, bl->length,
6310                                                  aspace, addr)));
6311 }
6312
6313 /* If LOC1 and LOC2's owners are not tracepoints, returns false directly.
6314    Then, if LOC1 and LOC2 represent the same tracepoint location, returns
6315    true, otherwise returns false.  */
6316
6317 static int
6318 tracepoint_locations_match (struct bp_location *loc1,
6319                             struct bp_location *loc2)
6320 {
6321   if (is_tracepoint (loc1->owner) && is_tracepoint (loc2->owner))
6322     /* Since tracepoint locations are never duplicated with others', tracepoint
6323        locations at the same address of different tracepoints are regarded as
6324        different locations.  */
6325     return (loc1->address == loc2->address && loc1->owner == loc2->owner);
6326   else
6327     return 0;
6328 }
6329
6330 /* Assuming LOC1 and LOC2's types' have meaningful target addresses
6331    (breakpoint_address_is_meaningful), returns true if LOC1 and LOC2
6332    represent the same location.  */
6333
6334 static int
6335 breakpoint_locations_match (struct bp_location *loc1, 
6336                             struct bp_location *loc2)
6337 {
6338   int hw_point1, hw_point2;
6339
6340   /* Both of them must not be in moribund_locations.  */
6341   gdb_assert (loc1->owner != NULL);
6342   gdb_assert (loc2->owner != NULL);
6343
6344   hw_point1 = is_hardware_watchpoint (loc1->owner);
6345   hw_point2 = is_hardware_watchpoint (loc2->owner);
6346
6347   if (hw_point1 != hw_point2)
6348     return 0;
6349   else if (hw_point1)
6350     return watchpoint_locations_match (loc1, loc2);
6351   else if (is_tracepoint (loc1->owner) || is_tracepoint (loc2->owner))
6352     return tracepoint_locations_match (loc1, loc2);
6353   else
6354     /* We compare bp_location.length in order to cover ranged breakpoints.  */
6355     return (breakpoint_address_match (loc1->pspace->aspace, loc1->address,
6356                                      loc2->pspace->aspace, loc2->address)
6357             && loc1->length == loc2->length);
6358 }
6359
6360 static void
6361 breakpoint_adjustment_warning (CORE_ADDR from_addr, CORE_ADDR to_addr,
6362                                int bnum, int have_bnum)
6363 {
6364   /* The longest string possibly returned by hex_string_custom
6365      is 50 chars.  These must be at least that big for safety.  */
6366   char astr1[64];
6367   char astr2[64];
6368
6369   strcpy (astr1, hex_string_custom ((unsigned long) from_addr, 8));
6370   strcpy (astr2, hex_string_custom ((unsigned long) to_addr, 8));
6371   if (have_bnum)
6372     warning (_("Breakpoint %d address previously adjusted from %s to %s."),
6373              bnum, astr1, astr2);
6374   else
6375     warning (_("Breakpoint address adjusted from %s to %s."), astr1, astr2);
6376 }
6377
6378 /* Adjust a breakpoint's address to account for architectural
6379    constraints on breakpoint placement.  Return the adjusted address.
6380    Note: Very few targets require this kind of adjustment.  For most
6381    targets, this function is simply the identity function.  */
6382
6383 static CORE_ADDR
6384 adjust_breakpoint_address (struct gdbarch *gdbarch,
6385                            CORE_ADDR bpaddr, enum bptype bptype)
6386 {
6387   if (!gdbarch_adjust_breakpoint_address_p (gdbarch))
6388     {
6389       /* Very few targets need any kind of breakpoint adjustment.  */
6390       return bpaddr;
6391     }
6392   else if (bptype == bp_watchpoint
6393            || bptype == bp_hardware_watchpoint
6394            || bptype == bp_read_watchpoint
6395            || bptype == bp_access_watchpoint
6396            || bptype == bp_catchpoint)
6397     {
6398       /* Watchpoints and the various bp_catch_* eventpoints should not
6399          have their addresses modified.  */
6400       return bpaddr;
6401     }
6402   else
6403     {
6404       CORE_ADDR adjusted_bpaddr;
6405
6406       /* Some targets have architectural constraints on the placement
6407          of breakpoint instructions.  Obtain the adjusted address.  */
6408       adjusted_bpaddr = gdbarch_adjust_breakpoint_address (gdbarch, bpaddr);
6409
6410       /* An adjusted breakpoint address can significantly alter
6411          a user's expectations.  Print a warning if an adjustment
6412          is required.  */
6413       if (adjusted_bpaddr != bpaddr)
6414         breakpoint_adjustment_warning (bpaddr, adjusted_bpaddr, 0, 0);
6415
6416       return adjusted_bpaddr;
6417     }
6418 }
6419
6420 void
6421 init_bp_location (struct bp_location *loc, const struct bp_location_ops *ops,
6422                   struct breakpoint *owner)
6423 {
6424   memset (loc, 0, sizeof (*loc));
6425
6426   gdb_assert (ops != NULL);
6427
6428   loc->ops = ops;
6429   loc->owner = owner;
6430   loc->cond = NULL;
6431   loc->cond_bytecode = NULL;
6432   loc->shlib_disabled = 0;
6433   loc->enabled = 1;
6434
6435   switch (owner->type)
6436     {
6437     case bp_breakpoint:
6438     case bp_until:
6439     case bp_finish:
6440     case bp_longjmp:
6441     case bp_longjmp_resume:
6442     case bp_exception:
6443     case bp_exception_resume:
6444     case bp_step_resume:
6445     case bp_hp_step_resume:
6446     case bp_watchpoint_scope:
6447     case bp_call_dummy:
6448     case bp_std_terminate:
6449     case bp_shlib_event:
6450     case bp_thread_event:
6451     case bp_overlay_event:
6452     case bp_jit_event:
6453     case bp_longjmp_master:
6454     case bp_std_terminate_master:
6455     case bp_exception_master:
6456     case bp_gnu_ifunc_resolver:
6457     case bp_gnu_ifunc_resolver_return:
6458     case bp_dprintf:
6459       loc->loc_type = bp_loc_software_breakpoint;
6460       mark_breakpoint_location_modified (loc);
6461       break;
6462     case bp_hardware_breakpoint:
6463       loc->loc_type = bp_loc_hardware_breakpoint;
6464       mark_breakpoint_location_modified (loc);
6465       break;
6466     case bp_hardware_watchpoint:
6467     case bp_read_watchpoint:
6468     case bp_access_watchpoint:
6469       loc->loc_type = bp_loc_hardware_watchpoint;
6470       break;
6471     case bp_watchpoint:
6472     case bp_catchpoint:
6473     case bp_tracepoint:
6474     case bp_fast_tracepoint:
6475     case bp_static_tracepoint:
6476       loc->loc_type = bp_loc_other;
6477       break;
6478     default:
6479       internal_error (__FILE__, __LINE__, _("unknown breakpoint type"));
6480     }
6481
6482   loc->refc = 1;
6483 }
6484
6485 /* Allocate a struct bp_location.  */
6486
6487 static struct bp_location *
6488 allocate_bp_location (struct breakpoint *bpt)
6489 {
6490   return bpt->ops->allocate_location (bpt);
6491 }
6492
6493 static void
6494 free_bp_location (struct bp_location *loc)
6495 {
6496   loc->ops->dtor (loc);
6497   xfree (loc);
6498 }
6499
6500 /* Increment reference count.  */
6501
6502 static void
6503 incref_bp_location (struct bp_location *bl)
6504 {
6505   ++bl->refc;
6506 }
6507
6508 /* Decrement reference count.  If the reference count reaches 0,
6509    destroy the bp_location.  Sets *BLP to NULL.  */
6510
6511 static void
6512 decref_bp_location (struct bp_location **blp)
6513 {
6514   gdb_assert ((*blp)->refc > 0);
6515
6516   if (--(*blp)->refc == 0)
6517     free_bp_location (*blp);
6518   *blp = NULL;
6519 }
6520
6521 /* Add breakpoint B at the end of the global breakpoint chain.  */
6522
6523 static void
6524 add_to_breakpoint_chain (struct breakpoint *b)
6525 {
6526   struct breakpoint *b1;
6527
6528   /* Add this breakpoint to the end of the chain so that a list of
6529      breakpoints will come out in order of increasing numbers.  */
6530
6531   b1 = breakpoint_chain;
6532   if (b1 == 0)
6533     breakpoint_chain = b;
6534   else
6535     {
6536       while (b1->next)
6537         b1 = b1->next;
6538       b1->next = b;
6539     }
6540 }
6541
6542 /* Initializes breakpoint B with type BPTYPE and no locations yet.  */
6543
6544 static void
6545 init_raw_breakpoint_without_location (struct breakpoint *b,
6546                                       struct gdbarch *gdbarch,
6547                                       enum bptype bptype,
6548                                       const struct breakpoint_ops *ops)
6549 {
6550   memset (b, 0, sizeof (*b));
6551
6552   gdb_assert (ops != NULL);
6553
6554   b->ops = ops;
6555   b->type = bptype;
6556   b->gdbarch = gdbarch;
6557   b->language = current_language->la_language;
6558   b->input_radix = input_radix;
6559   b->thread = -1;
6560   b->enable_state = bp_enabled;
6561   b->next = 0;
6562   b->silent = 0;
6563   b->ignore_count = 0;
6564   b->commands = NULL;
6565   b->frame_id = null_frame_id;
6566   b->condition_not_parsed = 0;
6567   b->py_bp_object = NULL;
6568   b->related_breakpoint = b;
6569 }
6570
6571 /* Helper to set_raw_breakpoint below.  Creates a breakpoint
6572    that has type BPTYPE and has no locations as yet.  */
6573
6574 static struct breakpoint *
6575 set_raw_breakpoint_without_location (struct gdbarch *gdbarch,
6576                                      enum bptype bptype,
6577                                      const struct breakpoint_ops *ops)
6578 {
6579   struct breakpoint *b = XNEW (struct breakpoint);
6580
6581   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6582   add_to_breakpoint_chain (b);
6583   return b;
6584 }
6585
6586 /* Initialize loc->function_name.  EXPLICIT_LOC says no indirect function
6587    resolutions should be made as the user specified the location explicitly
6588    enough.  */
6589
6590 static void
6591 set_breakpoint_location_function (struct bp_location *loc, int explicit_loc)
6592 {
6593   gdb_assert (loc->owner != NULL);
6594
6595   if (loc->owner->type == bp_breakpoint
6596       || loc->owner->type == bp_hardware_breakpoint
6597       || is_tracepoint (loc->owner))
6598     {
6599       int is_gnu_ifunc;
6600       const char *function_name;
6601
6602       find_pc_partial_function_gnu_ifunc (loc->address, &function_name,
6603                                           NULL, NULL, &is_gnu_ifunc);
6604
6605       if (is_gnu_ifunc && !explicit_loc)
6606         {
6607           struct breakpoint *b = loc->owner;
6608
6609           gdb_assert (loc->pspace == current_program_space);
6610           if (gnu_ifunc_resolve_name (function_name,
6611                                       &loc->requested_address))
6612             {
6613               /* Recalculate ADDRESS based on new REQUESTED_ADDRESS.  */
6614               loc->address = adjust_breakpoint_address (loc->gdbarch,
6615                                                         loc->requested_address,
6616                                                         b->type);
6617             }
6618           else if (b->type == bp_breakpoint && b->loc == loc
6619                    && loc->next == NULL && b->related_breakpoint == b)
6620             {
6621               /* Create only the whole new breakpoint of this type but do not
6622                  mess more complicated breakpoints with multiple locations.  */
6623               b->type = bp_gnu_ifunc_resolver;
6624             }
6625         }
6626
6627       if (function_name)
6628         loc->function_name = xstrdup (function_name);
6629     }
6630 }
6631
6632 /* Attempt to determine architecture of location identified by SAL.  */
6633 struct gdbarch *
6634 get_sal_arch (struct symtab_and_line sal)
6635 {
6636   if (sal.section)
6637     return get_objfile_arch (sal.section->objfile);
6638   if (sal.symtab)
6639     return get_objfile_arch (sal.symtab->objfile);
6640
6641   return NULL;
6642 }
6643
6644 /* Low level routine for partially initializing a breakpoint of type
6645    BPTYPE.  The newly created breakpoint's address, section, source
6646    file name, and line number are provided by SAL.
6647
6648    It is expected that the caller will complete the initialization of
6649    the newly created breakpoint struct as well as output any status
6650    information regarding the creation of a new breakpoint.  */
6651
6652 static void
6653 init_raw_breakpoint (struct breakpoint *b, struct gdbarch *gdbarch,
6654                      struct symtab_and_line sal, enum bptype bptype,
6655                      const struct breakpoint_ops *ops)
6656 {
6657   init_raw_breakpoint_without_location (b, gdbarch, bptype, ops);
6658
6659   add_location_to_breakpoint (b, &sal);
6660
6661   if (bptype != bp_catchpoint)
6662     gdb_assert (sal.pspace != NULL);
6663
6664   /* Store the program space that was used to set the breakpoint,
6665      except for ordinary breakpoints, which are independent of the
6666      program space.  */
6667   if (bptype != bp_breakpoint && bptype != bp_hardware_breakpoint)
6668     b->pspace = sal.pspace;
6669
6670   breakpoints_changed ();
6671 }
6672
6673 /* set_raw_breakpoint is a low level routine for allocating and
6674    partially initializing a breakpoint of type BPTYPE.  The newly
6675    created breakpoint's address, section, source file name, and line
6676    number are provided by SAL.  The newly created and partially
6677    initialized breakpoint is added to the breakpoint chain and
6678    is also returned as the value of this function.
6679
6680    It is expected that the caller will complete the initialization of
6681    the newly created breakpoint struct as well as output any status
6682    information regarding the creation of a new breakpoint.  In
6683    particular, set_raw_breakpoint does NOT set the breakpoint
6684    number!  Care should be taken to not allow an error to occur
6685    prior to completing the initialization of the breakpoint.  If this
6686    should happen, a bogus breakpoint will be left on the chain.  */
6687
6688 struct breakpoint *
6689 set_raw_breakpoint (struct gdbarch *gdbarch,
6690                     struct symtab_and_line sal, enum bptype bptype,
6691                     const struct breakpoint_ops *ops)
6692 {
6693   struct breakpoint *b = XNEW (struct breakpoint);
6694
6695   init_raw_breakpoint (b, gdbarch, sal, bptype, ops);
6696   add_to_breakpoint_chain (b);
6697   return b;
6698 }
6699
6700
6701 /* Note that the breakpoint object B describes a permanent breakpoint
6702    instruction, hard-wired into the inferior's code.  */
6703 void
6704 make_breakpoint_permanent (struct breakpoint *b)
6705 {
6706   struct bp_location *bl;
6707
6708   b->enable_state = bp_permanent;
6709
6710   /* By definition, permanent breakpoints are already present in the
6711      code.  Mark all locations as inserted.  For now,
6712      make_breakpoint_permanent is called in just one place, so it's
6713      hard to say if it's reasonable to have permanent breakpoint with
6714      multiple locations or not, but it's easy to implement.  */
6715   for (bl = b->loc; bl; bl = bl->next)
6716     bl->inserted = 1;
6717 }
6718
6719 /* Call this routine when stepping and nexting to enable a breakpoint
6720    if we do a longjmp() or 'throw' in TP.  FRAME is the frame which
6721    initiated the operation.  */
6722
6723 void
6724 set_longjmp_breakpoint (struct thread_info *tp, struct frame_id frame)
6725 {
6726   struct breakpoint *b, *b_tmp;
6727   int thread = tp->num;
6728
6729   /* To avoid having to rescan all objfile symbols at every step,
6730      we maintain a list of continually-inserted but always disabled
6731      longjmp "master" breakpoints.  Here, we simply create momentary
6732      clones of those and enable them for the requested thread.  */
6733   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6734     if (b->pspace == current_program_space
6735         && (b->type == bp_longjmp_master
6736             || b->type == bp_exception_master))
6737       {
6738         enum bptype type = b->type == bp_longjmp_master ? bp_longjmp : bp_exception;
6739         struct breakpoint *clone;
6740
6741         clone = momentary_breakpoint_from_master (b, type,
6742                                                   &momentary_breakpoint_ops);
6743         clone->thread = thread;
6744       }
6745
6746   tp->initiating_frame = frame;
6747 }
6748
6749 /* Delete all longjmp breakpoints from THREAD.  */
6750 void
6751 delete_longjmp_breakpoint (int thread)
6752 {
6753   struct breakpoint *b, *b_tmp;
6754
6755   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6756     if (b->type == bp_longjmp || b->type == bp_exception)
6757       {
6758         if (b->thread == thread)
6759           delete_breakpoint (b);
6760       }
6761 }
6762
6763 void
6764 delete_longjmp_breakpoint_at_next_stop (int thread)
6765 {
6766   struct breakpoint *b, *b_tmp;
6767
6768   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6769     if (b->type == bp_longjmp || b->type == bp_exception)
6770       {
6771         if (b->thread == thread)
6772           b->disposition = disp_del_at_next_stop;
6773       }
6774 }
6775
6776 void
6777 enable_overlay_breakpoints (void)
6778 {
6779   struct breakpoint *b;
6780
6781   ALL_BREAKPOINTS (b)
6782     if (b->type == bp_overlay_event)
6783     {
6784       b->enable_state = bp_enabled;
6785       update_global_location_list (1);
6786       overlay_events_enabled = 1;
6787     }
6788 }
6789
6790 void
6791 disable_overlay_breakpoints (void)
6792 {
6793   struct breakpoint *b;
6794
6795   ALL_BREAKPOINTS (b)
6796     if (b->type == bp_overlay_event)
6797     {
6798       b->enable_state = bp_disabled;
6799       update_global_location_list (0);
6800       overlay_events_enabled = 0;
6801     }
6802 }
6803
6804 /* Set an active std::terminate breakpoint for each std::terminate
6805    master breakpoint.  */
6806 void
6807 set_std_terminate_breakpoint (void)
6808 {
6809   struct breakpoint *b, *b_tmp;
6810
6811   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6812     if (b->pspace == current_program_space
6813         && b->type == bp_std_terminate_master)
6814       {
6815         momentary_breakpoint_from_master (b, bp_std_terminate,
6816                                           &momentary_breakpoint_ops);
6817       }
6818 }
6819
6820 /* Delete all the std::terminate breakpoints.  */
6821 void
6822 delete_std_terminate_breakpoint (void)
6823 {
6824   struct breakpoint *b, *b_tmp;
6825
6826   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6827     if (b->type == bp_std_terminate)
6828       delete_breakpoint (b);
6829 }
6830
6831 struct breakpoint *
6832 create_thread_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6833 {
6834   struct breakpoint *b;
6835
6836   b = create_internal_breakpoint (gdbarch, address, bp_thread_event,
6837                                   &internal_breakpoint_ops);
6838
6839   b->enable_state = bp_enabled;
6840   /* addr_string has to be used or breakpoint_re_set will delete me.  */
6841   b->addr_string
6842     = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
6843
6844   update_global_location_list_nothrow (1);
6845
6846   return b;
6847 }
6848
6849 void
6850 remove_thread_event_breakpoints (void)
6851 {
6852   struct breakpoint *b, *b_tmp;
6853
6854   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6855     if (b->type == bp_thread_event
6856         && b->loc->pspace == current_program_space)
6857       delete_breakpoint (b);
6858 }
6859
6860 struct lang_and_radix
6861   {
6862     enum language lang;
6863     int radix;
6864   };
6865
6866 /* Create a breakpoint for JIT code registration and unregistration.  */
6867
6868 struct breakpoint *
6869 create_jit_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6870 {
6871   struct breakpoint *b;
6872
6873   b = create_internal_breakpoint (gdbarch, address, bp_jit_event,
6874                                   &internal_breakpoint_ops);
6875   update_global_location_list_nothrow (1);
6876   return b;
6877 }
6878
6879 /* Remove JIT code registration and unregistration breakpoint(s).  */
6880
6881 void
6882 remove_jit_event_breakpoints (void)
6883 {
6884   struct breakpoint *b, *b_tmp;
6885
6886   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6887     if (b->type == bp_jit_event
6888         && b->loc->pspace == current_program_space)
6889       delete_breakpoint (b);
6890 }
6891
6892 void
6893 remove_solib_event_breakpoints (void)
6894 {
6895   struct breakpoint *b, *b_tmp;
6896
6897   ALL_BREAKPOINTS_SAFE (b, b_tmp)
6898     if (b->type == bp_shlib_event
6899         && b->loc->pspace == current_program_space)
6900       delete_breakpoint (b);
6901 }
6902
6903 struct breakpoint *
6904 create_solib_event_breakpoint (struct gdbarch *gdbarch, CORE_ADDR address)
6905 {
6906   struct breakpoint *b;
6907
6908   b = create_internal_breakpoint (gdbarch, address, bp_shlib_event,
6909                                   &internal_breakpoint_ops);
6910   update_global_location_list_nothrow (1);
6911   return b;
6912 }
6913
6914 /* Disable any breakpoints that are on code in shared libraries.  Only
6915    apply to enabled breakpoints, disabled ones can just stay disabled.  */
6916
6917 void
6918 disable_breakpoints_in_shlibs (void)
6919 {
6920   struct bp_location *loc, **locp_tmp;
6921
6922   ALL_BP_LOCATIONS (loc, locp_tmp)
6923   {
6924     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6925     struct breakpoint *b = loc->owner;
6926
6927     /* We apply the check to all breakpoints, including disabled for
6928        those with loc->duplicate set.  This is so that when breakpoint
6929        becomes enabled, or the duplicate is removed, gdb will try to
6930        insert all breakpoints.  If we don't set shlib_disabled here,
6931        we'll try to insert those breakpoints and fail.  */
6932     if (((b->type == bp_breakpoint)
6933          || (b->type == bp_jit_event)
6934          || (b->type == bp_hardware_breakpoint)
6935          || (is_tracepoint (b)))
6936         && loc->pspace == current_program_space
6937         && !loc->shlib_disabled
6938 #ifdef PC_SOLIB
6939         && PC_SOLIB (loc->address)
6940 #else
6941         && solib_name_from_address (loc->pspace, loc->address)
6942 #endif
6943         )
6944       {
6945         loc->shlib_disabled = 1;
6946       }
6947   }
6948 }
6949
6950 /* Disable any breakpoints and tracepoints that are in an unloaded shared
6951    library.  Only apply to enabled breakpoints, disabled ones can just stay
6952    disabled.  */
6953
6954 static void
6955 disable_breakpoints_in_unloaded_shlib (struct so_list *solib)
6956 {
6957   struct bp_location *loc, **locp_tmp;
6958   int disabled_shlib_breaks = 0;
6959
6960   /* SunOS a.out shared libraries are always mapped, so do not
6961      disable breakpoints; they will only be reported as unloaded
6962      through clear_solib when GDB discards its shared library
6963      list.  See clear_solib for more information.  */
6964   if (exec_bfd != NULL
6965       && bfd_get_flavour (exec_bfd) == bfd_target_aout_flavour)
6966     return;
6967
6968   ALL_BP_LOCATIONS (loc, locp_tmp)
6969   {
6970     /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always non-NULL.  */
6971     struct breakpoint *b = loc->owner;
6972
6973     if (solib->pspace == loc->pspace
6974         && !loc->shlib_disabled
6975         && (((b->type == bp_breakpoint
6976               || b->type == bp_jit_event
6977               || b->type == bp_hardware_breakpoint)
6978              && (loc->loc_type == bp_loc_hardware_breakpoint
6979                  || loc->loc_type == bp_loc_software_breakpoint))
6980             || is_tracepoint (b))
6981         && solib_contains_address_p (solib, loc->address))
6982       {
6983         loc->shlib_disabled = 1;
6984         /* At this point, we cannot rely on remove_breakpoint
6985            succeeding so we must mark the breakpoint as not inserted
6986            to prevent future errors occurring in remove_breakpoints.  */
6987         loc->inserted = 0;
6988
6989         /* This may cause duplicate notifications for the same breakpoint.  */
6990         observer_notify_breakpoint_modified (b);
6991
6992         if (!disabled_shlib_breaks)
6993           {
6994             target_terminal_ours_for_output ();
6995             warning (_("Temporarily disabling breakpoints "
6996                        "for unloaded shared library \"%s\""),
6997                      solib->so_name);
6998           }
6999         disabled_shlib_breaks = 1;
7000       }
7001   }
7002 }
7003
7004 /* FORK & VFORK catchpoints.  */
7005
7006 /* An instance of this type is used to represent a fork or vfork
7007    catchpoint.  It includes a "struct breakpoint" as a kind of base
7008    class; users downcast to "struct breakpoint *" when needed.  A
7009    breakpoint is really of this type iff its ops pointer points to
7010    CATCH_FORK_BREAKPOINT_OPS.  */
7011
7012 struct fork_catchpoint
7013 {
7014   /* The base class.  */
7015   struct breakpoint base;
7016
7017   /* Process id of a child process whose forking triggered this
7018      catchpoint.  This field is only valid immediately after this
7019      catchpoint has triggered.  */
7020   ptid_t forked_inferior_pid;
7021 };
7022
7023 /* Implement the "insert" breakpoint_ops method for fork
7024    catchpoints.  */
7025
7026 static int
7027 insert_catch_fork (struct bp_location *bl)
7028 {
7029   return target_insert_fork_catchpoint (PIDGET (inferior_ptid));
7030 }
7031
7032 /* Implement the "remove" breakpoint_ops method for fork
7033    catchpoints.  */
7034
7035 static int
7036 remove_catch_fork (struct bp_location *bl)
7037 {
7038   return target_remove_fork_catchpoint (PIDGET (inferior_ptid));
7039 }
7040
7041 /* Implement the "breakpoint_hit" breakpoint_ops method for fork
7042    catchpoints.  */
7043
7044 static int
7045 breakpoint_hit_catch_fork (const struct bp_location *bl,
7046                            struct address_space *aspace, CORE_ADDR bp_addr,
7047                            const struct target_waitstatus *ws)
7048 {
7049   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7050
7051   if (ws->kind != TARGET_WAITKIND_FORKED)
7052     return 0;
7053
7054   c->forked_inferior_pid = ws->value.related_pid;
7055   return 1;
7056 }
7057
7058 /* Implement the "print_it" breakpoint_ops method for fork
7059    catchpoints.  */
7060
7061 static enum print_stop_action
7062 print_it_catch_fork (bpstat bs)
7063 {
7064   struct ui_out *uiout = current_uiout;
7065   struct breakpoint *b = bs->breakpoint_at;
7066   struct fork_catchpoint *c = (struct fork_catchpoint *) bs->breakpoint_at;
7067
7068   annotate_catchpoint (b->number);
7069   if (b->disposition == disp_del)
7070     ui_out_text (uiout, "\nTemporary catchpoint ");
7071   else
7072     ui_out_text (uiout, "\nCatchpoint ");
7073   if (ui_out_is_mi_like_p (uiout))
7074     {
7075       ui_out_field_string (uiout, "reason",
7076                            async_reason_lookup (EXEC_ASYNC_FORK));
7077       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7078     }
7079   ui_out_field_int (uiout, "bkptno", b->number);
7080   ui_out_text (uiout, " (forked process ");
7081   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7082   ui_out_text (uiout, "), ");
7083   return PRINT_SRC_AND_LOC;
7084 }
7085
7086 /* Implement the "print_one" breakpoint_ops method for fork
7087    catchpoints.  */
7088
7089 static void
7090 print_one_catch_fork (struct breakpoint *b, struct bp_location **last_loc)
7091 {
7092   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7093   struct value_print_options opts;
7094   struct ui_out *uiout = current_uiout;
7095
7096   get_user_print_options (&opts);
7097
7098   /* Field 4, the address, is omitted (which makes the columns not
7099      line up too nicely with the headers, but the effect is relatively
7100      readable).  */
7101   if (opts.addressprint)
7102     ui_out_field_skip (uiout, "addr");
7103   annotate_field (5);
7104   ui_out_text (uiout, "fork");
7105   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7106     {
7107       ui_out_text (uiout, ", process ");
7108       ui_out_field_int (uiout, "what",
7109                         ptid_get_pid (c->forked_inferior_pid));
7110       ui_out_spaces (uiout, 1);
7111     }
7112 }
7113
7114 /* Implement the "print_mention" breakpoint_ops method for fork
7115    catchpoints.  */
7116
7117 static void
7118 print_mention_catch_fork (struct breakpoint *b)
7119 {
7120   printf_filtered (_("Catchpoint %d (fork)"), b->number);
7121 }
7122
7123 /* Implement the "print_recreate" breakpoint_ops method for fork
7124    catchpoints.  */
7125
7126 static void
7127 print_recreate_catch_fork (struct breakpoint *b, struct ui_file *fp)
7128 {
7129   fprintf_unfiltered (fp, "catch fork");
7130   print_recreate_thread (b, fp);
7131 }
7132
7133 /* The breakpoint_ops structure to be used in fork catchpoints.  */
7134
7135 static struct breakpoint_ops catch_fork_breakpoint_ops;
7136
7137 /* Implement the "insert" breakpoint_ops method for vfork
7138    catchpoints.  */
7139
7140 static int
7141 insert_catch_vfork (struct bp_location *bl)
7142 {
7143   return target_insert_vfork_catchpoint (PIDGET (inferior_ptid));
7144 }
7145
7146 /* Implement the "remove" breakpoint_ops method for vfork
7147    catchpoints.  */
7148
7149 static int
7150 remove_catch_vfork (struct bp_location *bl)
7151 {
7152   return target_remove_vfork_catchpoint (PIDGET (inferior_ptid));
7153 }
7154
7155 /* Implement the "breakpoint_hit" breakpoint_ops method for vfork
7156    catchpoints.  */
7157
7158 static int
7159 breakpoint_hit_catch_vfork (const struct bp_location *bl,
7160                             struct address_space *aspace, CORE_ADDR bp_addr,
7161                             const struct target_waitstatus *ws)
7162 {
7163   struct fork_catchpoint *c = (struct fork_catchpoint *) bl->owner;
7164
7165   if (ws->kind != TARGET_WAITKIND_VFORKED)
7166     return 0;
7167
7168   c->forked_inferior_pid = ws->value.related_pid;
7169   return 1;
7170 }
7171
7172 /* Implement the "print_it" breakpoint_ops method for vfork
7173    catchpoints.  */
7174
7175 static enum print_stop_action
7176 print_it_catch_vfork (bpstat bs)
7177 {
7178   struct ui_out *uiout = current_uiout;
7179   struct breakpoint *b = bs->breakpoint_at;
7180   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7181
7182   annotate_catchpoint (b->number);
7183   if (b->disposition == disp_del)
7184     ui_out_text (uiout, "\nTemporary catchpoint ");
7185   else
7186     ui_out_text (uiout, "\nCatchpoint ");
7187   if (ui_out_is_mi_like_p (uiout))
7188     {
7189       ui_out_field_string (uiout, "reason",
7190                            async_reason_lookup (EXEC_ASYNC_VFORK));
7191       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7192     }
7193   ui_out_field_int (uiout, "bkptno", b->number);
7194   ui_out_text (uiout, " (vforked process ");
7195   ui_out_field_int (uiout, "newpid", ptid_get_pid (c->forked_inferior_pid));
7196   ui_out_text (uiout, "), ");
7197   return PRINT_SRC_AND_LOC;
7198 }
7199
7200 /* Implement the "print_one" breakpoint_ops method for vfork
7201    catchpoints.  */
7202
7203 static void
7204 print_one_catch_vfork (struct breakpoint *b, struct bp_location **last_loc)
7205 {
7206   struct fork_catchpoint *c = (struct fork_catchpoint *) b;
7207   struct value_print_options opts;
7208   struct ui_out *uiout = current_uiout;
7209
7210   get_user_print_options (&opts);
7211   /* Field 4, the address, is omitted (which makes the columns not
7212      line up too nicely with the headers, but the effect is relatively
7213      readable).  */
7214   if (opts.addressprint)
7215     ui_out_field_skip (uiout, "addr");
7216   annotate_field (5);
7217   ui_out_text (uiout, "vfork");
7218   if (!ptid_equal (c->forked_inferior_pid, null_ptid))
7219     {
7220       ui_out_text (uiout, ", process ");
7221       ui_out_field_int (uiout, "what",
7222                         ptid_get_pid (c->forked_inferior_pid));
7223       ui_out_spaces (uiout, 1);
7224     }
7225 }
7226
7227 /* Implement the "print_mention" breakpoint_ops method for vfork
7228    catchpoints.  */
7229
7230 static void
7231 print_mention_catch_vfork (struct breakpoint *b)
7232 {
7233   printf_filtered (_("Catchpoint %d (vfork)"), b->number);
7234 }
7235
7236 /* Implement the "print_recreate" breakpoint_ops method for vfork
7237    catchpoints.  */
7238
7239 static void
7240 print_recreate_catch_vfork (struct breakpoint *b, struct ui_file *fp)
7241 {
7242   fprintf_unfiltered (fp, "catch vfork");
7243   print_recreate_thread (b, fp);
7244 }
7245
7246 /* The breakpoint_ops structure to be used in vfork catchpoints.  */
7247
7248 static struct breakpoint_ops catch_vfork_breakpoint_ops;
7249
7250 /* An instance of this type is used to represent an solib catchpoint.
7251    It includes a "struct breakpoint" as a kind of base class; users
7252    downcast to "struct breakpoint *" when needed.  A breakpoint is
7253    really of this type iff its ops pointer points to
7254    CATCH_SOLIB_BREAKPOINT_OPS.  */
7255
7256 struct solib_catchpoint
7257 {
7258   /* The base class.  */
7259   struct breakpoint base;
7260
7261   /* True for "catch load", false for "catch unload".  */
7262   unsigned char is_load;
7263
7264   /* Regular expression to match, if any.  COMPILED is only valid when
7265      REGEX is non-NULL.  */
7266   char *regex;
7267   regex_t compiled;
7268 };
7269
7270 static void
7271 dtor_catch_solib (struct breakpoint *b)
7272 {
7273   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7274
7275   if (self->regex)
7276     regfree (&self->compiled);
7277   xfree (self->regex);
7278
7279   base_breakpoint_ops.dtor (b);
7280 }
7281
7282 static int
7283 insert_catch_solib (struct bp_location *ignore)
7284 {
7285   return 0;
7286 }
7287
7288 static int
7289 remove_catch_solib (struct bp_location *ignore)
7290 {
7291   return 0;
7292 }
7293
7294 static int
7295 breakpoint_hit_catch_solib (const struct bp_location *bl,
7296                             struct address_space *aspace,
7297                             CORE_ADDR bp_addr,
7298                             const struct target_waitstatus *ws)
7299 {
7300   struct solib_catchpoint *self = (struct solib_catchpoint *) bl->owner;
7301   struct breakpoint *other;
7302
7303   if (ws->kind == TARGET_WAITKIND_LOADED)
7304     return 1;
7305
7306   ALL_BREAKPOINTS (other)
7307   {
7308     struct bp_location *other_bl;
7309
7310     if (other == bl->owner)
7311       continue;
7312
7313     if (other->type != bp_shlib_event)
7314       continue;
7315
7316     if (self->base.pspace != NULL && other->pspace != self->base.pspace)
7317       continue;
7318
7319     for (other_bl = other->loc; other_bl != NULL; other_bl = other_bl->next)
7320       {
7321         if (other->ops->breakpoint_hit (other_bl, aspace, bp_addr, ws))
7322           return 1;
7323       }
7324   }
7325
7326   return 0;
7327 }
7328
7329 static void
7330 check_status_catch_solib (struct bpstats *bs)
7331 {
7332   struct solib_catchpoint *self
7333     = (struct solib_catchpoint *) bs->breakpoint_at;
7334   int ix;
7335
7336   if (self->is_load)
7337     {
7338       struct so_list *iter;
7339
7340       for (ix = 0;
7341            VEC_iterate (so_list_ptr, current_program_space->added_solibs,
7342                         ix, iter);
7343            ++ix)
7344         {
7345           if (!self->regex
7346               || regexec (&self->compiled, iter->so_name, 0, NULL, 0) == 0)
7347             return;
7348         }
7349     }
7350   else
7351     {
7352       char *iter;
7353
7354       for (ix = 0;
7355            VEC_iterate (char_ptr, current_program_space->deleted_solibs,
7356                         ix, iter);
7357            ++ix)
7358         {
7359           if (!self->regex
7360               || regexec (&self->compiled, iter, 0, NULL, 0) == 0)
7361             return;
7362         }
7363     }
7364
7365   bs->stop = 0;
7366   bs->print_it = print_it_noop;
7367 }
7368
7369 static enum print_stop_action
7370 print_it_catch_solib (bpstat bs)
7371 {
7372   struct breakpoint *b = bs->breakpoint_at;
7373   struct ui_out *uiout = current_uiout;
7374
7375   annotate_catchpoint (b->number);
7376   if (b->disposition == disp_del)
7377     ui_out_text (uiout, "\nTemporary catchpoint ");
7378   else
7379     ui_out_text (uiout, "\nCatchpoint ");
7380   ui_out_field_int (uiout, "bkptno", b->number);
7381   ui_out_text (uiout, "\n");
7382   if (ui_out_is_mi_like_p (uiout))
7383     ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7384   print_solib_event (1);
7385   return PRINT_SRC_AND_LOC;
7386 }
7387
7388 static void
7389 print_one_catch_solib (struct breakpoint *b, struct bp_location **locs)
7390 {
7391   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7392   struct value_print_options opts;
7393   struct ui_out *uiout = current_uiout;
7394   char *msg;
7395
7396   get_user_print_options (&opts);
7397   /* Field 4, the address, is omitted (which makes the columns not
7398      line up too nicely with the headers, but the effect is relatively
7399      readable).  */
7400   if (opts.addressprint)
7401     {
7402       annotate_field (4);
7403       ui_out_field_skip (uiout, "addr");
7404     }
7405
7406   annotate_field (5);
7407   if (self->is_load)
7408     {
7409       if (self->regex)
7410         msg = xstrprintf (_("load of library matching %s"), self->regex);
7411       else
7412         msg = xstrdup (_("load of library"));
7413     }
7414   else
7415     {
7416       if (self->regex)
7417         msg = xstrprintf (_("unload of library matching %s"), self->regex);
7418       else
7419         msg = xstrdup (_("unload of library"));
7420     }
7421   ui_out_field_string (uiout, "what", msg);
7422   xfree (msg);
7423 }
7424
7425 static void
7426 print_mention_catch_solib (struct breakpoint *b)
7427 {
7428   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7429
7430   printf_filtered (_("Catchpoint %d (%s)"), b->number,
7431                    self->is_load ? "load" : "unload");
7432 }
7433
7434 static void
7435 print_recreate_catch_solib (struct breakpoint *b, struct ui_file *fp)
7436 {
7437   struct solib_catchpoint *self = (struct solib_catchpoint *) b;
7438
7439   fprintf_unfiltered (fp, "%s %s",
7440                       b->disposition == disp_del ? "tcatch" : "catch",
7441                       self->is_load ? "load" : "unload");
7442   if (self->regex)
7443     fprintf_unfiltered (fp, " %s", self->regex);
7444   fprintf_unfiltered (fp, "\n");
7445 }
7446
7447 static struct breakpoint_ops catch_solib_breakpoint_ops;
7448
7449 /* A helper function that does all the work for "catch load" and
7450    "catch unload".  */
7451
7452 static void
7453 catch_load_or_unload (char *arg, int from_tty, int is_load,
7454                       struct cmd_list_element *command)
7455 {
7456   struct solib_catchpoint *c;
7457   struct gdbarch *gdbarch = get_current_arch ();
7458   int tempflag;
7459   regex_t compiled;
7460   struct cleanup *cleanup;
7461
7462   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
7463
7464   if (!arg)
7465     arg = "";
7466   arg = skip_spaces (arg);
7467
7468   c = XCNEW (struct solib_catchpoint);
7469   cleanup = make_cleanup (xfree, c);
7470
7471   if (*arg != '\0')
7472     {
7473       int errcode;
7474
7475       errcode = regcomp (&c->compiled, arg, REG_NOSUB);
7476       if (errcode != 0)
7477         {
7478           char *err = get_regcomp_error (errcode, &c->compiled);
7479
7480           make_cleanup (xfree, err);
7481           error (_("Invalid regexp (%s): %s"), err, arg);
7482         }
7483       c->regex = xstrdup (arg);
7484     }
7485
7486   c->is_load = is_load;
7487   init_catchpoint (&c->base, gdbarch, tempflag, NULL,
7488                    &catch_solib_breakpoint_ops);
7489
7490   discard_cleanups (cleanup);
7491   install_breakpoint (0, &c->base, 1);
7492 }
7493
7494 static void
7495 catch_load_command_1 (char *arg, int from_tty,
7496                       struct cmd_list_element *command)
7497 {
7498   catch_load_or_unload (arg, from_tty, 1, command);
7499 }
7500
7501 static void
7502 catch_unload_command_1 (char *arg, int from_tty,
7503                         struct cmd_list_element *command)
7504 {
7505   catch_load_or_unload (arg, from_tty, 0, command);
7506 }
7507
7508 DEF_VEC_I(int);
7509
7510 /* An instance of this type is used to represent a syscall catchpoint.
7511    It includes a "struct breakpoint" as a kind of base class; users
7512    downcast to "struct breakpoint *" when needed.  A breakpoint is
7513    really of this type iff its ops pointer points to
7514    CATCH_SYSCALL_BREAKPOINT_OPS.  */
7515
7516 struct syscall_catchpoint
7517 {
7518   /* The base class.  */
7519   struct breakpoint base;
7520
7521   /* Syscall numbers used for the 'catch syscall' feature.  If no
7522      syscall has been specified for filtering, its value is NULL.
7523      Otherwise, it holds a list of all syscalls to be caught.  The
7524      list elements are allocated with xmalloc.  */
7525   VEC(int) *syscalls_to_be_caught;
7526 };
7527
7528 /* Implement the "dtor" breakpoint_ops method for syscall
7529    catchpoints.  */
7530
7531 static void
7532 dtor_catch_syscall (struct breakpoint *b)
7533 {
7534   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7535
7536   VEC_free (int, c->syscalls_to_be_caught);
7537
7538   base_breakpoint_ops.dtor (b);
7539 }
7540
7541 static const struct inferior_data *catch_syscall_inferior_data = NULL;
7542
7543 struct catch_syscall_inferior_data
7544 {
7545   /* We keep a count of the number of times the user has requested a
7546      particular syscall to be tracked, and pass this information to the
7547      target.  This lets capable targets implement filtering directly.  */
7548
7549   /* Number of times that "any" syscall is requested.  */
7550   int any_syscall_count;
7551
7552   /* Count of each system call.  */
7553   VEC(int) *syscalls_counts;
7554
7555   /* This counts all syscall catch requests, so we can readily determine
7556      if any catching is necessary.  */
7557   int total_syscalls_count;
7558 };
7559
7560 static struct catch_syscall_inferior_data*
7561 get_catch_syscall_inferior_data (struct inferior *inf)
7562 {
7563   struct catch_syscall_inferior_data *inf_data;
7564
7565   inf_data = inferior_data (inf, catch_syscall_inferior_data);
7566   if (inf_data == NULL)
7567     {
7568       inf_data = XZALLOC (struct catch_syscall_inferior_data);
7569       set_inferior_data (inf, catch_syscall_inferior_data, inf_data);
7570     }
7571
7572   return inf_data;
7573 }
7574
7575 static void
7576 catch_syscall_inferior_data_cleanup (struct inferior *inf, void *arg)
7577 {
7578   xfree (arg);
7579 }
7580
7581
7582 /* Implement the "insert" breakpoint_ops method for syscall
7583    catchpoints.  */
7584
7585 static int
7586 insert_catch_syscall (struct bp_location *bl)
7587 {
7588   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7589   struct inferior *inf = current_inferior ();
7590   struct catch_syscall_inferior_data *inf_data
7591     = get_catch_syscall_inferior_data (inf);
7592
7593   ++inf_data->total_syscalls_count;
7594   if (!c->syscalls_to_be_caught)
7595     ++inf_data->any_syscall_count;
7596   else
7597     {
7598       int i, iter;
7599
7600       for (i = 0;
7601            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7602            i++)
7603         {
7604           int elem;
7605
7606           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7607             {
7608               int old_size = VEC_length (int, inf_data->syscalls_counts);
7609               uintptr_t vec_addr_offset
7610                 = old_size * ((uintptr_t) sizeof (int));
7611               uintptr_t vec_addr;
7612               VEC_safe_grow (int, inf_data->syscalls_counts, iter + 1);
7613               vec_addr = ((uintptr_t) VEC_address (int,
7614                                                   inf_data->syscalls_counts)
7615                           + vec_addr_offset);
7616               memset ((void *) vec_addr, 0,
7617                       (iter + 1 - old_size) * sizeof (int));
7618             }
7619           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7620           VEC_replace (int, inf_data->syscalls_counts, iter, ++elem);
7621         }
7622     }
7623
7624   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7625                                         inf_data->total_syscalls_count != 0,
7626                                         inf_data->any_syscall_count,
7627                                         VEC_length (int,
7628                                                     inf_data->syscalls_counts),
7629                                         VEC_address (int,
7630                                                      inf_data->syscalls_counts));
7631 }
7632
7633 /* Implement the "remove" breakpoint_ops method for syscall
7634    catchpoints.  */
7635
7636 static int
7637 remove_catch_syscall (struct bp_location *bl)
7638 {
7639   struct syscall_catchpoint *c = (struct syscall_catchpoint *) bl->owner;
7640   struct inferior *inf = current_inferior ();
7641   struct catch_syscall_inferior_data *inf_data
7642     = get_catch_syscall_inferior_data (inf);
7643
7644   --inf_data->total_syscalls_count;
7645   if (!c->syscalls_to_be_caught)
7646     --inf_data->any_syscall_count;
7647   else
7648     {
7649       int i, iter;
7650
7651       for (i = 0;
7652            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7653            i++)
7654         {
7655           int elem;
7656           if (iter >= VEC_length (int, inf_data->syscalls_counts))
7657             /* Shouldn't happen.  */
7658             continue;
7659           elem = VEC_index (int, inf_data->syscalls_counts, iter);
7660           VEC_replace (int, inf_data->syscalls_counts, iter, --elem);
7661         }
7662     }
7663
7664   return target_set_syscall_catchpoint (PIDGET (inferior_ptid),
7665                                         inf_data->total_syscalls_count != 0,
7666                                         inf_data->any_syscall_count,
7667                                         VEC_length (int,
7668                                                     inf_data->syscalls_counts),
7669                                         VEC_address (int,
7670                                                      inf_data->syscalls_counts));
7671 }
7672
7673 /* Implement the "breakpoint_hit" breakpoint_ops method for syscall
7674    catchpoints.  */
7675
7676 static int
7677 breakpoint_hit_catch_syscall (const struct bp_location *bl,
7678                               struct address_space *aspace, CORE_ADDR bp_addr,
7679                               const struct target_waitstatus *ws)
7680 {
7681   /* We must check if we are catching specific syscalls in this
7682      breakpoint.  If we are, then we must guarantee that the called
7683      syscall is the same syscall we are catching.  */
7684   int syscall_number = 0;
7685   const struct syscall_catchpoint *c
7686     = (const struct syscall_catchpoint *) bl->owner;
7687
7688   if (ws->kind != TARGET_WAITKIND_SYSCALL_ENTRY
7689       && ws->kind != TARGET_WAITKIND_SYSCALL_RETURN)
7690     return 0;
7691
7692   syscall_number = ws->value.syscall_number;
7693
7694   /* Now, checking if the syscall is the same.  */
7695   if (c->syscalls_to_be_caught)
7696     {
7697       int i, iter;
7698
7699       for (i = 0;
7700            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7701            i++)
7702         if (syscall_number == iter)
7703           break;
7704       /* Not the same.  */
7705       if (!iter)
7706         return 0;
7707     }
7708
7709   return 1;
7710 }
7711
7712 /* Implement the "print_it" breakpoint_ops method for syscall
7713    catchpoints.  */
7714
7715 static enum print_stop_action
7716 print_it_catch_syscall (bpstat bs)
7717 {
7718   struct ui_out *uiout = current_uiout;
7719   struct breakpoint *b = bs->breakpoint_at;
7720   /* These are needed because we want to know in which state a
7721      syscall is.  It can be in the TARGET_WAITKIND_SYSCALL_ENTRY
7722      or TARGET_WAITKIND_SYSCALL_RETURN, and depending on it we
7723      must print "called syscall" or "returned from syscall".  */
7724   ptid_t ptid;
7725   struct target_waitstatus last;
7726   struct syscall s;
7727   char *syscall_id;
7728
7729   get_last_target_status (&ptid, &last);
7730
7731   get_syscall_by_number (last.value.syscall_number, &s);
7732
7733   annotate_catchpoint (b->number);
7734
7735   if (b->disposition == disp_del)
7736     ui_out_text (uiout, "\nTemporary catchpoint ");
7737   else
7738     ui_out_text (uiout, "\nCatchpoint ");
7739   if (ui_out_is_mi_like_p (uiout))
7740     {
7741       ui_out_field_string (uiout, "reason",
7742                            async_reason_lookup (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY
7743                                                 ? EXEC_ASYNC_SYSCALL_ENTRY
7744                                                 : EXEC_ASYNC_SYSCALL_RETURN));
7745       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
7746     }
7747   ui_out_field_int (uiout, "bkptno", b->number);
7748
7749   if (last.kind == TARGET_WAITKIND_SYSCALL_ENTRY)
7750     ui_out_text (uiout, " (call to syscall ");
7751   else
7752     ui_out_text (uiout, " (returned from syscall ");
7753
7754   if (s.name == NULL || ui_out_is_mi_like_p (uiout))
7755     ui_out_field_int (uiout, "syscall-number", last.value.syscall_number);
7756   if (s.name != NULL)
7757     ui_out_field_string (uiout, "syscall-name", s.name);
7758
7759   ui_out_text (uiout, "), ");
7760
7761   return PRINT_SRC_AND_LOC;
7762 }
7763
7764 /* Implement the "print_one" breakpoint_ops method for syscall
7765    catchpoints.  */
7766
7767 static void
7768 print_one_catch_syscall (struct breakpoint *b,
7769                          struct bp_location **last_loc)
7770 {
7771   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7772   struct value_print_options opts;
7773   struct ui_out *uiout = current_uiout;
7774
7775   get_user_print_options (&opts);
7776   /* Field 4, the address, is omitted (which makes the columns not
7777      line up too nicely with the headers, but the effect is relatively
7778      readable).  */
7779   if (opts.addressprint)
7780     ui_out_field_skip (uiout, "addr");
7781   annotate_field (5);
7782
7783   if (c->syscalls_to_be_caught
7784       && VEC_length (int, c->syscalls_to_be_caught) > 1)
7785     ui_out_text (uiout, "syscalls \"");
7786   else
7787     ui_out_text (uiout, "syscall \"");
7788
7789   if (c->syscalls_to_be_caught)
7790     {
7791       int i, iter;
7792       char *text = xstrprintf ("%s", "");
7793
7794       for (i = 0;
7795            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7796            i++)
7797         {
7798           char *x = text;
7799           struct syscall s;
7800           get_syscall_by_number (iter, &s);
7801
7802           if (s.name != NULL)
7803             text = xstrprintf ("%s%s, ", text, s.name);
7804           else
7805             text = xstrprintf ("%s%d, ", text, iter);
7806
7807           /* We have to xfree the last 'text' (now stored at 'x')
7808              because xstrprintf dynamically allocates new space for it
7809              on every call.  */
7810           xfree (x);
7811         }
7812       /* Remove the last comma.  */
7813       text[strlen (text) - 2] = '\0';
7814       ui_out_field_string (uiout, "what", text);
7815     }
7816   else
7817     ui_out_field_string (uiout, "what", "<any syscall>");
7818   ui_out_text (uiout, "\" ");
7819 }
7820
7821 /* Implement the "print_mention" breakpoint_ops method for syscall
7822    catchpoints.  */
7823
7824 static void
7825 print_mention_catch_syscall (struct breakpoint *b)
7826 {
7827   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7828
7829   if (c->syscalls_to_be_caught)
7830     {
7831       int i, iter;
7832
7833       if (VEC_length (int, c->syscalls_to_be_caught) > 1)
7834         printf_filtered (_("Catchpoint %d (syscalls"), b->number);
7835       else
7836         printf_filtered (_("Catchpoint %d (syscall"), b->number);
7837
7838       for (i = 0;
7839            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7840            i++)
7841         {
7842           struct syscall s;
7843           get_syscall_by_number (iter, &s);
7844
7845           if (s.name)
7846             printf_filtered (" '%s' [%d]", s.name, s.number);
7847           else
7848             printf_filtered (" %d", s.number);
7849         }
7850       printf_filtered (")");
7851     }
7852   else
7853     printf_filtered (_("Catchpoint %d (any syscall)"),
7854                      b->number);
7855 }
7856
7857 /* Implement the "print_recreate" breakpoint_ops method for syscall
7858    catchpoints.  */
7859
7860 static void
7861 print_recreate_catch_syscall (struct breakpoint *b, struct ui_file *fp)
7862 {
7863   struct syscall_catchpoint *c = (struct syscall_catchpoint *) b;
7864
7865   fprintf_unfiltered (fp, "catch syscall");
7866
7867   if (c->syscalls_to_be_caught)
7868     {
7869       int i, iter;
7870
7871       for (i = 0;
7872            VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
7873            i++)
7874         {
7875           struct syscall s;
7876
7877           get_syscall_by_number (iter, &s);
7878           if (s.name)
7879             fprintf_unfiltered (fp, " %s", s.name);
7880           else
7881             fprintf_unfiltered (fp, " %d", s.number);
7882         }
7883     }
7884   print_recreate_thread (b, fp);
7885 }
7886
7887 /* The breakpoint_ops structure to be used in syscall catchpoints.  */
7888
7889 static struct breakpoint_ops catch_syscall_breakpoint_ops;
7890
7891 /* Returns non-zero if 'b' is a syscall catchpoint.  */
7892
7893 static int
7894 syscall_catchpoint_p (struct breakpoint *b)
7895 {
7896   return (b->ops == &catch_syscall_breakpoint_ops);
7897 }
7898
7899 /* Initialize a new breakpoint of the bp_catchpoint kind.  If TEMPFLAG
7900    is non-zero, then make the breakpoint temporary.  If COND_STRING is
7901    not NULL, then store it in the breakpoint.  OPS, if not NULL, is
7902    the breakpoint_ops structure associated to the catchpoint.  */
7903
7904 static void
7905 init_catchpoint (struct breakpoint *b,
7906                  struct gdbarch *gdbarch, int tempflag,
7907                  char *cond_string,
7908                  const struct breakpoint_ops *ops)
7909 {
7910   struct symtab_and_line sal;
7911
7912   init_sal (&sal);
7913   sal.pspace = current_program_space;
7914
7915   init_raw_breakpoint (b, gdbarch, sal, bp_catchpoint, ops);
7916
7917   b->cond_string = (cond_string == NULL) ? NULL : xstrdup (cond_string);
7918   b->disposition = tempflag ? disp_del : disp_donttouch;
7919 }
7920
7921 void
7922 install_breakpoint (int internal, struct breakpoint *b, int update_gll)
7923 {
7924   add_to_breakpoint_chain (b);
7925   set_breakpoint_number (internal, b);
7926   if (!internal)
7927     mention (b);
7928   observer_notify_breakpoint_created (b);
7929
7930   if (update_gll)
7931     update_global_location_list (1);
7932 }
7933
7934 static void
7935 create_fork_vfork_event_catchpoint (struct gdbarch *gdbarch,
7936                                     int tempflag, char *cond_string,
7937                                     const struct breakpoint_ops *ops)
7938 {
7939   struct fork_catchpoint *c = XNEW (struct fork_catchpoint);
7940
7941   init_catchpoint (&c->base, gdbarch, tempflag, cond_string, ops);
7942
7943   c->forked_inferior_pid = null_ptid;
7944
7945   install_breakpoint (0, &c->base, 1);
7946 }
7947
7948 /* Exec catchpoints.  */
7949
7950 /* An instance of this type is used to represent an exec catchpoint.
7951    It includes a "struct breakpoint" as a kind of base class; users
7952    downcast to "struct breakpoint *" when needed.  A breakpoint is
7953    really of this type iff its ops pointer points to
7954    CATCH_EXEC_BREAKPOINT_OPS.  */
7955
7956 struct exec_catchpoint
7957 {
7958   /* The base class.  */
7959   struct breakpoint base;
7960
7961   /* Filename of a program whose exec triggered this catchpoint.
7962      This field is only valid immediately after this catchpoint has
7963      triggered.  */
7964   char *exec_pathname;
7965 };
7966
7967 /* Implement the "dtor" breakpoint_ops method for exec
7968    catchpoints.  */
7969
7970 static void
7971 dtor_catch_exec (struct breakpoint *b)
7972 {
7973   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
7974
7975   xfree (c->exec_pathname);
7976
7977   base_breakpoint_ops.dtor (b);
7978 }
7979
7980 static int
7981 insert_catch_exec (struct bp_location *bl)
7982 {
7983   return target_insert_exec_catchpoint (PIDGET (inferior_ptid));
7984 }
7985
7986 static int
7987 remove_catch_exec (struct bp_location *bl)
7988 {
7989   return target_remove_exec_catchpoint (PIDGET (inferior_ptid));
7990 }
7991
7992 static int
7993 breakpoint_hit_catch_exec (const struct bp_location *bl,
7994                            struct address_space *aspace, CORE_ADDR bp_addr,
7995                            const struct target_waitstatus *ws)
7996 {
7997   struct exec_catchpoint *c = (struct exec_catchpoint *) bl->owner;
7998
7999   if (ws->kind != TARGET_WAITKIND_EXECD)
8000     return 0;
8001
8002   c->exec_pathname = xstrdup (ws->value.execd_pathname);
8003   return 1;
8004 }
8005
8006 static enum print_stop_action
8007 print_it_catch_exec (bpstat bs)
8008 {
8009   struct ui_out *uiout = current_uiout;
8010   struct breakpoint *b = bs->breakpoint_at;
8011   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8012
8013   annotate_catchpoint (b->number);
8014   if (b->disposition == disp_del)
8015     ui_out_text (uiout, "\nTemporary catchpoint ");
8016   else
8017     ui_out_text (uiout, "\nCatchpoint ");
8018   if (ui_out_is_mi_like_p (uiout))
8019     {
8020       ui_out_field_string (uiout, "reason",
8021                            async_reason_lookup (EXEC_ASYNC_EXEC));
8022       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
8023     }
8024   ui_out_field_int (uiout, "bkptno", b->number);
8025   ui_out_text (uiout, " (exec'd ");
8026   ui_out_field_string (uiout, "new-exec", c->exec_pathname);
8027   ui_out_text (uiout, "), ");
8028
8029   return PRINT_SRC_AND_LOC;
8030 }
8031
8032 static void
8033 print_one_catch_exec (struct breakpoint *b, struct bp_location **last_loc)
8034 {
8035   struct exec_catchpoint *c = (struct exec_catchpoint *) b;
8036   struct value_print_options opts;
8037   struct ui_out *uiout = current_uiout;
8038
8039   get_user_print_options (&opts);
8040
8041   /* Field 4, the address, is omitted (which makes the columns
8042      not line up too nicely with the headers, but the effect
8043      is relatively readable).  */
8044   if (opts.addressprint)
8045     ui_out_field_skip (uiout, "addr");
8046   annotate_field (5);
8047   ui_out_text (uiout, "exec");
8048   if (c->exec_pathname != NULL)
8049     {
8050       ui_out_text (uiout, ", program \"");
8051       ui_out_field_string (uiout, "what", c->exec_pathname);
8052       ui_out_text (uiout, "\" ");
8053     }
8054 }
8055
8056 static void
8057 print_mention_catch_exec (struct breakpoint *b)
8058 {
8059   printf_filtered (_("Catchpoint %d (exec)"), b->number);
8060 }
8061
8062 /* Implement the "print_recreate" breakpoint_ops method for exec
8063    catchpoints.  */
8064
8065 static void
8066 print_recreate_catch_exec (struct breakpoint *b, struct ui_file *fp)
8067 {
8068   fprintf_unfiltered (fp, "catch exec");
8069   print_recreate_thread (b, fp);
8070 }
8071
8072 static struct breakpoint_ops catch_exec_breakpoint_ops;
8073
8074 static void
8075 create_syscall_event_catchpoint (int tempflag, VEC(int) *filter,
8076                                  const struct breakpoint_ops *ops)
8077 {
8078   struct syscall_catchpoint *c;
8079   struct gdbarch *gdbarch = get_current_arch ();
8080
8081   c = XNEW (struct syscall_catchpoint);
8082   init_catchpoint (&c->base, gdbarch, tempflag, NULL, ops);
8083   c->syscalls_to_be_caught = filter;
8084
8085   install_breakpoint (0, &c->base, 1);
8086 }
8087
8088 static int
8089 hw_breakpoint_used_count (void)
8090 {
8091   int i = 0;
8092   struct breakpoint *b;
8093   struct bp_location *bl;
8094
8095   ALL_BREAKPOINTS (b)
8096   {
8097     if (b->type == bp_hardware_breakpoint && breakpoint_enabled (b))
8098       for (bl = b->loc; bl; bl = bl->next)
8099         {
8100           /* Special types of hardware breakpoints may use more than
8101              one register.  */
8102           i += b->ops->resources_needed (bl);
8103         }
8104   }
8105
8106   return i;
8107 }
8108
8109 /* Returns the resources B would use if it were a hardware
8110    watchpoint.  */
8111
8112 static int
8113 hw_watchpoint_use_count (struct breakpoint *b)
8114 {
8115   int i = 0;
8116   struct bp_location *bl;
8117
8118   if (!breakpoint_enabled (b))
8119     return 0;
8120
8121   for (bl = b->loc; bl; bl = bl->next)
8122     {
8123       /* Special types of hardware watchpoints may use more than
8124          one register.  */
8125       i += b->ops->resources_needed (bl);
8126     }
8127
8128   return i;
8129 }
8130
8131 /* Returns the sum the used resources of all hardware watchpoints of
8132    type TYPE in the breakpoints list.  Also returns in OTHER_TYPE_USED
8133    the sum of the used resources of all hardware watchpoints of other
8134    types _not_ TYPE.  */
8135
8136 static int
8137 hw_watchpoint_used_count_others (struct breakpoint *except,
8138                                  enum bptype type, int *other_type_used)
8139 {
8140   int i = 0;
8141   struct breakpoint *b;
8142
8143   *other_type_used = 0;
8144   ALL_BREAKPOINTS (b)
8145     {
8146       if (b == except)
8147         continue;
8148       if (!breakpoint_enabled (b))
8149         continue;
8150
8151       if (b->type == type)
8152         i += hw_watchpoint_use_count (b);
8153       else if (is_hardware_watchpoint (b))
8154         *other_type_used = 1;
8155     }
8156
8157   return i;
8158 }
8159
8160 void
8161 disable_watchpoints_before_interactive_call_start (void)
8162 {
8163   struct breakpoint *b;
8164
8165   ALL_BREAKPOINTS (b)
8166   {
8167     if (is_watchpoint (b) && breakpoint_enabled (b))
8168       {
8169         b->enable_state = bp_call_disabled;
8170         update_global_location_list (0);
8171       }
8172   }
8173 }
8174
8175 void
8176 enable_watchpoints_after_interactive_call_stop (void)
8177 {
8178   struct breakpoint *b;
8179
8180   ALL_BREAKPOINTS (b)
8181   {
8182     if (is_watchpoint (b) && b->enable_state == bp_call_disabled)
8183       {
8184         b->enable_state = bp_enabled;
8185         update_global_location_list (1);
8186       }
8187   }
8188 }
8189
8190 void
8191 disable_breakpoints_before_startup (void)
8192 {
8193   current_program_space->executing_startup = 1;
8194   update_global_location_list (0);
8195 }
8196
8197 void
8198 enable_breakpoints_after_startup (void)
8199 {
8200   current_program_space->executing_startup = 0;
8201   breakpoint_re_set ();
8202 }
8203
8204
8205 /* Set a breakpoint that will evaporate an end of command
8206    at address specified by SAL.
8207    Restrict it to frame FRAME if FRAME is nonzero.  */
8208
8209 struct breakpoint *
8210 set_momentary_breakpoint (struct gdbarch *gdbarch, struct symtab_and_line sal,
8211                           struct frame_id frame_id, enum bptype type)
8212 {
8213   struct breakpoint *b;
8214
8215   /* If FRAME_ID is valid, it should be a real frame, not an inlined
8216      one.  */
8217   gdb_assert (!frame_id_inlined_p (frame_id));
8218
8219   b = set_raw_breakpoint (gdbarch, sal, type, &momentary_breakpoint_ops);
8220   b->enable_state = bp_enabled;
8221   b->disposition = disp_donttouch;
8222   b->frame_id = frame_id;
8223
8224   /* If we're debugging a multi-threaded program, then we want
8225      momentary breakpoints to be active in only a single thread of
8226      control.  */
8227   if (in_thread_list (inferior_ptid))
8228     b->thread = pid_to_thread_id (inferior_ptid);
8229
8230   update_global_location_list_nothrow (1);
8231
8232   return b;
8233 }
8234
8235 /* Make a momentary breakpoint based on the master breakpoint ORIG.
8236    The new breakpoint will have type TYPE, and use OPS as it
8237    breakpoint_ops.  */
8238
8239 static struct breakpoint *
8240 momentary_breakpoint_from_master (struct breakpoint *orig,
8241                                   enum bptype type,
8242                                   const struct breakpoint_ops *ops)
8243 {
8244   struct breakpoint *copy;
8245
8246   copy = set_raw_breakpoint_without_location (orig->gdbarch, type, ops);
8247   copy->loc = allocate_bp_location (copy);
8248   set_breakpoint_location_function (copy->loc, 1);
8249
8250   copy->loc->gdbarch = orig->loc->gdbarch;
8251   copy->loc->requested_address = orig->loc->requested_address;
8252   copy->loc->address = orig->loc->address;
8253   copy->loc->section = orig->loc->section;
8254   copy->loc->pspace = orig->loc->pspace;
8255   copy->loc->probe = orig->loc->probe;
8256
8257   if (orig->loc->source_file != NULL)
8258     copy->loc->source_file = xstrdup (orig->loc->source_file);
8259
8260   copy->loc->line_number = orig->loc->line_number;
8261   copy->frame_id = orig->frame_id;
8262   copy->thread = orig->thread;
8263   copy->pspace = orig->pspace;
8264
8265   copy->enable_state = bp_enabled;
8266   copy->disposition = disp_donttouch;
8267   copy->number = internal_breakpoint_number--;
8268
8269   update_global_location_list_nothrow (0);
8270   return copy;
8271 }
8272
8273 /* Make a deep copy of momentary breakpoint ORIG.  Returns NULL if
8274    ORIG is NULL.  */
8275
8276 struct breakpoint *
8277 clone_momentary_breakpoint (struct breakpoint *orig)
8278 {
8279   /* If there's nothing to clone, then return nothing.  */
8280   if (orig == NULL)
8281     return NULL;
8282
8283   return momentary_breakpoint_from_master (orig, orig->type, orig->ops);
8284 }
8285
8286 struct breakpoint *
8287 set_momentary_breakpoint_at_pc (struct gdbarch *gdbarch, CORE_ADDR pc,
8288                                 enum bptype type)
8289 {
8290   struct symtab_and_line sal;
8291
8292   sal = find_pc_line (pc, 0);
8293   sal.pc = pc;
8294   sal.section = find_pc_overlay (pc);
8295   sal.explicit_pc = 1;
8296
8297   return set_momentary_breakpoint (gdbarch, sal, null_frame_id, type);
8298 }
8299 \f
8300
8301 /* Tell the user we have just set a breakpoint B.  */
8302
8303 static void
8304 mention (struct breakpoint *b)
8305 {
8306   b->ops->print_mention (b);
8307   if (ui_out_is_mi_like_p (current_uiout))
8308     return;
8309   printf_filtered ("\n");
8310 }
8311 \f
8312
8313 static struct bp_location *
8314 add_location_to_breakpoint (struct breakpoint *b,
8315                             const struct symtab_and_line *sal)
8316 {
8317   struct bp_location *loc, **tmp;
8318   CORE_ADDR adjusted_address;
8319   struct gdbarch *loc_gdbarch = get_sal_arch (*sal);
8320
8321   if (loc_gdbarch == NULL)
8322     loc_gdbarch = b->gdbarch;
8323
8324   /* Adjust the breakpoint's address prior to allocating a location.
8325      Once we call allocate_bp_location(), that mostly uninitialized
8326      location will be placed on the location chain.  Adjustment of the
8327      breakpoint may cause target_read_memory() to be called and we do
8328      not want its scan of the location chain to find a breakpoint and
8329      location that's only been partially initialized.  */
8330   adjusted_address = adjust_breakpoint_address (loc_gdbarch,
8331                                                 sal->pc, b->type);
8332
8333   loc = allocate_bp_location (b);
8334   for (tmp = &(b->loc); *tmp != NULL; tmp = &((*tmp)->next))
8335     ;
8336   *tmp = loc;
8337
8338   loc->requested_address = sal->pc;
8339   loc->address = adjusted_address;
8340   loc->pspace = sal->pspace;
8341   loc->probe = sal->probe;
8342   gdb_assert (loc->pspace != NULL);
8343   loc->section = sal->section;
8344   loc->gdbarch = loc_gdbarch;
8345
8346   if (sal->symtab != NULL)
8347     loc->source_file = xstrdup (sal->symtab->filename);
8348   loc->line_number = sal->line;
8349
8350   set_breakpoint_location_function (loc,
8351                                     sal->explicit_pc || sal->explicit_line);
8352   return loc;
8353 }
8354 \f
8355
8356 /* Return 1 if LOC is pointing to a permanent breakpoint, 
8357    return 0 otherwise.  */
8358
8359 static int
8360 bp_loc_is_permanent (struct bp_location *loc)
8361 {
8362   int len;
8363   CORE_ADDR addr;
8364   const gdb_byte *bpoint;
8365   gdb_byte *target_mem;
8366   struct cleanup *cleanup;
8367   int retval = 0;
8368
8369   gdb_assert (loc != NULL);
8370
8371   addr = loc->address;
8372   bpoint = gdbarch_breakpoint_from_pc (loc->gdbarch, &addr, &len);
8373
8374   /* Software breakpoints unsupported?  */
8375   if (bpoint == NULL)
8376     return 0;
8377
8378   target_mem = alloca (len);
8379
8380   /* Enable the automatic memory restoration from breakpoints while
8381      we read the memory.  Otherwise we could say about our temporary
8382      breakpoints they are permanent.  */
8383   cleanup = save_current_space_and_thread ();
8384
8385   switch_to_program_space_and_thread (loc->pspace);
8386   make_show_memory_breakpoints_cleanup (0);
8387
8388   if (target_read_memory (loc->address, target_mem, len) == 0
8389       && memcmp (target_mem, bpoint, len) == 0)
8390     retval = 1;
8391
8392   do_cleanups (cleanup);
8393
8394   return retval;
8395 }
8396
8397 /* The style in which to perform a dynamic printf.  This is a user
8398    option because different output options have different tradeoffs;
8399    if GDB does the printing, there is better error handling if there
8400    is a problem with any of the arguments, but using an inferior
8401    function lets you have special-purpose printers and sending of
8402    output to the same place as compiled-in print functions.  (Future
8403    styles may include the ability to do a target-side printf.)  */
8404
8405 static const char dprintf_style_gdb[] = "gdb";
8406 static const char dprintf_style_call[] = "call";
8407 static const char *const dprintf_style_enums[] = {
8408   dprintf_style_gdb,
8409   dprintf_style_call,
8410   NULL
8411 };
8412 static const char *dprintf_style = dprintf_style_gdb;
8413
8414 /* The function to use for dynamic printf if the preferred style is to
8415    call into the inferior.  The value is simply a string that is
8416    copied into the command, so it can be anything that GDB can
8417    evaluate to a callable address, not necessarily a function name.  */
8418
8419 static char *dprintf_function = "";
8420
8421 /* The channel to use for dynamic printf if the preferred style is to
8422    call into the inferior; if a nonempty string, it will be passed to
8423    the call as the first argument, with the format string as the
8424    second.  As with the dprintf function, this can be anything that
8425    GDB knows how to evaluate, so in addition to common choices like
8426    "stderr", this could be an app-specific expression like
8427    "mystreams[curlogger]".  */
8428
8429 static char *dprintf_channel = "";
8430
8431 /* Build a command list for the dprintf corresponding to the current
8432    settings of the dprintf style options.  */
8433
8434 static void
8435 update_dprintf_command_list (struct breakpoint *b)
8436 {
8437   char *dprintf_args = b->extra_string;
8438   char *printf_line = NULL;
8439
8440   if (!dprintf_args)
8441     return;
8442
8443   dprintf_args = skip_spaces (dprintf_args);
8444
8445   /* Allow a comma, as it may have terminated a location, but don't
8446      insist on it.  */
8447   if (*dprintf_args == ',')
8448     ++dprintf_args;
8449   dprintf_args = skip_spaces (dprintf_args);
8450
8451   if (*dprintf_args != '"')
8452     error (_("Bad format string, missing '\"'."));
8453
8454   if (strcmp (dprintf_style, "gdb") == 0)
8455     printf_line = xstrprintf ("printf %s", dprintf_args);
8456   else if (strcmp (dprintf_style, "call") == 0)
8457     {
8458       if (!dprintf_function)
8459         error (_("No function supplied for dprintf call"));
8460
8461       if (dprintf_channel && strlen (dprintf_channel) > 0)
8462         printf_line = xstrprintf ("call (void) %s (%s,%s)",
8463                                   dprintf_function,
8464                                   dprintf_channel,
8465                                   dprintf_args);
8466       else
8467         printf_line = xstrprintf ("call (void) %s (%s)",
8468                                   dprintf_function,
8469                                   dprintf_args);
8470     }
8471   else
8472     internal_error (__FILE__, __LINE__,
8473                     _("Invalid dprintf style."));
8474
8475   /* Manufacture a printf/continue sequence.  */
8476   if (printf_line)
8477     {
8478       struct command_line *printf_cmd_line, *cont_cmd_line = NULL;
8479
8480       cont_cmd_line = xmalloc (sizeof (struct command_line));
8481       cont_cmd_line->control_type = simple_control;
8482       cont_cmd_line->body_count = 0;
8483       cont_cmd_line->body_list = NULL;
8484       cont_cmd_line->next = NULL;
8485       cont_cmd_line->line = xstrdup ("continue");
8486
8487       printf_cmd_line = xmalloc (sizeof (struct command_line));
8488       printf_cmd_line->control_type = simple_control;
8489       printf_cmd_line->body_count = 0;
8490       printf_cmd_line->body_list = NULL;
8491       printf_cmd_line->next = cont_cmd_line;
8492       printf_cmd_line->line = printf_line;
8493
8494       breakpoint_set_commands (b, printf_cmd_line);
8495     }
8496 }
8497
8498 /* Update all dprintf commands, making their command lists reflect
8499    current style settings.  */
8500
8501 static void
8502 update_dprintf_commands (char *args, int from_tty,
8503                          struct cmd_list_element *c)
8504 {
8505   struct breakpoint *b;
8506
8507   ALL_BREAKPOINTS (b)
8508     {
8509       if (b->type == bp_dprintf)
8510         update_dprintf_command_list (b);
8511     }
8512 }
8513
8514 /* Create a breakpoint with SAL as location.  Use ADDR_STRING
8515    as textual description of the location, and COND_STRING
8516    as condition expression.  */
8517
8518 static void
8519 init_breakpoint_sal (struct breakpoint *b, struct gdbarch *gdbarch,
8520                      struct symtabs_and_lines sals, char *addr_string,
8521                      char *filter, char *cond_string,
8522                      char *extra_string,
8523                      enum bptype type, enum bpdisp disposition,
8524                      int thread, int task, int ignore_count,
8525                      const struct breakpoint_ops *ops, int from_tty,
8526                      int enabled, int internal, unsigned flags,
8527                      int display_canonical)
8528 {
8529   int i;
8530
8531   if (type == bp_hardware_breakpoint)
8532     {
8533       int target_resources_ok;
8534
8535       i = hw_breakpoint_used_count ();
8536       target_resources_ok =
8537         target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
8538                                             i + 1, 0);
8539       if (target_resources_ok == 0)
8540         error (_("No hardware breakpoint support in the target."));
8541       else if (target_resources_ok < 0)
8542         error (_("Hardware breakpoints used exceeds limit."));
8543     }
8544
8545   gdb_assert (sals.nelts > 0);
8546
8547   for (i = 0; i < sals.nelts; ++i)
8548     {
8549       struct symtab_and_line sal = sals.sals[i];
8550       struct bp_location *loc;
8551
8552       if (from_tty)
8553         {
8554           struct gdbarch *loc_gdbarch = get_sal_arch (sal);
8555           if (!loc_gdbarch)
8556             loc_gdbarch = gdbarch;
8557
8558           describe_other_breakpoints (loc_gdbarch,
8559                                       sal.pspace, sal.pc, sal.section, thread);
8560         }
8561
8562       if (i == 0)
8563         {
8564           init_raw_breakpoint (b, gdbarch, sal, type, ops);
8565           b->thread = thread;
8566           b->task = task;
8567   
8568           b->cond_string = cond_string;
8569           b->extra_string = extra_string;
8570           b->ignore_count = ignore_count;
8571           b->enable_state = enabled ? bp_enabled : bp_disabled;
8572           b->disposition = disposition;
8573
8574           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8575             b->loc->inserted = 1;
8576
8577           if (type == bp_static_tracepoint)
8578             {
8579               struct tracepoint *t = (struct tracepoint *) b;
8580               struct static_tracepoint_marker marker;
8581
8582               if (strace_marker_p (b))
8583                 {
8584                   /* We already know the marker exists, otherwise, we
8585                      wouldn't see a sal for it.  */
8586                   char *p = &addr_string[3];
8587                   char *endp;
8588                   char *marker_str;
8589
8590                   p = skip_spaces (p);
8591
8592                   endp = skip_to_space (p);
8593
8594                   marker_str = savestring (p, endp - p);
8595                   t->static_trace_marker_id = marker_str;
8596
8597                   printf_filtered (_("Probed static tracepoint "
8598                                      "marker \"%s\"\n"),
8599                                    t->static_trace_marker_id);
8600                 }
8601               else if (target_static_tracepoint_marker_at (sal.pc, &marker))
8602                 {
8603                   t->static_trace_marker_id = xstrdup (marker.str_id);
8604                   release_static_tracepoint_marker (&marker);
8605
8606                   printf_filtered (_("Probed static tracepoint "
8607                                      "marker \"%s\"\n"),
8608                                    t->static_trace_marker_id);
8609                 }
8610               else
8611                 warning (_("Couldn't determine the static "
8612                            "tracepoint marker to probe"));
8613             }
8614
8615           loc = b->loc;
8616         }
8617       else
8618         {
8619           loc = add_location_to_breakpoint (b, &sal);
8620           if ((flags & CREATE_BREAKPOINT_FLAGS_INSERTED) != 0)
8621             loc->inserted = 1;
8622         }
8623
8624       if (bp_loc_is_permanent (loc))
8625         make_breakpoint_permanent (b);
8626
8627       if (b->cond_string)
8628         {
8629           char *arg = b->cond_string;
8630           loc->cond = parse_exp_1 (&arg, block_for_pc (loc->address), 0);
8631           if (*arg)
8632               error (_("Garbage %s follows condition"), arg);
8633         }
8634
8635       /* Dynamic printf requires and uses additional arguments on the
8636          command line, otherwise it's an error.  */
8637       if (type == bp_dprintf)
8638         {
8639           if (b->extra_string)
8640             update_dprintf_command_list (b);
8641           else
8642             error (_("Format string required"));
8643         }
8644       else if (b->extra_string)
8645         error (_("Garbage %s at end of command"), b->extra_string);
8646     }   
8647
8648   b->display_canonical = display_canonical;
8649   if (addr_string)
8650     b->addr_string = addr_string;
8651   else
8652     /* addr_string has to be used or breakpoint_re_set will delete
8653        me.  */
8654     b->addr_string
8655       = xstrprintf ("*%s", paddress (b->loc->gdbarch, b->loc->address));
8656   b->filter = filter;
8657 }
8658
8659 static void
8660 create_breakpoint_sal (struct gdbarch *gdbarch,
8661                        struct symtabs_and_lines sals, char *addr_string,
8662                        char *filter, char *cond_string,
8663                        char *extra_string,
8664                        enum bptype type, enum bpdisp disposition,
8665                        int thread, int task, int ignore_count,
8666                        const struct breakpoint_ops *ops, int from_tty,
8667                        int enabled, int internal, unsigned flags,
8668                        int display_canonical)
8669 {
8670   struct breakpoint *b;
8671   struct cleanup *old_chain;
8672
8673   if (is_tracepoint_type (type))
8674     {
8675       struct tracepoint *t;
8676
8677       t = XCNEW (struct tracepoint);
8678       b = &t->base;
8679     }
8680   else
8681     b = XNEW (struct breakpoint);
8682
8683   old_chain = make_cleanup (xfree, b);
8684
8685   init_breakpoint_sal (b, gdbarch,
8686                        sals, addr_string,
8687                        filter, cond_string, extra_string,
8688                        type, disposition,
8689                        thread, task, ignore_count,
8690                        ops, from_tty,
8691                        enabled, internal, flags,
8692                        display_canonical);
8693   discard_cleanups (old_chain);
8694
8695   install_breakpoint (internal, b, 0);
8696 }
8697
8698 /* Add SALS.nelts breakpoints to the breakpoint table.  For each
8699    SALS.sal[i] breakpoint, include the corresponding ADDR_STRING[i]
8700    value.  COND_STRING, if not NULL, specified the condition to be
8701    used for all breakpoints.  Essentially the only case where
8702    SALS.nelts is not 1 is when we set a breakpoint on an overloaded
8703    function.  In that case, it's still not possible to specify
8704    separate conditions for different overloaded functions, so
8705    we take just a single condition string.
8706    
8707    NOTE: If the function succeeds, the caller is expected to cleanup
8708    the arrays ADDR_STRING, COND_STRING, and SALS (but not the
8709    array contents).  If the function fails (error() is called), the
8710    caller is expected to cleanups both the ADDR_STRING, COND_STRING,
8711    COND and SALS arrays and each of those arrays contents.  */
8712
8713 static void
8714 create_breakpoints_sal (struct gdbarch *gdbarch,
8715                         struct linespec_result *canonical,
8716                         char *cond_string, char *extra_string,
8717                         enum bptype type, enum bpdisp disposition,
8718                         int thread, int task, int ignore_count,
8719                         const struct breakpoint_ops *ops, int from_tty,
8720                         int enabled, int internal, unsigned flags)
8721 {
8722   int i;
8723   struct linespec_sals *lsal;
8724
8725   if (canonical->pre_expanded)
8726     gdb_assert (VEC_length (linespec_sals, canonical->sals) == 1);
8727
8728   for (i = 0; VEC_iterate (linespec_sals, canonical->sals, i, lsal); ++i)
8729     {
8730       /* Note that 'addr_string' can be NULL in the case of a plain
8731          'break', without arguments.  */
8732       char *addr_string = (canonical->addr_string
8733                            ? xstrdup (canonical->addr_string)
8734                            : NULL);
8735       char *filter_string = lsal->canonical ? xstrdup (lsal->canonical) : NULL;
8736       struct cleanup *inner = make_cleanup (xfree, addr_string);
8737
8738       make_cleanup (xfree, filter_string);
8739       create_breakpoint_sal (gdbarch, lsal->sals,
8740                              addr_string,
8741                              filter_string,
8742                              cond_string, extra_string,
8743                              type, disposition,
8744                              thread, task, ignore_count, ops,
8745                              from_tty, enabled, internal, flags,
8746                              canonical->special_display);
8747       discard_cleanups (inner);
8748     }
8749 }
8750
8751 /* Parse ADDRESS which is assumed to be a SAL specification possibly
8752    followed by conditionals.  On return, SALS contains an array of SAL
8753    addresses found.  ADDR_STRING contains a vector of (canonical)
8754    address strings.  ADDRESS points to the end of the SAL.
8755
8756    The array and the line spec strings are allocated on the heap, it is
8757    the caller's responsibility to free them.  */
8758
8759 static void
8760 parse_breakpoint_sals (char **address,
8761                        struct linespec_result *canonical)
8762 {
8763   char *addr_start = *address;
8764
8765   /* If no arg given, or if first arg is 'if ', use the default
8766      breakpoint.  */
8767   if ((*address) == NULL
8768       || (strncmp ((*address), "if", 2) == 0 && isspace ((*address)[2])))
8769     {
8770       /* The last displayed codepoint, if it's valid, is our default breakpoint
8771          address.  */
8772       if (last_displayed_sal_is_valid ())
8773         {
8774           struct linespec_sals lsal;
8775           struct symtab_and_line sal;
8776
8777           init_sal (&sal);              /* Initialize to zeroes.  */
8778           lsal.sals.sals = (struct symtab_and_line *)
8779             xmalloc (sizeof (struct symtab_and_line));
8780
8781           /* Set sal's pspace, pc, symtab, and line to the values
8782              corresponding to the last call to print_frame_info.  */
8783           get_last_displayed_sal (&sal);
8784           sal.section = find_pc_overlay (sal.pc);
8785
8786           /* "break" without arguments is equivalent to "break *PC"
8787              where PC is the last displayed codepoint's address.  So
8788              make sure to set sal.explicit_pc to prevent GDB from
8789              trying to expand the list of sals to include all other
8790              instances with the same symtab and line.  */
8791           sal.explicit_pc = 1;
8792
8793           lsal.sals.sals[0] = sal;
8794           lsal.sals.nelts = 1;
8795           lsal.canonical = NULL;
8796
8797           VEC_safe_push (linespec_sals, canonical->sals, &lsal);
8798         }
8799       else
8800         error (_("No default breakpoint address now."));
8801     }
8802   else
8803     {
8804       /* Force almost all breakpoints to be in terms of the
8805          current_source_symtab (which is decode_line_1's default).
8806          This should produce the results we want almost all of the
8807          time while leaving default_breakpoint_* alone.  */
8808       if (last_displayed_sal_is_valid ())
8809         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8810                           get_last_displayed_symtab (),
8811                           get_last_displayed_line (),
8812                           canonical, NULL, NULL);
8813       else
8814         decode_line_full (address, DECODE_LINE_FUNFIRSTLINE,
8815                           (struct symtab *) NULL, 0,
8816                           canonical, NULL, NULL);
8817     }
8818 }
8819
8820
8821 /* Convert each SAL into a real PC.  Verify that the PC can be
8822    inserted as a breakpoint.  If it can't throw an error.  */
8823
8824 static void
8825 breakpoint_sals_to_pc (struct symtabs_and_lines *sals)
8826 {    
8827   int i;
8828
8829   for (i = 0; i < sals->nelts; i++)
8830     resolve_sal_pc (&sals->sals[i]);
8831 }
8832
8833 /* Fast tracepoints may have restrictions on valid locations.  For
8834    instance, a fast tracepoint using a jump instead of a trap will
8835    likely have to overwrite more bytes than a trap would, and so can
8836    only be placed where the instruction is longer than the jump, or a
8837    multi-instruction sequence does not have a jump into the middle of
8838    it, etc.  */
8839
8840 static void
8841 check_fast_tracepoint_sals (struct gdbarch *gdbarch,
8842                             struct symtabs_and_lines *sals)
8843 {
8844   int i, rslt;
8845   struct symtab_and_line *sal;
8846   char *msg;
8847   struct cleanup *old_chain;
8848
8849   for (i = 0; i < sals->nelts; i++)
8850     {
8851       struct gdbarch *sarch;
8852
8853       sal = &sals->sals[i];
8854
8855       sarch = get_sal_arch (*sal);
8856       /* We fall back to GDBARCH if there is no architecture
8857          associated with SAL.  */
8858       if (sarch == NULL)
8859         sarch = gdbarch;
8860       rslt = gdbarch_fast_tracepoint_valid_at (sarch, sal->pc,
8861                                                NULL, &msg);
8862       old_chain = make_cleanup (xfree, msg);
8863
8864       if (!rslt)
8865         error (_("May not have a fast tracepoint at 0x%s%s"),
8866                paddress (sarch, sal->pc), (msg ? msg : ""));
8867
8868       do_cleanups (old_chain);
8869     }
8870 }
8871
8872 /* Given TOK, a string specification of condition and thread, as
8873    accepted by the 'break' command, extract the condition
8874    string and thread number and set *COND_STRING and *THREAD.
8875    PC identifies the context at which the condition should be parsed.
8876    If no condition is found, *COND_STRING is set to NULL.
8877    If no thread is found, *THREAD is set to -1.  */
8878
8879 static void
8880 find_condition_and_thread (char *tok, CORE_ADDR pc,
8881                            char **cond_string, int *thread, int *task,
8882                            char **rest)
8883 {
8884   *cond_string = NULL;
8885   *thread = -1;
8886   while (tok && *tok)
8887     {
8888       char *end_tok;
8889       int toklen;
8890       char *cond_start = NULL;
8891       char *cond_end = NULL;
8892
8893       tok = skip_spaces (tok);
8894
8895       if ((*tok == '"' || *tok == ',') && rest)
8896         {
8897           *rest = savestring (tok, strlen (tok));
8898           return;
8899         }
8900
8901       end_tok = skip_to_space (tok);
8902
8903       toklen = end_tok - tok;
8904
8905       if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
8906         {
8907           struct expression *expr;
8908
8909           tok = cond_start = end_tok + 1;
8910           expr = parse_exp_1 (&tok, block_for_pc (pc), 0);
8911           xfree (expr);
8912           cond_end = tok;
8913           *cond_string = savestring (cond_start, cond_end - cond_start);
8914         }
8915       else if (toklen >= 1 && strncmp (tok, "thread", toklen) == 0)
8916         {
8917           char *tmptok;
8918
8919           tok = end_tok + 1;
8920           tmptok = tok;
8921           *thread = strtol (tok, &tok, 0);
8922           if (tok == tmptok)
8923             error (_("Junk after thread keyword."));
8924           if (!valid_thread_id (*thread))
8925             error (_("Unknown thread %d."), *thread);
8926         }
8927       else if (toklen >= 1 && strncmp (tok, "task", toklen) == 0)
8928         {
8929           char *tmptok;
8930
8931           tok = end_tok + 1;
8932           tmptok = tok;
8933           *task = strtol (tok, &tok, 0);
8934           if (tok == tmptok)
8935             error (_("Junk after task keyword."));
8936           if (!valid_task_id (*task))
8937             error (_("Unknown task %d."), *task);
8938         }
8939       else if (rest)
8940         {
8941           *rest = savestring (tok, strlen (tok));
8942           tok += toklen;
8943         }
8944       else
8945         error (_("Junk at end of arguments."));
8946     }
8947 }
8948
8949 /* Decode a static tracepoint marker spec.  */
8950
8951 static struct symtabs_and_lines
8952 decode_static_tracepoint_spec (char **arg_p)
8953 {
8954   VEC(static_tracepoint_marker_p) *markers = NULL;
8955   struct symtabs_and_lines sals;
8956   struct symtab_and_line sal;
8957   struct symbol *sym;
8958   struct cleanup *old_chain;
8959   char *p = &(*arg_p)[3];
8960   char *endp;
8961   char *marker_str;
8962   int i;
8963
8964   p = skip_spaces (p);
8965
8966   endp = skip_to_space (p);
8967
8968   marker_str = savestring (p, endp - p);
8969   old_chain = make_cleanup (xfree, marker_str);
8970
8971   markers = target_static_tracepoint_markers_by_strid (marker_str);
8972   if (VEC_empty(static_tracepoint_marker_p, markers))
8973     error (_("No known static tracepoint marker named %s"), marker_str);
8974
8975   sals.nelts = VEC_length(static_tracepoint_marker_p, markers);
8976   sals.sals = xmalloc (sizeof *sals.sals * sals.nelts);
8977
8978   for (i = 0; i < sals.nelts; i++)
8979     {
8980       struct static_tracepoint_marker *marker;
8981
8982       marker = VEC_index (static_tracepoint_marker_p, markers, i);
8983
8984       init_sal (&sals.sals[i]);
8985
8986       sals.sals[i] = find_pc_line (marker->address, 0);
8987       sals.sals[i].pc = marker->address;
8988
8989       release_static_tracepoint_marker (marker);
8990     }
8991
8992   do_cleanups (old_chain);
8993
8994   *arg_p = endp;
8995   return sals;
8996 }
8997
8998 /* Set a breakpoint.  This function is shared between CLI and MI
8999    functions for setting a breakpoint.  This function has two major
9000    modes of operations, selected by the PARSE_CONDITION_AND_THREAD
9001    parameter.  If non-zero, the function will parse arg, extracting
9002    breakpoint location, address and thread.  Otherwise, ARG is just
9003    the location of breakpoint, with condition and thread specified by
9004    the COND_STRING and THREAD parameters.  If INTERNAL is non-zero,
9005    the breakpoint number will be allocated from the internal
9006    breakpoint count.  Returns true if any breakpoint was created;
9007    false otherwise.  */
9008
9009 int
9010 create_breakpoint (struct gdbarch *gdbarch,
9011                    char *arg, char *cond_string,
9012                    int thread, char *extra_string,
9013                    int parse_condition_and_thread,
9014                    int tempflag, enum bptype type_wanted,
9015                    int ignore_count,
9016                    enum auto_boolean pending_break_support,
9017                    const struct breakpoint_ops *ops,
9018                    int from_tty, int enabled, int internal,
9019                    unsigned flags)
9020 {
9021   volatile struct gdb_exception e;
9022   char *copy_arg = NULL;
9023   char *addr_start = arg;
9024   struct linespec_result canonical;
9025   struct cleanup *old_chain;
9026   struct cleanup *bkpt_chain = NULL;
9027   int i;
9028   int pending = 0;
9029   int task = 0;
9030   int prev_bkpt_count = breakpoint_count;
9031
9032   gdb_assert (ops != NULL);
9033
9034   init_linespec_result (&canonical);
9035
9036   TRY_CATCH (e, RETURN_MASK_ALL)
9037     {
9038       ops->create_sals_from_address (&arg, &canonical, type_wanted,
9039                                      addr_start, &copy_arg);
9040     }
9041
9042   /* If caller is interested in rc value from parse, set value.  */
9043   switch (e.reason)
9044     {
9045     case GDB_NO_ERROR:
9046       if (VEC_empty (linespec_sals, canonical.sals))
9047         return 0;
9048       break;
9049     case RETURN_ERROR:
9050       switch (e.error)
9051         {
9052         case NOT_FOUND_ERROR:
9053
9054           /* If pending breakpoint support is turned off, throw
9055              error.  */
9056
9057           if (pending_break_support == AUTO_BOOLEAN_FALSE)
9058             throw_exception (e);
9059
9060           exception_print (gdb_stderr, e);
9061
9062           /* If pending breakpoint support is auto query and the user
9063              selects no, then simply return the error code.  */
9064           if (pending_break_support == AUTO_BOOLEAN_AUTO
9065               && !nquery (_("Make %s pending on future shared library load? "),
9066                           bptype_string (type_wanted)))
9067             return 0;
9068
9069           /* At this point, either the user was queried about setting
9070              a pending breakpoint and selected yes, or pending
9071              breakpoint behavior is on and thus a pending breakpoint
9072              is defaulted on behalf of the user.  */
9073           {
9074             struct linespec_sals lsal;
9075
9076             copy_arg = xstrdup (addr_start);
9077             lsal.canonical = xstrdup (copy_arg);
9078             lsal.sals.nelts = 1;
9079             lsal.sals.sals = XNEW (struct symtab_and_line);
9080             init_sal (&lsal.sals.sals[0]);
9081             pending = 1;
9082             VEC_safe_push (linespec_sals, canonical.sals, &lsal);
9083           }
9084           break;
9085         default:
9086           throw_exception (e);
9087         }
9088       break;
9089     default:
9090       throw_exception (e);
9091     }
9092
9093   /* Create a chain of things that always need to be cleaned up.  */
9094   old_chain = make_cleanup_destroy_linespec_result (&canonical);
9095
9096   /* ----------------------------- SNIP -----------------------------
9097      Anything added to the cleanup chain beyond this point is assumed
9098      to be part of a breakpoint.  If the breakpoint create succeeds
9099      then the memory is not reclaimed.  */
9100   bkpt_chain = make_cleanup (null_cleanup, 0);
9101
9102   /* Resolve all line numbers to PC's and verify that the addresses
9103      are ok for the target.  */
9104   if (!pending)
9105     {
9106       int ix;
9107       struct linespec_sals *iter;
9108
9109       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9110         breakpoint_sals_to_pc (&iter->sals);
9111     }
9112
9113   /* Fast tracepoints may have additional restrictions on location.  */
9114   if (!pending && type_wanted == bp_fast_tracepoint)
9115     {
9116       int ix;
9117       struct linespec_sals *iter;
9118
9119       for (ix = 0; VEC_iterate (linespec_sals, canonical.sals, ix, iter); ++ix)
9120         check_fast_tracepoint_sals (gdbarch, &iter->sals);
9121     }
9122
9123   /* Verify that condition can be parsed, before setting any
9124      breakpoints.  Allocate a separate condition expression for each
9125      breakpoint.  */
9126   if (!pending)
9127     {
9128       struct linespec_sals *lsal;
9129
9130       lsal = VEC_index (linespec_sals, canonical.sals, 0);
9131
9132       if (parse_condition_and_thread)
9133         {
9134             char *rest;
9135             /* Here we only parse 'arg' to separate condition
9136                from thread number, so parsing in context of first
9137                sal is OK.  When setting the breakpoint we'll 
9138                re-parse it in context of each sal.  */
9139             cond_string = NULL;
9140             thread = -1;
9141             rest = NULL;
9142             find_condition_and_thread (arg, lsal->sals.sals[0].pc, &cond_string,
9143                                        &thread, &task, &rest);
9144             if (cond_string)
9145                 make_cleanup (xfree, cond_string);
9146             if (rest)
9147               make_cleanup (xfree, rest);
9148             if (rest)
9149               extra_string = rest;
9150         }
9151       else
9152         {
9153             /* Create a private copy of condition string.  */
9154             if (cond_string)
9155             {
9156                 cond_string = xstrdup (cond_string);
9157                 make_cleanup (xfree, cond_string);
9158             }
9159             /* Create a private copy of any extra string.  */
9160             if (extra_string)
9161               {
9162                 extra_string = xstrdup (extra_string);
9163                 make_cleanup (xfree, extra_string);
9164               }
9165         }
9166
9167       ops->create_breakpoints_sal (gdbarch, &canonical, lsal,
9168                                    cond_string, extra_string, type_wanted,
9169                                    tempflag ? disp_del : disp_donttouch,
9170                                    thread, task, ignore_count, ops,
9171                                    from_tty, enabled, internal, flags);
9172     }
9173   else
9174     {
9175       struct breakpoint *b;
9176
9177       make_cleanup (xfree, copy_arg);
9178
9179       if (is_tracepoint_type (type_wanted))
9180         {
9181           struct tracepoint *t;
9182
9183           t = XCNEW (struct tracepoint);
9184           b = &t->base;
9185         }
9186       else
9187         b = XNEW (struct breakpoint);
9188
9189       init_raw_breakpoint_without_location (b, gdbarch, type_wanted, ops);
9190
9191       b->addr_string = copy_arg;
9192       b->cond_string = NULL;
9193       b->extra_string = NULL;
9194       b->ignore_count = ignore_count;
9195       b->disposition = tempflag ? disp_del : disp_donttouch;
9196       b->condition_not_parsed = 1;
9197       b->enable_state = enabled ? bp_enabled : bp_disabled;
9198       if ((type_wanted != bp_breakpoint
9199            && type_wanted != bp_hardware_breakpoint) || thread != -1)
9200         b->pspace = current_program_space;
9201
9202       install_breakpoint (internal, b, 0);
9203     }
9204   
9205   if (VEC_length (linespec_sals, canonical.sals) > 1)
9206     {
9207       warning (_("Multiple breakpoints were set.\nUse the "
9208                  "\"delete\" command to delete unwanted breakpoints."));
9209       prev_breakpoint_count = prev_bkpt_count;
9210     }
9211
9212   /* That's it.  Discard the cleanups for data inserted into the
9213      breakpoint.  */
9214   discard_cleanups (bkpt_chain);
9215   /* But cleanup everything else.  */
9216   do_cleanups (old_chain);
9217
9218   /* error call may happen here - have BKPT_CHAIN already discarded.  */
9219   update_global_location_list (1);
9220
9221   return 1;
9222 }
9223
9224 /* Set a breakpoint.
9225    ARG is a string describing breakpoint address,
9226    condition, and thread.
9227    FLAG specifies if a breakpoint is hardware on,
9228    and if breakpoint is temporary, using BP_HARDWARE_FLAG
9229    and BP_TEMPFLAG.  */
9230
9231 static void
9232 break_command_1 (char *arg, int flag, int from_tty)
9233 {
9234   int tempflag = flag & BP_TEMPFLAG;
9235   enum bptype type_wanted = (flag & BP_HARDWAREFLAG
9236                              ? bp_hardware_breakpoint
9237                              : bp_breakpoint);
9238   struct breakpoint_ops *ops;
9239   const char *arg_cp = arg;
9240
9241   /* Matching breakpoints on probes.  */
9242   if (arg && probe_linespec_to_ops (&arg_cp) != NULL)
9243     ops = &bkpt_probe_breakpoint_ops;
9244   else
9245     ops = &bkpt_breakpoint_ops;
9246
9247   create_breakpoint (get_current_arch (),
9248                      arg,
9249                      NULL, 0, NULL, 1 /* parse arg */,
9250                      tempflag, type_wanted,
9251                      0 /* Ignore count */,
9252                      pending_break_support,
9253                      ops,
9254                      from_tty,
9255                      1 /* enabled */,
9256                      0 /* internal */,
9257                      0);
9258 }
9259
9260 /* Helper function for break_command_1 and disassemble_command.  */
9261
9262 void
9263 resolve_sal_pc (struct symtab_and_line *sal)
9264 {
9265   CORE_ADDR pc;
9266
9267   if (sal->pc == 0 && sal->symtab != NULL)
9268     {
9269       if (!find_line_pc (sal->symtab, sal->line, &pc))
9270         error (_("No line %d in file \"%s\"."),
9271                sal->line, sal->symtab->filename);
9272       sal->pc = pc;
9273
9274       /* If this SAL corresponds to a breakpoint inserted using a line
9275          number, then skip the function prologue if necessary.  */
9276       if (sal->explicit_line)
9277         skip_prologue_sal (sal);
9278     }
9279
9280   if (sal->section == 0 && sal->symtab != NULL)
9281     {
9282       struct blockvector *bv;
9283       struct block *b;
9284       struct symbol *sym;
9285
9286       bv = blockvector_for_pc_sect (sal->pc, 0, &b, sal->symtab);
9287       if (bv != NULL)
9288         {
9289           sym = block_linkage_function (b);
9290           if (sym != NULL)
9291             {
9292               fixup_symbol_section (sym, sal->symtab->objfile);
9293               sal->section = SYMBOL_OBJ_SECTION (sym);
9294             }
9295           else
9296             {
9297               /* It really is worthwhile to have the section, so we'll
9298                  just have to look harder. This case can be executed
9299                  if we have line numbers but no functions (as can
9300                  happen in assembly source).  */
9301
9302               struct minimal_symbol *msym;
9303               struct cleanup *old_chain = save_current_space_and_thread ();
9304
9305               switch_to_program_space_and_thread (sal->pspace);
9306
9307               msym = lookup_minimal_symbol_by_pc (sal->pc);
9308               if (msym)
9309                 sal->section = SYMBOL_OBJ_SECTION (msym);
9310
9311               do_cleanups (old_chain);
9312             }
9313         }
9314     }
9315 }
9316
9317 void
9318 break_command (char *arg, int from_tty)
9319 {
9320   break_command_1 (arg, 0, from_tty);
9321 }
9322
9323 void
9324 tbreak_command (char *arg, int from_tty)
9325 {
9326   break_command_1 (arg, BP_TEMPFLAG, from_tty);
9327 }
9328
9329 static void
9330 hbreak_command (char *arg, int from_tty)
9331 {
9332   break_command_1 (arg, BP_HARDWAREFLAG, from_tty);
9333 }
9334
9335 static void
9336 thbreak_command (char *arg, int from_tty)
9337 {
9338   break_command_1 (arg, (BP_TEMPFLAG | BP_HARDWAREFLAG), from_tty);
9339 }
9340
9341 static void
9342 stop_command (char *arg, int from_tty)
9343 {
9344   printf_filtered (_("Specify the type of breakpoint to set.\n\
9345 Usage: stop in <function | address>\n\
9346        stop at <line>\n"));
9347 }
9348
9349 static void
9350 stopin_command (char *arg, int from_tty)
9351 {
9352   int badInput = 0;
9353
9354   if (arg == (char *) NULL)
9355     badInput = 1;
9356   else if (*arg != '*')
9357     {
9358       char *argptr = arg;
9359       int hasColon = 0;
9360
9361       /* Look for a ':'.  If this is a line number specification, then
9362          say it is bad, otherwise, it should be an address or
9363          function/method name.  */
9364       while (*argptr && !hasColon)
9365         {
9366           hasColon = (*argptr == ':');
9367           argptr++;
9368         }
9369
9370       if (hasColon)
9371         badInput = (*argptr != ':');    /* Not a class::method */
9372       else
9373         badInput = isdigit (*arg);      /* a simple line number */
9374     }
9375
9376   if (badInput)
9377     printf_filtered (_("Usage: stop in <function | address>\n"));
9378   else
9379     break_command_1 (arg, 0, from_tty);
9380 }
9381
9382 static void
9383 stopat_command (char *arg, int from_tty)
9384 {
9385   int badInput = 0;
9386
9387   if (arg == (char *) NULL || *arg == '*')      /* no line number */
9388     badInput = 1;
9389   else
9390     {
9391       char *argptr = arg;
9392       int hasColon = 0;
9393
9394       /* Look for a ':'.  If there is a '::' then get out, otherwise
9395          it is probably a line number.  */
9396       while (*argptr && !hasColon)
9397         {
9398           hasColon = (*argptr == ':');
9399           argptr++;
9400         }
9401
9402       if (hasColon)
9403         badInput = (*argptr == ':');    /* we have class::method */
9404       else
9405         badInput = !isdigit (*arg);     /* not a line number */
9406     }
9407
9408   if (badInput)
9409     printf_filtered (_("Usage: stop at <line>\n"));
9410   else
9411     break_command_1 (arg, 0, from_tty);
9412 }
9413
9414 void dprintf_command (char *arg, int from_tty);
9415
9416 /* The dynamic printf command is mostly like a regular breakpoint, but
9417    with a prewired command list consisting of a single output command,
9418    built from extra arguments supplied on the dprintf command
9419    line.  */
9420
9421 void
9422 dprintf_command (char *arg, int from_tty)
9423 {
9424   create_breakpoint (get_current_arch (),
9425                      arg,
9426                      NULL, 0, NULL, 1 /* parse arg */,
9427                      0, bp_dprintf,
9428                      0 /* Ignore count */,
9429                      pending_break_support,
9430                      &dprintf_breakpoint_ops,
9431                      from_tty,
9432                      1 /* enabled */,
9433                      0 /* internal */,
9434                      0);
9435 }
9436
9437 /* Implement the "breakpoint_hit" breakpoint_ops method for
9438    ranged breakpoints.  */
9439
9440 static int
9441 breakpoint_hit_ranged_breakpoint (const struct bp_location *bl,
9442                                   struct address_space *aspace,
9443                                   CORE_ADDR bp_addr,
9444                                   const struct target_waitstatus *ws)
9445 {
9446   if (ws->kind != TARGET_WAITKIND_STOPPED
9447       || ws->value.sig != TARGET_SIGNAL_TRAP)
9448     return 0;
9449
9450   return breakpoint_address_match_range (bl->pspace->aspace, bl->address,
9451                                          bl->length, aspace, bp_addr);
9452 }
9453
9454 /* Implement the "resources_needed" breakpoint_ops method for
9455    ranged breakpoints.  */
9456
9457 static int
9458 resources_needed_ranged_breakpoint (const struct bp_location *bl)
9459 {
9460   return target_ranged_break_num_registers ();
9461 }
9462
9463 /* Implement the "print_it" breakpoint_ops method for
9464    ranged breakpoints.  */
9465
9466 static enum print_stop_action
9467 print_it_ranged_breakpoint (bpstat bs)
9468 {
9469   struct breakpoint *b = bs->breakpoint_at;
9470   struct bp_location *bl = b->loc;
9471   struct ui_out *uiout = current_uiout;
9472
9473   gdb_assert (b->type == bp_hardware_breakpoint);
9474
9475   /* Ranged breakpoints have only one location.  */
9476   gdb_assert (bl && bl->next == NULL);
9477
9478   annotate_breakpoint (b->number);
9479   if (b->disposition == disp_del)
9480     ui_out_text (uiout, "\nTemporary ranged breakpoint ");
9481   else
9482     ui_out_text (uiout, "\nRanged breakpoint ");
9483   if (ui_out_is_mi_like_p (uiout))
9484     {
9485       ui_out_field_string (uiout, "reason",
9486                       async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
9487       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
9488     }
9489   ui_out_field_int (uiout, "bkptno", b->number);
9490   ui_out_text (uiout, ", ");
9491
9492   return PRINT_SRC_AND_LOC;
9493 }
9494
9495 /* Implement the "print_one" breakpoint_ops method for
9496    ranged breakpoints.  */
9497
9498 static void
9499 print_one_ranged_breakpoint (struct breakpoint *b,
9500                              struct bp_location **last_loc)
9501 {
9502   struct bp_location *bl = b->loc;
9503   struct value_print_options opts;
9504   struct ui_out *uiout = current_uiout;
9505
9506   /* Ranged breakpoints have only one location.  */
9507   gdb_assert (bl && bl->next == NULL);
9508
9509   get_user_print_options (&opts);
9510
9511   if (opts.addressprint)
9512     /* We don't print the address range here, it will be printed later
9513        by print_one_detail_ranged_breakpoint.  */
9514     ui_out_field_skip (uiout, "addr");
9515   annotate_field (5);
9516   print_breakpoint_location (b, bl);
9517   *last_loc = bl;
9518 }
9519
9520 /* Implement the "print_one_detail" breakpoint_ops method for
9521    ranged breakpoints.  */
9522
9523 static void
9524 print_one_detail_ranged_breakpoint (const struct breakpoint *b,
9525                                     struct ui_out *uiout)
9526 {
9527   CORE_ADDR address_start, address_end;
9528   struct bp_location *bl = b->loc;
9529   struct ui_file *stb = mem_fileopen ();
9530   struct cleanup *cleanup = make_cleanup_ui_file_delete (stb);
9531
9532   gdb_assert (bl);
9533
9534   address_start = bl->address;
9535   address_end = address_start + bl->length - 1;
9536
9537   ui_out_text (uiout, "\taddress range: ");
9538   fprintf_unfiltered (stb, "[%s, %s]",
9539                       print_core_address (bl->gdbarch, address_start),
9540                       print_core_address (bl->gdbarch, address_end));
9541   ui_out_field_stream (uiout, "addr", stb);
9542   ui_out_text (uiout, "\n");
9543
9544   do_cleanups (cleanup);
9545 }
9546
9547 /* Implement the "print_mention" breakpoint_ops method for
9548    ranged breakpoints.  */
9549
9550 static void
9551 print_mention_ranged_breakpoint (struct breakpoint *b)
9552 {
9553   struct bp_location *bl = b->loc;
9554   struct ui_out *uiout = current_uiout;
9555
9556   gdb_assert (bl);
9557   gdb_assert (b->type == bp_hardware_breakpoint);
9558
9559   if (ui_out_is_mi_like_p (uiout))
9560     return;
9561
9562   printf_filtered (_("Hardware assisted ranged breakpoint %d from %s to %s."),
9563                    b->number, paddress (bl->gdbarch, bl->address),
9564                    paddress (bl->gdbarch, bl->address + bl->length - 1));
9565 }
9566
9567 /* Implement the "print_recreate" breakpoint_ops method for
9568    ranged breakpoints.  */
9569
9570 static void
9571 print_recreate_ranged_breakpoint (struct breakpoint *b, struct ui_file *fp)
9572 {
9573   fprintf_unfiltered (fp, "break-range %s, %s", b->addr_string,
9574                       b->addr_string_range_end);
9575   print_recreate_thread (b, fp);
9576 }
9577
9578 /* The breakpoint_ops structure to be used in ranged breakpoints.  */
9579
9580 static struct breakpoint_ops ranged_breakpoint_ops;
9581
9582 /* Find the address where the end of the breakpoint range should be
9583    placed, given the SAL of the end of the range.  This is so that if
9584    the user provides a line number, the end of the range is set to the
9585    last instruction of the given line.  */
9586
9587 static CORE_ADDR
9588 find_breakpoint_range_end (struct symtab_and_line sal)
9589 {
9590   CORE_ADDR end;
9591
9592   /* If the user provided a PC value, use it.  Otherwise,
9593      find the address of the end of the given location.  */
9594   if (sal.explicit_pc)
9595     end = sal.pc;
9596   else
9597     {
9598       int ret;
9599       CORE_ADDR start;
9600
9601       ret = find_line_pc_range (sal, &start, &end);
9602       if (!ret)
9603         error (_("Could not find location of the end of the range."));
9604
9605       /* find_line_pc_range returns the start of the next line.  */
9606       end--;
9607     }
9608
9609   return end;
9610 }
9611
9612 /* Implement the "break-range" CLI command.  */
9613
9614 static void
9615 break_range_command (char *arg, int from_tty)
9616 {
9617   char *arg_start, *addr_string_start, *addr_string_end;
9618   struct linespec_result canonical_start, canonical_end;
9619   int bp_count, can_use_bp, length;
9620   CORE_ADDR end;
9621   struct breakpoint *b;
9622   struct symtab_and_line sal_start, sal_end;
9623   struct cleanup *cleanup_bkpt;
9624   struct linespec_sals *lsal_start, *lsal_end;
9625
9626   /* We don't support software ranged breakpoints.  */
9627   if (target_ranged_break_num_registers () < 0)
9628     error (_("This target does not support hardware ranged breakpoints."));
9629
9630   bp_count = hw_breakpoint_used_count ();
9631   bp_count += target_ranged_break_num_registers ();
9632   can_use_bp = target_can_use_hardware_watchpoint (bp_hardware_breakpoint,
9633                                                    bp_count, 0);
9634   if (can_use_bp < 0)
9635     error (_("Hardware breakpoints used exceeds limit."));
9636
9637   arg = skip_spaces (arg);
9638   if (arg == NULL || arg[0] == '\0')
9639     error(_("No address range specified."));
9640
9641   init_linespec_result (&canonical_start);
9642
9643   arg_start = arg;
9644   parse_breakpoint_sals (&arg, &canonical_start);
9645
9646   cleanup_bkpt = make_cleanup_destroy_linespec_result (&canonical_start);
9647
9648   if (arg[0] != ',')
9649     error (_("Too few arguments."));
9650   else if (VEC_empty (linespec_sals, canonical_start.sals))
9651     error (_("Could not find location of the beginning of the range."));
9652
9653   lsal_start = VEC_index (linespec_sals, canonical_start.sals, 0);
9654
9655   if (VEC_length (linespec_sals, canonical_start.sals) > 1
9656       || lsal_start->sals.nelts != 1)
9657     error (_("Cannot create a ranged breakpoint with multiple locations."));
9658
9659   sal_start = lsal_start->sals.sals[0];
9660   addr_string_start = savestring (arg_start, arg - arg_start);
9661   make_cleanup (xfree, addr_string_start);
9662
9663   arg++;        /* Skip the comma.  */
9664   arg = skip_spaces (arg);
9665
9666   /* Parse the end location.  */
9667
9668   init_linespec_result (&canonical_end);
9669   arg_start = arg;
9670
9671   /* We call decode_line_full directly here instead of using
9672      parse_breakpoint_sals because we need to specify the start location's
9673      symtab and line as the default symtab and line for the end of the
9674      range.  This makes it possible to have ranges like "foo.c:27, +14",
9675      where +14 means 14 lines from the start location.  */
9676   decode_line_full (&arg, DECODE_LINE_FUNFIRSTLINE,
9677                     sal_start.symtab, sal_start.line,
9678                     &canonical_end, NULL, NULL);
9679
9680   make_cleanup_destroy_linespec_result (&canonical_end);
9681
9682   if (VEC_empty (linespec_sals, canonical_end.sals))
9683     error (_("Could not find location of the end of the range."));
9684
9685   lsal_end = VEC_index (linespec_sals, canonical_end.sals, 0);
9686   if (VEC_length (linespec_sals, canonical_end.sals) > 1
9687       || lsal_end->sals.nelts != 1)
9688     error (_("Cannot create a ranged breakpoint with multiple locations."));
9689
9690   sal_end = lsal_end->sals.sals[0];
9691   addr_string_end = savestring (arg_start, arg - arg_start);
9692   make_cleanup (xfree, addr_string_end);
9693
9694   end = find_breakpoint_range_end (sal_end);
9695   if (sal_start.pc > end)
9696     error (_("Invalid address range, end precedes start."));
9697
9698   length = end - sal_start.pc + 1;
9699   if (length < 0)
9700     /* Length overflowed.  */
9701     error (_("Address range too large."));
9702   else if (length == 1)
9703     {
9704       /* This range is simple enough to be handled by
9705          the `hbreak' command.  */
9706       hbreak_command (addr_string_start, 1);
9707
9708       do_cleanups (cleanup_bkpt);
9709
9710       return;
9711     }
9712
9713   /* Now set up the breakpoint.  */
9714   b = set_raw_breakpoint (get_current_arch (), sal_start,
9715                           bp_hardware_breakpoint, &ranged_breakpoint_ops);
9716   set_breakpoint_count (breakpoint_count + 1);
9717   b->number = breakpoint_count;
9718   b->disposition = disp_donttouch;
9719   b->addr_string = xstrdup (addr_string_start);
9720   b->addr_string_range_end = xstrdup (addr_string_end);
9721   b->loc->length = length;
9722
9723   do_cleanups (cleanup_bkpt);
9724
9725   mention (b);
9726   observer_notify_breakpoint_created (b);
9727   update_global_location_list (1);
9728 }
9729
9730 /*  Return non-zero if EXP is verified as constant.  Returned zero
9731     means EXP is variable.  Also the constant detection may fail for
9732     some constant expressions and in such case still falsely return
9733     zero.  */
9734
9735 static int
9736 watchpoint_exp_is_const (const struct expression *exp)
9737 {
9738   int i = exp->nelts;
9739
9740   while (i > 0)
9741     {
9742       int oplenp, argsp;
9743
9744       /* We are only interested in the descriptor of each element.  */
9745       operator_length (exp, i, &oplenp, &argsp);
9746       i -= oplenp;
9747
9748       switch (exp->elts[i].opcode)
9749         {
9750         case BINOP_ADD:
9751         case BINOP_SUB:
9752         case BINOP_MUL:
9753         case BINOP_DIV:
9754         case BINOP_REM:
9755         case BINOP_MOD:
9756         case BINOP_LSH:
9757         case BINOP_RSH:
9758         case BINOP_LOGICAL_AND:
9759         case BINOP_LOGICAL_OR:
9760         case BINOP_BITWISE_AND:
9761         case BINOP_BITWISE_IOR:
9762         case BINOP_BITWISE_XOR:
9763         case BINOP_EQUAL:
9764         case BINOP_NOTEQUAL:
9765         case BINOP_LESS:
9766         case BINOP_GTR:
9767         case BINOP_LEQ:
9768         case BINOP_GEQ:
9769         case BINOP_REPEAT:
9770         case BINOP_COMMA:
9771         case BINOP_EXP:
9772         case BINOP_MIN:
9773         case BINOP_MAX:
9774         case BINOP_INTDIV:
9775         case BINOP_CONCAT:
9776         case BINOP_IN:
9777         case BINOP_RANGE:
9778         case TERNOP_COND:
9779         case TERNOP_SLICE:
9780         case TERNOP_SLICE_COUNT:
9781
9782         case OP_LONG:
9783         case OP_DOUBLE:
9784         case OP_DECFLOAT:
9785         case OP_LAST:
9786         case OP_COMPLEX:
9787         case OP_STRING:
9788         case OP_BITSTRING:
9789         case OP_ARRAY:
9790         case OP_TYPE:
9791         case OP_NAME:
9792         case OP_OBJC_NSSTRING:
9793
9794         case UNOP_NEG:
9795         case UNOP_LOGICAL_NOT:
9796         case UNOP_COMPLEMENT:
9797         case UNOP_ADDR:
9798         case UNOP_HIGH:
9799         case UNOP_CAST:
9800           /* Unary, binary and ternary operators: We have to check
9801              their operands.  If they are constant, then so is the
9802              result of that operation.  For instance, if A and B are
9803              determined to be constants, then so is "A + B".
9804
9805              UNOP_IND is one exception to the rule above, because the
9806              value of *ADDR is not necessarily a constant, even when
9807              ADDR is.  */
9808           break;
9809
9810         case OP_VAR_VALUE:
9811           /* Check whether the associated symbol is a constant.
9812
9813              We use SYMBOL_CLASS rather than TYPE_CONST because it's
9814              possible that a buggy compiler could mark a variable as
9815              constant even when it is not, and TYPE_CONST would return
9816              true in this case, while SYMBOL_CLASS wouldn't.
9817
9818              We also have to check for function symbols because they
9819              are always constant.  */
9820           {
9821             struct symbol *s = exp->elts[i + 2].symbol;
9822
9823             if (SYMBOL_CLASS (s) != LOC_BLOCK
9824                 && SYMBOL_CLASS (s) != LOC_CONST
9825                 && SYMBOL_CLASS (s) != LOC_CONST_BYTES)
9826               return 0;
9827             break;
9828           }
9829
9830         /* The default action is to return 0 because we are using
9831            the optimistic approach here: If we don't know something,
9832            then it is not a constant.  */
9833         default:
9834           return 0;
9835         }
9836     }
9837
9838   return 1;
9839 }
9840
9841 /* Implement the "dtor" breakpoint_ops method for watchpoints.  */
9842
9843 static void
9844 dtor_watchpoint (struct breakpoint *self)
9845 {
9846   struct watchpoint *w = (struct watchpoint *) self;
9847
9848   xfree (w->cond_exp);
9849   xfree (w->exp);
9850   xfree (w->exp_string);
9851   xfree (w->exp_string_reparse);
9852   value_free (w->val);
9853
9854   base_breakpoint_ops.dtor (self);
9855 }
9856
9857 /* Implement the "re_set" breakpoint_ops method for watchpoints.  */
9858
9859 static void
9860 re_set_watchpoint (struct breakpoint *b)
9861 {
9862   struct watchpoint *w = (struct watchpoint *) b;
9863
9864   /* Watchpoint can be either on expression using entirely global
9865      variables, or it can be on local variables.
9866
9867      Watchpoints of the first kind are never auto-deleted, and even
9868      persist across program restarts.  Since they can use variables
9869      from shared libraries, we need to reparse expression as libraries
9870      are loaded and unloaded.
9871
9872      Watchpoints on local variables can also change meaning as result
9873      of solib event.  For example, if a watchpoint uses both a local
9874      and a global variables in expression, it's a local watchpoint,
9875      but unloading of a shared library will make the expression
9876      invalid.  This is not a very common use case, but we still
9877      re-evaluate expression, to avoid surprises to the user.
9878
9879      Note that for local watchpoints, we re-evaluate it only if
9880      watchpoints frame id is still valid.  If it's not, it means the
9881      watchpoint is out of scope and will be deleted soon.  In fact,
9882      I'm not sure we'll ever be called in this case.
9883
9884      If a local watchpoint's frame id is still valid, then
9885      w->exp_valid_block is likewise valid, and we can safely use it.
9886
9887      Don't do anything about disabled watchpoints, since they will be
9888      reevaluated again when enabled.  */
9889   update_watchpoint (w, 1 /* reparse */);
9890 }
9891
9892 /* Implement the "insert" breakpoint_ops method for hardware watchpoints.  */
9893
9894 static int
9895 insert_watchpoint (struct bp_location *bl)
9896 {
9897   struct watchpoint *w = (struct watchpoint *) bl->owner;
9898   int length = w->exact ? 1 : bl->length;
9899
9900   return target_insert_watchpoint (bl->address, length, bl->watchpoint_type,
9901                                    w->cond_exp);
9902 }
9903
9904 /* Implement the "remove" breakpoint_ops method for hardware watchpoints.  */
9905
9906 static int
9907 remove_watchpoint (struct bp_location *bl)
9908 {
9909   struct watchpoint *w = (struct watchpoint *) bl->owner;
9910   int length = w->exact ? 1 : bl->length;
9911
9912   return target_remove_watchpoint (bl->address, length, bl->watchpoint_type,
9913                                    w->cond_exp);
9914 }
9915
9916 static int
9917 breakpoint_hit_watchpoint (const struct bp_location *bl,
9918                            struct address_space *aspace, CORE_ADDR bp_addr,
9919                            const struct target_waitstatus *ws)
9920 {
9921   struct breakpoint *b = bl->owner;
9922   struct watchpoint *w = (struct watchpoint *) b;
9923
9924   /* Continuable hardware watchpoints are treated as non-existent if the
9925      reason we stopped wasn't a hardware watchpoint (we didn't stop on
9926      some data address).  Otherwise gdb won't stop on a break instruction
9927      in the code (not from a breakpoint) when a hardware watchpoint has
9928      been defined.  Also skip watchpoints which we know did not trigger
9929      (did not match the data address).  */
9930   if (is_hardware_watchpoint (b)
9931       && w->watchpoint_triggered == watch_triggered_no)
9932     return 0;
9933
9934   return 1;
9935 }
9936
9937 static void
9938 check_status_watchpoint (bpstat bs)
9939 {
9940   gdb_assert (is_watchpoint (bs->breakpoint_at));
9941
9942   bpstat_check_watchpoint (bs);
9943 }
9944
9945 /* Implement the "resources_needed" breakpoint_ops method for
9946    hardware watchpoints.  */
9947
9948 static int
9949 resources_needed_watchpoint (const struct bp_location *bl)
9950 {
9951   struct watchpoint *w = (struct watchpoint *) bl->owner;
9952   int length = w->exact? 1 : bl->length;
9953
9954   return target_region_ok_for_hw_watchpoint (bl->address, length);
9955 }
9956
9957 /* Implement the "works_in_software_mode" breakpoint_ops method for
9958    hardware watchpoints.  */
9959
9960 static int
9961 works_in_software_mode_watchpoint (const struct breakpoint *b)
9962 {
9963   /* Read and access watchpoints only work with hardware support.  */
9964   return b->type == bp_watchpoint || b->type == bp_hardware_watchpoint;
9965 }
9966
9967 static enum print_stop_action
9968 print_it_watchpoint (bpstat bs)
9969 {
9970   struct cleanup *old_chain;
9971   struct breakpoint *b;
9972   const struct bp_location *bl;
9973   struct ui_file *stb;
9974   enum print_stop_action result;
9975   struct watchpoint *w;
9976   struct ui_out *uiout = current_uiout;
9977
9978   gdb_assert (bs->bp_location_at != NULL);
9979
9980   bl = bs->bp_location_at;
9981   b = bs->breakpoint_at;
9982   w = (struct watchpoint *) b;
9983
9984   stb = mem_fileopen ();
9985   old_chain = make_cleanup_ui_file_delete (stb);
9986
9987   switch (b->type)
9988     {
9989     case bp_watchpoint:
9990     case bp_hardware_watchpoint:
9991       annotate_watchpoint (b->number);
9992       if (ui_out_is_mi_like_p (uiout))
9993         ui_out_field_string
9994           (uiout, "reason",
9995            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
9996       mention (b);
9997       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
9998       ui_out_text (uiout, "\nOld value = ");
9999       watchpoint_value_print (bs->old_val, stb);
10000       ui_out_field_stream (uiout, "old", stb);
10001       ui_out_text (uiout, "\nNew value = ");
10002       watchpoint_value_print (w->val, stb);
10003       ui_out_field_stream (uiout, "new", stb);
10004       ui_out_text (uiout, "\n");
10005       /* More than one watchpoint may have been triggered.  */
10006       result = PRINT_UNKNOWN;
10007       break;
10008
10009     case bp_read_watchpoint:
10010       if (ui_out_is_mi_like_p (uiout))
10011         ui_out_field_string
10012           (uiout, "reason",
10013            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10014       mention (b);
10015       make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10016       ui_out_text (uiout, "\nValue = ");
10017       watchpoint_value_print (w->val, stb);
10018       ui_out_field_stream (uiout, "value", stb);
10019       ui_out_text (uiout, "\n");
10020       result = PRINT_UNKNOWN;
10021       break;
10022
10023     case bp_access_watchpoint:
10024       if (bs->old_val != NULL)
10025         {
10026           annotate_watchpoint (b->number);
10027           if (ui_out_is_mi_like_p (uiout))
10028             ui_out_field_string
10029               (uiout, "reason",
10030                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10031           mention (b);
10032           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10033           ui_out_text (uiout, "\nOld value = ");
10034           watchpoint_value_print (bs->old_val, stb);
10035           ui_out_field_stream (uiout, "old", stb);
10036           ui_out_text (uiout, "\nNew value = ");
10037         }
10038       else
10039         {
10040           mention (b);
10041           if (ui_out_is_mi_like_p (uiout))
10042             ui_out_field_string
10043               (uiout, "reason",
10044                async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10045           make_cleanup_ui_out_tuple_begin_end (uiout, "value");
10046           ui_out_text (uiout, "\nValue = ");
10047         }
10048       watchpoint_value_print (w->val, stb);
10049       ui_out_field_stream (uiout, "new", stb);
10050       ui_out_text (uiout, "\n");
10051       result = PRINT_UNKNOWN;
10052       break;
10053     default:
10054       result = PRINT_UNKNOWN;
10055     }
10056
10057   do_cleanups (old_chain);
10058   return result;
10059 }
10060
10061 /* Implement the "print_mention" breakpoint_ops method for hardware
10062    watchpoints.  */
10063
10064 static void
10065 print_mention_watchpoint (struct breakpoint *b)
10066 {
10067   struct cleanup *ui_out_chain;
10068   struct watchpoint *w = (struct watchpoint *) b;
10069   struct ui_out *uiout = current_uiout;
10070
10071   switch (b->type)
10072     {
10073     case bp_watchpoint:
10074       ui_out_text (uiout, "Watchpoint ");
10075       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10076       break;
10077     case bp_hardware_watchpoint:
10078       ui_out_text (uiout, "Hardware watchpoint ");
10079       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10080       break;
10081     case bp_read_watchpoint:
10082       ui_out_text (uiout, "Hardware read watchpoint ");
10083       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10084       break;
10085     case bp_access_watchpoint:
10086       ui_out_text (uiout, "Hardware access (read/write) watchpoint ");
10087       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10088       break;
10089     default:
10090       internal_error (__FILE__, __LINE__,
10091                       _("Invalid hardware watchpoint type."));
10092     }
10093
10094   ui_out_field_int (uiout, "number", b->number);
10095   ui_out_text (uiout, ": ");
10096   ui_out_field_string (uiout, "exp", w->exp_string);
10097   do_cleanups (ui_out_chain);
10098 }
10099
10100 /* Implement the "print_recreate" breakpoint_ops method for
10101    watchpoints.  */
10102
10103 static void
10104 print_recreate_watchpoint (struct breakpoint *b, struct ui_file *fp)
10105 {
10106   struct watchpoint *w = (struct watchpoint *) b;
10107
10108   switch (b->type)
10109     {
10110     case bp_watchpoint:
10111     case bp_hardware_watchpoint:
10112       fprintf_unfiltered (fp, "watch");
10113       break;
10114     case bp_read_watchpoint:
10115       fprintf_unfiltered (fp, "rwatch");
10116       break;
10117     case bp_access_watchpoint:
10118       fprintf_unfiltered (fp, "awatch");
10119       break;
10120     default:
10121       internal_error (__FILE__, __LINE__,
10122                       _("Invalid watchpoint type."));
10123     }
10124
10125   fprintf_unfiltered (fp, " %s", w->exp_string);
10126   print_recreate_thread (b, fp);
10127 }
10128
10129 /* The breakpoint_ops structure to be used in hardware watchpoints.  */
10130
10131 static struct breakpoint_ops watchpoint_breakpoint_ops;
10132
10133 /* Implement the "insert" breakpoint_ops method for
10134    masked hardware watchpoints.  */
10135
10136 static int
10137 insert_masked_watchpoint (struct bp_location *bl)
10138 {
10139   struct watchpoint *w = (struct watchpoint *) bl->owner;
10140
10141   return target_insert_mask_watchpoint (bl->address, w->hw_wp_mask,
10142                                         bl->watchpoint_type);
10143 }
10144
10145 /* Implement the "remove" breakpoint_ops method for
10146    masked hardware watchpoints.  */
10147
10148 static int
10149 remove_masked_watchpoint (struct bp_location *bl)
10150 {
10151   struct watchpoint *w = (struct watchpoint *) bl->owner;
10152
10153   return target_remove_mask_watchpoint (bl->address, w->hw_wp_mask,
10154                                         bl->watchpoint_type);
10155 }
10156
10157 /* Implement the "resources_needed" breakpoint_ops method for
10158    masked hardware watchpoints.  */
10159
10160 static int
10161 resources_needed_masked_watchpoint (const struct bp_location *bl)
10162 {
10163   struct watchpoint *w = (struct watchpoint *) bl->owner;
10164
10165   return target_masked_watch_num_registers (bl->address, w->hw_wp_mask);
10166 }
10167
10168 /* Implement the "works_in_software_mode" breakpoint_ops method for
10169    masked hardware watchpoints.  */
10170
10171 static int
10172 works_in_software_mode_masked_watchpoint (const struct breakpoint *b)
10173 {
10174   return 0;
10175 }
10176
10177 /* Implement the "print_it" breakpoint_ops method for
10178    masked hardware watchpoints.  */
10179
10180 static enum print_stop_action
10181 print_it_masked_watchpoint (bpstat bs)
10182 {
10183   struct breakpoint *b = bs->breakpoint_at;
10184   struct ui_out *uiout = current_uiout;
10185
10186   /* Masked watchpoints have only one location.  */
10187   gdb_assert (b->loc && b->loc->next == NULL);
10188
10189   switch (b->type)
10190     {
10191     case bp_hardware_watchpoint:
10192       annotate_watchpoint (b->number);
10193       if (ui_out_is_mi_like_p (uiout))
10194         ui_out_field_string
10195           (uiout, "reason",
10196            async_reason_lookup (EXEC_ASYNC_WATCHPOINT_TRIGGER));
10197       break;
10198
10199     case bp_read_watchpoint:
10200       if (ui_out_is_mi_like_p (uiout))
10201         ui_out_field_string
10202           (uiout, "reason",
10203            async_reason_lookup (EXEC_ASYNC_READ_WATCHPOINT_TRIGGER));
10204       break;
10205
10206     case bp_access_watchpoint:
10207       if (ui_out_is_mi_like_p (uiout))
10208         ui_out_field_string
10209           (uiout, "reason",
10210            async_reason_lookup (EXEC_ASYNC_ACCESS_WATCHPOINT_TRIGGER));
10211       break;
10212     default:
10213       internal_error (__FILE__, __LINE__,
10214                       _("Invalid hardware watchpoint type."));
10215     }
10216
10217   mention (b);
10218   ui_out_text (uiout, _("\n\
10219 Check the underlying instruction at PC for the memory\n\
10220 address and value which triggered this watchpoint.\n"));
10221   ui_out_text (uiout, "\n");
10222
10223   /* More than one watchpoint may have been triggered.  */
10224   return PRINT_UNKNOWN;
10225 }
10226
10227 /* Implement the "print_one_detail" breakpoint_ops method for
10228    masked hardware watchpoints.  */
10229
10230 static void
10231 print_one_detail_masked_watchpoint (const struct breakpoint *b,
10232                                     struct ui_out *uiout)
10233 {
10234   struct watchpoint *w = (struct watchpoint *) b;
10235
10236   /* Masked watchpoints have only one location.  */
10237   gdb_assert (b->loc && b->loc->next == NULL);
10238
10239   ui_out_text (uiout, "\tmask ");
10240   ui_out_field_core_addr (uiout, "mask", b->loc->gdbarch, w->hw_wp_mask);
10241   ui_out_text (uiout, "\n");
10242 }
10243
10244 /* Implement the "print_mention" breakpoint_ops method for
10245    masked hardware watchpoints.  */
10246
10247 static void
10248 print_mention_masked_watchpoint (struct breakpoint *b)
10249 {
10250   struct watchpoint *w = (struct watchpoint *) b;
10251   struct ui_out *uiout = current_uiout;
10252   struct cleanup *ui_out_chain;
10253
10254   switch (b->type)
10255     {
10256     case bp_hardware_watchpoint:
10257       ui_out_text (uiout, "Masked hardware watchpoint ");
10258       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "wpt");
10259       break;
10260     case bp_read_watchpoint:
10261       ui_out_text (uiout, "Masked hardware read watchpoint ");
10262       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-rwpt");
10263       break;
10264     case bp_access_watchpoint:
10265       ui_out_text (uiout, "Masked hardware access (read/write) watchpoint ");
10266       ui_out_chain = make_cleanup_ui_out_tuple_begin_end (uiout, "hw-awpt");
10267       break;
10268     default:
10269       internal_error (__FILE__, __LINE__,
10270                       _("Invalid hardware watchpoint type."));
10271     }
10272
10273   ui_out_field_int (uiout, "number", b->number);
10274   ui_out_text (uiout, ": ");
10275   ui_out_field_string (uiout, "exp", w->exp_string);
10276   do_cleanups (ui_out_chain);
10277 }
10278
10279 /* Implement the "print_recreate" breakpoint_ops method for
10280    masked hardware watchpoints.  */
10281
10282 static void
10283 print_recreate_masked_watchpoint (struct breakpoint *b, struct ui_file *fp)
10284 {
10285   struct watchpoint *w = (struct watchpoint *) b;
10286   char tmp[40];
10287
10288   switch (b->type)
10289     {
10290     case bp_hardware_watchpoint:
10291       fprintf_unfiltered (fp, "watch");
10292       break;
10293     case bp_read_watchpoint:
10294       fprintf_unfiltered (fp, "rwatch");
10295       break;
10296     case bp_access_watchpoint:
10297       fprintf_unfiltered (fp, "awatch");
10298       break;
10299     default:
10300       internal_error (__FILE__, __LINE__,
10301                       _("Invalid hardware watchpoint type."));
10302     }
10303
10304   sprintf_vma (tmp, w->hw_wp_mask);
10305   fprintf_unfiltered (fp, " %s mask 0x%s", w->exp_string, tmp);
10306   print_recreate_thread (b, fp);
10307 }
10308
10309 /* The breakpoint_ops structure to be used in masked hardware watchpoints.  */
10310
10311 static struct breakpoint_ops masked_watchpoint_breakpoint_ops;
10312
10313 /* Tell whether the given watchpoint is a masked hardware watchpoint.  */
10314
10315 static int
10316 is_masked_watchpoint (const struct breakpoint *b)
10317 {
10318   return b->ops == &masked_watchpoint_breakpoint_ops;
10319 }
10320
10321 /* accessflag:  hw_write:  watch write, 
10322                 hw_read:   watch read, 
10323                 hw_access: watch access (read or write) */
10324 static void
10325 watch_command_1 (char *arg, int accessflag, int from_tty,
10326                  int just_location, int internal)
10327 {
10328   volatile struct gdb_exception e;
10329   struct breakpoint *b, *scope_breakpoint = NULL;
10330   struct expression *exp;
10331   struct block *exp_valid_block = NULL, *cond_exp_valid_block = NULL;
10332   struct value *val, *mark, *result;
10333   struct frame_info *frame;
10334   char *exp_start = NULL;
10335   char *exp_end = NULL;
10336   char *tok, *end_tok;
10337   int toklen = -1;
10338   char *cond_start = NULL;
10339   char *cond_end = NULL;
10340   enum bptype bp_type;
10341   int thread = -1;
10342   int pc = 0;
10343   /* Flag to indicate whether we are going to use masks for
10344      the hardware watchpoint.  */
10345   int use_mask = 0;
10346   CORE_ADDR mask = 0;
10347   struct watchpoint *w;
10348
10349   /* Make sure that we actually have parameters to parse.  */
10350   if (arg != NULL && arg[0] != '\0')
10351     {
10352       char *value_start;
10353
10354       /* Look for "parameter value" pairs at the end
10355          of the arguments string.  */
10356       for (tok = arg + strlen (arg) - 1; tok > arg; tok--)
10357         {
10358           /* Skip whitespace at the end of the argument list.  */
10359           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10360             tok--;
10361
10362           /* Find the beginning of the last token.
10363              This is the value of the parameter.  */
10364           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10365             tok--;
10366           value_start = tok + 1;
10367
10368           /* Skip whitespace.  */
10369           while (tok > arg && (*tok == ' ' || *tok == '\t'))
10370             tok--;
10371
10372           end_tok = tok;
10373
10374           /* Find the beginning of the second to last token.
10375              This is the parameter itself.  */
10376           while (tok > arg && (*tok != ' ' && *tok != '\t'))
10377             tok--;
10378           tok++;
10379           toklen = end_tok - tok + 1;
10380
10381           if (toklen == 6 && !strncmp (tok, "thread", 6))
10382             {
10383               /* At this point we've found a "thread" token, which means
10384                  the user is trying to set a watchpoint that triggers
10385                  only in a specific thread.  */
10386               char *endp;
10387
10388               if (thread != -1)
10389                 error(_("You can specify only one thread."));
10390
10391               /* Extract the thread ID from the next token.  */
10392               thread = strtol (value_start, &endp, 0);
10393
10394               /* Check if the user provided a valid numeric value for the
10395                  thread ID.  */
10396               if (*endp != ' ' && *endp != '\t' && *endp != '\0')
10397                 error (_("Invalid thread ID specification %s."), value_start);
10398
10399               /* Check if the thread actually exists.  */
10400               if (!valid_thread_id (thread))
10401                 error (_("Unknown thread %d."), thread);
10402             }
10403           else if (toklen == 4 && !strncmp (tok, "mask", 4))
10404             {
10405               /* We've found a "mask" token, which means the user wants to
10406                  create a hardware watchpoint that is going to have the mask
10407                  facility.  */
10408               struct value *mask_value, *mark;
10409
10410               if (use_mask)
10411                 error(_("You can specify only one mask."));
10412
10413               use_mask = just_location = 1;
10414
10415               mark = value_mark ();
10416               mask_value = parse_to_comma_and_eval (&value_start);
10417               mask = value_as_address (mask_value);
10418               value_free_to_mark (mark);
10419             }
10420           else
10421             /* We didn't recognize what we found.  We should stop here.  */
10422             break;
10423
10424           /* Truncate the string and get rid of the "parameter value" pair before
10425              the arguments string is parsed by the parse_exp_1 function.  */
10426           *tok = '\0';
10427         }
10428     }
10429
10430   /* Parse the rest of the arguments.  */
10431   innermost_block = NULL;
10432   exp_start = arg;
10433   exp = parse_exp_1 (&arg, 0, 0);
10434   exp_end = arg;
10435   /* Remove trailing whitespace from the expression before saving it.
10436      This makes the eventual display of the expression string a bit
10437      prettier.  */
10438   while (exp_end > exp_start && (exp_end[-1] == ' ' || exp_end[-1] == '\t'))
10439     --exp_end;
10440
10441   /* Checking if the expression is not constant.  */
10442   if (watchpoint_exp_is_const (exp))
10443     {
10444       int len;
10445
10446       len = exp_end - exp_start;
10447       while (len > 0 && isspace (exp_start[len - 1]))
10448         len--;
10449       error (_("Cannot watch constant value `%.*s'."), len, exp_start);
10450     }
10451
10452   exp_valid_block = innermost_block;
10453   mark = value_mark ();
10454   fetch_subexp_value (exp, &pc, &val, &result, NULL);
10455
10456   if (just_location)
10457     {
10458       int ret;
10459
10460       exp_valid_block = NULL;
10461       val = value_addr (result);
10462       release_value (val);
10463       value_free_to_mark (mark);
10464
10465       if (use_mask)
10466         {
10467           ret = target_masked_watch_num_registers (value_as_address (val),
10468                                                    mask);
10469           if (ret == -1)
10470             error (_("This target does not support masked watchpoints."));
10471           else if (ret == -2)
10472             error (_("Invalid mask or memory region."));
10473         }
10474     }
10475   else if (val != NULL)
10476     release_value (val);
10477
10478   tok = skip_spaces (arg);
10479   end_tok = skip_to_space (tok);
10480
10481   toklen = end_tok - tok;
10482   if (toklen >= 1 && strncmp (tok, "if", toklen) == 0)
10483     {
10484       struct expression *cond;
10485
10486       innermost_block = NULL;
10487       tok = cond_start = end_tok + 1;
10488       cond = parse_exp_1 (&tok, 0, 0);
10489
10490       /* The watchpoint expression may not be local, but the condition
10491          may still be.  E.g.: `watch global if local > 0'.  */
10492       cond_exp_valid_block = innermost_block;
10493
10494       xfree (cond);
10495       cond_end = tok;
10496     }
10497   if (*tok)
10498     error (_("Junk at end of command."));
10499
10500   if (accessflag == hw_read)
10501     bp_type = bp_read_watchpoint;
10502   else if (accessflag == hw_access)
10503     bp_type = bp_access_watchpoint;
10504   else
10505     bp_type = bp_hardware_watchpoint;
10506
10507   frame = block_innermost_frame (exp_valid_block);
10508
10509   /* If the expression is "local", then set up a "watchpoint scope"
10510      breakpoint at the point where we've left the scope of the watchpoint
10511      expression.  Create the scope breakpoint before the watchpoint, so
10512      that we will encounter it first in bpstat_stop_status.  */
10513   if (exp_valid_block && frame)
10514     {
10515       if (frame_id_p (frame_unwind_caller_id (frame)))
10516         {
10517           scope_breakpoint
10518             = create_internal_breakpoint (frame_unwind_caller_arch (frame),
10519                                           frame_unwind_caller_pc (frame),
10520                                           bp_watchpoint_scope,
10521                                           &momentary_breakpoint_ops);
10522
10523           scope_breakpoint->enable_state = bp_enabled;
10524
10525           /* Automatically delete the breakpoint when it hits.  */
10526           scope_breakpoint->disposition = disp_del;
10527
10528           /* Only break in the proper frame (help with recursion).  */
10529           scope_breakpoint->frame_id = frame_unwind_caller_id (frame);
10530
10531           /* Set the address at which we will stop.  */
10532           scope_breakpoint->loc->gdbarch
10533             = frame_unwind_caller_arch (frame);
10534           scope_breakpoint->loc->requested_address
10535             = frame_unwind_caller_pc (frame);
10536           scope_breakpoint->loc->address
10537             = adjust_breakpoint_address (scope_breakpoint->loc->gdbarch,
10538                                          scope_breakpoint->loc->requested_address,
10539                                          scope_breakpoint->type);
10540         }
10541     }
10542
10543   /* Now set up the breakpoint.  */
10544
10545   w = XCNEW (struct watchpoint);
10546   b = &w->base;
10547   if (use_mask)
10548     init_raw_breakpoint_without_location (b, NULL, bp_type,
10549                                           &masked_watchpoint_breakpoint_ops);
10550   else
10551     init_raw_breakpoint_without_location (b, NULL, bp_type,
10552                                           &watchpoint_breakpoint_ops);
10553   b->thread = thread;
10554   b->disposition = disp_donttouch;
10555   b->pspace = current_program_space;
10556   w->exp = exp;
10557   w->exp_valid_block = exp_valid_block;
10558   w->cond_exp_valid_block = cond_exp_valid_block;
10559   if (just_location)
10560     {
10561       struct type *t = value_type (val);
10562       CORE_ADDR addr = value_as_address (val);
10563       char *name;
10564
10565       t = check_typedef (TYPE_TARGET_TYPE (check_typedef (t)));
10566       name = type_to_string (t);
10567
10568       w->exp_string_reparse = xstrprintf ("* (%s *) %s", name,
10569                                           core_addr_to_string (addr));
10570       xfree (name);
10571
10572       w->exp_string = xstrprintf ("-location %.*s",
10573                                   (int) (exp_end - exp_start), exp_start);
10574
10575       /* The above expression is in C.  */
10576       b->language = language_c;
10577     }
10578   else
10579     w->exp_string = savestring (exp_start, exp_end - exp_start);
10580
10581   if (use_mask)
10582     {
10583       w->hw_wp_mask = mask;
10584     }
10585   else
10586     {
10587       w->val = val;
10588       w->val_valid = 1;
10589     }
10590
10591   if (cond_start)
10592     b->cond_string = savestring (cond_start, cond_end - cond_start);
10593   else
10594     b->cond_string = 0;
10595
10596   if (frame)
10597     {
10598       w->watchpoint_frame = get_frame_id (frame);
10599       w->watchpoint_thread = inferior_ptid;
10600     }
10601   else
10602     {
10603       w->watchpoint_frame = null_frame_id;
10604       w->watchpoint_thread = null_ptid;
10605     }
10606
10607   if (scope_breakpoint != NULL)
10608     {
10609       /* The scope breakpoint is related to the watchpoint.  We will
10610          need to act on them together.  */
10611       b->related_breakpoint = scope_breakpoint;
10612       scope_breakpoint->related_breakpoint = b;
10613     }
10614
10615   if (!just_location)
10616     value_free_to_mark (mark);
10617
10618   TRY_CATCH (e, RETURN_MASK_ALL)
10619     {
10620       /* Finally update the new watchpoint.  This creates the locations
10621          that should be inserted.  */
10622       update_watchpoint (w, 1);
10623     }
10624   if (e.reason < 0)
10625     {
10626       delete_breakpoint (b);
10627       throw_exception (e);
10628     }
10629
10630   install_breakpoint (internal, b, 1);
10631 }
10632
10633 /* Return count of debug registers needed to watch the given expression.
10634    If the watchpoint cannot be handled in hardware return zero.  */
10635
10636 static int
10637 can_use_hardware_watchpoint (struct value *v)
10638 {
10639   int found_memory_cnt = 0;
10640   struct value *head = v;
10641
10642   /* Did the user specifically forbid us to use hardware watchpoints? */
10643   if (!can_use_hw_watchpoints)
10644     return 0;
10645
10646   /* Make sure that the value of the expression depends only upon
10647      memory contents, and values computed from them within GDB.  If we
10648      find any register references or function calls, we can't use a
10649      hardware watchpoint.
10650
10651      The idea here is that evaluating an expression generates a series
10652      of values, one holding the value of every subexpression.  (The
10653      expression a*b+c has five subexpressions: a, b, a*b, c, and
10654      a*b+c.)  GDB's values hold almost enough information to establish
10655      the criteria given above --- they identify memory lvalues,
10656      register lvalues, computed values, etcetera.  So we can evaluate
10657      the expression, and then scan the chain of values that leaves
10658      behind to decide whether we can detect any possible change to the
10659      expression's final value using only hardware watchpoints.
10660
10661      However, I don't think that the values returned by inferior
10662      function calls are special in any way.  So this function may not
10663      notice that an expression involving an inferior function call
10664      can't be watched with hardware watchpoints.  FIXME.  */
10665   for (; v; v = value_next (v))
10666     {
10667       if (VALUE_LVAL (v) == lval_memory)
10668         {
10669           if (v != head && value_lazy (v))
10670             /* A lazy memory lvalue in the chain is one that GDB never
10671                needed to fetch; we either just used its address (e.g.,
10672                `a' in `a.b') or we never needed it at all (e.g., `a'
10673                in `a,b').  This doesn't apply to HEAD; if that is
10674                lazy then it was not readable, but watch it anyway.  */
10675             ;
10676           else
10677             {
10678               /* Ahh, memory we actually used!  Check if we can cover
10679                  it with hardware watchpoints.  */
10680               struct type *vtype = check_typedef (value_type (v));
10681
10682               /* We only watch structs and arrays if user asked for it
10683                  explicitly, never if they just happen to appear in a
10684                  middle of some value chain.  */
10685               if (v == head
10686                   || (TYPE_CODE (vtype) != TYPE_CODE_STRUCT
10687                       && TYPE_CODE (vtype) != TYPE_CODE_ARRAY))
10688                 {
10689                   CORE_ADDR vaddr = value_address (v);
10690                   int len;
10691                   int num_regs;
10692
10693                   len = (target_exact_watchpoints
10694                          && is_scalar_type_recursive (vtype))?
10695                     1 : TYPE_LENGTH (value_type (v));
10696
10697                   num_regs = target_region_ok_for_hw_watchpoint (vaddr, len);
10698                   if (!num_regs)
10699                     return 0;
10700                   else
10701                     found_memory_cnt += num_regs;
10702                 }
10703             }
10704         }
10705       else if (VALUE_LVAL (v) != not_lval
10706                && deprecated_value_modifiable (v) == 0)
10707         return 0;       /* These are values from the history (e.g., $1).  */
10708       else if (VALUE_LVAL (v) == lval_register)
10709         return 0;       /* Cannot watch a register with a HW watchpoint.  */
10710     }
10711
10712   /* The expression itself looks suitable for using a hardware
10713      watchpoint, but give the target machine a chance to reject it.  */
10714   return found_memory_cnt;
10715 }
10716
10717 void
10718 watch_command_wrapper (char *arg, int from_tty, int internal)
10719 {
10720   watch_command_1 (arg, hw_write, from_tty, 0, internal);
10721 }
10722
10723 /* A helper function that looks for an argument at the start of a
10724    string.  The argument must also either be at the end of the string,
10725    or be followed by whitespace.  Returns 1 if it finds the argument,
10726    0 otherwise.  If the argument is found, it updates *STR.  */
10727
10728 static int
10729 check_for_argument (char **str, char *arg, int arg_len)
10730 {
10731   if (strncmp (*str, arg, arg_len) == 0
10732       && ((*str)[arg_len] == '\0' || isspace ((*str)[arg_len])))
10733     {
10734       *str += arg_len;
10735       return 1;
10736     }
10737   return 0;
10738 }
10739
10740 /* A helper function that looks for the "-location" argument and then
10741    calls watch_command_1.  */
10742
10743 static void
10744 watch_maybe_just_location (char *arg, int accessflag, int from_tty)
10745 {
10746   int just_location = 0;
10747
10748   if (arg
10749       && (check_for_argument (&arg, "-location", sizeof ("-location") - 1)
10750           || check_for_argument (&arg, "-l", sizeof ("-l") - 1)))
10751     {
10752       arg = skip_spaces (arg);
10753       just_location = 1;
10754     }
10755
10756   watch_command_1 (arg, accessflag, from_tty, just_location, 0);
10757 }
10758
10759 static void
10760 watch_command (char *arg, int from_tty)
10761 {
10762   watch_maybe_just_location (arg, hw_write, from_tty);
10763 }
10764
10765 void
10766 rwatch_command_wrapper (char *arg, int from_tty, int internal)
10767 {
10768   watch_command_1 (arg, hw_read, from_tty, 0, internal);
10769 }
10770
10771 static void
10772 rwatch_command (char *arg, int from_tty)
10773 {
10774   watch_maybe_just_location (arg, hw_read, from_tty);
10775 }
10776
10777 void
10778 awatch_command_wrapper (char *arg, int from_tty, int internal)
10779 {
10780   watch_command_1 (arg, hw_access, from_tty, 0, internal);
10781 }
10782
10783 static void
10784 awatch_command (char *arg, int from_tty)
10785 {
10786   watch_maybe_just_location (arg, hw_access, from_tty);
10787 }
10788 \f
10789
10790 /* Helper routines for the until_command routine in infcmd.c.  Here
10791    because it uses the mechanisms of breakpoints.  */
10792
10793 struct until_break_command_continuation_args
10794 {
10795   struct breakpoint *breakpoint;
10796   struct breakpoint *breakpoint2;
10797   int thread_num;
10798 };
10799
10800 /* This function is called by fetch_inferior_event via the
10801    cmd_continuation pointer, to complete the until command.  It takes
10802    care of cleaning up the temporary breakpoints set up by the until
10803    command.  */
10804 static void
10805 until_break_command_continuation (void *arg, int err)
10806 {
10807   struct until_break_command_continuation_args *a = arg;
10808
10809   delete_breakpoint (a->breakpoint);
10810   if (a->breakpoint2)
10811     delete_breakpoint (a->breakpoint2);
10812   delete_longjmp_breakpoint (a->thread_num);
10813 }
10814
10815 void
10816 until_break_command (char *arg, int from_tty, int anywhere)
10817 {
10818   struct symtabs_and_lines sals;
10819   struct symtab_and_line sal;
10820   struct frame_info *frame = get_selected_frame (NULL);
10821   struct gdbarch *frame_gdbarch = get_frame_arch (frame);
10822   struct frame_id stack_frame_id = get_stack_frame_id (frame);
10823   struct frame_id caller_frame_id = frame_unwind_caller_id (frame);
10824   struct breakpoint *breakpoint;
10825   struct breakpoint *breakpoint2 = NULL;
10826   struct cleanup *old_chain;
10827   int thread;
10828   struct thread_info *tp;
10829
10830   clear_proceed_status ();
10831
10832   /* Set a breakpoint where the user wants it and at return from
10833      this function.  */
10834
10835   if (last_displayed_sal_is_valid ())
10836     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10837                           get_last_displayed_symtab (),
10838                           get_last_displayed_line ());
10839   else
10840     sals = decode_line_1 (&arg, DECODE_LINE_FUNFIRSTLINE,
10841                           (struct symtab *) NULL, 0);
10842
10843   if (sals.nelts != 1)
10844     error (_("Couldn't get information on specified line."));
10845
10846   sal = sals.sals[0];
10847   xfree (sals.sals);    /* malloc'd, so freed.  */
10848
10849   if (*arg)
10850     error (_("Junk at end of arguments."));
10851
10852   resolve_sal_pc (&sal);
10853
10854   tp = inferior_thread ();
10855   thread = tp->num;
10856
10857   old_chain = make_cleanup (null_cleanup, NULL);
10858
10859   /* Installing a breakpoint invalidates the frame chain (as it may
10860      need to switch threads), so do any frame handling first.  */
10861
10862   /* Keep within the current frame, or in frames called by the current
10863      one.  */
10864
10865   if (frame_id_p (caller_frame_id))
10866     {
10867       struct symtab_and_line sal2;
10868
10869       sal2 = find_pc_line (frame_unwind_caller_pc (frame), 0);
10870       sal2.pc = frame_unwind_caller_pc (frame);
10871       breakpoint2 = set_momentary_breakpoint (frame_unwind_caller_arch (frame),
10872                                               sal2,
10873                                               caller_frame_id,
10874                                               bp_until);
10875       make_cleanup_delete_breakpoint (breakpoint2);
10876
10877       set_longjmp_breakpoint (tp, caller_frame_id);
10878       make_cleanup (delete_longjmp_breakpoint_cleanup, &thread);
10879     }
10880
10881   /* set_momentary_breakpoint could invalidate FRAME.  */
10882   frame = NULL;
10883
10884   if (anywhere)
10885     /* If the user told us to continue until a specified location,
10886        we don't specify a frame at which we need to stop.  */
10887     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10888                                            null_frame_id, bp_until);
10889   else
10890     /* Otherwise, specify the selected frame, because we want to stop
10891        only at the very same frame.  */
10892     breakpoint = set_momentary_breakpoint (frame_gdbarch, sal,
10893                                            stack_frame_id, bp_until);
10894   make_cleanup_delete_breakpoint (breakpoint);
10895
10896   proceed (-1, TARGET_SIGNAL_DEFAULT, 0);
10897
10898   /* If we are running asynchronously, and proceed call above has
10899      actually managed to start the target, arrange for breakpoints to
10900      be deleted when the target stops.  Otherwise, we're already
10901      stopped and delete breakpoints via cleanup chain.  */
10902
10903   if (target_can_async_p () && is_running (inferior_ptid))
10904     {
10905       struct until_break_command_continuation_args *args;
10906       args = xmalloc (sizeof (*args));
10907
10908       args->breakpoint = breakpoint;
10909       args->breakpoint2 = breakpoint2;
10910       args->thread_num = thread;
10911
10912       discard_cleanups (old_chain);
10913       add_continuation (inferior_thread (),
10914                         until_break_command_continuation, args,
10915                         xfree);
10916     }
10917   else
10918     do_cleanups (old_chain);
10919 }
10920
10921 /* This function attempts to parse an optional "if <cond>" clause
10922    from the arg string.  If one is not found, it returns NULL.
10923
10924    Else, it returns a pointer to the condition string.  (It does not
10925    attempt to evaluate the string against a particular block.)  And,
10926    it updates arg to point to the first character following the parsed
10927    if clause in the arg string.  */
10928
10929 static char *
10930 ep_parse_optional_if_clause (char **arg)
10931 {
10932   char *cond_string;
10933
10934   if (((*arg)[0] != 'i') || ((*arg)[1] != 'f') || !isspace ((*arg)[2]))
10935     return NULL;
10936
10937   /* Skip the "if" keyword.  */
10938   (*arg) += 2;
10939
10940   /* Skip any extra leading whitespace, and record the start of the
10941      condition string.  */
10942   *arg = skip_spaces (*arg);
10943   cond_string = *arg;
10944
10945   /* Assume that the condition occupies the remainder of the arg
10946      string.  */
10947   (*arg) += strlen (cond_string);
10948
10949   return cond_string;
10950 }
10951
10952 /* Commands to deal with catching events, such as signals, exceptions,
10953    process start/exit, etc.  */
10954
10955 typedef enum
10956 {
10957   catch_fork_temporary, catch_vfork_temporary,
10958   catch_fork_permanent, catch_vfork_permanent
10959 }
10960 catch_fork_kind;
10961
10962 static void
10963 catch_fork_command_1 (char *arg, int from_tty, 
10964                       struct cmd_list_element *command)
10965 {
10966   struct gdbarch *gdbarch = get_current_arch ();
10967   char *cond_string = NULL;
10968   catch_fork_kind fork_kind;
10969   int tempflag;
10970
10971   fork_kind = (catch_fork_kind) (uintptr_t) get_cmd_context (command);
10972   tempflag = (fork_kind == catch_fork_temporary
10973               || fork_kind == catch_vfork_temporary);
10974
10975   if (!arg)
10976     arg = "";
10977   arg = skip_spaces (arg);
10978
10979   /* The allowed syntax is:
10980      catch [v]fork
10981      catch [v]fork if <cond>
10982
10983      First, check if there's an if clause.  */
10984   cond_string = ep_parse_optional_if_clause (&arg);
10985
10986   if ((*arg != '\0') && !isspace (*arg))
10987     error (_("Junk at end of arguments."));
10988
10989   /* If this target supports it, create a fork or vfork catchpoint
10990      and enable reporting of such events.  */
10991   switch (fork_kind)
10992     {
10993     case catch_fork_temporary:
10994     case catch_fork_permanent:
10995       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
10996                                           &catch_fork_breakpoint_ops);
10997       break;
10998     case catch_vfork_temporary:
10999     case catch_vfork_permanent:
11000       create_fork_vfork_event_catchpoint (gdbarch, tempflag, cond_string,
11001                                           &catch_vfork_breakpoint_ops);
11002       break;
11003     default:
11004       error (_("unsupported or unknown fork kind; cannot catch it"));
11005       break;
11006     }
11007 }
11008
11009 static void
11010 catch_exec_command_1 (char *arg, int from_tty, 
11011                       struct cmd_list_element *command)
11012 {
11013   struct exec_catchpoint *c;
11014   struct gdbarch *gdbarch = get_current_arch ();
11015   int tempflag;
11016   char *cond_string = NULL;
11017
11018   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11019
11020   if (!arg)
11021     arg = "";
11022   arg = skip_spaces (arg);
11023
11024   /* The allowed syntax is:
11025      catch exec
11026      catch exec if <cond>
11027
11028      First, check if there's an if clause.  */
11029   cond_string = ep_parse_optional_if_clause (&arg);
11030
11031   if ((*arg != '\0') && !isspace (*arg))
11032     error (_("Junk at end of arguments."));
11033
11034   c = XNEW (struct exec_catchpoint);
11035   init_catchpoint (&c->base, gdbarch, tempflag, cond_string,
11036                    &catch_exec_breakpoint_ops);
11037   c->exec_pathname = NULL;
11038
11039   install_breakpoint (0, &c->base, 1);
11040 }
11041
11042 static enum print_stop_action
11043 print_it_exception_catchpoint (bpstat bs)
11044 {
11045   struct ui_out *uiout = current_uiout;
11046   struct breakpoint *b = bs->breakpoint_at;
11047   int bp_temp, bp_throw;
11048
11049   annotate_catchpoint (b->number);
11050
11051   bp_throw = strstr (b->addr_string, "throw") != NULL;
11052   if (b->loc->address != b->loc->requested_address)
11053     breakpoint_adjustment_warning (b->loc->requested_address,
11054                                    b->loc->address,
11055                                    b->number, 1);
11056   bp_temp = b->disposition == disp_del;
11057   ui_out_text (uiout, 
11058                bp_temp ? "Temporary catchpoint "
11059                        : "Catchpoint ");
11060   if (!ui_out_is_mi_like_p (uiout))
11061     ui_out_field_int (uiout, "bkptno", b->number);
11062   ui_out_text (uiout,
11063                bp_throw ? " (exception thrown), "
11064                         : " (exception caught), ");
11065   if (ui_out_is_mi_like_p (uiout))
11066     {
11067       ui_out_field_string (uiout, "reason", 
11068                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
11069       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
11070       ui_out_field_int (uiout, "bkptno", b->number);
11071     }
11072   return PRINT_SRC_AND_LOC;
11073 }
11074
11075 static void
11076 print_one_exception_catchpoint (struct breakpoint *b, 
11077                                 struct bp_location **last_loc)
11078 {
11079   struct value_print_options opts;
11080   struct ui_out *uiout = current_uiout;
11081
11082   get_user_print_options (&opts);
11083   if (opts.addressprint)
11084     {
11085       annotate_field (4);
11086       if (b->loc == NULL || b->loc->shlib_disabled)
11087         ui_out_field_string (uiout, "addr", "<PENDING>");
11088       else
11089         ui_out_field_core_addr (uiout, "addr",
11090                                 b->loc->gdbarch, b->loc->address);
11091     }
11092   annotate_field (5);
11093   if (b->loc)
11094     *last_loc = b->loc;
11095   if (strstr (b->addr_string, "throw") != NULL)
11096     ui_out_field_string (uiout, "what", "exception throw");
11097   else
11098     ui_out_field_string (uiout, "what", "exception catch");
11099 }
11100
11101 static void
11102 print_mention_exception_catchpoint (struct breakpoint *b)
11103 {
11104   struct ui_out *uiout = current_uiout;
11105   int bp_temp;
11106   int bp_throw;
11107
11108   bp_temp = b->disposition == disp_del;
11109   bp_throw = strstr (b->addr_string, "throw") != NULL;
11110   ui_out_text (uiout, bp_temp ? _("Temporary catchpoint ")
11111                               : _("Catchpoint "));
11112   ui_out_field_int (uiout, "bkptno", b->number);
11113   ui_out_text (uiout, bp_throw ? _(" (throw)")
11114                                : _(" (catch)"));
11115 }
11116
11117 /* Implement the "print_recreate" breakpoint_ops method for throw and
11118    catch catchpoints.  */
11119
11120 static void
11121 print_recreate_exception_catchpoint (struct breakpoint *b, 
11122                                      struct ui_file *fp)
11123 {
11124   int bp_temp;
11125   int bp_throw;
11126
11127   bp_temp = b->disposition == disp_del;
11128   bp_throw = strstr (b->addr_string, "throw") != NULL;
11129   fprintf_unfiltered (fp, bp_temp ? "tcatch " : "catch ");
11130   fprintf_unfiltered (fp, bp_throw ? "throw" : "catch");
11131   print_recreate_thread (b, fp);
11132 }
11133
11134 static struct breakpoint_ops gnu_v3_exception_catchpoint_ops;
11135
11136 static int
11137 handle_gnu_v3_exceptions (int tempflag, char *cond_string,
11138                           enum exception_event_kind ex_event, int from_tty)
11139 {
11140   char *trigger_func_name;
11141  
11142   if (ex_event == EX_EVENT_CATCH)
11143     trigger_func_name = "__cxa_begin_catch";
11144   else
11145     trigger_func_name = "__cxa_throw";
11146
11147   create_breakpoint (get_current_arch (),
11148                      trigger_func_name, cond_string, -1, NULL,
11149                      0 /* condition and thread are valid.  */,
11150                      tempflag, bp_breakpoint,
11151                      0,
11152                      AUTO_BOOLEAN_TRUE /* pending */,
11153                      &gnu_v3_exception_catchpoint_ops, from_tty,
11154                      1 /* enabled */,
11155                      0 /* internal */,
11156                      0);
11157
11158   return 1;
11159 }
11160
11161 /* Deal with "catch catch" and "catch throw" commands.  */
11162
11163 static void
11164 catch_exception_command_1 (enum exception_event_kind ex_event, char *arg,
11165                            int tempflag, int from_tty)
11166 {
11167   char *cond_string = NULL;
11168
11169   if (!arg)
11170     arg = "";
11171   arg = skip_spaces (arg);
11172
11173   cond_string = ep_parse_optional_if_clause (&arg);
11174
11175   if ((*arg != '\0') && !isspace (*arg))
11176     error (_("Junk at end of arguments."));
11177
11178   if (ex_event != EX_EVENT_THROW
11179       && ex_event != EX_EVENT_CATCH)
11180     error (_("Unsupported or unknown exception event; cannot catch it"));
11181
11182   if (handle_gnu_v3_exceptions (tempflag, cond_string, ex_event, from_tty))
11183     return;
11184
11185   warning (_("Unsupported with this platform/compiler combination."));
11186 }
11187
11188 /* Implementation of "catch catch" command.  */
11189
11190 static void
11191 catch_catch_command (char *arg, int from_tty, struct cmd_list_element *command)
11192 {
11193   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11194
11195   catch_exception_command_1 (EX_EVENT_CATCH, arg, tempflag, from_tty);
11196 }
11197
11198 /* Implementation of "catch throw" command.  */
11199
11200 static void
11201 catch_throw_command (char *arg, int from_tty, struct cmd_list_element *command)
11202 {
11203   int tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11204
11205   catch_exception_command_1 (EX_EVENT_THROW, arg, tempflag, from_tty);
11206 }
11207
11208 void
11209 init_ada_exception_breakpoint (struct breakpoint *b,
11210                                struct gdbarch *gdbarch,
11211                                struct symtab_and_line sal,
11212                                char *addr_string,
11213                                const struct breakpoint_ops *ops,
11214                                int tempflag,
11215                                int from_tty)
11216 {
11217   if (from_tty)
11218     {
11219       struct gdbarch *loc_gdbarch = get_sal_arch (sal);
11220       if (!loc_gdbarch)
11221         loc_gdbarch = gdbarch;
11222
11223       describe_other_breakpoints (loc_gdbarch,
11224                                   sal.pspace, sal.pc, sal.section, -1);
11225       /* FIXME: brobecker/2006-12-28: Actually, re-implement a special
11226          version for exception catchpoints, because two catchpoints
11227          used for different exception names will use the same address.
11228          In this case, a "breakpoint ... also set at..." warning is
11229          unproductive.  Besides, the warning phrasing is also a bit
11230          inappropriate, we should use the word catchpoint, and tell
11231          the user what type of catchpoint it is.  The above is good
11232          enough for now, though.  */
11233     }
11234
11235   init_raw_breakpoint (b, gdbarch, sal, bp_breakpoint, ops);
11236
11237   b->enable_state = bp_enabled;
11238   b->disposition = tempflag ? disp_del : disp_donttouch;
11239   b->addr_string = addr_string;
11240   b->language = language_ada;
11241 }
11242
11243 /* Splits the argument using space as delimiter.  Returns an xmalloc'd
11244    filter list, or NULL if no filtering is required.  */
11245 static VEC(int) *
11246 catch_syscall_split_args (char *arg)
11247 {
11248   VEC(int) *result = NULL;
11249   struct cleanup *cleanup = make_cleanup (VEC_cleanup (int), &result);
11250
11251   while (*arg != '\0')
11252     {
11253       int i, syscall_number;
11254       char *endptr;
11255       char cur_name[128];
11256       struct syscall s;
11257
11258       /* Skip whitespace.  */
11259       while (isspace (*arg))
11260         arg++;
11261
11262       for (i = 0; i < 127 && arg[i] && !isspace (arg[i]); ++i)
11263         cur_name[i] = arg[i];
11264       cur_name[i] = '\0';
11265       arg += i;
11266
11267       /* Check if the user provided a syscall name or a number.  */
11268       syscall_number = (int) strtol (cur_name, &endptr, 0);
11269       if (*endptr == '\0')
11270         get_syscall_by_number (syscall_number, &s);
11271       else
11272         {
11273           /* We have a name.  Let's check if it's valid and convert it
11274              to a number.  */
11275           get_syscall_by_name (cur_name, &s);
11276
11277           if (s.number == UNKNOWN_SYSCALL)
11278             /* Here we have to issue an error instead of a warning,
11279                because GDB cannot do anything useful if there's no
11280                syscall number to be caught.  */
11281             error (_("Unknown syscall name '%s'."), cur_name);
11282         }
11283
11284       /* Ok, it's valid.  */
11285       VEC_safe_push (int, result, s.number);
11286     }
11287
11288   discard_cleanups (cleanup);
11289   return result;
11290 }
11291
11292 /* Implement the "catch syscall" command.  */
11293
11294 static void
11295 catch_syscall_command_1 (char *arg, int from_tty, 
11296                          struct cmd_list_element *command)
11297 {
11298   int tempflag;
11299   VEC(int) *filter;
11300   struct syscall s;
11301   struct gdbarch *gdbarch = get_current_arch ();
11302
11303   /* Checking if the feature if supported.  */
11304   if (gdbarch_get_syscall_number_p (gdbarch) == 0)
11305     error (_("The feature 'catch syscall' is not supported on \
11306 this architecture yet."));
11307
11308   tempflag = get_cmd_context (command) == CATCH_TEMPORARY;
11309
11310   arg = skip_spaces (arg);
11311
11312   /* We need to do this first "dummy" translation in order
11313      to get the syscall XML file loaded or, most important,
11314      to display a warning to the user if there's no XML file
11315      for his/her architecture.  */
11316   get_syscall_by_number (0, &s);
11317
11318   /* The allowed syntax is:
11319      catch syscall
11320      catch syscall <name | number> [<name | number> ... <name | number>]
11321
11322      Let's check if there's a syscall name.  */
11323
11324   if (arg != NULL)
11325     filter = catch_syscall_split_args (arg);
11326   else
11327     filter = NULL;
11328
11329   create_syscall_event_catchpoint (tempflag, filter,
11330                                    &catch_syscall_breakpoint_ops);
11331 }
11332
11333 static void
11334 catch_command (char *arg, int from_tty)
11335 {
11336   error (_("Catch requires an event name."));
11337 }
11338 \f
11339
11340 static void
11341 tcatch_command (char *arg, int from_tty)
11342 {
11343   error (_("Catch requires an event name."));
11344 }
11345
11346 /* A qsort comparison function that sorts breakpoints in order.  */
11347
11348 static int
11349 compare_breakpoints (const void *a, const void *b)
11350 {
11351   const breakpoint_p *ba = a;
11352   uintptr_t ua = (uintptr_t) *ba;
11353   const breakpoint_p *bb = b;
11354   uintptr_t ub = (uintptr_t) *bb;
11355
11356   if ((*ba)->number < (*bb)->number)
11357     return -1;
11358   else if ((*ba)->number > (*bb)->number)
11359     return 1;
11360
11361   /* Now sort by address, in case we see, e..g, two breakpoints with
11362      the number 0.  */
11363   if (ua < ub)
11364     return -1;
11365   return ub > ub ? 1 : 0;
11366 }
11367
11368 /* Delete breakpoints by address or line.  */
11369
11370 static void
11371 clear_command (char *arg, int from_tty)
11372 {
11373   struct breakpoint *b, *prev;
11374   VEC(breakpoint_p) *found = 0;
11375   int ix;
11376   int default_match;
11377   struct symtabs_and_lines sals;
11378   struct symtab_and_line sal;
11379   int i;
11380   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
11381
11382   if (arg)
11383     {
11384       sals = decode_line_spec (arg, (DECODE_LINE_FUNFIRSTLINE
11385                                      | DECODE_LINE_LIST_MODE));
11386       default_match = 0;
11387     }
11388   else
11389     {
11390       sals.sals = (struct symtab_and_line *)
11391         xmalloc (sizeof (struct symtab_and_line));
11392       make_cleanup (xfree, sals.sals);
11393       init_sal (&sal);          /* Initialize to zeroes.  */
11394
11395       /* Set sal's line, symtab, pc, and pspace to the values
11396          corresponding to the last call to print_frame_info.  If the
11397          codepoint is not valid, this will set all the fields to 0.  */
11398       get_last_displayed_sal (&sal);
11399       if (sal.symtab == 0)
11400         error (_("No source file specified."));
11401
11402       sals.sals[0] = sal;
11403       sals.nelts = 1;
11404
11405       default_match = 1;
11406     }
11407
11408   /* We don't call resolve_sal_pc here.  That's not as bad as it
11409      seems, because all existing breakpoints typically have both
11410      file/line and pc set.  So, if clear is given file/line, we can
11411      match this to existing breakpoint without obtaining pc at all.
11412
11413      We only support clearing given the address explicitly 
11414      present in breakpoint table.  Say, we've set breakpoint 
11415      at file:line.  There were several PC values for that file:line,
11416      due to optimization, all in one block.
11417
11418      We've picked one PC value.  If "clear" is issued with another
11419      PC corresponding to the same file:line, the breakpoint won't
11420      be cleared.  We probably can still clear the breakpoint, but 
11421      since the other PC value is never presented to user, user
11422      can only find it by guessing, and it does not seem important
11423      to support that.  */
11424
11425   /* For each line spec given, delete bps which correspond to it.  Do
11426      it in two passes, solely to preserve the current behavior that
11427      from_tty is forced true if we delete more than one
11428      breakpoint.  */
11429
11430   found = NULL;
11431   make_cleanup (VEC_cleanup (breakpoint_p), &found);
11432   for (i = 0; i < sals.nelts; i++)
11433     {
11434       int is_abs, sal_name_len;
11435
11436       /* If exact pc given, clear bpts at that pc.
11437          If line given (pc == 0), clear all bpts on specified line.
11438          If defaulting, clear all bpts on default line
11439          or at default pc.
11440
11441          defaulting    sal.pc != 0    tests to do
11442
11443          0              1             pc
11444          1              1             pc _and_ line
11445          0              0             line
11446          1              0             <can't happen> */
11447
11448       sal = sals.sals[i];
11449       is_abs = sal.symtab == NULL ? 1 : IS_ABSOLUTE_PATH (sal.symtab->filename);
11450       sal_name_len = is_abs ? 0 : strlen (sal.symtab->filename);
11451
11452       /* Find all matching breakpoints and add them to 'found'.  */
11453       ALL_BREAKPOINTS (b)
11454         {
11455           int match = 0;
11456           /* Are we going to delete b?  */
11457           if (b->type != bp_none && !is_watchpoint (b))
11458             {
11459               struct bp_location *loc = b->loc;
11460               for (; loc; loc = loc->next)
11461                 {
11462                   /* If the user specified file:line, don't allow a PC
11463                      match.  This matches historical gdb behavior.  */
11464                   int pc_match = (!sal.explicit_line
11465                                   && sal.pc
11466                                   && (loc->pspace == sal.pspace)
11467                                   && (loc->address == sal.pc)
11468                                   && (!section_is_overlay (loc->section)
11469                                       || loc->section == sal.section));
11470                   int line_match = 0;
11471
11472                   if ((default_match || sal.explicit_line)
11473                       && loc->source_file != NULL
11474                       && sal.symtab != NULL
11475                       && sal.pspace == loc->pspace
11476                       && loc->line_number == sal.line)
11477                     {
11478                       if (filename_cmp (loc->source_file,
11479                                         sal.symtab->filename) == 0)
11480                         line_match = 1;
11481                       else if (!IS_ABSOLUTE_PATH (sal.symtab->filename)
11482                                && compare_filenames_for_search (loc->source_file,
11483                                                                 sal.symtab->filename,
11484                                                                 sal_name_len))
11485                         line_match = 1;
11486                     }
11487
11488                   if (pc_match || line_match)
11489                     {
11490                       match = 1;
11491                       break;
11492                     }
11493                 }
11494             }
11495
11496           if (match)
11497             VEC_safe_push(breakpoint_p, found, b);
11498         }
11499     }
11500
11501   /* Now go thru the 'found' chain and delete them.  */
11502   if (VEC_empty(breakpoint_p, found))
11503     {
11504       if (arg)
11505         error (_("No breakpoint at %s."), arg);
11506       else
11507         error (_("No breakpoint at this line."));
11508     }
11509
11510   /* Remove duplicates from the vec.  */
11511   qsort (VEC_address (breakpoint_p, found),
11512          VEC_length (breakpoint_p, found),
11513          sizeof (breakpoint_p),
11514          compare_breakpoints);
11515   prev = VEC_index (breakpoint_p, found, 0);
11516   for (ix = 1; VEC_iterate (breakpoint_p, found, ix, b); ++ix)
11517     {
11518       if (b == prev)
11519         {
11520           VEC_ordered_remove (breakpoint_p, found, ix);
11521           --ix;
11522         }
11523     }
11524
11525   if (VEC_length(breakpoint_p, found) > 1)
11526     from_tty = 1;       /* Always report if deleted more than one.  */
11527   if (from_tty)
11528     {
11529       if (VEC_length(breakpoint_p, found) == 1)
11530         printf_unfiltered (_("Deleted breakpoint "));
11531       else
11532         printf_unfiltered (_("Deleted breakpoints "));
11533     }
11534   breakpoints_changed ();
11535
11536   for (ix = 0; VEC_iterate(breakpoint_p, found, ix, b); ix++)
11537     {
11538       if (from_tty)
11539         printf_unfiltered ("%d ", b->number);
11540       delete_breakpoint (b);
11541     }
11542   if (from_tty)
11543     putchar_unfiltered ('\n');
11544
11545   do_cleanups (cleanups);
11546 }
11547 \f
11548 /* Delete breakpoint in BS if they are `delete' breakpoints and
11549    all breakpoints that are marked for deletion, whether hit or not.
11550    This is called after any breakpoint is hit, or after errors.  */
11551
11552 void
11553 breakpoint_auto_delete (bpstat bs)
11554 {
11555   struct breakpoint *b, *b_tmp;
11556
11557   for (; bs; bs = bs->next)
11558     if (bs->breakpoint_at
11559         && bs->breakpoint_at->disposition == disp_del
11560         && bs->stop)
11561       delete_breakpoint (bs->breakpoint_at);
11562
11563   ALL_BREAKPOINTS_SAFE (b, b_tmp)
11564   {
11565     if (b->disposition == disp_del_at_next_stop)
11566       delete_breakpoint (b);
11567   }
11568 }
11569
11570 /* A comparison function for bp_location AP and BP being interfaced to
11571    qsort.  Sort elements primarily by their ADDRESS (no matter what
11572    does breakpoint_address_is_meaningful say for its OWNER),
11573    secondarily by ordering first bp_permanent OWNERed elements and
11574    terciarily just ensuring the array is sorted stable way despite
11575    qsort being an unstable algorithm.  */
11576
11577 static int
11578 bp_location_compare (const void *ap, const void *bp)
11579 {
11580   struct bp_location *a = *(void **) ap;
11581   struct bp_location *b = *(void **) bp;
11582   /* A and B come from existing breakpoints having non-NULL OWNER.  */
11583   int a_perm = a->owner->enable_state == bp_permanent;
11584   int b_perm = b->owner->enable_state == bp_permanent;
11585
11586   if (a->address != b->address)
11587     return (a->address > b->address) - (a->address < b->address);
11588
11589   /* Sort locations at the same address by their pspace number, keeping
11590      locations of the same inferior (in a multi-inferior environment)
11591      grouped.  */
11592
11593   if (a->pspace->num != b->pspace->num)
11594     return ((a->pspace->num > b->pspace->num)
11595             - (a->pspace->num < b->pspace->num));
11596
11597   /* Sort permanent breakpoints first.  */
11598   if (a_perm != b_perm)
11599     return (a_perm < b_perm) - (a_perm > b_perm);
11600
11601   /* Make the internal GDB representation stable across GDB runs
11602      where A and B memory inside GDB can differ.  Breakpoint locations of
11603      the same type at the same address can be sorted in arbitrary order.  */
11604
11605   if (a->owner->number != b->owner->number)
11606     return ((a->owner->number > b->owner->number)
11607             - (a->owner->number < b->owner->number));
11608
11609   return (a > b) - (a < b);
11610 }
11611
11612 /* Set bp_location_placed_address_before_address_max and
11613    bp_location_shadow_len_after_address_max according to the current
11614    content of the bp_location array.  */
11615
11616 static void
11617 bp_location_target_extensions_update (void)
11618 {
11619   struct bp_location *bl, **blp_tmp;
11620
11621   bp_location_placed_address_before_address_max = 0;
11622   bp_location_shadow_len_after_address_max = 0;
11623
11624   ALL_BP_LOCATIONS (bl, blp_tmp)
11625     {
11626       CORE_ADDR start, end, addr;
11627
11628       if (!bp_location_has_shadow (bl))
11629         continue;
11630
11631       start = bl->target_info.placed_address;
11632       end = start + bl->target_info.shadow_len;
11633
11634       gdb_assert (bl->address >= start);
11635       addr = bl->address - start;
11636       if (addr > bp_location_placed_address_before_address_max)
11637         bp_location_placed_address_before_address_max = addr;
11638
11639       /* Zero SHADOW_LEN would not pass bp_location_has_shadow.  */
11640
11641       gdb_assert (bl->address < end);
11642       addr = end - bl->address;
11643       if (addr > bp_location_shadow_len_after_address_max)
11644         bp_location_shadow_len_after_address_max = addr;
11645     }
11646 }
11647
11648 /* Download tracepoint locations if they haven't been.  */
11649
11650 static void
11651 download_tracepoint_locations (void)
11652 {
11653   struct bp_location *bl, **blp_tmp;
11654   struct cleanup *old_chain;
11655
11656   if (!target_can_download_tracepoint ())
11657     return;
11658
11659   old_chain = save_current_space_and_thread ();
11660
11661   ALL_BP_LOCATIONS (bl, blp_tmp)
11662     {
11663       struct tracepoint *t;
11664
11665       if (!is_tracepoint (bl->owner))
11666         continue;
11667
11668       if ((bl->owner->type == bp_fast_tracepoint
11669            ? !may_insert_fast_tracepoints
11670            : !may_insert_tracepoints))
11671         continue;
11672
11673       /* In tracepoint, locations are _never_ duplicated, so
11674          should_be_inserted is equivalent to
11675          unduplicated_should_be_inserted.  */
11676       if (!should_be_inserted (bl) || bl->inserted)
11677         continue;
11678
11679       switch_to_program_space_and_thread (bl->pspace);
11680
11681       target_download_tracepoint (bl);
11682
11683       bl->inserted = 1;
11684       t = (struct tracepoint *) bl->owner;
11685       t->number_on_target = bl->owner->number;
11686     }
11687
11688   do_cleanups (old_chain);
11689 }
11690
11691 /* Swap the insertion/duplication state between two locations.  */
11692
11693 static void
11694 swap_insertion (struct bp_location *left, struct bp_location *right)
11695 {
11696   const int left_inserted = left->inserted;
11697   const int left_duplicate = left->duplicate;
11698   const int left_needs_update = left->needs_update;
11699   const struct bp_target_info left_target_info = left->target_info;
11700
11701   /* Locations of tracepoints can never be duplicated.  */
11702   if (is_tracepoint (left->owner))
11703     gdb_assert (!left->duplicate);
11704   if (is_tracepoint (right->owner))
11705     gdb_assert (!right->duplicate);
11706
11707   left->inserted = right->inserted;
11708   left->duplicate = right->duplicate;
11709   left->needs_update = right->needs_update;
11710   left->target_info = right->target_info;
11711   right->inserted = left_inserted;
11712   right->duplicate = left_duplicate;
11713   right->needs_update = left_needs_update;
11714   right->target_info = left_target_info;
11715 }
11716
11717 /* Force the re-insertion of the locations at ADDRESS.  This is called
11718    once a new/deleted/modified duplicate location is found and we are evaluating
11719    conditions on the target's side.  Such conditions need to be updated on
11720    the target.  */
11721
11722 static void
11723 force_breakpoint_reinsertion (struct bp_location *bl)
11724 {
11725   struct bp_location **locp = NULL, **loc2p;
11726   struct bp_location *loc;
11727   CORE_ADDR address = 0;
11728   int pspace_num;
11729
11730   address = bl->address;
11731   pspace_num = bl->pspace->num;
11732
11733   /* This is only meaningful if the target is
11734      evaluating conditions and if the user has
11735      opted for condition evaluation on the target's
11736      side.  */
11737   if (gdb_evaluates_breakpoint_condition_p ()
11738       || !target_supports_evaluation_of_breakpoint_conditions ())
11739     return;
11740
11741   /* Flag all breakpoint locations with this address and
11742      the same program space as the location
11743      as "its condition has changed".  We need to
11744      update the conditions on the target's side.  */
11745   ALL_BP_LOCATIONS_AT_ADDR (loc2p, locp, address)
11746     {
11747       loc = *loc2p;
11748
11749       if (!is_breakpoint (loc->owner)
11750           || pspace_num != loc->pspace->num)
11751         continue;
11752
11753       /* Flag the location appropriately.  We use a different state to
11754          let everyone know that we already updated the set of locations
11755          with addr bl->address and program space bl->pspace.  This is so
11756          we don't have to keep calling these functions just to mark locations
11757          that have already been marked.  */
11758       loc->condition_changed = condition_updated;
11759
11760       /* Free the agent expression bytecode as well.  We will compute
11761          it later on.  */
11762       if (loc->cond_bytecode)
11763         {
11764           free_agent_expr (loc->cond_bytecode);
11765           loc->cond_bytecode = NULL;
11766         }
11767     }
11768 }
11769
11770 /* If SHOULD_INSERT is false, do not insert any breakpoint locations
11771    into the inferior, only remove already-inserted locations that no
11772    longer should be inserted.  Functions that delete a breakpoint or
11773    breakpoints should pass false, so that deleting a breakpoint
11774    doesn't have the side effect of inserting the locations of other
11775    breakpoints that are marked not-inserted, but should_be_inserted
11776    returns true on them.
11777
11778    This behaviour is useful is situations close to tear-down -- e.g.,
11779    after an exec, while the target still has execution, but breakpoint
11780    shadows of the previous executable image should *NOT* be restored
11781    to the new image; or before detaching, where the target still has
11782    execution and wants to delete breakpoints from GDB's lists, and all
11783    breakpoints had already been removed from the inferior.  */
11784
11785 static void
11786 update_global_location_list (int should_insert)
11787 {
11788   struct breakpoint *b;
11789   struct bp_location **locp, *loc;
11790   struct cleanup *cleanups;
11791   /* Last breakpoint location address that was marked for update.  */
11792   CORE_ADDR last_addr = 0;
11793   /* Last breakpoint location program space that was marked for update.  */
11794   int last_pspace_num = -1;
11795
11796   /* Used in the duplicates detection below.  When iterating over all
11797      bp_locations, points to the first bp_location of a given address.
11798      Breakpoints and watchpoints of different types are never
11799      duplicates of each other.  Keep one pointer for each type of
11800      breakpoint/watchpoint, so we only need to loop over all locations
11801      once.  */
11802   struct bp_location *bp_loc_first;  /* breakpoint */
11803   struct bp_location *wp_loc_first;  /* hardware watchpoint */
11804   struct bp_location *awp_loc_first; /* access watchpoint */
11805   struct bp_location *rwp_loc_first; /* read watchpoint */
11806
11807   /* Saved former bp_location array which we compare against the newly
11808      built bp_location from the current state of ALL_BREAKPOINTS.  */
11809   struct bp_location **old_location, **old_locp;
11810   unsigned old_location_count;
11811
11812   old_location = bp_location;
11813   old_location_count = bp_location_count;
11814   bp_location = NULL;
11815   bp_location_count = 0;
11816   cleanups = make_cleanup (xfree, old_location);
11817
11818   ALL_BREAKPOINTS (b)
11819     for (loc = b->loc; loc; loc = loc->next)
11820       bp_location_count++;
11821
11822   bp_location = xmalloc (sizeof (*bp_location) * bp_location_count);
11823   locp = bp_location;
11824   ALL_BREAKPOINTS (b)
11825     for (loc = b->loc; loc; loc = loc->next)
11826       *locp++ = loc;
11827   qsort (bp_location, bp_location_count, sizeof (*bp_location),
11828          bp_location_compare);
11829
11830   bp_location_target_extensions_update ();
11831
11832   /* Identify bp_location instances that are no longer present in the
11833      new list, and therefore should be freed.  Note that it's not
11834      necessary that those locations should be removed from inferior --
11835      if there's another location at the same address (previously
11836      marked as duplicate), we don't need to remove/insert the
11837      location.
11838      
11839      LOCP is kept in sync with OLD_LOCP, each pointing to the current
11840      and former bp_location array state respectively.  */
11841
11842   locp = bp_location;
11843   for (old_locp = old_location; old_locp < old_location + old_location_count;
11844        old_locp++)
11845     {
11846       struct bp_location *old_loc = *old_locp;
11847       struct bp_location **loc2p;
11848
11849       /* Tells if 'old_loc' is found among the new locations.  If
11850          not, we have to free it.  */
11851       int found_object = 0;
11852       /* Tells if the location should remain inserted in the target.  */
11853       int keep_in_target = 0;
11854       int removed = 0;
11855
11856       /* Skip LOCP entries which will definitely never be needed.
11857          Stop either at or being the one matching OLD_LOC.  */
11858       while (locp < bp_location + bp_location_count
11859              && (*locp)->address < old_loc->address)
11860         locp++;
11861
11862       for (loc2p = locp;
11863            (loc2p < bp_location + bp_location_count
11864             && (*loc2p)->address == old_loc->address);
11865            loc2p++)
11866         {
11867           /* Check if this is a new/duplicated location or a duplicated
11868              location that had its condition modified.  If so, we want to send
11869              its condition to the target if evaluation of conditions is taking
11870              place there.  */
11871           if ((*loc2p)->condition_changed == condition_modified
11872               && (last_addr != old_loc->address
11873                   || last_pspace_num != old_loc->pspace->num))
11874             {
11875               force_breakpoint_reinsertion (*loc2p);
11876               last_pspace_num = old_loc->pspace->num;
11877             }
11878
11879           if (*loc2p == old_loc)
11880             found_object = 1;
11881         }
11882
11883       /* We have already handled this address, update it so that we don't
11884          have to go through updates again.  */
11885       last_addr = old_loc->address;
11886
11887       /* Target-side condition evaluation: Handle deleted locations.  */
11888       if (!found_object)
11889         force_breakpoint_reinsertion (old_loc);
11890
11891       /* If this location is no longer present, and inserted, look if
11892          there's maybe a new location at the same address.  If so,
11893          mark that one inserted, and don't remove this one.  This is
11894          needed so that we don't have a time window where a breakpoint
11895          at certain location is not inserted.  */
11896
11897       if (old_loc->inserted)
11898         {
11899           /* If the location is inserted now, we might have to remove
11900              it.  */
11901
11902           if (found_object && should_be_inserted (old_loc))
11903             {
11904               /* The location is still present in the location list,
11905                  and still should be inserted.  Don't do anything.  */
11906               keep_in_target = 1;
11907             }
11908           else
11909             {
11910               /* This location still exists, but it won't be kept in the
11911                  target since it may have been disabled.  We proceed to
11912                  remove its target-side condition.  */
11913
11914               /* The location is either no longer present, or got
11915                  disabled.  See if there's another location at the
11916                  same address, in which case we don't need to remove
11917                  this one from the target.  */
11918
11919               /* OLD_LOC comes from existing struct breakpoint.  */
11920               if (breakpoint_address_is_meaningful (old_loc->owner))
11921                 {
11922                   for (loc2p = locp;
11923                        (loc2p < bp_location + bp_location_count
11924                         && (*loc2p)->address == old_loc->address);
11925                        loc2p++)
11926                     {
11927                       struct bp_location *loc2 = *loc2p;
11928
11929                       if (breakpoint_locations_match (loc2, old_loc))
11930                         {
11931                           /* Read watchpoint locations are switched to
11932                              access watchpoints, if the former are not
11933                              supported, but the latter are.  */
11934                           if (is_hardware_watchpoint (old_loc->owner))
11935                             {
11936                               gdb_assert (is_hardware_watchpoint (loc2->owner));
11937                               loc2->watchpoint_type = old_loc->watchpoint_type;
11938                             }
11939
11940                           /* loc2 is a duplicated location. We need to check
11941                              if it should be inserted in case it will be
11942                              unduplicated.  */
11943                           if (loc2 != old_loc
11944                               && unduplicated_should_be_inserted (loc2))
11945                             {
11946                               swap_insertion (old_loc, loc2);
11947                               keep_in_target = 1;
11948                               break;
11949                             }
11950                         }
11951                     }
11952                 }
11953             }
11954
11955           if (!keep_in_target)
11956             {
11957               if (remove_breakpoint (old_loc, mark_uninserted))
11958                 {
11959                   /* This is just about all we can do.  We could keep
11960                      this location on the global list, and try to
11961                      remove it next time, but there's no particular
11962                      reason why we will succeed next time.
11963                      
11964                      Note that at this point, old_loc->owner is still
11965                      valid, as delete_breakpoint frees the breakpoint
11966                      only after calling us.  */
11967                   printf_filtered (_("warning: Error removing "
11968                                      "breakpoint %d\n"), 
11969                                    old_loc->owner->number);
11970                 }
11971               removed = 1;
11972             }
11973         }
11974
11975       if (!found_object)
11976         {
11977           if (removed && non_stop
11978               && breakpoint_address_is_meaningful (old_loc->owner)
11979               && !is_hardware_watchpoint (old_loc->owner))
11980             {
11981               /* This location was removed from the target.  In
11982                  non-stop mode, a race condition is possible where
11983                  we've removed a breakpoint, but stop events for that
11984                  breakpoint are already queued and will arrive later.
11985                  We apply an heuristic to be able to distinguish such
11986                  SIGTRAPs from other random SIGTRAPs: we keep this
11987                  breakpoint location for a bit, and will retire it
11988                  after we see some number of events.  The theory here
11989                  is that reporting of events should, "on the average",
11990                  be fair, so after a while we'll see events from all
11991                  threads that have anything of interest, and no longer
11992                  need to keep this breakpoint location around.  We
11993                  don't hold locations forever so to reduce chances of
11994                  mistaking a non-breakpoint SIGTRAP for a breakpoint
11995                  SIGTRAP.
11996
11997                  The heuristic failing can be disastrous on
11998                  decr_pc_after_break targets.
11999
12000                  On decr_pc_after_break targets, like e.g., x86-linux,
12001                  if we fail to recognize a late breakpoint SIGTRAP,
12002                  because events_till_retirement has reached 0 too
12003                  soon, we'll fail to do the PC adjustment, and report
12004                  a random SIGTRAP to the user.  When the user resumes
12005                  the inferior, it will most likely immediately crash
12006                  with SIGILL/SIGBUS/SIGSEGV, or worse, get silently
12007                  corrupted, because of being resumed e.g., in the
12008                  middle of a multi-byte instruction, or skipped a
12009                  one-byte instruction.  This was actually seen happen
12010                  on native x86-linux, and should be less rare on
12011                  targets that do not support new thread events, like
12012                  remote, due to the heuristic depending on
12013                  thread_count.
12014
12015                  Mistaking a random SIGTRAP for a breakpoint trap
12016                  causes similar symptoms (PC adjustment applied when
12017                  it shouldn't), but then again, playing with SIGTRAPs
12018                  behind the debugger's back is asking for trouble.
12019
12020                  Since hardware watchpoint traps are always
12021                  distinguishable from other traps, so we don't need to
12022                  apply keep hardware watchpoint moribund locations
12023                  around.  We simply always ignore hardware watchpoint
12024                  traps we can no longer explain.  */
12025
12026               old_loc->events_till_retirement = 3 * (thread_count () + 1);
12027               old_loc->owner = NULL;
12028
12029               VEC_safe_push (bp_location_p, moribund_locations, old_loc);
12030             }
12031           else
12032             {
12033               old_loc->owner = NULL;
12034               decref_bp_location (&old_loc);
12035             }
12036         }
12037     }
12038
12039   /* Rescan breakpoints at the same address and section, marking the
12040      first one as "first" and any others as "duplicates".  This is so
12041      that the bpt instruction is only inserted once.  If we have a
12042      permanent breakpoint at the same place as BPT, make that one the
12043      official one, and the rest as duplicates.  Permanent breakpoints
12044      are sorted first for the same address.
12045
12046      Do the same for hardware watchpoints, but also considering the
12047      watchpoint's type (regular/access/read) and length.  */
12048
12049   bp_loc_first = NULL;
12050   wp_loc_first = NULL;
12051   awp_loc_first = NULL;
12052   rwp_loc_first = NULL;
12053   ALL_BP_LOCATIONS (loc, locp)
12054     {
12055       /* ALL_BP_LOCATIONS bp_location has LOC->OWNER always
12056          non-NULL.  */
12057       struct bp_location **loc_first_p;
12058       b = loc->owner;
12059
12060       if (!should_be_inserted (loc)
12061           || !breakpoint_address_is_meaningful (b)
12062           /* Don't detect duplicate for tracepoint locations because they are
12063            never duplicated.  See the comments in field `duplicate' of
12064            `struct bp_location'.  */
12065           || is_tracepoint (b))
12066         {
12067           /* Clear the condition modification flag.  */
12068           loc->condition_changed = condition_unchanged;
12069           continue;
12070         }
12071
12072       /* Permanent breakpoint should always be inserted.  */
12073       if (b->enable_state == bp_permanent && ! loc->inserted)
12074         internal_error (__FILE__, __LINE__,
12075                         _("allegedly permanent breakpoint is not "
12076                         "actually inserted"));
12077
12078       if (b->type == bp_hardware_watchpoint)
12079         loc_first_p = &wp_loc_first;
12080       else if (b->type == bp_read_watchpoint)
12081         loc_first_p = &rwp_loc_first;
12082       else if (b->type == bp_access_watchpoint)
12083         loc_first_p = &awp_loc_first;
12084       else
12085         loc_first_p = &bp_loc_first;
12086
12087       if (*loc_first_p == NULL
12088           || (overlay_debugging && loc->section != (*loc_first_p)->section)
12089           || !breakpoint_locations_match (loc, *loc_first_p))
12090         {
12091           *loc_first_p = loc;
12092           loc->duplicate = 0;
12093
12094           if (is_breakpoint (loc->owner) && loc->condition_changed)
12095             {
12096               loc->needs_update = 1;
12097               /* Clear the condition modification flag.  */
12098               loc->condition_changed = condition_unchanged;
12099             }
12100           continue;
12101         }
12102
12103
12104       /* This and the above ensure the invariant that the first location
12105          is not duplicated, and is the inserted one.
12106          All following are marked as duplicated, and are not inserted.  */
12107       if (loc->inserted)
12108         swap_insertion (loc, *loc_first_p);
12109       loc->duplicate = 1;
12110
12111       /* Clear the condition modification flag.  */
12112       loc->condition_changed = condition_unchanged;
12113
12114       if ((*loc_first_p)->owner->enable_state == bp_permanent && loc->inserted
12115           && b->enable_state != bp_permanent)
12116         internal_error (__FILE__, __LINE__,
12117                         _("another breakpoint was inserted on top of "
12118                         "a permanent breakpoint"));
12119     }
12120
12121   if (breakpoints_always_inserted_mode ()
12122       && (have_live_inferiors ()
12123           || (gdbarch_has_global_breakpoints (target_gdbarch))))
12124     {
12125       if (should_insert)
12126         insert_breakpoint_locations ();
12127       else
12128         {
12129           /* Though should_insert is false, we may need to update conditions
12130              on the target's side if it is evaluating such conditions.  We
12131              only update conditions for locations that are marked
12132              "needs_update".  */
12133           update_inserted_breakpoint_locations ();
12134         }
12135     }
12136
12137   if (should_insert)
12138     download_tracepoint_locations ();
12139
12140   do_cleanups (cleanups);
12141 }
12142
12143 void
12144 breakpoint_retire_moribund (void)
12145 {
12146   struct bp_location *loc;
12147   int ix;
12148
12149   for (ix = 0; VEC_iterate (bp_location_p, moribund_locations, ix, loc); ++ix)
12150     if (--(loc->events_till_retirement) == 0)
12151       {
12152         decref_bp_location (&loc);
12153         VEC_unordered_remove (bp_location_p, moribund_locations, ix);
12154         --ix;
12155       }
12156 }
12157
12158 static void
12159 update_global_location_list_nothrow (int inserting)
12160 {
12161   volatile struct gdb_exception e;
12162
12163   TRY_CATCH (e, RETURN_MASK_ERROR)
12164     update_global_location_list (inserting);
12165 }
12166
12167 /* Clear BKP from a BPS.  */
12168
12169 static void
12170 bpstat_remove_bp_location (bpstat bps, struct breakpoint *bpt)
12171 {
12172   bpstat bs;
12173
12174   for (bs = bps; bs; bs = bs->next)
12175     if (bs->breakpoint_at == bpt)
12176       {
12177         bs->breakpoint_at = NULL;
12178         bs->old_val = NULL;
12179         /* bs->commands will be freed later.  */
12180       }
12181 }
12182
12183 /* Callback for iterate_over_threads.  */
12184 static int
12185 bpstat_remove_breakpoint_callback (struct thread_info *th, void *data)
12186 {
12187   struct breakpoint *bpt = data;
12188
12189   bpstat_remove_bp_location (th->control.stop_bpstat, bpt);
12190   return 0;
12191 }
12192
12193 /* Helper for breakpoint and tracepoint breakpoint_ops->mention
12194    callbacks.  */
12195
12196 static void
12197 say_where (struct breakpoint *b)
12198 {
12199   struct ui_out *uiout = current_uiout;
12200   struct value_print_options opts;
12201
12202   get_user_print_options (&opts);
12203
12204   /* i18n: cagney/2005-02-11: Below needs to be merged into a
12205      single string.  */
12206   if (b->loc == NULL)
12207     {
12208       printf_filtered (_(" (%s) pending."), b->addr_string);
12209     }
12210   else
12211     {
12212       if (opts.addressprint || b->loc->source_file == NULL)
12213         {
12214           printf_filtered (" at ");
12215           fputs_filtered (paddress (b->loc->gdbarch, b->loc->address),
12216                           gdb_stdout);
12217         }
12218       if (b->loc->source_file)
12219         {
12220           /* If there is a single location, we can print the location
12221              more nicely.  */
12222           if (b->loc->next == NULL)
12223             printf_filtered (": file %s, line %d.",
12224                              b->loc->source_file, b->loc->line_number);
12225           else
12226             /* This is not ideal, but each location may have a
12227                different file name, and this at least reflects the
12228                real situation somewhat.  */
12229             printf_filtered (": %s.", b->addr_string);
12230         }
12231
12232       if (b->loc->next)
12233         {
12234           struct bp_location *loc = b->loc;
12235           int n = 0;
12236           for (; loc; loc = loc->next)
12237             ++n;
12238           printf_filtered (" (%d locations)", n);
12239         }
12240     }
12241 }
12242
12243 /* Default bp_location_ops methods.  */
12244
12245 static void
12246 bp_location_dtor (struct bp_location *self)
12247 {
12248   xfree (self->cond);
12249   if (self->cond_bytecode)
12250     free_agent_expr (self->cond_bytecode);
12251   xfree (self->function_name);
12252   xfree (self->source_file);
12253 }
12254
12255 static const struct bp_location_ops bp_location_ops =
12256 {
12257   bp_location_dtor
12258 };
12259
12260 /* Default breakpoint_ops methods all breakpoint_ops ultimately
12261    inherit from.  */
12262
12263 static void
12264 base_breakpoint_dtor (struct breakpoint *self)
12265 {
12266   decref_counted_command_line (&self->commands);
12267   xfree (self->cond_string);
12268   xfree (self->addr_string);
12269   xfree (self->filter);
12270   xfree (self->addr_string_range_end);
12271 }
12272
12273 static struct bp_location *
12274 base_breakpoint_allocate_location (struct breakpoint *self)
12275 {
12276   struct bp_location *loc;
12277
12278   loc = XNEW (struct bp_location);
12279   init_bp_location (loc, &bp_location_ops, self);
12280   return loc;
12281 }
12282
12283 static void
12284 base_breakpoint_re_set (struct breakpoint *b)
12285 {
12286   /* Nothing to re-set. */
12287 }
12288
12289 #define internal_error_pure_virtual_called() \
12290   gdb_assert_not_reached ("pure virtual function called")
12291
12292 static int
12293 base_breakpoint_insert_location (struct bp_location *bl)
12294 {
12295   internal_error_pure_virtual_called ();
12296 }
12297
12298 static int
12299 base_breakpoint_remove_location (struct bp_location *bl)
12300 {
12301   internal_error_pure_virtual_called ();
12302 }
12303
12304 static int
12305 base_breakpoint_breakpoint_hit (const struct bp_location *bl,
12306                                 struct address_space *aspace,
12307                                 CORE_ADDR bp_addr,
12308                                 const struct target_waitstatus *ws)
12309 {
12310   internal_error_pure_virtual_called ();
12311 }
12312
12313 static void
12314 base_breakpoint_check_status (bpstat bs)
12315 {
12316   /* Always stop.   */
12317 }
12318
12319 /* A "works_in_software_mode" breakpoint_ops method that just internal
12320    errors.  */
12321
12322 static int
12323 base_breakpoint_works_in_software_mode (const struct breakpoint *b)
12324 {
12325   internal_error_pure_virtual_called ();
12326 }
12327
12328 /* A "resources_needed" breakpoint_ops method that just internal
12329    errors.  */
12330
12331 static int
12332 base_breakpoint_resources_needed (const struct bp_location *bl)
12333 {
12334   internal_error_pure_virtual_called ();
12335 }
12336
12337 static enum print_stop_action
12338 base_breakpoint_print_it (bpstat bs)
12339 {
12340   internal_error_pure_virtual_called ();
12341 }
12342
12343 static void
12344 base_breakpoint_print_one_detail (const struct breakpoint *self,
12345                                   struct ui_out *uiout)
12346 {
12347   /* nothing */
12348 }
12349
12350 static void
12351 base_breakpoint_print_mention (struct breakpoint *b)
12352 {
12353   internal_error_pure_virtual_called ();
12354 }
12355
12356 static void
12357 base_breakpoint_print_recreate (struct breakpoint *b, struct ui_file *fp)
12358 {
12359   internal_error_pure_virtual_called ();
12360 }
12361
12362 static void
12363 base_breakpoint_create_sals_from_address (char **arg,
12364                                           struct linespec_result *canonical,
12365                                           enum bptype type_wanted,
12366                                           char *addr_start,
12367                                           char **copy_arg)
12368 {
12369   internal_error_pure_virtual_called ();
12370 }
12371
12372 static void
12373 base_breakpoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12374                                         struct linespec_result *c,
12375                                         struct linespec_sals *lsal,
12376                                         char *cond_string,
12377                                         char *extra_string,
12378                                         enum bptype type_wanted,
12379                                         enum bpdisp disposition,
12380                                         int thread,
12381                                         int task, int ignore_count,
12382                                         const struct breakpoint_ops *o,
12383                                         int from_tty, int enabled,
12384                                         int internal, unsigned flags)
12385 {
12386   internal_error_pure_virtual_called ();
12387 }
12388
12389 static void
12390 base_breakpoint_decode_linespec (struct breakpoint *b, char **s,
12391                                  struct symtabs_and_lines *sals)
12392 {
12393   internal_error_pure_virtual_called ();
12394 }
12395
12396 static struct breakpoint_ops base_breakpoint_ops =
12397 {
12398   base_breakpoint_dtor,
12399   base_breakpoint_allocate_location,
12400   base_breakpoint_re_set,
12401   base_breakpoint_insert_location,
12402   base_breakpoint_remove_location,
12403   base_breakpoint_breakpoint_hit,
12404   base_breakpoint_check_status,
12405   base_breakpoint_resources_needed,
12406   base_breakpoint_works_in_software_mode,
12407   base_breakpoint_print_it,
12408   NULL,
12409   base_breakpoint_print_one_detail,
12410   base_breakpoint_print_mention,
12411   base_breakpoint_print_recreate,
12412   base_breakpoint_create_sals_from_address,
12413   base_breakpoint_create_breakpoints_sal,
12414   base_breakpoint_decode_linespec,
12415 };
12416
12417 /* Default breakpoint_ops methods.  */
12418
12419 static void
12420 bkpt_re_set (struct breakpoint *b)
12421 {
12422   /* FIXME: is this still reachable?  */
12423   if (b->addr_string == NULL)
12424     {
12425       /* Anything without a string can't be re-set.  */
12426       delete_breakpoint (b);
12427       return;
12428     }
12429
12430   breakpoint_re_set_default (b);
12431 }
12432
12433 static int
12434 bkpt_insert_location (struct bp_location *bl)
12435 {
12436   if (bl->loc_type == bp_loc_hardware_breakpoint)
12437     return target_insert_hw_breakpoint (bl->gdbarch,
12438                                         &bl->target_info);
12439   else
12440     return target_insert_breakpoint (bl->gdbarch,
12441                                      &bl->target_info);
12442 }
12443
12444 static int
12445 bkpt_remove_location (struct bp_location *bl)
12446 {
12447   if (bl->loc_type == bp_loc_hardware_breakpoint)
12448     return target_remove_hw_breakpoint (bl->gdbarch, &bl->target_info);
12449   else
12450     return target_remove_breakpoint (bl->gdbarch, &bl->target_info);
12451 }
12452
12453 static int
12454 bkpt_breakpoint_hit (const struct bp_location *bl,
12455                      struct address_space *aspace, CORE_ADDR bp_addr,
12456                      const struct target_waitstatus *ws)
12457 {
12458   struct breakpoint *b = bl->owner;
12459
12460   if (ws->kind != TARGET_WAITKIND_STOPPED
12461       || ws->value.sig != TARGET_SIGNAL_TRAP)
12462     return 0;
12463
12464   if (!breakpoint_address_match (bl->pspace->aspace, bl->address,
12465                                  aspace, bp_addr))
12466     return 0;
12467
12468   if (overlay_debugging         /* unmapped overlay section */
12469       && section_is_overlay (bl->section)
12470       && !section_is_mapped (bl->section))
12471     return 0;
12472
12473   return 1;
12474 }
12475
12476 static int
12477 bkpt_resources_needed (const struct bp_location *bl)
12478 {
12479   gdb_assert (bl->owner->type == bp_hardware_breakpoint);
12480
12481   return 1;
12482 }
12483
12484 static enum print_stop_action
12485 bkpt_print_it (bpstat bs)
12486 {
12487   struct breakpoint *b;
12488   const struct bp_location *bl;
12489   int bp_temp;
12490   struct ui_out *uiout = current_uiout;
12491
12492   gdb_assert (bs->bp_location_at != NULL);
12493
12494   bl = bs->bp_location_at;
12495   b = bs->breakpoint_at;
12496
12497   bp_temp = b->disposition == disp_del;
12498   if (bl->address != bl->requested_address)
12499     breakpoint_adjustment_warning (bl->requested_address,
12500                                    bl->address,
12501                                    b->number, 1);
12502   annotate_breakpoint (b->number);
12503   if (bp_temp)
12504     ui_out_text (uiout, "\nTemporary breakpoint ");
12505   else
12506     ui_out_text (uiout, "\nBreakpoint ");
12507   if (ui_out_is_mi_like_p (uiout))
12508     {
12509       ui_out_field_string (uiout, "reason",
12510                            async_reason_lookup (EXEC_ASYNC_BREAKPOINT_HIT));
12511       ui_out_field_string (uiout, "disp", bpdisp_text (b->disposition));
12512     }
12513   ui_out_field_int (uiout, "bkptno", b->number);
12514   ui_out_text (uiout, ", ");
12515
12516   return PRINT_SRC_AND_LOC;
12517 }
12518
12519 static void
12520 bkpt_print_mention (struct breakpoint *b)
12521 {
12522   if (ui_out_is_mi_like_p (current_uiout))
12523     return;
12524
12525   switch (b->type)
12526     {
12527     case bp_breakpoint:
12528     case bp_gnu_ifunc_resolver:
12529       if (b->disposition == disp_del)
12530         printf_filtered (_("Temporary breakpoint"));
12531       else
12532         printf_filtered (_("Breakpoint"));
12533       printf_filtered (_(" %d"), b->number);
12534       if (b->type == bp_gnu_ifunc_resolver)
12535         printf_filtered (_(" at gnu-indirect-function resolver"));
12536       break;
12537     case bp_hardware_breakpoint:
12538       printf_filtered (_("Hardware assisted breakpoint %d"), b->number);
12539       break;
12540     case bp_dprintf:
12541       printf_filtered (_("Dprintf %d"), b->number);
12542       break;
12543     }
12544
12545   say_where (b);
12546 }
12547
12548 static void
12549 bkpt_print_recreate (struct breakpoint *tp, struct ui_file *fp)
12550 {
12551   if (tp->type == bp_breakpoint && tp->disposition == disp_del)
12552     fprintf_unfiltered (fp, "tbreak");
12553   else if (tp->type == bp_breakpoint)
12554     fprintf_unfiltered (fp, "break");
12555   else if (tp->type == bp_hardware_breakpoint
12556            && tp->disposition == disp_del)
12557     fprintf_unfiltered (fp, "thbreak");
12558   else if (tp->type == bp_hardware_breakpoint)
12559     fprintf_unfiltered (fp, "hbreak");
12560   else
12561     internal_error (__FILE__, __LINE__,
12562                     _("unhandled breakpoint type %d"), (int) tp->type);
12563
12564   fprintf_unfiltered (fp, " %s", tp->addr_string);
12565   print_recreate_thread (tp, fp);
12566 }
12567
12568 static void
12569 bkpt_create_sals_from_address (char **arg,
12570                                struct linespec_result *canonical,
12571                                enum bptype type_wanted,
12572                                char *addr_start, char **copy_arg)
12573 {
12574   create_sals_from_address_default (arg, canonical, type_wanted,
12575                                     addr_start, copy_arg);
12576 }
12577
12578 static void
12579 bkpt_create_breakpoints_sal (struct gdbarch *gdbarch,
12580                              struct linespec_result *canonical,
12581                              struct linespec_sals *lsal,
12582                              char *cond_string,
12583                              char *extra_string,
12584                              enum bptype type_wanted,
12585                              enum bpdisp disposition,
12586                              int thread,
12587                              int task, int ignore_count,
12588                              const struct breakpoint_ops *ops,
12589                              int from_tty, int enabled,
12590                              int internal, unsigned flags)
12591 {
12592   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12593                                   cond_string, extra_string,
12594                                   type_wanted,
12595                                   disposition, thread, task,
12596                                   ignore_count, ops, from_tty,
12597                                   enabled, internal, flags);
12598 }
12599
12600 static void
12601 bkpt_decode_linespec (struct breakpoint *b, char **s,
12602                       struct symtabs_and_lines *sals)
12603 {
12604   decode_linespec_default (b, s, sals);
12605 }
12606
12607 /* Virtual table for internal breakpoints.  */
12608
12609 static void
12610 internal_bkpt_re_set (struct breakpoint *b)
12611 {
12612   switch (b->type)
12613     {
12614       /* Delete overlay event and longjmp master breakpoints; they
12615          will be reset later by breakpoint_re_set.  */
12616     case bp_overlay_event:
12617     case bp_longjmp_master:
12618     case bp_std_terminate_master:
12619     case bp_exception_master:
12620       delete_breakpoint (b);
12621       break;
12622
12623       /* This breakpoint is special, it's set up when the inferior
12624          starts and we really don't want to touch it.  */
12625     case bp_shlib_event:
12626
12627       /* Like bp_shlib_event, this breakpoint type is special.  Once
12628          it is set up, we do not want to touch it.  */
12629     case bp_thread_event:
12630       break;
12631     }
12632 }
12633
12634 static void
12635 internal_bkpt_check_status (bpstat bs)
12636 {
12637   if (bs->breakpoint_at->type == bp_shlib_event)
12638     {
12639       /* If requested, stop when the dynamic linker notifies GDB of
12640          events.  This allows the user to get control and place
12641          breakpoints in initializer routines for dynamically loaded
12642          objects (among other things).  */
12643       bs->stop = stop_on_solib_events;
12644       bs->print = stop_on_solib_events;
12645     }
12646   else
12647     bs->stop = 0;
12648 }
12649
12650 static enum print_stop_action
12651 internal_bkpt_print_it (bpstat bs)
12652 {
12653   struct ui_out *uiout = current_uiout;
12654   struct breakpoint *b;
12655
12656   b = bs->breakpoint_at;
12657
12658   switch (b->type)
12659     {
12660     case bp_shlib_event:
12661       /* Did we stop because the user set the stop_on_solib_events
12662          variable?  (If so, we report this as a generic, "Stopped due
12663          to shlib event" message.) */
12664       print_solib_event (0);
12665       break;
12666
12667     case bp_thread_event:
12668       /* Not sure how we will get here.
12669          GDB should not stop for these breakpoints.  */
12670       printf_filtered (_("Thread Event Breakpoint: gdb should not stop!\n"));
12671       break;
12672
12673     case bp_overlay_event:
12674       /* By analogy with the thread event, GDB should not stop for these.  */
12675       printf_filtered (_("Overlay Event Breakpoint: gdb should not stop!\n"));
12676       break;
12677
12678     case bp_longjmp_master:
12679       /* These should never be enabled.  */
12680       printf_filtered (_("Longjmp Master Breakpoint: gdb should not stop!\n"));
12681       break;
12682
12683     case bp_std_terminate_master:
12684       /* These should never be enabled.  */
12685       printf_filtered (_("std::terminate Master Breakpoint: "
12686                          "gdb should not stop!\n"));
12687       break;
12688
12689     case bp_exception_master:
12690       /* These should never be enabled.  */
12691       printf_filtered (_("Exception Master Breakpoint: "
12692                          "gdb should not stop!\n"));
12693       break;
12694     }
12695
12696   return PRINT_NOTHING;
12697 }
12698
12699 static void
12700 internal_bkpt_print_mention (struct breakpoint *b)
12701 {
12702   /* Nothing to mention.  These breakpoints are internal.  */
12703 }
12704
12705 /* Virtual table for momentary breakpoints  */
12706
12707 static void
12708 momentary_bkpt_re_set (struct breakpoint *b)
12709 {
12710   /* Keep temporary breakpoints, which can be encountered when we step
12711      over a dlopen call and SOLIB_ADD is resetting the breakpoints.
12712      Otherwise these should have been blown away via the cleanup chain
12713      or by breakpoint_init_inferior when we rerun the executable.  */
12714 }
12715
12716 static void
12717 momentary_bkpt_check_status (bpstat bs)
12718 {
12719   /* Nothing.  The point of these breakpoints is causing a stop.  */
12720 }
12721
12722 static enum print_stop_action
12723 momentary_bkpt_print_it (bpstat bs)
12724 {
12725   struct ui_out *uiout = current_uiout;
12726
12727   if (ui_out_is_mi_like_p (uiout))
12728     {
12729       struct breakpoint *b = bs->breakpoint_at;
12730
12731       switch (b->type)
12732         {
12733         case bp_finish:
12734           ui_out_field_string
12735             (uiout, "reason",
12736              async_reason_lookup (EXEC_ASYNC_FUNCTION_FINISHED));
12737           break;
12738
12739         case bp_until:
12740           ui_out_field_string
12741             (uiout, "reason",
12742              async_reason_lookup (EXEC_ASYNC_LOCATION_REACHED));
12743           break;
12744         }
12745     }
12746
12747   return PRINT_UNKNOWN;
12748 }
12749
12750 static void
12751 momentary_bkpt_print_mention (struct breakpoint *b)
12752 {
12753   /* Nothing to mention.  These breakpoints are internal.  */
12754 }
12755
12756 /* Specific methods for probe breakpoints.  */
12757
12758 static int
12759 bkpt_probe_insert_location (struct bp_location *bl)
12760 {
12761   int v = bkpt_insert_location (bl);
12762
12763   if (v == 0)
12764     {
12765       /* The insertion was successful, now let's set the probe's semaphore
12766          if needed.  */
12767       bl->probe->pops->set_semaphore (bl->probe, bl->gdbarch);
12768     }
12769
12770   return v;
12771 }
12772
12773 static int
12774 bkpt_probe_remove_location (struct bp_location *bl)
12775 {
12776   /* Let's clear the semaphore before removing the location.  */
12777   bl->probe->pops->clear_semaphore (bl->probe, bl->gdbarch);
12778
12779   return bkpt_remove_location (bl);
12780 }
12781
12782 static void
12783 bkpt_probe_create_sals_from_address (char **arg,
12784                                      struct linespec_result *canonical,
12785                                      enum bptype type_wanted,
12786                                      char *addr_start, char **copy_arg)
12787 {
12788   struct linespec_sals lsal;
12789
12790   lsal.sals = parse_probes (arg, canonical);
12791
12792   *copy_arg = xstrdup (canonical->addr_string);
12793   lsal.canonical = xstrdup (*copy_arg);
12794
12795   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12796 }
12797
12798 static void
12799 bkpt_probe_decode_linespec (struct breakpoint *b, char **s,
12800                             struct symtabs_and_lines *sals)
12801 {
12802   *sals = parse_probes (s, NULL);
12803   if (!sals->sals)
12804     error (_("probe not found"));
12805 }
12806
12807 /* The breakpoint_ops structure to be used in tracepoints.  */
12808
12809 static void
12810 tracepoint_re_set (struct breakpoint *b)
12811 {
12812   breakpoint_re_set_default (b);
12813 }
12814
12815 static int
12816 tracepoint_breakpoint_hit (const struct bp_location *bl,
12817                            struct address_space *aspace, CORE_ADDR bp_addr,
12818                            const struct target_waitstatus *ws)
12819 {
12820   /* By definition, the inferior does not report stops at
12821      tracepoints.  */
12822   return 0;
12823 }
12824
12825 static void
12826 tracepoint_print_one_detail (const struct breakpoint *self,
12827                              struct ui_out *uiout)
12828 {
12829   struct tracepoint *tp = (struct tracepoint *) self;
12830   if (tp->static_trace_marker_id)
12831     {
12832       gdb_assert (self->type == bp_static_tracepoint);
12833
12834       ui_out_text (uiout, "\tmarker id is ");
12835       ui_out_field_string (uiout, "static-tracepoint-marker-string-id",
12836                            tp->static_trace_marker_id);
12837       ui_out_text (uiout, "\n");
12838     }
12839 }
12840
12841 static void
12842 tracepoint_print_mention (struct breakpoint *b)
12843 {
12844   if (ui_out_is_mi_like_p (current_uiout))
12845     return;
12846
12847   switch (b->type)
12848     {
12849     case bp_tracepoint:
12850       printf_filtered (_("Tracepoint"));
12851       printf_filtered (_(" %d"), b->number);
12852       break;
12853     case bp_fast_tracepoint:
12854       printf_filtered (_("Fast tracepoint"));
12855       printf_filtered (_(" %d"), b->number);
12856       break;
12857     case bp_static_tracepoint:
12858       printf_filtered (_("Static tracepoint"));
12859       printf_filtered (_(" %d"), b->number);
12860       break;
12861     default:
12862       internal_error (__FILE__, __LINE__,
12863                       _("unhandled tracepoint type %d"), (int) b->type);
12864     }
12865
12866   say_where (b);
12867 }
12868
12869 static void
12870 tracepoint_print_recreate (struct breakpoint *self, struct ui_file *fp)
12871 {
12872   struct tracepoint *tp = (struct tracepoint *) self;
12873
12874   if (self->type == bp_fast_tracepoint)
12875     fprintf_unfiltered (fp, "ftrace");
12876   if (self->type == bp_static_tracepoint)
12877     fprintf_unfiltered (fp, "strace");
12878   else if (self->type == bp_tracepoint)
12879     fprintf_unfiltered (fp, "trace");
12880   else
12881     internal_error (__FILE__, __LINE__,
12882                     _("unhandled tracepoint type %d"), (int) self->type);
12883
12884   fprintf_unfiltered (fp, " %s", self->addr_string);
12885   print_recreate_thread (self, fp);
12886
12887   if (tp->pass_count)
12888     fprintf_unfiltered (fp, "  passcount %d\n", tp->pass_count);
12889 }
12890
12891 static void
12892 tracepoint_create_sals_from_address (char **arg,
12893                                      struct linespec_result *canonical,
12894                                      enum bptype type_wanted,
12895                                      char *addr_start, char **copy_arg)
12896 {
12897   create_sals_from_address_default (arg, canonical, type_wanted,
12898                                     addr_start, copy_arg);
12899 }
12900
12901 static void
12902 tracepoint_create_breakpoints_sal (struct gdbarch *gdbarch,
12903                                    struct linespec_result *canonical,
12904                                    struct linespec_sals *lsal,
12905                                    char *cond_string,
12906                                    char *extra_string,
12907                                    enum bptype type_wanted,
12908                                    enum bpdisp disposition,
12909                                    int thread,
12910                                    int task, int ignore_count,
12911                                    const struct breakpoint_ops *ops,
12912                                    int from_tty, int enabled,
12913                                    int internal, unsigned flags)
12914 {
12915   create_breakpoints_sal_default (gdbarch, canonical, lsal,
12916                                   cond_string, extra_string,
12917                                   type_wanted,
12918                                   disposition, thread, task,
12919                                   ignore_count, ops, from_tty,
12920                                   enabled, internal, flags);
12921 }
12922
12923 static void
12924 tracepoint_decode_linespec (struct breakpoint *b, char **s,
12925                             struct symtabs_and_lines *sals)
12926 {
12927   decode_linespec_default (b, s, sals);
12928 }
12929
12930 struct breakpoint_ops tracepoint_breakpoint_ops;
12931
12932 /* The breakpoint_ops structure to be use on tracepoints placed in a
12933    static probe.  */
12934
12935 static void
12936 tracepoint_probe_create_sals_from_address (char **arg,
12937                                            struct linespec_result *canonical,
12938                                            enum bptype type_wanted,
12939                                            char *addr_start, char **copy_arg)
12940 {
12941   /* We use the same method for breakpoint on probes.  */
12942   bkpt_probe_create_sals_from_address (arg, canonical, type_wanted,
12943                                        addr_start, copy_arg);
12944 }
12945
12946 static void
12947 tracepoint_probe_decode_linespec (struct breakpoint *b, char **s,
12948                                   struct symtabs_and_lines *sals)
12949 {
12950   /* We use the same method for breakpoint on probes.  */
12951   bkpt_probe_decode_linespec (b, s, sals);
12952 }
12953
12954 static struct breakpoint_ops tracepoint_probe_breakpoint_ops;
12955
12956 /* The breakpoint_ops structure to be used on static tracepoints with
12957    markers (`-m').  */
12958
12959 static void
12960 strace_marker_create_sals_from_address (char **arg,
12961                                         struct linespec_result *canonical,
12962                                         enum bptype type_wanted,
12963                                         char *addr_start, char **copy_arg)
12964 {
12965   struct linespec_sals lsal;
12966
12967   lsal.sals = decode_static_tracepoint_spec (arg);
12968
12969   *copy_arg = savestring (addr_start, *arg - addr_start);
12970
12971   canonical->addr_string = xstrdup (*copy_arg);
12972   lsal.canonical = xstrdup (*copy_arg);
12973   VEC_safe_push (linespec_sals, canonical->sals, &lsal);
12974 }
12975
12976 static void
12977 strace_marker_create_breakpoints_sal (struct gdbarch *gdbarch,
12978                                       struct linespec_result *canonical,
12979                                       struct linespec_sals *lsal,
12980                                       char *cond_string,
12981                                       char *extra_string,
12982                                       enum bptype type_wanted,
12983                                       enum bpdisp disposition,
12984                                       int thread,
12985                                       int task, int ignore_count,
12986                                       const struct breakpoint_ops *ops,
12987                                       int from_tty, int enabled,
12988                                       int internal, unsigned flags)
12989 {
12990   int i;
12991
12992   /* If the user is creating a static tracepoint by marker id
12993      (strace -m MARKER_ID), then store the sals index, so that
12994      breakpoint_re_set can try to match up which of the newly
12995      found markers corresponds to this one, and, don't try to
12996      expand multiple locations for each sal, given than SALS
12997      already should contain all sals for MARKER_ID.  */
12998
12999   for (i = 0; i < lsal->sals.nelts; ++i)
13000     {
13001       struct symtabs_and_lines expanded;
13002       struct tracepoint *tp;
13003       struct cleanup *old_chain;
13004       char *addr_string;
13005
13006       expanded.nelts = 1;
13007       expanded.sals = &lsal->sals.sals[i];
13008
13009       addr_string = xstrdup (canonical->addr_string);
13010       old_chain = make_cleanup (xfree, addr_string);
13011
13012       tp = XCNEW (struct tracepoint);
13013       init_breakpoint_sal (&tp->base, gdbarch, expanded,
13014                            addr_string, NULL,
13015                            cond_string, extra_string,
13016                            type_wanted, disposition,
13017                            thread, task, ignore_count, ops,
13018                            from_tty, enabled, internal, flags,
13019                            canonical->special_display);
13020       /* Given that its possible to have multiple markers with
13021          the same string id, if the user is creating a static
13022          tracepoint by marker id ("strace -m MARKER_ID"), then
13023          store the sals index, so that breakpoint_re_set can
13024          try to match up which of the newly found markers
13025          corresponds to this one  */
13026       tp->static_trace_marker_id_idx = i;
13027
13028       install_breakpoint (internal, &tp->base, 0);
13029
13030       discard_cleanups (old_chain);
13031     }
13032 }
13033
13034 static void
13035 strace_marker_decode_linespec (struct breakpoint *b, char **s,
13036                                struct symtabs_and_lines *sals)
13037 {
13038   struct tracepoint *tp = (struct tracepoint *) b;
13039
13040   *sals = decode_static_tracepoint_spec (s);
13041   if (sals->nelts > tp->static_trace_marker_id_idx)
13042     {
13043       sals->sals[0] = sals->sals[tp->static_trace_marker_id_idx];
13044       sals->nelts = 1;
13045     }
13046   else
13047     error (_("marker %s not found"), tp->static_trace_marker_id);
13048 }
13049
13050 static struct breakpoint_ops strace_marker_breakpoint_ops;
13051
13052 static int
13053 strace_marker_p (struct breakpoint *b)
13054 {
13055   return b->ops == &strace_marker_breakpoint_ops;
13056 }
13057
13058 /* Delete a breakpoint and clean up all traces of it in the data
13059    structures.  */
13060
13061 void
13062 delete_breakpoint (struct breakpoint *bpt)
13063 {
13064   struct breakpoint *b;
13065
13066   gdb_assert (bpt != NULL);
13067
13068   /* Has this bp already been deleted?  This can happen because
13069      multiple lists can hold pointers to bp's.  bpstat lists are
13070      especial culprits.
13071
13072      One example of this happening is a watchpoint's scope bp.  When
13073      the scope bp triggers, we notice that the watchpoint is out of
13074      scope, and delete it.  We also delete its scope bp.  But the
13075      scope bp is marked "auto-deleting", and is already on a bpstat.
13076      That bpstat is then checked for auto-deleting bp's, which are
13077      deleted.
13078
13079      A real solution to this problem might involve reference counts in
13080      bp's, and/or giving them pointers back to their referencing
13081      bpstat's, and teaching delete_breakpoint to only free a bp's
13082      storage when no more references were extent.  A cheaper bandaid
13083      was chosen.  */
13084   if (bpt->type == bp_none)
13085     return;
13086
13087   /* At least avoid this stale reference until the reference counting
13088      of breakpoints gets resolved.  */
13089   if (bpt->related_breakpoint != bpt)
13090     {
13091       struct breakpoint *related;
13092       struct watchpoint *w;
13093
13094       if (bpt->type == bp_watchpoint_scope)
13095         w = (struct watchpoint *) bpt->related_breakpoint;
13096       else if (bpt->related_breakpoint->type == bp_watchpoint_scope)
13097         w = (struct watchpoint *) bpt;
13098       else
13099         w = NULL;
13100       if (w != NULL)
13101         watchpoint_del_at_next_stop (w);
13102
13103       /* Unlink bpt from the bpt->related_breakpoint ring.  */
13104       for (related = bpt; related->related_breakpoint != bpt;
13105            related = related->related_breakpoint);
13106       related->related_breakpoint = bpt->related_breakpoint;
13107       bpt->related_breakpoint = bpt;
13108     }
13109
13110   /* watch_command_1 creates a watchpoint but only sets its number if
13111      update_watchpoint succeeds in creating its bp_locations.  If there's
13112      a problem in that process, we'll be asked to delete the half-created
13113      watchpoint.  In that case, don't announce the deletion.  */
13114   if (bpt->number)
13115     observer_notify_breakpoint_deleted (bpt);
13116
13117   if (breakpoint_chain == bpt)
13118     breakpoint_chain = bpt->next;
13119
13120   ALL_BREAKPOINTS (b)
13121     if (b->next == bpt)
13122     {
13123       b->next = bpt->next;
13124       break;
13125     }
13126
13127   /* Be sure no bpstat's are pointing at the breakpoint after it's
13128      been freed.  */
13129   /* FIXME, how can we find all bpstat's?  We just check stop_bpstat
13130      in all threads for now.  Note that we cannot just remove bpstats
13131      pointing at bpt from the stop_bpstat list entirely, as breakpoint
13132      commands are associated with the bpstat; if we remove it here,
13133      then the later call to bpstat_do_actions (&stop_bpstat); in
13134      event-top.c won't do anything, and temporary breakpoints with
13135      commands won't work.  */
13136
13137   iterate_over_threads (bpstat_remove_breakpoint_callback, bpt);
13138
13139   /* Now that breakpoint is removed from breakpoint list, update the
13140      global location list.  This will remove locations that used to
13141      belong to this breakpoint.  Do this before freeing the breakpoint
13142      itself, since remove_breakpoint looks at location's owner.  It
13143      might be better design to have location completely
13144      self-contained, but it's not the case now.  */
13145   update_global_location_list (0);
13146
13147   bpt->ops->dtor (bpt);
13148   /* On the chance that someone will soon try again to delete this
13149      same bp, we mark it as deleted before freeing its storage.  */
13150   bpt->type = bp_none;
13151   xfree (bpt);
13152 }
13153
13154 static void
13155 do_delete_breakpoint_cleanup (void *b)
13156 {
13157   delete_breakpoint (b);
13158 }
13159
13160 struct cleanup *
13161 make_cleanup_delete_breakpoint (struct breakpoint *b)
13162 {
13163   return make_cleanup (do_delete_breakpoint_cleanup, b);
13164 }
13165
13166 /* Iterator function to call a user-provided callback function once
13167    for each of B and its related breakpoints.  */
13168
13169 static void
13170 iterate_over_related_breakpoints (struct breakpoint *b,
13171                                   void (*function) (struct breakpoint *,
13172                                                     void *),
13173                                   void *data)
13174 {
13175   struct breakpoint *related;
13176
13177   related = b;
13178   do
13179     {
13180       struct breakpoint *next;
13181
13182       /* FUNCTION may delete RELATED.  */
13183       next = related->related_breakpoint;
13184
13185       if (next == related)
13186         {
13187           /* RELATED is the last ring entry.  */
13188           function (related, data);
13189
13190           /* FUNCTION may have deleted it, so we'd never reach back to
13191              B.  There's nothing left to do anyway, so just break
13192              out.  */
13193           break;
13194         }
13195       else
13196         function (related, data);
13197
13198       related = next;
13199     }
13200   while (related != b);
13201 }
13202
13203 static void
13204 do_delete_breakpoint (struct breakpoint *b, void *ignore)
13205 {
13206   delete_breakpoint (b);
13207 }
13208
13209 /* A callback for map_breakpoint_numbers that calls
13210    delete_breakpoint.  */
13211
13212 static void
13213 do_map_delete_breakpoint (struct breakpoint *b, void *ignore)
13214 {
13215   iterate_over_related_breakpoints (b, do_delete_breakpoint, NULL);
13216 }
13217
13218 void
13219 delete_command (char *arg, int from_tty)
13220 {
13221   struct breakpoint *b, *b_tmp;
13222
13223   dont_repeat ();
13224
13225   if (arg == 0)
13226     {
13227       int breaks_to_delete = 0;
13228
13229       /* Delete all breakpoints if no argument.  Do not delete
13230          internal breakpoints, these have to be deleted with an
13231          explicit breakpoint number argument.  */
13232       ALL_BREAKPOINTS (b)
13233         if (user_breakpoint_p (b))
13234           {
13235             breaks_to_delete = 1;
13236             break;
13237           }
13238
13239       /* Ask user only if there are some breakpoints to delete.  */
13240       if (!from_tty
13241           || (breaks_to_delete && query (_("Delete all breakpoints? "))))
13242         {
13243           ALL_BREAKPOINTS_SAFE (b, b_tmp)
13244             if (user_breakpoint_p (b))
13245               delete_breakpoint (b);
13246         }
13247     }
13248   else
13249     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
13250 }
13251
13252 static int
13253 all_locations_are_pending (struct bp_location *loc)
13254 {
13255   for (; loc; loc = loc->next)
13256     if (!loc->shlib_disabled
13257         && !loc->pspace->executing_startup)
13258       return 0;
13259   return 1;
13260 }
13261
13262 /* Subroutine of update_breakpoint_locations to simplify it.
13263    Return non-zero if multiple fns in list LOC have the same name.
13264    Null names are ignored.  */
13265
13266 static int
13267 ambiguous_names_p (struct bp_location *loc)
13268 {
13269   struct bp_location *l;
13270   htab_t htab = htab_create_alloc (13, htab_hash_string,
13271                                    (int (*) (const void *, 
13272                                              const void *)) streq,
13273                                    NULL, xcalloc, xfree);
13274
13275   for (l = loc; l != NULL; l = l->next)
13276     {
13277       const char **slot;
13278       const char *name = l->function_name;
13279
13280       /* Allow for some names to be NULL, ignore them.  */
13281       if (name == NULL)
13282         continue;
13283
13284       slot = (const char **) htab_find_slot (htab, (const void *) name,
13285                                              INSERT);
13286       /* NOTE: We can assume slot != NULL here because xcalloc never
13287          returns NULL.  */
13288       if (*slot != NULL)
13289         {
13290           htab_delete (htab);
13291           return 1;
13292         }
13293       *slot = name;
13294     }
13295
13296   htab_delete (htab);
13297   return 0;
13298 }
13299
13300 /* When symbols change, it probably means the sources changed as well,
13301    and it might mean the static tracepoint markers are no longer at
13302    the same address or line numbers they used to be at last we
13303    checked.  Losing your static tracepoints whenever you rebuild is
13304    undesirable.  This function tries to resync/rematch gdb static
13305    tracepoints with the markers on the target, for static tracepoints
13306    that have not been set by marker id.  Static tracepoint that have
13307    been set by marker id are reset by marker id in breakpoint_re_set.
13308    The heuristic is:
13309
13310    1) For a tracepoint set at a specific address, look for a marker at
13311    the old PC.  If one is found there, assume to be the same marker.
13312    If the name / string id of the marker found is different from the
13313    previous known name, assume that means the user renamed the marker
13314    in the sources, and output a warning.
13315
13316    2) For a tracepoint set at a given line number, look for a marker
13317    at the new address of the old line number.  If one is found there,
13318    assume to be the same marker.  If the name / string id of the
13319    marker found is different from the previous known name, assume that
13320    means the user renamed the marker in the sources, and output a
13321    warning.
13322
13323    3) If a marker is no longer found at the same address or line, it
13324    may mean the marker no longer exists.  But it may also just mean
13325    the code changed a bit.  Maybe the user added a few lines of code
13326    that made the marker move up or down (in line number terms).  Ask
13327    the target for info about the marker with the string id as we knew
13328    it.  If found, update line number and address in the matching
13329    static tracepoint.  This will get confused if there's more than one
13330    marker with the same ID (possible in UST, although unadvised
13331    precisely because it confuses tools).  */
13332
13333 static struct symtab_and_line
13334 update_static_tracepoint (struct breakpoint *b, struct symtab_and_line sal)
13335 {
13336   struct tracepoint *tp = (struct tracepoint *) b;
13337   struct static_tracepoint_marker marker;
13338   CORE_ADDR pc;
13339   int i;
13340
13341   pc = sal.pc;
13342   if (sal.line)
13343     find_line_pc (sal.symtab, sal.line, &pc);
13344
13345   if (target_static_tracepoint_marker_at (pc, &marker))
13346     {
13347       if (strcmp (tp->static_trace_marker_id, marker.str_id) != 0)
13348         warning (_("static tracepoint %d changed probed marker from %s to %s"),
13349                  b->number,
13350                  tp->static_trace_marker_id, marker.str_id);
13351
13352       xfree (tp->static_trace_marker_id);
13353       tp->static_trace_marker_id = xstrdup (marker.str_id);
13354       release_static_tracepoint_marker (&marker);
13355
13356       return sal;
13357     }
13358
13359   /* Old marker wasn't found on target at lineno.  Try looking it up
13360      by string ID.  */
13361   if (!sal.explicit_pc
13362       && sal.line != 0
13363       && sal.symtab != NULL
13364       && tp->static_trace_marker_id != NULL)
13365     {
13366       VEC(static_tracepoint_marker_p) *markers;
13367
13368       markers
13369         = target_static_tracepoint_markers_by_strid (tp->static_trace_marker_id);
13370
13371       if (!VEC_empty(static_tracepoint_marker_p, markers))
13372         {
13373           struct symtab_and_line sal2;
13374           struct symbol *sym;
13375           struct static_tracepoint_marker *tpmarker;
13376           struct ui_out *uiout = current_uiout;
13377
13378           tpmarker = VEC_index (static_tracepoint_marker_p, markers, 0);
13379
13380           xfree (tp->static_trace_marker_id);
13381           tp->static_trace_marker_id = xstrdup (tpmarker->str_id);
13382
13383           warning (_("marker for static tracepoint %d (%s) not "
13384                      "found at previous line number"),
13385                    b->number, tp->static_trace_marker_id);
13386
13387           init_sal (&sal2);
13388
13389           sal2.pc = tpmarker->address;
13390
13391           sal2 = find_pc_line (tpmarker->address, 0);
13392           sym = find_pc_sect_function (tpmarker->address, NULL);
13393           ui_out_text (uiout, "Now in ");
13394           if (sym)
13395             {
13396               ui_out_field_string (uiout, "func",
13397                                    SYMBOL_PRINT_NAME (sym));
13398               ui_out_text (uiout, " at ");
13399             }
13400           ui_out_field_string (uiout, "file", sal2.symtab->filename);
13401           ui_out_text (uiout, ":");
13402
13403           if (ui_out_is_mi_like_p (uiout))
13404             {
13405               char *fullname = symtab_to_fullname (sal2.symtab);
13406
13407               if (fullname)
13408                 ui_out_field_string (uiout, "fullname", fullname);
13409             }
13410
13411           ui_out_field_int (uiout, "line", sal2.line);
13412           ui_out_text (uiout, "\n");
13413
13414           b->loc->line_number = sal2.line;
13415
13416           xfree (b->loc->source_file);
13417           if (sym)
13418             b->loc->source_file = xstrdup (sal2.symtab->filename);
13419           else
13420             b->loc->source_file = NULL;
13421
13422           xfree (b->addr_string);
13423           b->addr_string = xstrprintf ("%s:%d",
13424                                        sal2.symtab->filename,
13425                                        b->loc->line_number);
13426
13427           /* Might be nice to check if function changed, and warn if
13428              so.  */
13429
13430           release_static_tracepoint_marker (tpmarker);
13431         }
13432     }
13433   return sal;
13434 }
13435
13436 /* Returns 1 iff locations A and B are sufficiently same that
13437    we don't need to report breakpoint as changed.  */
13438
13439 static int
13440 locations_are_equal (struct bp_location *a, struct bp_location *b)
13441 {
13442   while (a && b)
13443     {
13444       if (a->address != b->address)
13445         return 0;
13446
13447       if (a->shlib_disabled != b->shlib_disabled)
13448         return 0;
13449
13450       if (a->enabled != b->enabled)
13451         return 0;
13452
13453       a = a->next;
13454       b = b->next;
13455     }
13456
13457   if ((a == NULL) != (b == NULL))
13458     return 0;
13459
13460   return 1;
13461 }
13462
13463 /* Create new breakpoint locations for B (a hardware or software breakpoint)
13464    based on SALS and SALS_END.  If SALS_END.NELTS is not zero, then B is
13465    a ranged breakpoint.  */
13466
13467 void
13468 update_breakpoint_locations (struct breakpoint *b,
13469                              struct symtabs_and_lines sals,
13470                              struct symtabs_and_lines sals_end)
13471 {
13472   int i;
13473   struct bp_location *existing_locations = b->loc;
13474
13475   if (sals_end.nelts != 0 && (sals.nelts != 1 || sals_end.nelts != 1))
13476     {
13477       /* Ranged breakpoints have only one start location and one end
13478          location.  */
13479       b->enable_state = bp_disabled;
13480       update_global_location_list (1);
13481       printf_unfiltered (_("Could not reset ranged breakpoint %d: "
13482                            "multiple locations found\n"),
13483                          b->number);
13484       return;
13485     }
13486
13487   /* If there's no new locations, and all existing locations are
13488      pending, don't do anything.  This optimizes the common case where
13489      all locations are in the same shared library, that was unloaded.
13490      We'd like to retain the location, so that when the library is
13491      loaded again, we don't loose the enabled/disabled status of the
13492      individual locations.  */
13493   if (all_locations_are_pending (existing_locations) && sals.nelts == 0)
13494     return;
13495
13496   b->loc = NULL;
13497
13498   for (i = 0; i < sals.nelts; ++i)
13499     {
13500       struct bp_location *new_loc;
13501
13502       switch_to_program_space_and_thread (sals.sals[i].pspace);
13503
13504       new_loc = add_location_to_breakpoint (b, &(sals.sals[i]));
13505
13506       /* Reparse conditions, they might contain references to the
13507          old symtab.  */
13508       if (b->cond_string != NULL)
13509         {
13510           char *s;
13511           volatile struct gdb_exception e;
13512
13513           s = b->cond_string;
13514           TRY_CATCH (e, RETURN_MASK_ERROR)
13515             {
13516               new_loc->cond = parse_exp_1 (&s, block_for_pc (sals.sals[i].pc), 
13517                                            0);
13518             }
13519           if (e.reason < 0)
13520             {
13521               warning (_("failed to reevaluate condition "
13522                          "for breakpoint %d: %s"), 
13523                        b->number, e.message);
13524               new_loc->enabled = 0;
13525             }
13526         }
13527
13528       if (sals_end.nelts)
13529         {
13530           CORE_ADDR end = find_breakpoint_range_end (sals_end.sals[0]);
13531
13532           new_loc->length = end - sals.sals[0].pc + 1;
13533         }
13534     }
13535
13536   /* Update locations of permanent breakpoints.  */
13537   if (b->enable_state == bp_permanent)
13538     make_breakpoint_permanent (b);
13539
13540   /* If possible, carry over 'disable' status from existing
13541      breakpoints.  */
13542   {
13543     struct bp_location *e = existing_locations;
13544     /* If there are multiple breakpoints with the same function name,
13545        e.g. for inline functions, comparing function names won't work.
13546        Instead compare pc addresses; this is just a heuristic as things
13547        may have moved, but in practice it gives the correct answer
13548        often enough until a better solution is found.  */
13549     int have_ambiguous_names = ambiguous_names_p (b->loc);
13550
13551     for (; e; e = e->next)
13552       {
13553         if (!e->enabled && e->function_name)
13554           {
13555             struct bp_location *l = b->loc;
13556             if (have_ambiguous_names)
13557               {
13558                 for (; l; l = l->next)
13559                   if (breakpoint_locations_match (e, l))
13560                     {
13561                       l->enabled = 0;
13562                       break;
13563                     }
13564               }
13565             else
13566               {
13567                 for (; l; l = l->next)
13568                   if (l->function_name
13569                       && strcmp (e->function_name, l->function_name) == 0)
13570                     {
13571                       l->enabled = 0;
13572                       break;
13573                     }
13574               }
13575           }
13576       }
13577   }
13578
13579   if (!locations_are_equal (existing_locations, b->loc))
13580     observer_notify_breakpoint_modified (b);
13581
13582   update_global_location_list (1);
13583 }
13584
13585 /* Find the SaL locations corresponding to the given ADDR_STRING.
13586    On return, FOUND will be 1 if any SaL was found, zero otherwise.  */
13587
13588 static struct symtabs_and_lines
13589 addr_string_to_sals (struct breakpoint *b, char *addr_string, int *found)
13590 {
13591   char *s;
13592   struct symtabs_and_lines sals = {0};
13593   volatile struct gdb_exception e;
13594
13595   gdb_assert (b->ops != NULL);
13596   s = addr_string;
13597
13598   TRY_CATCH (e, RETURN_MASK_ERROR)
13599     {
13600       b->ops->decode_linespec (b, &s, &sals);
13601     }
13602   if (e.reason < 0)
13603     {
13604       int not_found_and_ok = 0;
13605       /* For pending breakpoints, it's expected that parsing will
13606          fail until the right shared library is loaded.  User has
13607          already told to create pending breakpoints and don't need
13608          extra messages.  If breakpoint is in bp_shlib_disabled
13609          state, then user already saw the message about that
13610          breakpoint being disabled, and don't want to see more
13611          errors.  */
13612       if (e.error == NOT_FOUND_ERROR
13613           && (b->condition_not_parsed 
13614               || (b->loc && b->loc->shlib_disabled)
13615               || (b->loc && b->loc->pspace->executing_startup)
13616               || b->enable_state == bp_disabled))
13617         not_found_and_ok = 1;
13618
13619       if (!not_found_and_ok)
13620         {
13621           /* We surely don't want to warn about the same breakpoint
13622              10 times.  One solution, implemented here, is disable
13623              the breakpoint on error.  Another solution would be to
13624              have separate 'warning emitted' flag.  Since this
13625              happens only when a binary has changed, I don't know
13626              which approach is better.  */
13627           b->enable_state = bp_disabled;
13628           throw_exception (e);
13629         }
13630     }
13631
13632   if (e.reason == 0 || e.error != NOT_FOUND_ERROR)
13633     {
13634       int i;
13635
13636       for (i = 0; i < sals.nelts; ++i)
13637         resolve_sal_pc (&sals.sals[i]);
13638       if (b->condition_not_parsed && s && s[0])
13639         {
13640           char *cond_string = 0;
13641           int thread = -1;
13642           int task = 0;
13643           char *extra_string = NULL;
13644
13645           find_condition_and_thread (s, sals.sals[0].pc,
13646                                      &cond_string, &thread, &task,
13647                                      &extra_string);
13648           if (cond_string)
13649             b->cond_string = cond_string;
13650           b->thread = thread;
13651           b->task = task;
13652           if (extra_string)
13653             b->extra_string = extra_string;
13654           b->condition_not_parsed = 0;
13655         }
13656
13657       if (b->type == bp_static_tracepoint && !strace_marker_p (b))
13658         sals.sals[0] = update_static_tracepoint (b, sals.sals[0]);
13659
13660       *found = 1;
13661     }
13662   else
13663     *found = 0;
13664
13665   return sals;
13666 }
13667
13668 /* The default re_set method, for typical hardware or software
13669    breakpoints.  Reevaluate the breakpoint and recreate its
13670    locations.  */
13671
13672 static void
13673 breakpoint_re_set_default (struct breakpoint *b)
13674 {
13675   int found;
13676   struct symtabs_and_lines sals, sals_end;
13677   struct symtabs_and_lines expanded = {0};
13678   struct symtabs_and_lines expanded_end = {0};
13679
13680   sals = addr_string_to_sals (b, b->addr_string, &found);
13681   if (found)
13682     {
13683       make_cleanup (xfree, sals.sals);
13684       expanded = sals;
13685     }
13686
13687   if (b->addr_string_range_end)
13688     {
13689       sals_end = addr_string_to_sals (b, b->addr_string_range_end, &found);
13690       if (found)
13691         {
13692           make_cleanup (xfree, sals_end.sals);
13693           expanded_end = sals_end;
13694         }
13695     }
13696
13697   update_breakpoint_locations (b, expanded, expanded_end);
13698 }
13699
13700 /* Default method for creating SALs from an address string.  It basically
13701    calls parse_breakpoint_sals.  Return 1 for success, zero for failure.  */
13702
13703 static void
13704 create_sals_from_address_default (char **arg,
13705                                   struct linespec_result *canonical,
13706                                   enum bptype type_wanted,
13707                                   char *addr_start, char **copy_arg)
13708 {
13709   parse_breakpoint_sals (arg, canonical);
13710 }
13711
13712 /* Call create_breakpoints_sal for the given arguments.  This is the default
13713    function for the `create_breakpoints_sal' method of
13714    breakpoint_ops.  */
13715
13716 static void
13717 create_breakpoints_sal_default (struct gdbarch *gdbarch,
13718                                 struct linespec_result *canonical,
13719                                 struct linespec_sals *lsal,
13720                                 char *cond_string,
13721                                 char *extra_string,
13722                                 enum bptype type_wanted,
13723                                 enum bpdisp disposition,
13724                                 int thread,
13725                                 int task, int ignore_count,
13726                                 const struct breakpoint_ops *ops,
13727                                 int from_tty, int enabled,
13728                                 int internal, unsigned flags)
13729 {
13730   create_breakpoints_sal (gdbarch, canonical, cond_string,
13731                           extra_string,
13732                           type_wanted, disposition,
13733                           thread, task, ignore_count, ops, from_tty,
13734                           enabled, internal, flags);
13735 }
13736
13737 /* Decode the line represented by S by calling decode_line_full.  This is the
13738    default function for the `decode_linespec' method of breakpoint_ops.  */
13739
13740 static void
13741 decode_linespec_default (struct breakpoint *b, char **s,
13742                          struct symtabs_and_lines *sals)
13743 {
13744   struct linespec_result canonical;
13745
13746   init_linespec_result (&canonical);
13747   decode_line_full (s, DECODE_LINE_FUNFIRSTLINE,
13748                     (struct symtab *) NULL, 0,
13749                     &canonical, multiple_symbols_all,
13750                     b->filter);
13751
13752   /* We should get 0 or 1 resulting SALs.  */
13753   gdb_assert (VEC_length (linespec_sals, canonical.sals) < 2);
13754
13755   if (VEC_length (linespec_sals, canonical.sals) > 0)
13756     {
13757       struct linespec_sals *lsal;
13758
13759       lsal = VEC_index (linespec_sals, canonical.sals, 0);
13760       *sals = lsal->sals;
13761       /* Arrange it so the destructor does not free the
13762          contents.  */
13763       lsal->sals.sals = NULL;
13764     }
13765
13766   destroy_linespec_result (&canonical);
13767 }
13768
13769 /* Prepare the global context for a re-set of breakpoint B.  */
13770
13771 static struct cleanup *
13772 prepare_re_set_context (struct breakpoint *b)
13773 {
13774   struct cleanup *cleanups;
13775
13776   input_radix = b->input_radix;
13777   cleanups = save_current_space_and_thread ();
13778   if (b->pspace != NULL)
13779     switch_to_program_space_and_thread (b->pspace);
13780   set_language (b->language);
13781
13782   return cleanups;
13783 }
13784
13785 /* Reset a breakpoint given it's struct breakpoint * BINT.
13786    The value we return ends up being the return value from catch_errors.
13787    Unused in this case.  */
13788
13789 static int
13790 breakpoint_re_set_one (void *bint)
13791 {
13792   /* Get past catch_errs.  */
13793   struct breakpoint *b = (struct breakpoint *) bint;
13794   struct cleanup *cleanups;
13795
13796   cleanups = prepare_re_set_context (b);
13797   b->ops->re_set (b);
13798   do_cleanups (cleanups);
13799   return 0;
13800 }
13801
13802 /* Re-set all breakpoints after symbols have been re-loaded.  */
13803 void
13804 breakpoint_re_set (void)
13805 {
13806   struct breakpoint *b, *b_tmp;
13807   enum language save_language;
13808   int save_input_radix;
13809   struct cleanup *old_chain;
13810
13811   save_language = current_language->la_language;
13812   save_input_radix = input_radix;
13813   old_chain = save_current_program_space ();
13814
13815   ALL_BREAKPOINTS_SAFE (b, b_tmp)
13816   {
13817     /* Format possible error msg.  */
13818     char *message = xstrprintf ("Error in re-setting breakpoint %d: ",
13819                                 b->number);
13820     struct cleanup *cleanups = make_cleanup (xfree, message);
13821     catch_errors (breakpoint_re_set_one, b, message, RETURN_MASK_ALL);
13822     do_cleanups (cleanups);
13823   }
13824   set_language (save_language);
13825   input_radix = save_input_radix;
13826
13827   jit_breakpoint_re_set ();
13828
13829   do_cleanups (old_chain);
13830
13831   create_overlay_event_breakpoint ();
13832   create_longjmp_master_breakpoint ();
13833   create_std_terminate_master_breakpoint ();
13834   create_exception_master_breakpoint ();
13835
13836   /* While we're at it, reset the skip list too.  */
13837   skip_re_set ();
13838 }
13839 \f
13840 /* Reset the thread number of this breakpoint:
13841
13842    - If the breakpoint is for all threads, leave it as-is.
13843    - Else, reset it to the current thread for inferior_ptid.  */
13844 void
13845 breakpoint_re_set_thread (struct breakpoint *b)
13846 {
13847   if (b->thread != -1)
13848     {
13849       if (in_thread_list (inferior_ptid))
13850         b->thread = pid_to_thread_id (inferior_ptid);
13851
13852       /* We're being called after following a fork.  The new fork is
13853          selected as current, and unless this was a vfork will have a
13854          different program space from the original thread.  Reset that
13855          as well.  */
13856       b->loc->pspace = current_program_space;
13857     }
13858 }
13859
13860 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
13861    If from_tty is nonzero, it prints a message to that effect,
13862    which ends with a period (no newline).  */
13863
13864 void
13865 set_ignore_count (int bptnum, int count, int from_tty)
13866 {
13867   struct breakpoint *b;
13868
13869   if (count < 0)
13870     count = 0;
13871
13872   ALL_BREAKPOINTS (b)
13873     if (b->number == bptnum)
13874     {
13875       if (is_tracepoint (b))
13876         {
13877           if (from_tty && count != 0)
13878             printf_filtered (_("Ignore count ignored for tracepoint %d."),
13879                              bptnum);
13880           return;
13881         }
13882       
13883       b->ignore_count = count;
13884       if (from_tty)
13885         {
13886           if (count == 0)
13887             printf_filtered (_("Will stop next time "
13888                                "breakpoint %d is reached."),
13889                              bptnum);
13890           else if (count == 1)
13891             printf_filtered (_("Will ignore next crossing of breakpoint %d."),
13892                              bptnum);
13893           else
13894             printf_filtered (_("Will ignore next %d "
13895                                "crossings of breakpoint %d."),
13896                              count, bptnum);
13897         }
13898       breakpoints_changed ();
13899       observer_notify_breakpoint_modified (b);
13900       return;
13901     }
13902
13903   error (_("No breakpoint number %d."), bptnum);
13904 }
13905
13906 /* Command to set ignore-count of breakpoint N to COUNT.  */
13907
13908 static void
13909 ignore_command (char *args, int from_tty)
13910 {
13911   char *p = args;
13912   int num;
13913
13914   if (p == 0)
13915     error_no_arg (_("a breakpoint number"));
13916
13917   num = get_number (&p);
13918   if (num == 0)
13919     error (_("bad breakpoint number: '%s'"), args);
13920   if (*p == 0)
13921     error (_("Second argument (specified ignore-count) is missing."));
13922
13923   set_ignore_count (num,
13924                     longest_to_int (value_as_long (parse_and_eval (p))),
13925                     from_tty);
13926   if (from_tty)
13927     printf_filtered ("\n");
13928 }
13929 \f
13930 /* Call FUNCTION on each of the breakpoints
13931    whose numbers are given in ARGS.  */
13932
13933 static void
13934 map_breakpoint_numbers (char *args, void (*function) (struct breakpoint *,
13935                                                       void *),
13936                         void *data)
13937 {
13938   int num;
13939   struct breakpoint *b, *tmp;
13940   int match;
13941   struct get_number_or_range_state state;
13942
13943   if (args == 0)
13944     error_no_arg (_("one or more breakpoint numbers"));
13945
13946   init_number_or_range (&state, args);
13947
13948   while (!state.finished)
13949     {
13950       char *p = state.string;
13951
13952       match = 0;
13953
13954       num = get_number_or_range (&state);
13955       if (num == 0)
13956         {
13957           warning (_("bad breakpoint number at or near '%s'"), p);
13958         }
13959       else
13960         {
13961           ALL_BREAKPOINTS_SAFE (b, tmp)
13962             if (b->number == num)
13963               {
13964                 match = 1;
13965                 function (b, data);
13966                 break;
13967               }
13968           if (match == 0)
13969             printf_unfiltered (_("No breakpoint number %d.\n"), num);
13970         }
13971     }
13972 }
13973
13974 static struct bp_location *
13975 find_location_by_number (char *number)
13976 {
13977   char *dot = strchr (number, '.');
13978   char *p1;
13979   int bp_num;
13980   int loc_num;
13981   struct breakpoint *b;
13982   struct bp_location *loc;  
13983
13984   *dot = '\0';
13985
13986   p1 = number;
13987   bp_num = get_number (&p1);
13988   if (bp_num == 0)
13989     error (_("Bad breakpoint number '%s'"), number);
13990
13991   ALL_BREAKPOINTS (b)
13992     if (b->number == bp_num)
13993       {
13994         break;
13995       }
13996
13997   if (!b || b->number != bp_num)
13998     error (_("Bad breakpoint number '%s'"), number);
13999   
14000   p1 = dot+1;
14001   loc_num = get_number (&p1);
14002   if (loc_num == 0)
14003     error (_("Bad breakpoint location number '%s'"), number);
14004
14005   --loc_num;
14006   loc = b->loc;
14007   for (;loc_num && loc; --loc_num, loc = loc->next)
14008     ;
14009   if (!loc)
14010     error (_("Bad breakpoint location number '%s'"), dot+1);
14011     
14012   return loc;  
14013 }
14014
14015
14016 /* Set ignore-count of breakpoint number BPTNUM to COUNT.
14017    If from_tty is nonzero, it prints a message to that effect,
14018    which ends with a period (no newline).  */
14019
14020 void
14021 disable_breakpoint (struct breakpoint *bpt)
14022 {
14023   /* Never disable a watchpoint scope breakpoint; we want to
14024      hit them when we leave scope so we can delete both the
14025      watchpoint and its scope breakpoint at that time.  */
14026   if (bpt->type == bp_watchpoint_scope)
14027     return;
14028
14029   /* You can't disable permanent breakpoints.  */
14030   if (bpt->enable_state == bp_permanent)
14031     return;
14032
14033   bpt->enable_state = bp_disabled;
14034
14035   /* Mark breakpoint locations modified.  */
14036   mark_breakpoint_modified (bpt);
14037
14038   if (target_supports_enable_disable_tracepoint ()
14039       && current_trace_status ()->running && is_tracepoint (bpt))
14040     {
14041       struct bp_location *location;
14042      
14043       for (location = bpt->loc; location; location = location->next)
14044         target_disable_tracepoint (location);
14045     }
14046
14047   update_global_location_list (0);
14048
14049   observer_notify_breakpoint_modified (bpt);
14050 }
14051
14052 /* A callback for iterate_over_related_breakpoints.  */
14053
14054 static void
14055 do_disable_breakpoint (struct breakpoint *b, void *ignore)
14056 {
14057   disable_breakpoint (b);
14058 }
14059
14060 /* A callback for map_breakpoint_numbers that calls
14061    disable_breakpoint.  */
14062
14063 static void
14064 do_map_disable_breakpoint (struct breakpoint *b, void *ignore)
14065 {
14066   iterate_over_related_breakpoints (b, do_disable_breakpoint, NULL);
14067 }
14068
14069 static void
14070 disable_command (char *args, int from_tty)
14071 {
14072   if (args == 0)
14073     {
14074       struct breakpoint *bpt;
14075
14076       ALL_BREAKPOINTS (bpt)
14077         if (user_breakpoint_p (bpt))
14078           disable_breakpoint (bpt);
14079     }
14080   else if (strchr (args, '.'))
14081     {
14082       struct bp_location *loc = find_location_by_number (args);
14083       if (loc)
14084         {
14085           if (loc->enabled)
14086             {
14087               loc->enabled = 0;
14088               mark_breakpoint_location_modified (loc);
14089             }
14090           if (target_supports_enable_disable_tracepoint ()
14091               && current_trace_status ()->running && loc->owner
14092               && is_tracepoint (loc->owner))
14093             target_disable_tracepoint (loc);
14094         }
14095       update_global_location_list (0);
14096     }
14097   else
14098     map_breakpoint_numbers (args, do_map_disable_breakpoint, NULL);
14099 }
14100
14101 static void
14102 enable_breakpoint_disp (struct breakpoint *bpt, enum bpdisp disposition,
14103                         int count)
14104 {
14105   int target_resources_ok;
14106
14107   if (bpt->type == bp_hardware_breakpoint)
14108     {
14109       int i;
14110       i = hw_breakpoint_used_count ();
14111       target_resources_ok = 
14112         target_can_use_hardware_watchpoint (bp_hardware_breakpoint, 
14113                                             i + 1, 0);
14114       if (target_resources_ok == 0)
14115         error (_("No hardware breakpoint support in the target."));
14116       else if (target_resources_ok < 0)
14117         error (_("Hardware breakpoints used exceeds limit."));
14118     }
14119
14120   if (is_watchpoint (bpt))
14121     {
14122       /* Initialize it just to avoid a GCC false warning.  */
14123       enum enable_state orig_enable_state = 0;
14124       volatile struct gdb_exception e;
14125
14126       TRY_CATCH (e, RETURN_MASK_ALL)
14127         {
14128           struct watchpoint *w = (struct watchpoint *) bpt;
14129
14130           orig_enable_state = bpt->enable_state;
14131           bpt->enable_state = bp_enabled;
14132           update_watchpoint (w, 1 /* reparse */);
14133         }
14134       if (e.reason < 0)
14135         {
14136           bpt->enable_state = orig_enable_state;
14137           exception_fprintf (gdb_stderr, e, _("Cannot enable watchpoint %d: "),
14138                              bpt->number);
14139           return;
14140         }
14141     }
14142
14143   if (bpt->enable_state != bp_permanent)
14144     bpt->enable_state = bp_enabled;
14145
14146   bpt->enable_state = bp_enabled;
14147
14148   /* Mark breakpoint locations modified.  */
14149   mark_breakpoint_modified (bpt);
14150
14151   if (target_supports_enable_disable_tracepoint ()
14152       && current_trace_status ()->running && is_tracepoint (bpt))
14153     {
14154       struct bp_location *location;
14155
14156       for (location = bpt->loc; location; location = location->next)
14157         target_enable_tracepoint (location);
14158     }
14159
14160   bpt->disposition = disposition;
14161   bpt->enable_count = count;
14162   update_global_location_list (1);
14163   breakpoints_changed ();
14164   
14165   observer_notify_breakpoint_modified (bpt);
14166 }
14167
14168
14169 void
14170 enable_breakpoint (struct breakpoint *bpt)
14171 {
14172   enable_breakpoint_disp (bpt, bpt->disposition, 0);
14173 }
14174
14175 static void
14176 do_enable_breakpoint (struct breakpoint *bpt, void *arg)
14177 {
14178   enable_breakpoint (bpt);
14179 }
14180
14181 /* A callback for map_breakpoint_numbers that calls
14182    enable_breakpoint.  */
14183
14184 static void
14185 do_map_enable_breakpoint (struct breakpoint *b, void *ignore)
14186 {
14187   iterate_over_related_breakpoints (b, do_enable_breakpoint, NULL);
14188 }
14189
14190 /* The enable command enables the specified breakpoints (or all defined
14191    breakpoints) so they once again become (or continue to be) effective
14192    in stopping the inferior.  */
14193
14194 static void
14195 enable_command (char *args, int from_tty)
14196 {
14197   if (args == 0)
14198     {
14199       struct breakpoint *bpt;
14200
14201       ALL_BREAKPOINTS (bpt)
14202         if (user_breakpoint_p (bpt))
14203           enable_breakpoint (bpt);
14204     }
14205   else if (strchr (args, '.'))
14206     {
14207       struct bp_location *loc = find_location_by_number (args);
14208       if (loc)
14209         {
14210           if (!loc->enabled)
14211             {
14212               loc->enabled = 1;
14213               mark_breakpoint_location_modified (loc);
14214             }
14215           if (target_supports_enable_disable_tracepoint ()
14216               && current_trace_status ()->running && loc->owner
14217               && is_tracepoint (loc->owner))
14218             target_enable_tracepoint (loc);
14219         }
14220       update_global_location_list (1);
14221     }
14222   else
14223     map_breakpoint_numbers (args, do_map_enable_breakpoint, NULL);
14224 }
14225
14226 /* This struct packages up disposition data for application to multiple
14227    breakpoints.  */
14228
14229 struct disp_data
14230 {
14231   enum bpdisp disp;
14232   int count;
14233 };
14234
14235 static void
14236 do_enable_breakpoint_disp (struct breakpoint *bpt, void *arg)
14237 {
14238   struct disp_data disp_data = *(struct disp_data *) arg;
14239
14240   enable_breakpoint_disp (bpt, disp_data.disp, disp_data.count);
14241 }
14242
14243 static void
14244 do_map_enable_once_breakpoint (struct breakpoint *bpt, void *ignore)
14245 {
14246   struct disp_data disp = { disp_disable, 1 };
14247
14248   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14249 }
14250
14251 static void
14252 enable_once_command (char *args, int from_tty)
14253 {
14254   map_breakpoint_numbers (args, do_map_enable_once_breakpoint, NULL);
14255 }
14256
14257 static void
14258 do_map_enable_count_breakpoint (struct breakpoint *bpt, void *countptr)
14259 {
14260   struct disp_data disp = { disp_disable, *(int *) countptr };
14261
14262   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14263 }
14264
14265 static void
14266 enable_count_command (char *args, int from_tty)
14267 {
14268   int count = get_number (&args);
14269
14270   map_breakpoint_numbers (args, do_map_enable_count_breakpoint, &count);
14271 }
14272
14273 static void
14274 do_map_enable_delete_breakpoint (struct breakpoint *bpt, void *ignore)
14275 {
14276   struct disp_data disp = { disp_del, 1 };
14277
14278   iterate_over_related_breakpoints (bpt, do_enable_breakpoint_disp, &disp);
14279 }
14280
14281 static void
14282 enable_delete_command (char *args, int from_tty)
14283 {
14284   map_breakpoint_numbers (args, do_map_enable_delete_breakpoint, NULL);
14285 }
14286 \f
14287 static void
14288 set_breakpoint_cmd (char *args, int from_tty)
14289 {
14290 }
14291
14292 static void
14293 show_breakpoint_cmd (char *args, int from_tty)
14294 {
14295 }
14296
14297 /* Invalidate last known value of any hardware watchpoint if
14298    the memory which that value represents has been written to by
14299    GDB itself.  */
14300
14301 static void
14302 invalidate_bp_value_on_memory_change (CORE_ADDR addr, int len,
14303                                       const bfd_byte *data)
14304 {
14305   struct breakpoint *bp;
14306
14307   ALL_BREAKPOINTS (bp)
14308     if (bp->enable_state == bp_enabled
14309         && bp->type == bp_hardware_watchpoint)
14310       {
14311         struct watchpoint *wp = (struct watchpoint *) bp;
14312
14313         if (wp->val_valid && wp->val)
14314           {
14315             struct bp_location *loc;
14316
14317             for (loc = bp->loc; loc != NULL; loc = loc->next)
14318               if (loc->loc_type == bp_loc_hardware_watchpoint
14319                   && loc->address + loc->length > addr
14320                   && addr + len > loc->address)
14321                 {
14322                   value_free (wp->val);
14323                   wp->val = NULL;
14324                   wp->val_valid = 0;
14325                 }
14326           }
14327       }
14328 }
14329
14330 /* Use the last displayed codepoint's values, or nothing
14331    if they aren't valid.  */
14332
14333 struct symtabs_and_lines
14334 decode_line_spec_1 (char *string, int flags)
14335 {
14336   struct symtabs_and_lines sals;
14337
14338   if (string == 0)
14339     error (_("Empty line specification."));
14340   if (last_displayed_sal_is_valid ())
14341     sals = decode_line_1 (&string, flags,
14342                           get_last_displayed_symtab (),
14343                           get_last_displayed_line ());
14344   else
14345     sals = decode_line_1 (&string, flags, (struct symtab *) NULL, 0);
14346   if (*string)
14347     error (_("Junk at end of line specification: %s"), string);
14348   return sals;
14349 }
14350
14351 /* Create and insert a raw software breakpoint at PC.  Return an
14352    identifier, which should be used to remove the breakpoint later.
14353    In general, places which call this should be using something on the
14354    breakpoint chain instead; this function should be eliminated
14355    someday.  */
14356
14357 void *
14358 deprecated_insert_raw_breakpoint (struct gdbarch *gdbarch,
14359                                   struct address_space *aspace, CORE_ADDR pc)
14360 {
14361   struct bp_target_info *bp_tgt;
14362
14363   bp_tgt = XZALLOC (struct bp_target_info);
14364
14365   bp_tgt->placed_address_space = aspace;
14366   bp_tgt->placed_address = pc;
14367
14368   if (target_insert_breakpoint (gdbarch, bp_tgt) != 0)
14369     {
14370       /* Could not insert the breakpoint.  */
14371       xfree (bp_tgt);
14372       return NULL;
14373     }
14374
14375   return bp_tgt;
14376 }
14377
14378 /* Remove a breakpoint BP inserted by
14379    deprecated_insert_raw_breakpoint.  */
14380
14381 int
14382 deprecated_remove_raw_breakpoint (struct gdbarch *gdbarch, void *bp)
14383 {
14384   struct bp_target_info *bp_tgt = bp;
14385   int ret;
14386
14387   ret = target_remove_breakpoint (gdbarch, bp_tgt);
14388   xfree (bp_tgt);
14389
14390   return ret;
14391 }
14392
14393 /* One (or perhaps two) breakpoints used for software single
14394    stepping.  */
14395
14396 static void *single_step_breakpoints[2];
14397 static struct gdbarch *single_step_gdbarch[2];
14398
14399 /* Create and insert a breakpoint for software single step.  */
14400
14401 void
14402 insert_single_step_breakpoint (struct gdbarch *gdbarch,
14403                                struct address_space *aspace, 
14404                                CORE_ADDR next_pc)
14405 {
14406   void **bpt_p;
14407
14408   if (single_step_breakpoints[0] == NULL)
14409     {
14410       bpt_p = &single_step_breakpoints[0];
14411       single_step_gdbarch[0] = gdbarch;
14412     }
14413   else
14414     {
14415       gdb_assert (single_step_breakpoints[1] == NULL);
14416       bpt_p = &single_step_breakpoints[1];
14417       single_step_gdbarch[1] = gdbarch;
14418     }
14419
14420   /* NOTE drow/2006-04-11: A future improvement to this function would
14421      be to only create the breakpoints once, and actually put them on
14422      the breakpoint chain.  That would let us use set_raw_breakpoint.
14423      We could adjust the addresses each time they were needed.  Doing
14424      this requires corresponding changes elsewhere where single step
14425      breakpoints are handled, however.  So, for now, we use this.  */
14426
14427   *bpt_p = deprecated_insert_raw_breakpoint (gdbarch, aspace, next_pc);
14428   if (*bpt_p == NULL)
14429     error (_("Could not insert single-step breakpoint at %s"),
14430              paddress (gdbarch, next_pc));
14431 }
14432
14433 /* Check if the breakpoints used for software single stepping
14434    were inserted or not.  */
14435
14436 int
14437 single_step_breakpoints_inserted (void)
14438 {
14439   return (single_step_breakpoints[0] != NULL
14440           || single_step_breakpoints[1] != NULL);
14441 }
14442
14443 /* Remove and delete any breakpoints used for software single step.  */
14444
14445 void
14446 remove_single_step_breakpoints (void)
14447 {
14448   gdb_assert (single_step_breakpoints[0] != NULL);
14449
14450   /* See insert_single_step_breakpoint for more about this deprecated
14451      call.  */
14452   deprecated_remove_raw_breakpoint (single_step_gdbarch[0],
14453                                     single_step_breakpoints[0]);
14454   single_step_gdbarch[0] = NULL;
14455   single_step_breakpoints[0] = NULL;
14456
14457   if (single_step_breakpoints[1] != NULL)
14458     {
14459       deprecated_remove_raw_breakpoint (single_step_gdbarch[1],
14460                                         single_step_breakpoints[1]);
14461       single_step_gdbarch[1] = NULL;
14462       single_step_breakpoints[1] = NULL;
14463     }
14464 }
14465
14466 /* Delete software single step breakpoints without removing them from
14467    the inferior.  This is intended to be used if the inferior's address
14468    space where they were inserted is already gone, e.g. after exit or
14469    exec.  */
14470
14471 void
14472 cancel_single_step_breakpoints (void)
14473 {
14474   int i;
14475
14476   for (i = 0; i < 2; i++)
14477     if (single_step_breakpoints[i])
14478       {
14479         xfree (single_step_breakpoints[i]);
14480         single_step_breakpoints[i] = NULL;
14481         single_step_gdbarch[i] = NULL;
14482       }
14483 }
14484
14485 /* Detach software single-step breakpoints from INFERIOR_PTID without
14486    removing them.  */
14487
14488 static void
14489 detach_single_step_breakpoints (void)
14490 {
14491   int i;
14492
14493   for (i = 0; i < 2; i++)
14494     if (single_step_breakpoints[i])
14495       target_remove_breakpoint (single_step_gdbarch[i],
14496                                 single_step_breakpoints[i]);
14497 }
14498
14499 /* Check whether a software single-step breakpoint is inserted at
14500    PC.  */
14501
14502 static int
14503 single_step_breakpoint_inserted_here_p (struct address_space *aspace, 
14504                                         CORE_ADDR pc)
14505 {
14506   int i;
14507
14508   for (i = 0; i < 2; i++)
14509     {
14510       struct bp_target_info *bp_tgt = single_step_breakpoints[i];
14511       if (bp_tgt
14512           && breakpoint_address_match (bp_tgt->placed_address_space,
14513                                        bp_tgt->placed_address,
14514                                        aspace, pc))
14515         return 1;
14516     }
14517
14518   return 0;
14519 }
14520
14521 /* Returns 0 if 'bp' is NOT a syscall catchpoint,
14522    non-zero otherwise.  */
14523 static int
14524 is_syscall_catchpoint_enabled (struct breakpoint *bp)
14525 {
14526   if (syscall_catchpoint_p (bp)
14527       && bp->enable_state != bp_disabled
14528       && bp->enable_state != bp_call_disabled)
14529     return 1;
14530   else
14531     return 0;
14532 }
14533
14534 int
14535 catch_syscall_enabled (void)
14536 {
14537   struct catch_syscall_inferior_data *inf_data
14538     = get_catch_syscall_inferior_data (current_inferior ());
14539
14540   return inf_data->total_syscalls_count != 0;
14541 }
14542
14543 int
14544 catching_syscall_number (int syscall_number)
14545 {
14546   struct breakpoint *bp;
14547
14548   ALL_BREAKPOINTS (bp)
14549     if (is_syscall_catchpoint_enabled (bp))
14550       {
14551         struct syscall_catchpoint *c = (struct syscall_catchpoint *) bp;
14552
14553         if (c->syscalls_to_be_caught)
14554           {
14555             int i, iter;
14556             for (i = 0;
14557                  VEC_iterate (int, c->syscalls_to_be_caught, i, iter);
14558                  i++)
14559               if (syscall_number == iter)
14560                 return 1;
14561           }
14562         else
14563           return 1;
14564       }
14565
14566   return 0;
14567 }
14568
14569 /* Complete syscall names.  Used by "catch syscall".  */
14570 static char **
14571 catch_syscall_completer (struct cmd_list_element *cmd,
14572                          char *text, char *word)
14573 {
14574   const char **list = get_syscall_names ();
14575   char **retlist
14576     = (list == NULL) ? NULL : complete_on_enum (list, text, word);
14577
14578   xfree (list);
14579   return retlist;
14580 }
14581
14582 /* Tracepoint-specific operations.  */
14583
14584 /* Set tracepoint count to NUM.  */
14585 static void
14586 set_tracepoint_count (int num)
14587 {
14588   tracepoint_count = num;
14589   set_internalvar_integer (lookup_internalvar ("tpnum"), num);
14590 }
14591
14592 static void
14593 trace_command (char *arg, int from_tty)
14594 {
14595   struct breakpoint_ops *ops;
14596   const char *arg_cp = arg;
14597
14598   if (arg && probe_linespec_to_ops (&arg_cp))
14599     ops = &tracepoint_probe_breakpoint_ops;
14600   else
14601     ops = &tracepoint_breakpoint_ops;
14602
14603   if (create_breakpoint (get_current_arch (),
14604                          arg,
14605                          NULL, 0, NULL, 1 /* parse arg */,
14606                          0 /* tempflag */,
14607                          bp_tracepoint /* type_wanted */,
14608                          0 /* Ignore count */,
14609                          pending_break_support,
14610                          ops,
14611                          from_tty,
14612                          1 /* enabled */,
14613                          0 /* internal */, 0))
14614     set_tracepoint_count (breakpoint_count);
14615 }
14616
14617 static void
14618 ftrace_command (char *arg, int from_tty)
14619 {
14620   if (create_breakpoint (get_current_arch (),
14621                          arg,
14622                          NULL, 0, NULL, 1 /* parse arg */,
14623                          0 /* tempflag */,
14624                          bp_fast_tracepoint /* type_wanted */,
14625                          0 /* Ignore count */,
14626                          pending_break_support,
14627                          &tracepoint_breakpoint_ops,
14628                          from_tty,
14629                          1 /* enabled */,
14630                          0 /* internal */, 0))
14631     set_tracepoint_count (breakpoint_count);
14632 }
14633
14634 /* strace command implementation.  Creates a static tracepoint.  */
14635
14636 static void
14637 strace_command (char *arg, int from_tty)
14638 {
14639   struct breakpoint_ops *ops;
14640
14641   /* Decide if we are dealing with a static tracepoint marker (`-m'),
14642      or with a normal static tracepoint.  */
14643   if (arg && strncmp (arg, "-m", 2) == 0 && isspace (arg[2]))
14644     ops = &strace_marker_breakpoint_ops;
14645   else
14646     ops = &tracepoint_breakpoint_ops;
14647
14648   if (create_breakpoint (get_current_arch (),
14649                          arg,
14650                          NULL, 0, NULL, 1 /* parse arg */,
14651                          0 /* tempflag */,
14652                          bp_static_tracepoint /* type_wanted */,
14653                          0 /* Ignore count */,
14654                          pending_break_support,
14655                          ops,
14656                          from_tty,
14657                          1 /* enabled */,
14658                          0 /* internal */, 0))
14659     set_tracepoint_count (breakpoint_count);
14660 }
14661
14662 /* Set up a fake reader function that gets command lines from a linked
14663    list that was acquired during tracepoint uploading.  */
14664
14665 static struct uploaded_tp *this_utp;
14666 static int next_cmd;
14667
14668 static char *
14669 read_uploaded_action (void)
14670 {
14671   char *rslt;
14672
14673   VEC_iterate (char_ptr, this_utp->cmd_strings, next_cmd, rslt);
14674
14675   next_cmd++;
14676
14677   return rslt;
14678 }
14679
14680 /* Given information about a tracepoint as recorded on a target (which
14681    can be either a live system or a trace file), attempt to create an
14682    equivalent GDB tracepoint.  This is not a reliable process, since
14683    the target does not necessarily have all the information used when
14684    the tracepoint was originally defined.  */
14685   
14686 struct tracepoint *
14687 create_tracepoint_from_upload (struct uploaded_tp *utp)
14688 {
14689   char *addr_str, small_buf[100];
14690   struct tracepoint *tp;
14691
14692   if (utp->at_string)
14693     addr_str = utp->at_string;
14694   else
14695     {
14696       /* In the absence of a source location, fall back to raw
14697          address.  Since there is no way to confirm that the address
14698          means the same thing as when the trace was started, warn the
14699          user.  */
14700       warning (_("Uploaded tracepoint %d has no "
14701                  "source location, using raw address"),
14702                utp->number);
14703       sprintf (small_buf, "*%s", hex_string (utp->addr));
14704       addr_str = small_buf;
14705     }
14706
14707   /* There's not much we can do with a sequence of bytecodes.  */
14708   if (utp->cond && !utp->cond_string)
14709     warning (_("Uploaded tracepoint %d condition "
14710                "has no source form, ignoring it"),
14711              utp->number);
14712
14713   if (!create_breakpoint (get_current_arch (),
14714                           addr_str,
14715                           utp->cond_string, -1, NULL,
14716                           0 /* parse cond/thread */,
14717                           0 /* tempflag */,
14718                           utp->type /* type_wanted */,
14719                           0 /* Ignore count */,
14720                           pending_break_support,
14721                           &tracepoint_breakpoint_ops,
14722                           0 /* from_tty */,
14723                           utp->enabled /* enabled */,
14724                           0 /* internal */,
14725                           CREATE_BREAKPOINT_FLAGS_INSERTED))
14726     return NULL;
14727
14728   set_tracepoint_count (breakpoint_count);
14729   
14730   /* Get the tracepoint we just created.  */
14731   tp = get_tracepoint (tracepoint_count);
14732   gdb_assert (tp != NULL);
14733
14734   if (utp->pass > 0)
14735     {
14736       sprintf (small_buf, "%d %d", utp->pass, tp->base.number);
14737
14738       trace_pass_command (small_buf, 0);
14739     }
14740
14741   /* If we have uploaded versions of the original commands, set up a
14742      special-purpose "reader" function and call the usual command line
14743      reader, then pass the result to the breakpoint command-setting
14744      function.  */
14745   if (!VEC_empty (char_ptr, utp->cmd_strings))
14746     {
14747       struct command_line *cmd_list;
14748
14749       this_utp = utp;
14750       next_cmd = 0;
14751
14752       cmd_list = read_command_lines_1 (read_uploaded_action, 1, NULL, NULL);
14753
14754       breakpoint_set_commands (&tp->base, cmd_list);
14755     }
14756   else if (!VEC_empty (char_ptr, utp->actions)
14757            || !VEC_empty (char_ptr, utp->step_actions))
14758     warning (_("Uploaded tracepoint %d actions "
14759                "have no source form, ignoring them"),
14760              utp->number);
14761
14762   /* Copy any status information that might be available.  */
14763   tp->base.hit_count = utp->hit_count;
14764   tp->traceframe_usage = utp->traceframe_usage;
14765
14766   return tp;
14767 }
14768   
14769 /* Print information on tracepoint number TPNUM_EXP, or all if
14770    omitted.  */
14771
14772 static void
14773 tracepoints_info (char *args, int from_tty)
14774 {
14775   struct ui_out *uiout = current_uiout;
14776   int num_printed;
14777
14778   num_printed = breakpoint_1 (args, 0, is_tracepoint);
14779
14780   if (num_printed == 0)
14781     {
14782       if (args == NULL || *args == '\0')
14783         ui_out_message (uiout, 0, "No tracepoints.\n");
14784       else
14785         ui_out_message (uiout, 0, "No tracepoint matching '%s'.\n", args);
14786     }
14787
14788   default_collect_info ();
14789 }
14790
14791 /* The 'enable trace' command enables tracepoints.
14792    Not supported by all targets.  */
14793 static void
14794 enable_trace_command (char *args, int from_tty)
14795 {
14796   enable_command (args, from_tty);
14797 }
14798
14799 /* The 'disable trace' command disables tracepoints.
14800    Not supported by all targets.  */
14801 static void
14802 disable_trace_command (char *args, int from_tty)
14803 {
14804   disable_command (args, from_tty);
14805 }
14806
14807 /* Remove a tracepoint (or all if no argument).  */
14808 static void
14809 delete_trace_command (char *arg, int from_tty)
14810 {
14811   struct breakpoint *b, *b_tmp;
14812
14813   dont_repeat ();
14814
14815   if (arg == 0)
14816     {
14817       int breaks_to_delete = 0;
14818
14819       /* Delete all breakpoints if no argument.
14820          Do not delete internal or call-dummy breakpoints, these
14821          have to be deleted with an explicit breakpoint number 
14822          argument.  */
14823       ALL_TRACEPOINTS (b)
14824         if (is_tracepoint (b) && user_breakpoint_p (b))
14825           {
14826             breaks_to_delete = 1;
14827             break;
14828           }
14829
14830       /* Ask user only if there are some breakpoints to delete.  */
14831       if (!from_tty
14832           || (breaks_to_delete && query (_("Delete all tracepoints? "))))
14833         {
14834           ALL_BREAKPOINTS_SAFE (b, b_tmp)
14835             if (is_tracepoint (b) && user_breakpoint_p (b))
14836               delete_breakpoint (b);
14837         }
14838     }
14839   else
14840     map_breakpoint_numbers (arg, do_map_delete_breakpoint, NULL);
14841 }
14842
14843 /* Helper function for trace_pass_command.  */
14844
14845 static void
14846 trace_pass_set_count (struct tracepoint *tp, int count, int from_tty)
14847 {
14848   tp->pass_count = count;
14849   observer_notify_tracepoint_modified (tp->base.number);
14850   if (from_tty)
14851     printf_filtered (_("Setting tracepoint %d's passcount to %d\n"),
14852                      tp->base.number, count);
14853 }
14854
14855 /* Set passcount for tracepoint.
14856
14857    First command argument is passcount, second is tracepoint number.
14858    If tracepoint number omitted, apply to most recently defined.
14859    Also accepts special argument "all".  */
14860
14861 static void
14862 trace_pass_command (char *args, int from_tty)
14863 {
14864   struct tracepoint *t1;
14865   unsigned int count;
14866
14867   if (args == 0 || *args == 0)
14868     error (_("passcount command requires an "
14869              "argument (count + optional TP num)"));
14870
14871   count = strtoul (args, &args, 10);    /* Count comes first, then TP num.  */
14872
14873   while (*args && isspace ((int) *args))
14874     args++;
14875
14876   if (*args && strncasecmp (args, "all", 3) == 0)
14877     {
14878       struct breakpoint *b;
14879
14880       args += 3;                        /* Skip special argument "all".  */
14881       if (*args)
14882         error (_("Junk at end of arguments."));
14883
14884       ALL_TRACEPOINTS (b)
14885       {
14886         t1 = (struct tracepoint *) b;
14887         trace_pass_set_count (t1, count, from_tty);
14888       }
14889     }
14890   else if (*args == '\0')
14891     {
14892       t1 = get_tracepoint_by_number (&args, NULL, 1);
14893       if (t1)
14894         trace_pass_set_count (t1, count, from_tty);
14895     }
14896   else
14897     {
14898       struct get_number_or_range_state state;
14899
14900       init_number_or_range (&state, args);
14901       while (!state.finished)
14902         {
14903           t1 = get_tracepoint_by_number (&args, &state, 1);
14904           if (t1)
14905             trace_pass_set_count (t1, count, from_tty);
14906         }
14907     }
14908 }
14909
14910 struct tracepoint *
14911 get_tracepoint (int num)
14912 {
14913   struct breakpoint *t;
14914
14915   ALL_TRACEPOINTS (t)
14916     if (t->number == num)
14917       return (struct tracepoint *) t;
14918
14919   return NULL;
14920 }
14921
14922 /* Find the tracepoint with the given target-side number (which may be
14923    different from the tracepoint number after disconnecting and
14924    reconnecting).  */
14925
14926 struct tracepoint *
14927 get_tracepoint_by_number_on_target (int num)
14928 {
14929   struct breakpoint *b;
14930
14931   ALL_TRACEPOINTS (b)
14932     {
14933       struct tracepoint *t = (struct tracepoint *) b;
14934
14935       if (t->number_on_target == num)
14936         return t;
14937     }
14938
14939   return NULL;
14940 }
14941
14942 /* Utility: parse a tracepoint number and look it up in the list.
14943    If STATE is not NULL, use, get_number_or_range_state and ignore ARG.
14944    If OPTIONAL_P is true, then if the argument is missing, the most
14945    recent tracepoint (tracepoint_count) is returned.  */
14946 struct tracepoint *
14947 get_tracepoint_by_number (char **arg,
14948                           struct get_number_or_range_state *state,
14949                           int optional_p)
14950 {
14951   extern int tracepoint_count;
14952   struct breakpoint *t;
14953   int tpnum;
14954   char *instring = arg == NULL ? NULL : *arg;
14955
14956   if (state)
14957     {
14958       gdb_assert (!state->finished);
14959       tpnum = get_number_or_range (state);
14960     }
14961   else if (arg == NULL || *arg == NULL || ! **arg)
14962     {
14963       if (optional_p)
14964         tpnum = tracepoint_count;
14965       else
14966         error_no_arg (_("tracepoint number"));
14967     }
14968   else
14969     tpnum = get_number (arg);
14970
14971   if (tpnum <= 0)
14972     {
14973       if (instring && *instring)
14974         printf_filtered (_("bad tracepoint number at or near '%s'\n"), 
14975                          instring);
14976       else
14977         printf_filtered (_("Tracepoint argument missing "
14978                            "and no previous tracepoint\n"));
14979       return NULL;
14980     }
14981
14982   ALL_TRACEPOINTS (t)
14983     if (t->number == tpnum)
14984     {
14985       return (struct tracepoint *) t;
14986     }
14987
14988   printf_unfiltered ("No tracepoint number %d.\n", tpnum);
14989   return NULL;
14990 }
14991
14992 void
14993 print_recreate_thread (struct breakpoint *b, struct ui_file *fp)
14994 {
14995   if (b->thread != -1)
14996     fprintf_unfiltered (fp, " thread %d", b->thread);
14997
14998   if (b->task != 0)
14999     fprintf_unfiltered (fp, " task %d", b->task);
15000
15001   fprintf_unfiltered (fp, "\n");
15002 }
15003
15004 /* Save information on user settable breakpoints (watchpoints, etc) to
15005    a new script file named FILENAME.  If FILTER is non-NULL, call it
15006    on each breakpoint and only include the ones for which it returns
15007    non-zero.  */
15008
15009 static void
15010 save_breakpoints (char *filename, int from_tty,
15011                   int (*filter) (const struct breakpoint *))
15012 {
15013   struct breakpoint *tp;
15014   int any = 0;
15015   char *pathname;
15016   struct cleanup *cleanup;
15017   struct ui_file *fp;
15018   int extra_trace_bits = 0;
15019
15020   if (filename == 0 || *filename == 0)
15021     error (_("Argument required (file name in which to save)"));
15022
15023   /* See if we have anything to save.  */
15024   ALL_BREAKPOINTS (tp)
15025   {
15026     /* Skip internal and momentary breakpoints.  */
15027     if (!user_breakpoint_p (tp))
15028       continue;
15029
15030     /* If we have a filter, only save the breakpoints it accepts.  */
15031     if (filter && !filter (tp))
15032       continue;
15033
15034     any = 1;
15035
15036     if (is_tracepoint (tp))
15037       {
15038         extra_trace_bits = 1;
15039
15040         /* We can stop searching.  */
15041         break;
15042       }
15043   }
15044
15045   if (!any)
15046     {
15047       warning (_("Nothing to save."));
15048       return;
15049     }
15050
15051   pathname = tilde_expand (filename);
15052   cleanup = make_cleanup (xfree, pathname);
15053   fp = gdb_fopen (pathname, "w");
15054   if (!fp)
15055     error (_("Unable to open file '%s' for saving (%s)"),
15056            filename, safe_strerror (errno));
15057   make_cleanup_ui_file_delete (fp);
15058
15059   if (extra_trace_bits)
15060     save_trace_state_variables (fp);
15061
15062   ALL_BREAKPOINTS (tp)
15063   {
15064     /* Skip internal and momentary breakpoints.  */
15065     if (!user_breakpoint_p (tp))
15066       continue;
15067
15068     /* If we have a filter, only save the breakpoints it accepts.  */
15069     if (filter && !filter (tp))
15070       continue;
15071
15072     tp->ops->print_recreate (tp, fp);
15073
15074     /* Note, we can't rely on tp->number for anything, as we can't
15075        assume the recreated breakpoint numbers will match.  Use $bpnum
15076        instead.  */
15077
15078     if (tp->cond_string)
15079       fprintf_unfiltered (fp, "  condition $bpnum %s\n", tp->cond_string);
15080
15081     if (tp->ignore_count)
15082       fprintf_unfiltered (fp, "  ignore $bpnum %d\n", tp->ignore_count);
15083
15084     if (tp->commands)
15085       {
15086         volatile struct gdb_exception ex;       
15087
15088         fprintf_unfiltered (fp, "  commands\n");
15089         
15090         ui_out_redirect (current_uiout, fp);
15091         TRY_CATCH (ex, RETURN_MASK_ALL)
15092           {
15093             print_command_lines (current_uiout, tp->commands->commands, 2);
15094           }
15095         ui_out_redirect (current_uiout, NULL);
15096
15097         if (ex.reason < 0)
15098           throw_exception (ex);
15099
15100         fprintf_unfiltered (fp, "  end\n");
15101       }
15102
15103     if (tp->enable_state == bp_disabled)
15104       fprintf_unfiltered (fp, "disable\n");
15105
15106     /* If this is a multi-location breakpoint, check if the locations
15107        should be individually disabled.  Watchpoint locations are
15108        special, and not user visible.  */
15109     if (!is_watchpoint (tp) && tp->loc && tp->loc->next)
15110       {
15111         struct bp_location *loc;
15112         int n = 1;
15113
15114         for (loc = tp->loc; loc != NULL; loc = loc->next, n++)
15115           if (!loc->enabled)
15116             fprintf_unfiltered (fp, "disable $bpnum.%d\n", n);
15117       }
15118   }
15119
15120   if (extra_trace_bits && *default_collect)
15121     fprintf_unfiltered (fp, "set default-collect %s\n", default_collect);
15122
15123   do_cleanups (cleanup);
15124   if (from_tty)
15125     printf_filtered (_("Saved to file '%s'.\n"), filename);
15126 }
15127
15128 /* The `save breakpoints' command.  */
15129
15130 static void
15131 save_breakpoints_command (char *args, int from_tty)
15132 {
15133   save_breakpoints (args, from_tty, NULL);
15134 }
15135
15136 /* The `save tracepoints' command.  */
15137
15138 static void
15139 save_tracepoints_command (char *args, int from_tty)
15140 {
15141   save_breakpoints (args, from_tty, is_tracepoint);
15142 }
15143
15144 /* Create a vector of all tracepoints.  */
15145
15146 VEC(breakpoint_p) *
15147 all_tracepoints (void)
15148 {
15149   VEC(breakpoint_p) *tp_vec = 0;
15150   struct breakpoint *tp;
15151
15152   ALL_TRACEPOINTS (tp)
15153   {
15154     VEC_safe_push (breakpoint_p, tp_vec, tp);
15155   }
15156
15157   return tp_vec;
15158 }
15159
15160 \f
15161 /* This help string is used for the break, hbreak, tbreak and thbreak
15162    commands.  It is defined as a macro to prevent duplication.
15163    COMMAND should be a string constant containing the name of the
15164    command.  */
15165 #define BREAK_ARGS_HELP(command) \
15166 command" [LOCATION] [thread THREADNUM] [if CONDITION]\n\
15167 LOCATION may be a line number, function name, or \"*\" and an address.\n\
15168 If a line number is specified, break at start of code for that line.\n\
15169 If a function is specified, break at start of code for that function.\n\
15170 If an address is specified, break at that exact address.\n\
15171 With no LOCATION, uses current execution address of the selected\n\
15172 stack frame.  This is useful for breaking on return to a stack frame.\n\
15173 \n\
15174 THREADNUM is the number from \"info threads\".\n\
15175 CONDITION is a boolean expression.\n\
15176 \n\
15177 Multiple breakpoints at one place are permitted, and useful if their\n\
15178 conditions are different.\n\
15179 \n\
15180 Do \"help breakpoints\" for info on other commands dealing with breakpoints."
15181
15182 /* List of subcommands for "catch".  */
15183 static struct cmd_list_element *catch_cmdlist;
15184
15185 /* List of subcommands for "tcatch".  */
15186 static struct cmd_list_element *tcatch_cmdlist;
15187
15188 void
15189 add_catch_command (char *name, char *docstring,
15190                    void (*sfunc) (char *args, int from_tty,
15191                                   struct cmd_list_element *command),
15192                    char **(*completer) (struct cmd_list_element *cmd,
15193                                          char *text, char *word),
15194                    void *user_data_catch,
15195                    void *user_data_tcatch)
15196 {
15197   struct cmd_list_element *command;
15198
15199   command = add_cmd (name, class_breakpoint, NULL, docstring,
15200                      &catch_cmdlist);
15201   set_cmd_sfunc (command, sfunc);
15202   set_cmd_context (command, user_data_catch);
15203   set_cmd_completer (command, completer);
15204
15205   command = add_cmd (name, class_breakpoint, NULL, docstring,
15206                      &tcatch_cmdlist);
15207   set_cmd_sfunc (command, sfunc);
15208   set_cmd_context (command, user_data_tcatch);
15209   set_cmd_completer (command, completer);
15210 }
15211
15212 static void
15213 clear_syscall_counts (struct inferior *inf)
15214 {
15215   struct catch_syscall_inferior_data *inf_data
15216     = get_catch_syscall_inferior_data (inf);
15217
15218   inf_data->total_syscalls_count = 0;
15219   inf_data->any_syscall_count = 0;
15220   VEC_free (int, inf_data->syscalls_counts);
15221 }
15222
15223 static void
15224 save_command (char *arg, int from_tty)
15225 {
15226   printf_unfiltered (_("\"save\" must be followed by "
15227                        "the name of a save subcommand.\n"));
15228   help_list (save_cmdlist, "save ", -1, gdb_stdout);
15229 }
15230
15231 struct breakpoint *
15232 iterate_over_breakpoints (int (*callback) (struct breakpoint *, void *),
15233                           void *data)
15234 {
15235   struct breakpoint *b, *b_tmp;
15236
15237   ALL_BREAKPOINTS_SAFE (b, b_tmp)
15238     {
15239       if ((*callback) (b, data))
15240         return b;
15241     }
15242
15243   return NULL;
15244 }
15245
15246 /* Zero if any of the breakpoint's locations could be a location where
15247    functions have been inlined, nonzero otherwise.  */
15248
15249 static int
15250 is_non_inline_function (struct breakpoint *b)
15251 {
15252   /* The shared library event breakpoint is set on the address of a
15253      non-inline function.  */
15254   if (b->type == bp_shlib_event)
15255     return 1;
15256
15257   return 0;
15258 }
15259
15260 /* Nonzero if the specified PC cannot be a location where functions
15261    have been inlined.  */
15262
15263 int
15264 pc_at_non_inline_function (struct address_space *aspace, CORE_ADDR pc,
15265                            const struct target_waitstatus *ws)
15266 {
15267   struct breakpoint *b;
15268   struct bp_location *bl;
15269
15270   ALL_BREAKPOINTS (b)
15271     {
15272       if (!is_non_inline_function (b))
15273         continue;
15274
15275       for (bl = b->loc; bl != NULL; bl = bl->next)
15276         {
15277           if (!bl->shlib_disabled
15278               && bpstat_check_location (bl, aspace, pc, ws))
15279             return 1;
15280         }
15281     }
15282
15283   return 0;
15284 }
15285
15286 void
15287 initialize_breakpoint_ops (void)
15288 {
15289   static int initialized = 0;
15290
15291   struct breakpoint_ops *ops;
15292
15293   if (initialized)
15294     return;
15295   initialized = 1;
15296
15297   /* The breakpoint_ops structure to be inherit by all kinds of
15298      breakpoints (real breakpoints, i.e., user "break" breakpoints,
15299      internal and momentary breakpoints, etc.).  */
15300   ops = &bkpt_base_breakpoint_ops;
15301   *ops = base_breakpoint_ops;
15302   ops->re_set = bkpt_re_set;
15303   ops->insert_location = bkpt_insert_location;
15304   ops->remove_location = bkpt_remove_location;
15305   ops->breakpoint_hit = bkpt_breakpoint_hit;
15306   ops->create_sals_from_address = bkpt_create_sals_from_address;
15307   ops->create_breakpoints_sal = bkpt_create_breakpoints_sal;
15308   ops->decode_linespec = bkpt_decode_linespec;
15309
15310   /* The breakpoint_ops structure to be used in regular breakpoints.  */
15311   ops = &bkpt_breakpoint_ops;
15312   *ops = bkpt_base_breakpoint_ops;
15313   ops->re_set = bkpt_re_set;
15314   ops->resources_needed = bkpt_resources_needed;
15315   ops->print_it = bkpt_print_it;
15316   ops->print_mention = bkpt_print_mention;
15317   ops->print_recreate = bkpt_print_recreate;
15318
15319   /* Ranged breakpoints.  */
15320   ops = &ranged_breakpoint_ops;
15321   *ops = bkpt_breakpoint_ops;
15322   ops->breakpoint_hit = breakpoint_hit_ranged_breakpoint;
15323   ops->resources_needed = resources_needed_ranged_breakpoint;
15324   ops->print_it = print_it_ranged_breakpoint;
15325   ops->print_one = print_one_ranged_breakpoint;
15326   ops->print_one_detail = print_one_detail_ranged_breakpoint;
15327   ops->print_mention = print_mention_ranged_breakpoint;
15328   ops->print_recreate = print_recreate_ranged_breakpoint;
15329
15330   /* Internal breakpoints.  */
15331   ops = &internal_breakpoint_ops;
15332   *ops = bkpt_base_breakpoint_ops;
15333   ops->re_set = internal_bkpt_re_set;
15334   ops->check_status = internal_bkpt_check_status;
15335   ops->print_it = internal_bkpt_print_it;
15336   ops->print_mention = internal_bkpt_print_mention;
15337
15338   /* Momentary breakpoints.  */
15339   ops = &momentary_breakpoint_ops;
15340   *ops = bkpt_base_breakpoint_ops;
15341   ops->re_set = momentary_bkpt_re_set;
15342   ops->check_status = momentary_bkpt_check_status;
15343   ops->print_it = momentary_bkpt_print_it;
15344   ops->print_mention = momentary_bkpt_print_mention;
15345
15346   /* Probe breakpoints.  */
15347   ops = &bkpt_probe_breakpoint_ops;
15348   *ops = bkpt_breakpoint_ops;
15349   ops->insert_location = bkpt_probe_insert_location;
15350   ops->remove_location = bkpt_probe_remove_location;
15351   ops->create_sals_from_address = bkpt_probe_create_sals_from_address;
15352   ops->decode_linespec = bkpt_probe_decode_linespec;
15353
15354   /* GNU v3 exception catchpoints.  */
15355   ops = &gnu_v3_exception_catchpoint_ops;
15356   *ops = bkpt_breakpoint_ops;
15357   ops->print_it = print_it_exception_catchpoint;
15358   ops->print_one = print_one_exception_catchpoint;
15359   ops->print_mention = print_mention_exception_catchpoint;
15360   ops->print_recreate = print_recreate_exception_catchpoint;
15361
15362   /* Watchpoints.  */
15363   ops = &watchpoint_breakpoint_ops;
15364   *ops = base_breakpoint_ops;
15365   ops->dtor = dtor_watchpoint;
15366   ops->re_set = re_set_watchpoint;
15367   ops->insert_location = insert_watchpoint;
15368   ops->remove_location = remove_watchpoint;
15369   ops->breakpoint_hit = breakpoint_hit_watchpoint;
15370   ops->check_status = check_status_watchpoint;
15371   ops->resources_needed = resources_needed_watchpoint;
15372   ops->works_in_software_mode = works_in_software_mode_watchpoint;
15373   ops->print_it = print_it_watchpoint;
15374   ops->print_mention = print_mention_watchpoint;
15375   ops->print_recreate = print_recreate_watchpoint;
15376
15377   /* Masked watchpoints.  */
15378   ops = &masked_watchpoint_breakpoint_ops;
15379   *ops = watchpoint_breakpoint_ops;
15380   ops->insert_location = insert_masked_watchpoint;
15381   ops->remove_location = remove_masked_watchpoint;
15382   ops->resources_needed = resources_needed_masked_watchpoint;
15383   ops->works_in_software_mode = works_in_software_mode_masked_watchpoint;
15384   ops->print_it = print_it_masked_watchpoint;
15385   ops->print_one_detail = print_one_detail_masked_watchpoint;
15386   ops->print_mention = print_mention_masked_watchpoint;
15387   ops->print_recreate = print_recreate_masked_watchpoint;
15388
15389   /* Tracepoints.  */
15390   ops = &tracepoint_breakpoint_ops;
15391   *ops = base_breakpoint_ops;
15392   ops->re_set = tracepoint_re_set;
15393   ops->breakpoint_hit = tracepoint_breakpoint_hit;
15394   ops->print_one_detail = tracepoint_print_one_detail;
15395   ops->print_mention = tracepoint_print_mention;
15396   ops->print_recreate = tracepoint_print_recreate;
15397   ops->create_sals_from_address = tracepoint_create_sals_from_address;
15398   ops->create_breakpoints_sal = tracepoint_create_breakpoints_sal;
15399   ops->decode_linespec = tracepoint_decode_linespec;
15400
15401   /* Probe tracepoints.  */
15402   ops = &tracepoint_probe_breakpoint_ops;
15403   *ops = tracepoint_breakpoint_ops;
15404   ops->create_sals_from_address = tracepoint_probe_create_sals_from_address;
15405   ops->decode_linespec = tracepoint_probe_decode_linespec;
15406
15407   /* Static tracepoints with marker (`-m').  */
15408   ops = &strace_marker_breakpoint_ops;
15409   *ops = tracepoint_breakpoint_ops;
15410   ops->create_sals_from_address = strace_marker_create_sals_from_address;
15411   ops->create_breakpoints_sal = strace_marker_create_breakpoints_sal;
15412   ops->decode_linespec = strace_marker_decode_linespec;
15413
15414   /* Fork catchpoints.  */
15415   ops = &catch_fork_breakpoint_ops;
15416   *ops = base_breakpoint_ops;
15417   ops->insert_location = insert_catch_fork;
15418   ops->remove_location = remove_catch_fork;
15419   ops->breakpoint_hit = breakpoint_hit_catch_fork;
15420   ops->print_it = print_it_catch_fork;
15421   ops->print_one = print_one_catch_fork;
15422   ops->print_mention = print_mention_catch_fork;
15423   ops->print_recreate = print_recreate_catch_fork;
15424
15425   /* Vfork catchpoints.  */
15426   ops = &catch_vfork_breakpoint_ops;
15427   *ops = base_breakpoint_ops;
15428   ops->insert_location = insert_catch_vfork;
15429   ops->remove_location = remove_catch_vfork;
15430   ops->breakpoint_hit = breakpoint_hit_catch_vfork;
15431   ops->print_it = print_it_catch_vfork;
15432   ops->print_one = print_one_catch_vfork;
15433   ops->print_mention = print_mention_catch_vfork;
15434   ops->print_recreate = print_recreate_catch_vfork;
15435
15436   /* Exec catchpoints.  */
15437   ops = &catch_exec_breakpoint_ops;
15438   *ops = base_breakpoint_ops;
15439   ops->dtor = dtor_catch_exec;
15440   ops->insert_location = insert_catch_exec;
15441   ops->remove_location = remove_catch_exec;
15442   ops->breakpoint_hit = breakpoint_hit_catch_exec;
15443   ops->print_it = print_it_catch_exec;
15444   ops->print_one = print_one_catch_exec;
15445   ops->print_mention = print_mention_catch_exec;
15446   ops->print_recreate = print_recreate_catch_exec;
15447
15448   /* Syscall catchpoints.  */
15449   ops = &catch_syscall_breakpoint_ops;
15450   *ops = base_breakpoint_ops;
15451   ops->dtor = dtor_catch_syscall;
15452   ops->insert_location = insert_catch_syscall;
15453   ops->remove_location = remove_catch_syscall;
15454   ops->breakpoint_hit = breakpoint_hit_catch_syscall;
15455   ops->print_it = print_it_catch_syscall;
15456   ops->print_one = print_one_catch_syscall;
15457   ops->print_mention = print_mention_catch_syscall;
15458   ops->print_recreate = print_recreate_catch_syscall;
15459
15460   /* Solib-related catchpoints.  */
15461   ops = &catch_solib_breakpoint_ops;
15462   *ops = base_breakpoint_ops;
15463   ops->dtor = dtor_catch_solib;
15464   ops->insert_location = insert_catch_solib;
15465   ops->remove_location = remove_catch_solib;
15466   ops->breakpoint_hit = breakpoint_hit_catch_solib;
15467   ops->check_status = check_status_catch_solib;
15468   ops->print_it = print_it_catch_solib;
15469   ops->print_one = print_one_catch_solib;
15470   ops->print_mention = print_mention_catch_solib;
15471   ops->print_recreate = print_recreate_catch_solib;
15472
15473   ops = &dprintf_breakpoint_ops;
15474   *ops = bkpt_base_breakpoint_ops;
15475   ops->re_set = bkpt_re_set;
15476   ops->resources_needed = bkpt_resources_needed;
15477   ops->print_it = bkpt_print_it;
15478   ops->print_mention = bkpt_print_mention;
15479   ops->print_recreate = bkpt_print_recreate;
15480 }
15481
15482 void
15483 _initialize_breakpoint (void)
15484 {
15485   struct cmd_list_element *c;
15486
15487   initialize_breakpoint_ops ();
15488
15489   observer_attach_solib_unloaded (disable_breakpoints_in_unloaded_shlib);
15490   observer_attach_inferior_exit (clear_syscall_counts);
15491   observer_attach_memory_changed (invalidate_bp_value_on_memory_change);
15492
15493   breakpoint_objfile_key
15494     = register_objfile_data_with_cleanup (NULL, free_breakpoint_probes);
15495
15496   catch_syscall_inferior_data
15497     = register_inferior_data_with_cleanup (catch_syscall_inferior_data_cleanup);
15498
15499   breakpoint_chain = 0;
15500   /* Don't bother to call set_breakpoint_count.  $bpnum isn't useful
15501      before a breakpoint is set.  */
15502   breakpoint_count = 0;
15503
15504   tracepoint_count = 0;
15505
15506   add_com ("ignore", class_breakpoint, ignore_command, _("\
15507 Set ignore-count of breakpoint number N to COUNT.\n\
15508 Usage is `ignore N COUNT'."));
15509   if (xdb_commands)
15510     add_com_alias ("bc", "ignore", class_breakpoint, 1);
15511
15512   add_com ("commands", class_breakpoint, commands_command, _("\
15513 Set commands to be executed when a breakpoint is hit.\n\
15514 Give breakpoint number as argument after \"commands\".\n\
15515 With no argument, the targeted breakpoint is the last one set.\n\
15516 The commands themselves follow starting on the next line.\n\
15517 Type a line containing \"end\" to indicate the end of them.\n\
15518 Give \"silent\" as the first line to make the breakpoint silent;\n\
15519 then no output is printed when it is hit, except what the commands print."));
15520
15521   add_com ("condition", class_breakpoint, condition_command, _("\
15522 Specify breakpoint number N to break only if COND is true.\n\
15523 Usage is `condition N COND', where N is an integer and COND is an\n\
15524 expression to be evaluated whenever breakpoint N is reached."));
15525
15526   c = add_com ("tbreak", class_breakpoint, tbreak_command, _("\
15527 Set a temporary breakpoint.\n\
15528 Like \"break\" except the breakpoint is only temporary,\n\
15529 so it will be deleted when hit.  Equivalent to \"break\" followed\n\
15530 by using \"enable delete\" on the breakpoint number.\n\
15531 \n"
15532 BREAK_ARGS_HELP ("tbreak")));
15533   set_cmd_completer (c, location_completer);
15534
15535   c = add_com ("hbreak", class_breakpoint, hbreak_command, _("\
15536 Set a hardware assisted breakpoint.\n\
15537 Like \"break\" except the breakpoint requires hardware support,\n\
15538 some target hardware may not have this support.\n\
15539 \n"
15540 BREAK_ARGS_HELP ("hbreak")));
15541   set_cmd_completer (c, location_completer);
15542
15543   c = add_com ("thbreak", class_breakpoint, thbreak_command, _("\
15544 Set a temporary hardware assisted breakpoint.\n\
15545 Like \"hbreak\" except the breakpoint is only temporary,\n\
15546 so it will be deleted when hit.\n\
15547 \n"
15548 BREAK_ARGS_HELP ("thbreak")));
15549   set_cmd_completer (c, location_completer);
15550
15551   add_prefix_cmd ("enable", class_breakpoint, enable_command, _("\
15552 Enable some breakpoints.\n\
15553 Give breakpoint numbers (separated by spaces) as arguments.\n\
15554 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15555 This is used to cancel the effect of the \"disable\" command.\n\
15556 With a subcommand you can enable temporarily."),
15557                   &enablelist, "enable ", 1, &cmdlist);
15558   if (xdb_commands)
15559     add_com ("ab", class_breakpoint, enable_command, _("\
15560 Enable some breakpoints.\n\
15561 Give breakpoint numbers (separated by spaces) as arguments.\n\
15562 With no subcommand, breakpoints are enabled until you command otherwise.\n\
15563 This is used to cancel the effect of the \"disable\" command.\n\
15564 With a subcommand you can enable temporarily."));
15565
15566   add_com_alias ("en", "enable", class_breakpoint, 1);
15567
15568   add_prefix_cmd ("breakpoints", class_breakpoint, enable_command, _("\
15569 Enable some breakpoints.\n\
15570 Give breakpoint numbers (separated by spaces) as arguments.\n\
15571 This is used to cancel the effect of the \"disable\" command.\n\
15572 May be abbreviated to simply \"enable\".\n"),
15573                    &enablebreaklist, "enable breakpoints ", 1, &enablelist);
15574
15575   add_cmd ("once", no_class, enable_once_command, _("\
15576 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15577 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15578            &enablebreaklist);
15579
15580   add_cmd ("delete", no_class, enable_delete_command, _("\
15581 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15582 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15583            &enablebreaklist);
15584
15585   add_cmd ("count", no_class, enable_count_command, _("\
15586 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15587 If a breakpoint is hit while enabled in this fashion,\n\
15588 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15589            &enablebreaklist);
15590
15591   add_cmd ("delete", no_class, enable_delete_command, _("\
15592 Enable breakpoints and delete when hit.  Give breakpoint numbers.\n\
15593 If a breakpoint is hit while enabled in this fashion, it is deleted."),
15594            &enablelist);
15595
15596   add_cmd ("once", no_class, enable_once_command, _("\
15597 Enable breakpoints for one hit.  Give breakpoint numbers.\n\
15598 If a breakpoint is hit while enabled in this fashion, it becomes disabled."),
15599            &enablelist);
15600
15601   add_cmd ("count", no_class, enable_count_command, _("\
15602 Enable breakpoints for COUNT hits.  Give count and then breakpoint numbers.\n\
15603 If a breakpoint is hit while enabled in this fashion,\n\
15604 the count is decremented; when it reaches zero, the breakpoint is disabled."),
15605            &enablelist);
15606
15607   add_prefix_cmd ("disable", class_breakpoint, disable_command, _("\
15608 Disable some breakpoints.\n\
15609 Arguments are breakpoint numbers with spaces in between.\n\
15610 To disable all breakpoints, give no argument.\n\
15611 A disabled breakpoint is not forgotten, but has no effect until re-enabled."),
15612                   &disablelist, "disable ", 1, &cmdlist);
15613   add_com_alias ("dis", "disable", class_breakpoint, 1);
15614   add_com_alias ("disa", "disable", class_breakpoint, 1);
15615   if (xdb_commands)
15616     add_com ("sb", class_breakpoint, disable_command, _("\
15617 Disable some breakpoints.\n\
15618 Arguments are breakpoint numbers with spaces in between.\n\
15619 To disable all breakpoints, give no argument.\n\
15620 A disabled breakpoint is not forgotten, but has no effect until re-enabled."));
15621
15622   add_cmd ("breakpoints", class_alias, disable_command, _("\
15623 Disable some breakpoints.\n\
15624 Arguments are breakpoint numbers with spaces in between.\n\
15625 To disable all breakpoints, give no argument.\n\
15626 A disabled breakpoint is not forgotten, but has no effect until re-enabled.\n\
15627 This command may be abbreviated \"disable\"."),
15628            &disablelist);
15629
15630   add_prefix_cmd ("delete", class_breakpoint, delete_command, _("\
15631 Delete some breakpoints or auto-display expressions.\n\
15632 Arguments are breakpoint numbers with spaces in between.\n\
15633 To delete all breakpoints, give no argument.\n\
15634 \n\
15635 Also a prefix command for deletion of other GDB objects.\n\
15636 The \"unset\" command is also an alias for \"delete\"."),
15637                   &deletelist, "delete ", 1, &cmdlist);
15638   add_com_alias ("d", "delete", class_breakpoint, 1);
15639   add_com_alias ("del", "delete", class_breakpoint, 1);
15640   if (xdb_commands)
15641     add_com ("db", class_breakpoint, delete_command, _("\
15642 Delete some breakpoints.\n\
15643 Arguments are breakpoint numbers with spaces in between.\n\
15644 To delete all breakpoints, give no argument.\n"));
15645
15646   add_cmd ("breakpoints", class_alias, delete_command, _("\
15647 Delete some breakpoints or auto-display expressions.\n\
15648 Arguments are breakpoint numbers with spaces in between.\n\
15649 To delete all breakpoints, give no argument.\n\
15650 This command may be abbreviated \"delete\"."),
15651            &deletelist);
15652
15653   add_com ("clear", class_breakpoint, clear_command, _("\
15654 Clear breakpoint at specified line or function.\n\
15655 Argument may be line number, function name, or \"*\" and an address.\n\
15656 If line number is specified, all breakpoints in that line are cleared.\n\
15657 If function is specified, breakpoints at beginning of function are cleared.\n\
15658 If an address is specified, breakpoints at that address are cleared.\n\
15659 \n\
15660 With no argument, clears all breakpoints in the line that the selected frame\n\
15661 is executing in.\n\
15662 \n\
15663 See also the \"delete\" command which clears breakpoints by number."));
15664   add_com_alias ("cl", "clear", class_breakpoint, 1);
15665
15666   c = add_com ("break", class_breakpoint, break_command, _("\
15667 Set breakpoint at specified line or function.\n"
15668 BREAK_ARGS_HELP ("break")));
15669   set_cmd_completer (c, location_completer);
15670
15671   add_com_alias ("b", "break", class_run, 1);
15672   add_com_alias ("br", "break", class_run, 1);
15673   add_com_alias ("bre", "break", class_run, 1);
15674   add_com_alias ("brea", "break", class_run, 1);
15675
15676   if (xdb_commands)
15677    add_com_alias ("ba", "break", class_breakpoint, 1);
15678
15679   if (dbx_commands)
15680     {
15681       add_abbrev_prefix_cmd ("stop", class_breakpoint, stop_command, _("\
15682 Break in function/address or break at a line in the current file."),
15683                              &stoplist, "stop ", 1, &cmdlist);
15684       add_cmd ("in", class_breakpoint, stopin_command,
15685                _("Break in function or address."), &stoplist);
15686       add_cmd ("at", class_breakpoint, stopat_command,
15687                _("Break at a line in the current file."), &stoplist);
15688       add_com ("status", class_info, breakpoints_info, _("\
15689 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15690 The \"Type\" column indicates one of:\n\
15691 \tbreakpoint     - normal breakpoint\n\
15692 \twatchpoint     - watchpoint\n\
15693 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15694 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15695 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15696 address and file/line number respectively.\n\
15697 \n\
15698 Convenience variable \"$_\" and default examine address for \"x\"\n\
15699 are set to the address of the last breakpoint listed unless the command\n\
15700 is prefixed with \"server \".\n\n\
15701 Convenience variable \"$bpnum\" contains the number of the last\n\
15702 breakpoint set."));
15703     }
15704
15705   add_info ("breakpoints", breakpoints_info, _("\
15706 Status of specified breakpoints (all user-settable breakpoints if no argument).\n\
15707 The \"Type\" column indicates one of:\n\
15708 \tbreakpoint     - normal breakpoint\n\
15709 \twatchpoint     - watchpoint\n\
15710 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15711 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15712 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15713 address and file/line number respectively.\n\
15714 \n\
15715 Convenience variable \"$_\" and default examine address for \"x\"\n\
15716 are set to the address of the last breakpoint listed unless the command\n\
15717 is prefixed with \"server \".\n\n\
15718 Convenience variable \"$bpnum\" contains the number of the last\n\
15719 breakpoint set."));
15720
15721   add_info_alias ("b", "breakpoints", 1);
15722
15723   if (xdb_commands)
15724     add_com ("lb", class_breakpoint, breakpoints_info, _("\
15725 Status of user-settable breakpoints, or breakpoint number NUMBER.\n\
15726 The \"Type\" column indicates one of:\n\
15727 \tbreakpoint     - normal breakpoint\n\
15728 \twatchpoint     - watchpoint\n\
15729 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15730 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15731 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15732 address and file/line number respectively.\n\
15733 \n\
15734 Convenience variable \"$_\" and default examine address for \"x\"\n\
15735 are set to the address of the last breakpoint listed unless the command\n\
15736 is prefixed with \"server \".\n\n\
15737 Convenience variable \"$bpnum\" contains the number of the last\n\
15738 breakpoint set."));
15739
15740   add_cmd ("breakpoints", class_maintenance, maintenance_info_breakpoints, _("\
15741 Status of all breakpoints, or breakpoint number NUMBER.\n\
15742 The \"Type\" column indicates one of:\n\
15743 \tbreakpoint     - normal breakpoint\n\
15744 \twatchpoint     - watchpoint\n\
15745 \tlongjmp        - internal breakpoint used to step through longjmp()\n\
15746 \tlongjmp resume - internal breakpoint at the target of longjmp()\n\
15747 \tuntil          - internal breakpoint used by the \"until\" command\n\
15748 \tfinish         - internal breakpoint used by the \"finish\" command\n\
15749 The \"Disp\" column contains one of \"keep\", \"del\", or \"dis\" to indicate\n\
15750 the disposition of the breakpoint after it gets hit.  \"dis\" means that the\n\
15751 breakpoint will be disabled.  The \"Address\" and \"What\" columns indicate the\n\
15752 address and file/line number respectively.\n\
15753 \n\
15754 Convenience variable \"$_\" and default examine address for \"x\"\n\
15755 are set to the address of the last breakpoint listed unless the command\n\
15756 is prefixed with \"server \".\n\n\
15757 Convenience variable \"$bpnum\" contains the number of the last\n\
15758 breakpoint set."),
15759            &maintenanceinfolist);
15760
15761   add_prefix_cmd ("catch", class_breakpoint, catch_command, _("\
15762 Set catchpoints to catch events."),
15763                   &catch_cmdlist, "catch ",
15764                   0/*allow-unknown*/, &cmdlist);
15765
15766   add_prefix_cmd ("tcatch", class_breakpoint, tcatch_command, _("\
15767 Set temporary catchpoints to catch events."),
15768                   &tcatch_cmdlist, "tcatch ",
15769                   0/*allow-unknown*/, &cmdlist);
15770
15771   /* Add catch and tcatch sub-commands.  */
15772   add_catch_command ("catch", _("\
15773 Catch an exception, when caught."),
15774                      catch_catch_command,
15775                      NULL,
15776                      CATCH_PERMANENT,
15777                      CATCH_TEMPORARY);
15778   add_catch_command ("throw", _("\
15779 Catch an exception, when thrown."),
15780                      catch_throw_command,
15781                      NULL,
15782                      CATCH_PERMANENT,
15783                      CATCH_TEMPORARY);
15784   add_catch_command ("fork", _("Catch calls to fork."),
15785                      catch_fork_command_1,
15786                      NULL,
15787                      (void *) (uintptr_t) catch_fork_permanent,
15788                      (void *) (uintptr_t) catch_fork_temporary);
15789   add_catch_command ("vfork", _("Catch calls to vfork."),
15790                      catch_fork_command_1,
15791                      NULL,
15792                      (void *) (uintptr_t) catch_vfork_permanent,
15793                      (void *) (uintptr_t) catch_vfork_temporary);
15794   add_catch_command ("exec", _("Catch calls to exec."),
15795                      catch_exec_command_1,
15796                      NULL,
15797                      CATCH_PERMANENT,
15798                      CATCH_TEMPORARY);
15799   add_catch_command ("load", _("Catch loads of shared libraries.\n\
15800 Usage: catch load [REGEX]\n\
15801 If REGEX is given, only stop for libraries matching the regular expression."),
15802                      catch_load_command_1,
15803                      NULL,
15804                      CATCH_PERMANENT,
15805                      CATCH_TEMPORARY);
15806   add_catch_command ("unload", _("Catch unloads of shared libraries.\n\
15807 Usage: catch unload [REGEX]\n\
15808 If REGEX is given, only stop for libraries matching the regular expression."),
15809                      catch_unload_command_1,
15810                      NULL,
15811                      CATCH_PERMANENT,
15812                      CATCH_TEMPORARY);
15813   add_catch_command ("syscall", _("\
15814 Catch system calls by their names and/or numbers.\n\
15815 Arguments say which system calls to catch.  If no arguments\n\
15816 are given, every system call will be caught.\n\
15817 Arguments, if given, should be one or more system call names\n\
15818 (if your system supports that), or system call numbers."),
15819                      catch_syscall_command_1,
15820                      catch_syscall_completer,
15821                      CATCH_PERMANENT,
15822                      CATCH_TEMPORARY);
15823
15824   c = add_com ("watch", class_breakpoint, watch_command, _("\
15825 Set a watchpoint for an expression.\n\
15826 Usage: watch [-l|-location] EXPRESSION\n\
15827 A watchpoint stops execution of your program whenever the value of\n\
15828 an expression changes.\n\
15829 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15830 the memory to which it refers."));
15831   set_cmd_completer (c, expression_completer);
15832
15833   c = add_com ("rwatch", class_breakpoint, rwatch_command, _("\
15834 Set a read watchpoint for an expression.\n\
15835 Usage: rwatch [-l|-location] EXPRESSION\n\
15836 A watchpoint stops execution of your program whenever the value of\n\
15837 an expression is read.\n\
15838 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15839 the memory to which it refers."));
15840   set_cmd_completer (c, expression_completer);
15841
15842   c = add_com ("awatch", class_breakpoint, awatch_command, _("\
15843 Set a watchpoint for an expression.\n\
15844 Usage: awatch [-l|-location] EXPRESSION\n\
15845 A watchpoint stops execution of your program whenever the value of\n\
15846 an expression is either read or written.\n\
15847 If -l or -location is given, this evaluates EXPRESSION and watches\n\
15848 the memory to which it refers."));
15849   set_cmd_completer (c, expression_completer);
15850
15851   add_info ("watchpoints", watchpoints_info, _("\
15852 Status of specified watchpoints (all watchpoints if no argument)."));
15853
15854   /* XXX: cagney/2005-02-23: This should be a boolean, and should
15855      respond to changes - contrary to the description.  */
15856   add_setshow_zinteger_cmd ("can-use-hw-watchpoints", class_support,
15857                             &can_use_hw_watchpoints, _("\
15858 Set debugger's willingness to use watchpoint hardware."), _("\
15859 Show debugger's willingness to use watchpoint hardware."), _("\
15860 If zero, gdb will not use hardware for new watchpoints, even if\n\
15861 such is available.  (However, any hardware watchpoints that were\n\
15862 created before setting this to nonzero, will continue to use watchpoint\n\
15863 hardware.)"),
15864                             NULL,
15865                             show_can_use_hw_watchpoints,
15866                             &setlist, &showlist);
15867
15868   can_use_hw_watchpoints = 1;
15869
15870   /* Tracepoint manipulation commands.  */
15871
15872   c = add_com ("trace", class_breakpoint, trace_command, _("\
15873 Set a tracepoint at specified line or function.\n\
15874 \n"
15875 BREAK_ARGS_HELP ("trace") "\n\
15876 Do \"help tracepoints\" for info on other tracepoint commands."));
15877   set_cmd_completer (c, location_completer);
15878
15879   add_com_alias ("tp", "trace", class_alias, 0);
15880   add_com_alias ("tr", "trace", class_alias, 1);
15881   add_com_alias ("tra", "trace", class_alias, 1);
15882   add_com_alias ("trac", "trace", class_alias, 1);
15883
15884   c = add_com ("ftrace", class_breakpoint, ftrace_command, _("\
15885 Set a fast tracepoint at specified line or function.\n\
15886 \n"
15887 BREAK_ARGS_HELP ("ftrace") "\n\
15888 Do \"help tracepoints\" for info on other tracepoint commands."));
15889   set_cmd_completer (c, location_completer);
15890
15891   c = add_com ("strace", class_breakpoint, strace_command, _("\
15892 Set a static tracepoint at specified line, function or marker.\n\
15893 \n\
15894 strace [LOCATION] [if CONDITION]\n\
15895 LOCATION may be a line number, function name, \"*\" and an address,\n\
15896 or -m MARKER_ID.\n\
15897 If a line number is specified, probe the marker at start of code\n\
15898 for that line.  If a function is specified, probe the marker at start\n\
15899 of code for that function.  If an address is specified, probe the marker\n\
15900 at that exact address.  If a marker id is specified, probe the marker\n\
15901 with that name.  With no LOCATION, uses current execution address of\n\
15902 the selected stack frame.\n\
15903 Static tracepoints accept an extra collect action -- ``collect $_sdata''.\n\
15904 This collects arbitrary user data passed in the probe point call to the\n\
15905 tracing library.  You can inspect it when analyzing the trace buffer,\n\
15906 by printing the $_sdata variable like any other convenience variable.\n\
15907 \n\
15908 CONDITION is a boolean expression.\n\
15909 \n\
15910 Multiple tracepoints at one place are permitted, and useful if their\n\
15911 conditions are different.\n\
15912 \n\
15913 Do \"help breakpoints\" for info on other commands dealing with breakpoints.\n\
15914 Do \"help tracepoints\" for info on other tracepoint commands."));
15915   set_cmd_completer (c, location_completer);
15916
15917   add_info ("tracepoints", tracepoints_info, _("\
15918 Status of specified tracepoints (all tracepoints if no argument).\n\
15919 Convenience variable \"$tpnum\" contains the number of the\n\
15920 last tracepoint set."));
15921
15922   add_info_alias ("tp", "tracepoints", 1);
15923
15924   add_cmd ("tracepoints", class_trace, delete_trace_command, _("\
15925 Delete specified tracepoints.\n\
15926 Arguments are tracepoint numbers, separated by spaces.\n\
15927 No argument means delete all tracepoints."),
15928            &deletelist);
15929
15930   c = add_cmd ("tracepoints", class_trace, disable_trace_command, _("\
15931 Disable specified tracepoints.\n\
15932 Arguments are tracepoint numbers, separated by spaces.\n\
15933 No argument means disable all tracepoints."),
15934            &disablelist);
15935   deprecate_cmd (c, "disable");
15936
15937   c = add_cmd ("tracepoints", class_trace, enable_trace_command, _("\
15938 Enable specified tracepoints.\n\
15939 Arguments are tracepoint numbers, separated by spaces.\n\
15940 No argument means enable all tracepoints."),
15941            &enablelist);
15942   deprecate_cmd (c, "enable");
15943
15944   add_com ("passcount", class_trace, trace_pass_command, _("\
15945 Set the passcount for a tracepoint.\n\
15946 The trace will end when the tracepoint has been passed 'count' times.\n\
15947 Usage: passcount COUNT TPNUM, where TPNUM may also be \"all\";\n\
15948 if TPNUM is omitted, passcount refers to the last tracepoint defined."));
15949
15950   add_prefix_cmd ("save", class_breakpoint, save_command,
15951                   _("Save breakpoint definitions as a script."),
15952                   &save_cmdlist, "save ",
15953                   0/*allow-unknown*/, &cmdlist);
15954
15955   c = add_cmd ("breakpoints", class_breakpoint, save_breakpoints_command, _("\
15956 Save current breakpoint definitions as a script.\n\
15957 This includes all types of breakpoints (breakpoints, watchpoints,\n\
15958 catchpoints, tracepoints).  Use the 'source' command in another debug\n\
15959 session to restore them."),
15960                &save_cmdlist);
15961   set_cmd_completer (c, filename_completer);
15962
15963   c = add_cmd ("tracepoints", class_trace, save_tracepoints_command, _("\
15964 Save current tracepoint definitions as a script.\n\
15965 Use the 'source' command in another debug session to restore them."),
15966                &save_cmdlist);
15967   set_cmd_completer (c, filename_completer);
15968
15969   c = add_com_alias ("save-tracepoints", "save tracepoints", class_trace, 0);
15970   deprecate_cmd (c, "save tracepoints");
15971
15972   add_prefix_cmd ("breakpoint", class_maintenance, set_breakpoint_cmd, _("\
15973 Breakpoint specific settings\n\
15974 Configure various breakpoint-specific variables such as\n\
15975 pending breakpoint behavior"),
15976                   &breakpoint_set_cmdlist, "set breakpoint ",
15977                   0/*allow-unknown*/, &setlist);
15978   add_prefix_cmd ("breakpoint", class_maintenance, show_breakpoint_cmd, _("\
15979 Breakpoint specific settings\n\
15980 Configure various breakpoint-specific variables such as\n\
15981 pending breakpoint behavior"),
15982                   &breakpoint_show_cmdlist, "show breakpoint ",
15983                   0/*allow-unknown*/, &showlist);
15984
15985   add_setshow_auto_boolean_cmd ("pending", no_class,
15986                                 &pending_break_support, _("\
15987 Set debugger's behavior regarding pending breakpoints."), _("\
15988 Show debugger's behavior regarding pending breakpoints."), _("\
15989 If on, an unrecognized breakpoint location will cause gdb to create a\n\
15990 pending breakpoint.  If off, an unrecognized breakpoint location results in\n\
15991 an error.  If auto, an unrecognized breakpoint location results in a\n\
15992 user-query to see if a pending breakpoint should be created."),
15993                                 NULL,
15994                                 show_pending_break_support,
15995                                 &breakpoint_set_cmdlist,
15996                                 &breakpoint_show_cmdlist);
15997
15998   pending_break_support = AUTO_BOOLEAN_AUTO;
15999
16000   add_setshow_boolean_cmd ("auto-hw", no_class,
16001                            &automatic_hardware_breakpoints, _("\
16002 Set automatic usage of hardware breakpoints."), _("\
16003 Show automatic usage of hardware breakpoints."), _("\
16004 If set, the debugger will automatically use hardware breakpoints for\n\
16005 breakpoints set with \"break\" but falling in read-only memory.  If not set,\n\
16006 a warning will be emitted for such breakpoints."),
16007                            NULL,
16008                            show_automatic_hardware_breakpoints,
16009                            &breakpoint_set_cmdlist,
16010                            &breakpoint_show_cmdlist);
16011
16012   add_setshow_enum_cmd ("always-inserted", class_support,
16013                         always_inserted_enums, &always_inserted_mode, _("\
16014 Set mode for inserting breakpoints."), _("\
16015 Show mode for inserting breakpoints."), _("\
16016 When this mode is off, breakpoints are inserted in inferior when it is\n\
16017 resumed, and removed when execution stops.  When this mode is on,\n\
16018 breakpoints are inserted immediately and removed only when the user\n\
16019 deletes the breakpoint.  When this mode is auto (which is the default),\n\
16020 the behaviour depends on the non-stop setting (see help set non-stop).\n\
16021 In this case, if gdb is controlling the inferior in non-stop mode, gdb\n\
16022 behaves as if always-inserted mode is on; if gdb is controlling the\n\
16023 inferior in all-stop mode, gdb behaves as if always-inserted mode is off."),
16024                            NULL,
16025                            &show_always_inserted_mode,
16026                            &breakpoint_set_cmdlist,
16027                            &breakpoint_show_cmdlist);
16028
16029   add_setshow_enum_cmd ("condition-evaluation", class_breakpoint,
16030                         condition_evaluation_enums,
16031                         &condition_evaluation_mode_1, _("\
16032 Set mode of breakpoint condition evaluation."), _("\
16033 Show mode of breakpoint condition evaluation."), _("\
16034 When this is set to \"host\", breakpoint conditions will be\n\
16035 evaluated on the host's side by GDB.  When it is set to \"target\",\n\
16036 breakpoint conditions will be downloaded to the target (if the target\n\
16037 supports such feature) and conditions will be evaluated on the target's side.\n\
16038 If this is set to \"auto\" (default), this will be automatically set to\n\
16039 \"target\" if it supports condition evaluation, otherwise it will\n\
16040 be set to \"gdb\""),
16041                            &set_condition_evaluation_mode,
16042                            &show_condition_evaluation_mode,
16043                            &breakpoint_set_cmdlist,
16044                            &breakpoint_show_cmdlist);
16045
16046   add_com ("break-range", class_breakpoint, break_range_command, _("\
16047 Set a breakpoint for an address range.\n\
16048 break-range START-LOCATION, END-LOCATION\n\
16049 where START-LOCATION and END-LOCATION can be one of the following:\n\
16050   LINENUM, for that line in the current file,\n\
16051   FILE:LINENUM, for that line in that file,\n\
16052   +OFFSET, for that number of lines after the current line\n\
16053            or the start of the range\n\
16054   FUNCTION, for the first line in that function,\n\
16055   FILE:FUNCTION, to distinguish among like-named static functions.\n\
16056   *ADDRESS, for the instruction at that address.\n\
16057 \n\
16058 The breakpoint will stop execution of the inferior whenever it executes\n\
16059 an instruction at any address within the [START-LOCATION, END-LOCATION]\n\
16060 range (including START-LOCATION and END-LOCATION)."));
16061
16062   c = add_com ("dprintf", class_breakpoint, dprintf_command, _("\
16063 Set a dynamic printf at specified line or function.\n\
16064 dprintf location,format string,arg1,arg2,...\n\
16065 location may be a line number, function name, or \"*\" and an address.\n\
16066 If a line number is specified, break at start of code for that line.\n\
16067 If a function is specified, break at start of code for that function.\n\
16068 "));
16069   set_cmd_completer (c, location_completer);
16070
16071   add_setshow_enum_cmd ("dprintf-style", class_support,
16072                         dprintf_style_enums, &dprintf_style, _("\
16073 Set the style of usage for dynamic printf."), _("\
16074 Show the style of usage for dynamic printf."), _("\
16075 This setting chooses how GDB will do a dynamic printf.\n\
16076 If the value is \"gdb\", then the printing is done by GDB to its own\n\
16077 console, as with the \"printf\" command.\n\
16078 If the value is \"call\", the print is done by calling a function in your\n\
16079 program; by default printf(), but you can choose a different function or\n\
16080 output stream by setting dprintf-function and dprintf-channel."),
16081                         update_dprintf_commands, NULL,
16082                         &setlist, &showlist);
16083
16084   dprintf_function = xstrdup ("printf");
16085   add_setshow_string_cmd ("dprintf-function", class_support,
16086                           &dprintf_function, _("\
16087 Set the function to use for dynamic printf"), _("\
16088 Show the function to use for dynamic printf"), NULL,
16089                           update_dprintf_commands, NULL,
16090                           &setlist, &showlist);
16091
16092   dprintf_channel = xstrdup ("");
16093   add_setshow_string_cmd ("dprintf-channel", class_support,
16094                           &dprintf_channel, _("\
16095 Set the channel to use for dynamic printf"), _("\
16096 Show the channel to use for dynamic printf"), NULL,
16097                           update_dprintf_commands, NULL,
16098                           &setlist, &showlist);
16099
16100   automatic_hardware_breakpoints = 1;
16101
16102   observer_attach_about_to_proceed (breakpoint_about_to_proceed);
16103 }