OSDN Git Service

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