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