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