OSDN Git Service

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