1 /* Python interface to breakpoints
2 
3    Copyright (C) 2008-2021 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11 
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16 
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19 
20 #include "defs.h"
21 #include "value.h"
22 #include "python-internal.h"
23 #include "python.h"
24 #include "charset.h"
25 #include "breakpoint.h"
26 #include "gdbcmd.h"
27 #include "gdbthread.h"
28 #include "observable.h"
29 #include "cli/cli-script.h"
30 #include "ada-lang.h"
31 #include "arch-utils.h"
32 #include "language.h"
33 #include "location.h"
34 #include "py-event.h"
35 #include "linespec.h"
36 
37 /* Debugging of Python breakpoints.  */
38 
39 static bool pybp_debug;
40 
41 /* Implementation of "show debug py-breakpoint".  */
42 
43 static void
show_pybp_debug(struct ui_file * file,int from_tty,struct cmd_list_element * c,const char * value)44 show_pybp_debug (struct ui_file *file, int from_tty,
45 		 struct cmd_list_element *c, const char *value)
46 {
47   fprintf_filtered (file, _("Python breakpoint debugging is %s.\n"), value);
48 }
49 
50 /* Print a "py-breakpoint" debug statement.  */
51 
52 #define pybp_debug_printf(fmt, ...) \
53   debug_prefixed_printf_cond (pybp_debug, "py-breakpoint", fmt, ##__VA_ARGS__)
54 
55 /* Print a "py-breakpoint" enter/exit debug statements.  */
56 
57 #define PYBP_SCOPED_DEBUG_ENTER_EXIT \
58   scoped_debug_enter_exit (pybp_debug, "py-breakpoint")
59 
60 /* Number of live breakpoints.  */
61 static int bppy_live;
62 
63 /* Variables used to pass information between the Breakpoint
64    constructor and the breakpoint-created hook function.  */
65 gdbpy_breakpoint_object *bppy_pending_object;
66 
67 /* Function that is called when a Python condition is evaluated.  */
68 static const char stop_func[] = "stop";
69 
70 /* This is used to initialize various gdb.bp_* constants.  */
71 struct pybp_code
72 {
73   /* The name.  */
74   const char *name;
75   /* The code.  */
76   int code;
77 };
78 
79 /* Entries related to the type of user set breakpoints.  */
80 static struct pybp_code pybp_codes[] =
81 {
82   { "BP_NONE", bp_none},
83   { "BP_BREAKPOINT", bp_breakpoint},
84   { "BP_HARDWARE_BREAKPOINT", bp_hardware_breakpoint},
85   { "BP_WATCHPOINT", bp_watchpoint},
86   { "BP_HARDWARE_WATCHPOINT", bp_hardware_watchpoint},
87   { "BP_READ_WATCHPOINT", bp_read_watchpoint},
88   { "BP_ACCESS_WATCHPOINT", bp_access_watchpoint},
89   { "BP_CATCHPOINT", bp_catchpoint},
90   {NULL} /* Sentinel.  */
91 };
92 
93 /* Entries related to the type of watchpoint.  */
94 static struct pybp_code pybp_watch_types[] =
95 {
96   { "WP_READ", hw_read},
97   { "WP_WRITE", hw_write},
98   { "WP_ACCESS", hw_access},
99   {NULL} /* Sentinel.  */
100 };
101 
102 /* Python function which checks the validity of a breakpoint object.  */
103 static PyObject *
bppy_is_valid(PyObject * self,PyObject * args)104 bppy_is_valid (PyObject *self, PyObject *args)
105 {
106   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
107 
108   if (self_bp->bp)
109     Py_RETURN_TRUE;
110   Py_RETURN_FALSE;
111 }
112 
113 /* Python function to test whether or not the breakpoint is enabled.  */
114 static PyObject *
bppy_get_enabled(PyObject * self,void * closure)115 bppy_get_enabled (PyObject *self, void *closure)
116 {
117   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
118 
119   BPPY_REQUIRE_VALID (self_bp);
120   if (! self_bp->bp)
121     Py_RETURN_FALSE;
122   if (self_bp->bp->enable_state == bp_enabled)
123     Py_RETURN_TRUE;
124   Py_RETURN_FALSE;
125 }
126 
127 /* Python function to test whether or not the breakpoint is silent.  */
128 static PyObject *
bppy_get_silent(PyObject * self,void * closure)129 bppy_get_silent (PyObject *self, void *closure)
130 {
131   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
132 
133   BPPY_REQUIRE_VALID (self_bp);
134   if (self_bp->bp->silent)
135     Py_RETURN_TRUE;
136   Py_RETURN_FALSE;
137 }
138 
139 /* Python function to set the enabled state of a breakpoint.  */
140 static int
bppy_set_enabled(PyObject * self,PyObject * newvalue,void * closure)141 bppy_set_enabled (PyObject *self, PyObject *newvalue, void *closure)
142 {
143   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
144   int cmp;
145 
146   BPPY_SET_REQUIRE_VALID (self_bp);
147 
148   if (newvalue == NULL)
149     {
150       PyErr_SetString (PyExc_TypeError,
151 		       _("Cannot delete `enabled' attribute."));
152 
153       return -1;
154     }
155   else if (! PyBool_Check (newvalue))
156     {
157       PyErr_SetString (PyExc_TypeError,
158 		       _("The value of `enabled' must be a boolean."));
159       return -1;
160     }
161 
162   cmp = PyObject_IsTrue (newvalue);
163   if (cmp < 0)
164     return -1;
165 
166   try
167     {
168       if (cmp == 1)
169 	enable_breakpoint (self_bp->bp);
170       else
171 	disable_breakpoint (self_bp->bp);
172     }
173   catch (const gdb_exception &except)
174     {
175       GDB_PY_SET_HANDLE_EXCEPTION (except);
176     }
177 
178   return 0;
179 }
180 
181 /* Python function to set the 'silent' state of a breakpoint.  */
182 static int
bppy_set_silent(PyObject * self,PyObject * newvalue,void * closure)183 bppy_set_silent (PyObject *self, PyObject *newvalue, void *closure)
184 {
185   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
186   int cmp;
187 
188   BPPY_SET_REQUIRE_VALID (self_bp);
189 
190   if (newvalue == NULL)
191     {
192       PyErr_SetString (PyExc_TypeError,
193 		       _("Cannot delete `silent' attribute."));
194       return -1;
195     }
196   else if (! PyBool_Check (newvalue))
197     {
198       PyErr_SetString (PyExc_TypeError,
199 		       _("The value of `silent' must be a boolean."));
200       return -1;
201     }
202 
203   cmp = PyObject_IsTrue (newvalue);
204   if (cmp < 0)
205     return -1;
206   else
207     breakpoint_set_silent (self_bp->bp, cmp);
208 
209   return 0;
210 }
211 
212 /* Python function to set the thread of a breakpoint.  */
213 static int
bppy_set_thread(PyObject * self,PyObject * newvalue,void * closure)214 bppy_set_thread (PyObject *self, PyObject *newvalue, void *closure)
215 {
216   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
217   long id;
218 
219   BPPY_SET_REQUIRE_VALID (self_bp);
220 
221   if (newvalue == NULL)
222     {
223       PyErr_SetString (PyExc_TypeError,
224 		       _("Cannot delete `thread' attribute."));
225       return -1;
226     }
227   else if (PyInt_Check (newvalue))
228     {
229       if (! gdb_py_int_as_long (newvalue, &id))
230 	return -1;
231 
232       if (!valid_global_thread_id (id))
233 	{
234 	  PyErr_SetString (PyExc_RuntimeError,
235 			   _("Invalid thread ID."));
236 	  return -1;
237 	}
238     }
239   else if (newvalue == Py_None)
240     id = -1;
241   else
242     {
243       PyErr_SetString (PyExc_TypeError,
244 		       _("The value of `thread' must be an integer or None."));
245       return -1;
246     }
247 
248   breakpoint_set_thread (self_bp->bp, id);
249 
250   return 0;
251 }
252 
253 /* Python function to set the (Ada) task of a breakpoint.  */
254 static int
bppy_set_task(PyObject * self,PyObject * newvalue,void * closure)255 bppy_set_task (PyObject *self, PyObject *newvalue, void *closure)
256 {
257   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
258   long id;
259   int valid_id = 0;
260 
261   BPPY_SET_REQUIRE_VALID (self_bp);
262 
263   if (newvalue == NULL)
264     {
265       PyErr_SetString (PyExc_TypeError,
266 		       _("Cannot delete `task' attribute."));
267       return -1;
268     }
269   else if (PyInt_Check (newvalue))
270     {
271       if (! gdb_py_int_as_long (newvalue, &id))
272 	return -1;
273 
274       try
275 	{
276 	  valid_id = valid_task_id (id);
277 	}
278       catch (const gdb_exception &except)
279 	{
280 	  GDB_PY_SET_HANDLE_EXCEPTION (except);
281 	}
282 
283       if (! valid_id)
284 	{
285 	  PyErr_SetString (PyExc_RuntimeError,
286 			   _("Invalid task ID."));
287 	  return -1;
288 	}
289     }
290   else if (newvalue == Py_None)
291     id = 0;
292   else
293     {
294       PyErr_SetString (PyExc_TypeError,
295 		       _("The value of `task' must be an integer or None."));
296       return -1;
297     }
298 
299   breakpoint_set_task (self_bp->bp, id);
300 
301   return 0;
302 }
303 
304 /* Python function which deletes the underlying GDB breakpoint.  This
305    triggers the breakpoint_deleted observer which will call
306    gdbpy_breakpoint_deleted; that function cleans up the Python
307    sections.  */
308 
309 static PyObject *
bppy_delete_breakpoint(PyObject * self,PyObject * args)310 bppy_delete_breakpoint (PyObject *self, PyObject *args)
311 {
312   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
313 
314   BPPY_REQUIRE_VALID (self_bp);
315 
316   try
317     {
318       delete_breakpoint (self_bp->bp);
319     }
320   catch (const gdb_exception &except)
321     {
322       GDB_PY_HANDLE_EXCEPTION (except);
323     }
324 
325   Py_RETURN_NONE;
326 }
327 
328 
329 /* Python function to set the ignore count of a breakpoint.  */
330 static int
bppy_set_ignore_count(PyObject * self,PyObject * newvalue,void * closure)331 bppy_set_ignore_count (PyObject *self, PyObject *newvalue, void *closure)
332 {
333   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
334   long value;
335 
336   BPPY_SET_REQUIRE_VALID (self_bp);
337 
338   if (newvalue == NULL)
339     {
340       PyErr_SetString (PyExc_TypeError,
341 		       _("Cannot delete `ignore_count' attribute."));
342       return -1;
343     }
344   else if (! PyInt_Check (newvalue))
345     {
346       PyErr_SetString (PyExc_TypeError,
347 		       _("The value of `ignore_count' must be an integer."));
348       return -1;
349     }
350 
351   if (! gdb_py_int_as_long (newvalue, &value))
352     return -1;
353 
354   if (value < 0)
355     value = 0;
356 
357   try
358     {
359       set_ignore_count (self_bp->number, (int) value, 0);
360     }
361   catch (const gdb_exception &except)
362     {
363       GDB_PY_SET_HANDLE_EXCEPTION (except);
364     }
365 
366   return 0;
367 }
368 
369 /* Python function to set the hit count of a breakpoint.  */
370 static int
bppy_set_hit_count(PyObject * self,PyObject * newvalue,void * closure)371 bppy_set_hit_count (PyObject *self, PyObject *newvalue, void *closure)
372 {
373   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
374 
375   BPPY_SET_REQUIRE_VALID (self_bp);
376 
377   if (newvalue == NULL)
378     {
379       PyErr_SetString (PyExc_TypeError,
380 		       _("Cannot delete `hit_count' attribute."));
381       return -1;
382     }
383   else
384     {
385       long value;
386 
387       if (! gdb_py_int_as_long (newvalue, &value))
388 	return -1;
389 
390       if (value != 0)
391 	{
392 	  PyErr_SetString (PyExc_AttributeError,
393 			   _("The value of `hit_count' must be zero."));
394 	  return -1;
395 	}
396     }
397 
398   self_bp->bp->hit_count = 0;
399 
400   return 0;
401 }
402 
403 /* Python function to get the location of a breakpoint.  */
404 static PyObject *
bppy_get_location(PyObject * self,void * closure)405 bppy_get_location (PyObject *self, void *closure)
406 {
407   gdbpy_breakpoint_object *obj = (gdbpy_breakpoint_object *) self;
408 
409   BPPY_REQUIRE_VALID (obj);
410 
411   if (obj->bp->type != bp_breakpoint
412       && obj->bp->type != bp_hardware_breakpoint)
413     Py_RETURN_NONE;
414 
415   const char *str = event_location_to_string (obj->bp->location.get ());
416   if (! str)
417     str = "";
418   return host_string_to_python_string (str).release ();
419 }
420 
421 /* Python function to get the breakpoint expression.  */
422 static PyObject *
bppy_get_expression(PyObject * self,void * closure)423 bppy_get_expression (PyObject *self, void *closure)
424 {
425   const char *str;
426   gdbpy_breakpoint_object *obj = (gdbpy_breakpoint_object *) self;
427   struct watchpoint *wp;
428 
429   BPPY_REQUIRE_VALID (obj);
430 
431   if (!is_watchpoint (obj->bp))
432     Py_RETURN_NONE;
433 
434   wp = (struct watchpoint *) obj->bp;
435 
436   str = wp->exp_string;
437   if (! str)
438     str = "";
439 
440   return host_string_to_python_string (str).release ();
441 }
442 
443 /* Python function to get the condition expression of a breakpoint.  */
444 static PyObject *
bppy_get_condition(PyObject * self,void * closure)445 bppy_get_condition (PyObject *self, void *closure)
446 {
447   char *str;
448   gdbpy_breakpoint_object *obj = (gdbpy_breakpoint_object *) self;
449 
450   BPPY_REQUIRE_VALID (obj);
451 
452   str = obj->bp->cond_string;
453   if (! str)
454     Py_RETURN_NONE;
455 
456   return host_string_to_python_string (str).release ();
457 }
458 
459 /* Returns 0 on success.  Returns -1 on error, with a python exception set.
460    */
461 
462 static int
bppy_set_condition(PyObject * self,PyObject * newvalue,void * closure)463 bppy_set_condition (PyObject *self, PyObject *newvalue, void *closure)
464 {
465   gdb::unique_xmalloc_ptr<char> exp_holder;
466   const char *exp = NULL;
467   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
468   struct gdb_exception except;
469 
470   BPPY_SET_REQUIRE_VALID (self_bp);
471 
472   if (newvalue == NULL)
473     {
474       PyErr_SetString (PyExc_TypeError,
475 		       _("Cannot delete `condition' attribute."));
476       return -1;
477     }
478   else if (newvalue == Py_None)
479     exp = "";
480   else
481     {
482       exp_holder = python_string_to_host_string (newvalue);
483       if (exp_holder == NULL)
484 	return -1;
485       exp = exp_holder.get ();
486     }
487 
488   try
489     {
490       set_breakpoint_condition (self_bp->bp, exp, 0, false);
491     }
492   catch (gdb_exception &ex)
493     {
494       except = std::move (ex);
495     }
496 
497   GDB_PY_SET_HANDLE_EXCEPTION (except);
498 
499   return 0;
500 }
501 
502 /* Python function to get the commands attached to a breakpoint.  */
503 static PyObject *
bppy_get_commands(PyObject * self,void * closure)504 bppy_get_commands (PyObject *self, void *closure)
505 {
506   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
507   struct breakpoint *bp = self_bp->bp;
508 
509   BPPY_REQUIRE_VALID (self_bp);
510 
511   if (! self_bp->bp->commands)
512     Py_RETURN_NONE;
513 
514   string_file stb;
515 
516   current_uiout->redirect (&stb);
517   try
518     {
519       print_command_lines (current_uiout, breakpoint_commands (bp), 0);
520     }
521   catch (const gdb_exception &except)
522     {
523       current_uiout->redirect (NULL);
524       gdbpy_convert_exception (except);
525       return NULL;
526     }
527 
528   current_uiout->redirect (NULL);
529   return host_string_to_python_string (stb.c_str ()).release ();
530 }
531 
532 /* Set the commands attached to a breakpoint.  Returns 0 on success.
533    Returns -1 on error, with a python exception set.  */
534 static int
bppy_set_commands(PyObject * self,PyObject * newvalue,void * closure)535 bppy_set_commands (PyObject *self, PyObject *newvalue, void *closure)
536 {
537   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
538   struct gdb_exception except;
539 
540   BPPY_SET_REQUIRE_VALID (self_bp);
541 
542   gdb::unique_xmalloc_ptr<char> commands
543     (python_string_to_host_string (newvalue));
544   if (commands == nullptr)
545     return -1;
546 
547   try
548     {
549       bool first = true;
550       char *save_ptr = nullptr;
551       auto reader
552 	= [&] ()
553 	  {
554 	    const char *result = strtok_r (first ? commands.get () : nullptr,
555 					   "\n", &save_ptr);
556 	    first = false;
557 	    return result;
558 	  };
559 
560       counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
561       breakpoint_set_commands (self_bp->bp, std::move (lines));
562     }
563   catch (gdb_exception &ex)
564     {
565       except = std::move (ex);
566     }
567 
568   GDB_PY_SET_HANDLE_EXCEPTION (except);
569 
570   return 0;
571 }
572 
573 /* Python function to get the breakpoint type.  */
574 static PyObject *
bppy_get_type(PyObject * self,void * closure)575 bppy_get_type (PyObject *self, void *closure)
576 {
577   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
578 
579   BPPY_REQUIRE_VALID (self_bp);
580 
581   return gdb_py_object_from_longest (self_bp->bp->type).release ();
582 }
583 
584 /* Python function to get the visibility of the breakpoint.  */
585 
586 static PyObject *
bppy_get_visibility(PyObject * self,void * closure)587 bppy_get_visibility (PyObject *self, void *closure)
588 {
589   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
590 
591   BPPY_REQUIRE_VALID (self_bp);
592 
593   if (user_breakpoint_p (self_bp->bp))
594     Py_RETURN_TRUE;
595 
596   Py_RETURN_FALSE;
597 }
598 
599 /* Python function to determine if the breakpoint is a temporary
600    breakpoint.  */
601 
602 static PyObject *
bppy_get_temporary(PyObject * self,void * closure)603 bppy_get_temporary (PyObject *self, void *closure)
604 {
605   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
606 
607   BPPY_REQUIRE_VALID (self_bp);
608 
609   if (self_bp->bp->disposition == disp_del
610       || self_bp->bp->disposition == disp_del_at_next_stop)
611     Py_RETURN_TRUE;
612 
613   Py_RETURN_FALSE;
614 }
615 
616 /* Python function to determine if the breakpoint is a pending
617    breakpoint.  */
618 
619 static PyObject *
bppy_get_pending(PyObject * self,void * closure)620 bppy_get_pending (PyObject *self, void *closure)
621 {
622   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
623 
624   BPPY_REQUIRE_VALID (self_bp);
625 
626   if (is_watchpoint (self_bp->bp))
627     Py_RETURN_FALSE;
628   if (pending_breakpoint_p (self_bp->bp))
629     Py_RETURN_TRUE;
630 
631   Py_RETURN_FALSE;
632 }
633 
634 /* Python function to get the breakpoint's number.  */
635 static PyObject *
bppy_get_number(PyObject * self,void * closure)636 bppy_get_number (PyObject *self, void *closure)
637 {
638   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
639 
640   BPPY_REQUIRE_VALID (self_bp);
641 
642   return gdb_py_object_from_longest (self_bp->number).release ();
643 }
644 
645 /* Python function to get the breakpoint's thread ID.  */
646 static PyObject *
bppy_get_thread(PyObject * self,void * closure)647 bppy_get_thread (PyObject *self, void *closure)
648 {
649   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
650 
651   BPPY_REQUIRE_VALID (self_bp);
652 
653   if (self_bp->bp->thread == -1)
654     Py_RETURN_NONE;
655 
656   return gdb_py_object_from_longest (self_bp->bp->thread).release ();
657 }
658 
659 /* Python function to get the breakpoint's task ID (in Ada).  */
660 static PyObject *
bppy_get_task(PyObject * self,void * closure)661 bppy_get_task (PyObject *self, void *closure)
662 {
663   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
664 
665   BPPY_REQUIRE_VALID (self_bp);
666 
667   if (self_bp->bp->task == 0)
668     Py_RETURN_NONE;
669 
670   return gdb_py_object_from_longest (self_bp->bp->task).release ();
671 }
672 
673 /* Python function to get the breakpoint's hit count.  */
674 static PyObject *
bppy_get_hit_count(PyObject * self,void * closure)675 bppy_get_hit_count (PyObject *self, void *closure)
676 {
677   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
678 
679   BPPY_REQUIRE_VALID (self_bp);
680 
681   return gdb_py_object_from_longest (self_bp->bp->hit_count).release ();
682 }
683 
684 /* Python function to get the breakpoint's ignore count.  */
685 static PyObject *
bppy_get_ignore_count(PyObject * self,void * closure)686 bppy_get_ignore_count (PyObject *self, void *closure)
687 {
688   gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
689 
690   BPPY_REQUIRE_VALID (self_bp);
691 
692   return gdb_py_object_from_longest (self_bp->bp->ignore_count).release ();
693 }
694 
695 /* Internal function to validate the Python parameters/keywords
696    provided to bppy_init.  */
697 
698 static int
bppy_init_validate_args(const char * spec,char * source,char * function,char * label,char * line,enum bptype type)699 bppy_init_validate_args (const char *spec, char *source,
700 			 char *function, char *label,
701 			 char *line, enum bptype type)
702 {
703   /* If spec is defined, ensure that none of the explicit location
704      keywords are also defined.  */
705   if (spec != NULL)
706     {
707       if (source != NULL || function != NULL || label != NULL || line != NULL)
708 	{
709 	  PyErr_SetString (PyExc_RuntimeError,
710 			   _("Breakpoints specified with spec cannot "
711 			     "have source, function, label or line defined."));
712 	  return -1;
713 	}
714     }
715   else
716     {
717       /* If spec isn't defined, ensure that the user is not trying to
718 	 define a watchpoint with an explicit location.  */
719       if (type == bp_watchpoint)
720 	{
721 	  PyErr_SetString (PyExc_RuntimeError,
722 			   _("Watchpoints cannot be set by explicit "
723 			     "location parameters."));
724 	  return -1;
725 	}
726       else
727 	{
728 	  /* Otherwise, ensure some explicit locations are defined.  */
729 	  if (source == NULL && function == NULL && label == NULL
730 	      && line == NULL)
731 	    {
732 	      PyErr_SetString (PyExc_RuntimeError,
733 			       _("Neither spec nor explicit location set."));
734 	      return -1;
735 	    }
736 	  /* Finally, if source is specified, ensure that line, label
737 	     or function are specified too.  */
738 	  if (source != NULL && function == NULL && label == NULL
739 	      && line == NULL)
740 	    {
741 	      PyErr_SetString (PyExc_RuntimeError,
742 			       _("Specifying a source must also include a "
743 				 "line, label or function."));
744 	      return -1;
745 	    }
746 	}
747     }
748   return 1;
749 }
750 
751 /* Python function to create a new breakpoint.  */
752 static int
bppy_init(PyObject * self,PyObject * args,PyObject * kwargs)753 bppy_init (PyObject *self, PyObject *args, PyObject *kwargs)
754 {
755   static const char *keywords[] = { "spec", "type", "wp_class", "internal",
756 				    "temporary","source", "function",
757 				    "label", "line", "qualified", NULL };
758   const char *spec = NULL;
759   enum bptype type = bp_breakpoint;
760   int access_type = hw_write;
761   PyObject *internal = NULL;
762   PyObject *temporary = NULL;
763   PyObject *lineobj = NULL;;
764   int internal_bp = 0;
765   int temporary_bp = 0;
766   gdb::unique_xmalloc_ptr<char> line;
767   char *label = NULL;
768   char *source = NULL;
769   char *function = NULL;
770   PyObject * qualified = NULL;
771 
772   if (!gdb_PyArg_ParseTupleAndKeywords (args, kwargs, "|siiOOsssOO", keywords,
773 					&spec, &type, &access_type,
774 					&internal,
775 					&temporary, &source,
776 					&function, &label, &lineobj,
777 					&qualified))
778     return -1;
779 
780 
781   if (lineobj != NULL)
782     {
783       if (PyInt_Check (lineobj))
784 	line.reset (xstrprintf ("%ld", PyInt_AsLong (lineobj)));
785       else if (PyString_Check (lineobj))
786 	line = python_string_to_host_string (lineobj);
787       else
788 	{
789 	  PyErr_SetString (PyExc_RuntimeError,
790 			   _("Line keyword should be an integer or a string. "));
791 	  return -1;
792 	}
793     }
794 
795   if (internal)
796     {
797       internal_bp = PyObject_IsTrue (internal);
798       if (internal_bp == -1)
799 	return -1;
800     }
801 
802   if (temporary != NULL)
803     {
804       temporary_bp = PyObject_IsTrue (temporary);
805       if (temporary_bp == -1)
806 	return -1;
807     }
808 
809   if (bppy_init_validate_args (spec, source, function, label, line.get (),
810 			       type) == -1)
811     return -1;
812 
813   bppy_pending_object = (gdbpy_breakpoint_object *) self;
814   bppy_pending_object->number = -1;
815   bppy_pending_object->bp = NULL;
816 
817   try
818     {
819       switch (type)
820 	{
821 	case bp_breakpoint:
822 	case bp_hardware_breakpoint:
823 	  {
824 	    event_location_up location;
825 	    symbol_name_match_type func_name_match_type
826 	      = (qualified != NULL && PyObject_IsTrue (qualified)
827 		  ? symbol_name_match_type::FULL
828 		  : symbol_name_match_type::WILD);
829 
830 	    if (spec != NULL)
831 	      {
832 		gdb::unique_xmalloc_ptr<char>
833 		  copy_holder (xstrdup (skip_spaces (spec)));
834 		const char *copy = copy_holder.get ();
835 
836 		location  = string_to_event_location (&copy,
837 						      current_language,
838 						      func_name_match_type);
839 	      }
840 	    else
841 	      {
842 		struct explicit_location explicit_loc;
843 
844 		initialize_explicit_location (&explicit_loc);
845 		explicit_loc.source_filename = source;
846 		explicit_loc.function_name = function;
847 		explicit_loc.label_name = label;
848 
849 		if (line != NULL)
850 		  explicit_loc.line_offset =
851 		    linespec_parse_line_offset (line.get ());
852 
853 		explicit_loc.func_name_match_type = func_name_match_type;
854 
855 		location = new_explicit_location (&explicit_loc);
856 	      }
857 
858 	    const struct breakpoint_ops *ops =
859 	      breakpoint_ops_for_event_location (location.get (), false);
860 
861 	    create_breakpoint (python_gdbarch,
862 			       location.get (), NULL, -1, NULL, false,
863 			       0,
864 			       temporary_bp, type,
865 			       0,
866 			       AUTO_BOOLEAN_TRUE,
867 			       ops,
868 			       0, 1, internal_bp, 0);
869 	    break;
870 	  }
871 	case bp_watchpoint:
872 	  {
873 	    gdb::unique_xmalloc_ptr<char>
874 	      copy_holder (xstrdup (skip_spaces (spec)));
875 	    char *copy = copy_holder.get ();
876 
877 	    if (access_type == hw_write)
878 	      watch_command_wrapper (copy, 0, internal_bp);
879 	    else if (access_type == hw_access)
880 	      awatch_command_wrapper (copy, 0, internal_bp);
881 	    else if (access_type == hw_read)
882 	      rwatch_command_wrapper (copy, 0, internal_bp);
883 	    else
884 	      error(_("Cannot understand watchpoint access type."));
885 	    break;
886 	  }
887 	case bp_catchpoint:
888 	  error (_("BP_CATCHPOINT not supported"));
889 	default:
890 	  error(_("Do not understand breakpoint type to set."));
891 	}
892     }
893   catch (const gdb_exception &except)
894     {
895       bppy_pending_object = NULL;
896       gdbpy_convert_exception (except);
897       return -1;
898     }
899 
900   BPPY_SET_REQUIRE_VALID ((gdbpy_breakpoint_object *) self);
901   return 0;
902 }
903 
904 /* Append to LIST the breakpoint Python object associated to B.
905 
906    Return true on success.  Return false on failure, with the Python error
907    indicator set.  */
908 
909 static bool
build_bp_list(struct breakpoint * b,PyObject * list)910 build_bp_list (struct breakpoint *b, PyObject *list)
911 {
912   PyObject *bp = (PyObject *) b->py_bp_object;
913 
914   /* Not all breakpoints will have a companion Python object.
915      Only breakpoints that were created via bppy_new, or
916      breakpoints that were created externally and are tracked by
917      the Python Scripting API.  */
918   if (bp == nullptr)
919     return true;
920 
921   return PyList_Append (list, bp) == 0;
922 }
923 
924 /* Static function to return a tuple holding all breakpoints.  */
925 
926 PyObject *
gdbpy_breakpoints(PyObject * self,PyObject * args)927 gdbpy_breakpoints (PyObject *self, PyObject *args)
928 {
929   if (bppy_live == 0)
930     return PyTuple_New (0);
931 
932   gdbpy_ref<> list (PyList_New (0));
933   if (list == NULL)
934     return NULL;
935 
936   /* If build_bp_list returns false, it signals an error condition.  In that
937      case abandon building the list and return nullptr.  */
938   for (breakpoint *bp : all_breakpoints ())
939     if (!build_bp_list (bp, list.get ()))
940       return nullptr;
941 
942   return PyList_AsTuple (list.get ());
943 }
944 
945 /* Call the "stop" method (if implemented) in the breakpoint
946    class.  If the method returns True, the inferior  will be
947    stopped at the breakpoint.  Otherwise the inferior will be
948    allowed to continue.  */
949 
950 enum ext_lang_bp_stop
gdbpy_breakpoint_cond_says_stop(const struct extension_language_defn * extlang,struct breakpoint * b)951 gdbpy_breakpoint_cond_says_stop (const struct extension_language_defn *extlang,
952 				 struct breakpoint *b)
953 {
954   int stop;
955   struct gdbpy_breakpoint_object *bp_obj = b->py_bp_object;
956   PyObject *py_bp = (PyObject *) bp_obj;
957   struct gdbarch *garch;
958 
959   if (bp_obj == NULL)
960     return EXT_LANG_BP_STOP_UNSET;
961 
962   stop = -1;
963   garch = b->gdbarch ? b->gdbarch : get_current_arch ();
964 
965   gdbpy_enter enter_py (garch, current_language);
966 
967   if (bp_obj->is_finish_bp)
968     bpfinishpy_pre_stop_hook (bp_obj);
969 
970   if (PyObject_HasAttrString (py_bp, stop_func))
971     {
972       gdbpy_ref<> result (PyObject_CallMethod (py_bp, stop_func, NULL));
973 
974       stop = 1;
975       if (result != NULL)
976 	{
977 	  int evaluate = PyObject_IsTrue (result.get ());
978 
979 	  if (evaluate == -1)
980 	    gdbpy_print_stack ();
981 
982 	  /* If the "stop" function returns False that means
983 	     the Python breakpoint wants GDB to continue.  */
984 	  if (! evaluate)
985 	    stop = 0;
986 	}
987       else
988 	gdbpy_print_stack ();
989     }
990 
991   if (bp_obj->is_finish_bp)
992     bpfinishpy_post_stop_hook (bp_obj);
993 
994   if (stop < 0)
995     return EXT_LANG_BP_STOP_UNSET;
996   return stop ? EXT_LANG_BP_STOP_YES : EXT_LANG_BP_STOP_NO;
997 }
998 
999 /* Checks if the  "stop" method exists in this breakpoint.
1000    Used by condition_command to ensure mutual exclusion of breakpoint
1001    conditions.  */
1002 
1003 int
gdbpy_breakpoint_has_cond(const struct extension_language_defn * extlang,struct breakpoint * b)1004 gdbpy_breakpoint_has_cond (const struct extension_language_defn *extlang,
1005 			   struct breakpoint *b)
1006 {
1007   PyObject *py_bp;
1008   struct gdbarch *garch;
1009 
1010   if (b->py_bp_object == NULL)
1011     return 0;
1012 
1013   py_bp = (PyObject *) b->py_bp_object;
1014   garch = b->gdbarch ? b->gdbarch : get_current_arch ();
1015 
1016   gdbpy_enter enter_py (garch, current_language);
1017   return PyObject_HasAttrString (py_bp, stop_func);
1018 }
1019 
1020 
1021 
1022 /* Event callback functions.  */
1023 
1024 /* Callback that is used when a breakpoint is created.  This function
1025    will create a new Python breakpoint object.  */
1026 static void
gdbpy_breakpoint_created(struct breakpoint * bp)1027 gdbpy_breakpoint_created (struct breakpoint *bp)
1028 {
1029   PYBP_SCOPED_DEBUG_ENTER_EXIT;
1030 
1031   gdbpy_breakpoint_object *newbp;
1032 
1033   if (!user_breakpoint_p (bp) && bppy_pending_object == NULL)
1034     {
1035       pybp_debug_printf ("not attaching python object to this breakpoint");
1036       return;
1037     }
1038 
1039   if (bp->type != bp_breakpoint
1040       && bp->type != bp_hardware_breakpoint
1041       && bp->type != bp_watchpoint
1042       && bp->type != bp_hardware_watchpoint
1043       && bp->type != bp_read_watchpoint
1044       && bp->type != bp_access_watchpoint
1045       && bp->type != bp_catchpoint)
1046     {
1047       pybp_debug_printf ("is not a breakpoint or watchpoint");
1048       return;
1049     }
1050 
1051   struct gdbarch *garch = bp->gdbarch ? bp->gdbarch : get_current_arch ();
1052   gdbpy_enter enter_py (garch, current_language);
1053 
1054   if (bppy_pending_object)
1055     {
1056       newbp = bppy_pending_object;
1057       Py_INCREF (newbp);
1058       bppy_pending_object = NULL;
1059       pybp_debug_printf ("attaching existing breakpoint object");
1060     }
1061   else
1062     {
1063       newbp = PyObject_New (gdbpy_breakpoint_object, &breakpoint_object_type);
1064       pybp_debug_printf ("attaching new breakpoint object");
1065     }
1066   if (newbp)
1067     {
1068       newbp->number = bp->number;
1069       newbp->bp = bp;
1070       newbp->bp->py_bp_object = newbp;
1071       newbp->is_finish_bp = 0;
1072       ++bppy_live;
1073     }
1074   else
1075     {
1076       PyErr_SetString (PyExc_RuntimeError,
1077 		       _("Error while creating breakpoint from GDB."));
1078       gdbpy_print_stack ();
1079     }
1080 
1081   if (!evregpy_no_listeners_p (gdb_py_events.breakpoint_created))
1082     {
1083       if (evpy_emit_event ((PyObject *) newbp,
1084 			   gdb_py_events.breakpoint_created) < 0)
1085 	gdbpy_print_stack ();
1086     }
1087 }
1088 
1089 /* Callback that is used when a breakpoint is deleted.  This will
1090    invalidate the corresponding Python object.  */
1091 static void
gdbpy_breakpoint_deleted(struct breakpoint * b)1092 gdbpy_breakpoint_deleted (struct breakpoint *b)
1093 {
1094   PYBP_SCOPED_DEBUG_ENTER_EXIT;
1095 
1096   int num = b->number;
1097   struct breakpoint *bp = NULL;
1098 
1099   bp = get_breakpoint (num);
1100   if (bp)
1101     {
1102       struct gdbarch *garch = bp->gdbarch ? bp->gdbarch : get_current_arch ();
1103       gdbpy_enter enter_py (garch, current_language);
1104 
1105       gdbpy_ref<gdbpy_breakpoint_object> bp_obj (bp->py_bp_object);
1106       if (bp_obj != NULL)
1107 	{
1108 	  if (!evregpy_no_listeners_p (gdb_py_events.breakpoint_deleted))
1109 	    {
1110 	      if (evpy_emit_event ((PyObject *) bp_obj.get (),
1111 				   gdb_py_events.breakpoint_deleted) < 0)
1112 		gdbpy_print_stack ();
1113 	    }
1114 
1115 	  bp_obj->bp = NULL;
1116 	  --bppy_live;
1117 	}
1118     }
1119 }
1120 
1121 /* Callback that is used when a breakpoint is modified.  */
1122 
1123 static void
gdbpy_breakpoint_modified(struct breakpoint * b)1124 gdbpy_breakpoint_modified (struct breakpoint *b)
1125 {
1126   PYBP_SCOPED_DEBUG_ENTER_EXIT;
1127 
1128   int num = b->number;
1129   struct breakpoint *bp = NULL;
1130 
1131   bp = get_breakpoint (num);
1132   if (bp)
1133     {
1134       struct gdbarch *garch = bp->gdbarch ? bp->gdbarch : get_current_arch ();
1135       gdbpy_enter enter_py (garch, current_language);
1136 
1137       PyObject *bp_obj = (PyObject *) bp->py_bp_object;
1138       if (bp_obj)
1139 	{
1140 	  if (!evregpy_no_listeners_p (gdb_py_events.breakpoint_modified))
1141 	    {
1142 	      if (evpy_emit_event (bp_obj,
1143 				   gdb_py_events.breakpoint_modified) < 0)
1144 		gdbpy_print_stack ();
1145 	    }
1146 	}
1147     }
1148 }
1149 
1150 
1151 
1152 /* Initialize the Python breakpoint code.  */
1153 int
gdbpy_initialize_breakpoints(void)1154 gdbpy_initialize_breakpoints (void)
1155 {
1156   int i;
1157 
1158   breakpoint_object_type.tp_new = PyType_GenericNew;
1159   if (PyType_Ready (&breakpoint_object_type) < 0)
1160     return -1;
1161 
1162   if (gdb_pymodule_addobject (gdb_module, "Breakpoint",
1163 			      (PyObject *) &breakpoint_object_type) < 0)
1164     return -1;
1165 
1166   gdb::observers::breakpoint_created.attach (gdbpy_breakpoint_created,
1167 					     "py-breakpoint");
1168   gdb::observers::breakpoint_deleted.attach (gdbpy_breakpoint_deleted,
1169 					     "py-breakpoint");
1170   gdb::observers::breakpoint_modified.attach (gdbpy_breakpoint_modified,
1171 					      "py-breakpoint");
1172 
1173   /* Add breakpoint types constants.  */
1174   for (i = 0; pybp_codes[i].name; ++i)
1175     {
1176       if (PyModule_AddIntConstant (gdb_module, pybp_codes[i].name,
1177 				   pybp_codes[i].code) < 0)
1178 	return -1;
1179     }
1180 
1181   /* Add watchpoint types constants.  */
1182   for (i = 0; pybp_watch_types[i].name; ++i)
1183     {
1184       if (PyModule_AddIntConstant (gdb_module, pybp_watch_types[i].name,
1185 				   pybp_watch_types[i].code) < 0)
1186 	return -1;
1187     }
1188 
1189   return 0;
1190 }
1191 
1192 
1193 
1194 /* Helper function that overrides this Python object's
1195    PyObject_GenericSetAttr to allow extra validation of the attribute
1196    being set.  */
1197 
1198 static int
local_setattro(PyObject * self,PyObject * name,PyObject * v)1199 local_setattro (PyObject *self, PyObject *name, PyObject *v)
1200 {
1201   gdbpy_breakpoint_object *obj = (gdbpy_breakpoint_object *) self;
1202   gdb::unique_xmalloc_ptr<char> attr (python_string_to_host_string (name));
1203 
1204   if (attr == NULL)
1205     return -1;
1206 
1207   /* If the attribute trying to be set is the "stop" method,
1208      but we already have a condition set in the CLI or other extension
1209      language, disallow this operation.  */
1210   if (strcmp (attr.get (), stop_func) == 0)
1211     {
1212       const struct extension_language_defn *extlang = NULL;
1213 
1214       if (obj->bp->cond_string != NULL)
1215 	extlang = get_ext_lang_defn (EXT_LANG_GDB);
1216       if (extlang == NULL)
1217 	extlang = get_breakpoint_cond_ext_lang (obj->bp, EXT_LANG_PYTHON);
1218       if (extlang != NULL)
1219 	{
1220 	  std::string error_text
1221 	    = string_printf (_("Only one stop condition allowed.  There is"
1222 			       " currently a %s stop condition defined for"
1223 			       " this breakpoint."),
1224 			     ext_lang_capitalized_name (extlang));
1225 	  PyErr_SetString (PyExc_RuntimeError, error_text.c_str ());
1226 	  return -1;
1227 	}
1228     }
1229 
1230   return PyObject_GenericSetAttr (self, name, v);
1231 }
1232 
1233 static gdb_PyGetSetDef breakpoint_object_getset[] = {
1234   { "enabled", bppy_get_enabled, bppy_set_enabled,
1235     "Boolean telling whether the breakpoint is enabled.", NULL },
1236   { "silent", bppy_get_silent, bppy_set_silent,
1237     "Boolean telling whether the breakpoint is silent.", NULL },
1238   { "thread", bppy_get_thread, bppy_set_thread,
1239     "Thread ID for the breakpoint.\n\
1240 If the value is a thread ID (integer), then this is a thread-specific breakpoint.\n\
1241 If the value is None, then this breakpoint is not thread-specific.\n\
1242 No other type of value can be used.", NULL },
1243   { "task", bppy_get_task, bppy_set_task,
1244     "Thread ID for the breakpoint.\n\
1245 If the value is a task ID (integer), then this is an Ada task-specific breakpoint.\n\
1246 If the value is None, then this breakpoint is not task-specific.\n\
1247 No other type of value can be used.", NULL },
1248   { "ignore_count", bppy_get_ignore_count, bppy_set_ignore_count,
1249     "Number of times this breakpoint should be automatically continued.",
1250     NULL },
1251   { "number", bppy_get_number, NULL,
1252     "Breakpoint's number assigned by GDB.", NULL },
1253   { "hit_count", bppy_get_hit_count, bppy_set_hit_count,
1254     "Number of times the breakpoint has been hit.\n\
1255 Can be set to zero to clear the count. No other value is valid\n\
1256 when setting this property.", NULL },
1257   { "location", bppy_get_location, NULL,
1258     "Location of the breakpoint, as specified by the user.", NULL},
1259   { "expression", bppy_get_expression, NULL,
1260     "Expression of the breakpoint, as specified by the user.", NULL},
1261   { "condition", bppy_get_condition, bppy_set_condition,
1262     "Condition of the breakpoint, as specified by the user,\
1263 or None if no condition set."},
1264   { "commands", bppy_get_commands, bppy_set_commands,
1265     "Commands of the breakpoint, as specified by the user."},
1266   { "type", bppy_get_type, NULL,
1267     "Type of breakpoint."},
1268   { "visible", bppy_get_visibility, NULL,
1269     "Whether the breakpoint is visible to the user."},
1270   { "temporary", bppy_get_temporary, NULL,
1271     "Whether this breakpoint is a temporary breakpoint."},
1272   { "pending", bppy_get_pending, NULL,
1273     "Whether this breakpoint is a pending breakpoint."},
1274   { NULL }  /* Sentinel.  */
1275 };
1276 
1277 static PyMethodDef breakpoint_object_methods[] =
1278 {
1279   { "is_valid", bppy_is_valid, METH_NOARGS,
1280     "Return true if this breakpoint is valid, false if not." },
1281   { "delete", bppy_delete_breakpoint, METH_NOARGS,
1282     "Delete the underlying GDB breakpoint." },
1283   { NULL } /* Sentinel.  */
1284 };
1285 
1286 PyTypeObject breakpoint_object_type =
1287 {
1288   PyVarObject_HEAD_INIT (NULL, 0)
1289   "gdb.Breakpoint",		  /*tp_name*/
1290   sizeof (gdbpy_breakpoint_object), /*tp_basicsize*/
1291   0,				  /*tp_itemsize*/
1292   0,				  /*tp_dealloc*/
1293   0,				  /*tp_print*/
1294   0,				  /*tp_getattr*/
1295   0,				  /*tp_setattr*/
1296   0,				  /*tp_compare*/
1297   0,				  /*tp_repr*/
1298   0,				  /*tp_as_number*/
1299   0,				  /*tp_as_sequence*/
1300   0,				  /*tp_as_mapping*/
1301   0,				  /*tp_hash */
1302   0,				  /*tp_call*/
1303   0,				  /*tp_str*/
1304   0,				  /*tp_getattro*/
1305   (setattrofunc)local_setattro,   /*tp_setattro */
1306   0,				  /*tp_as_buffer*/
1307   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,  /*tp_flags*/
1308   "GDB breakpoint object",	  /* tp_doc */
1309   0,				  /* tp_traverse */
1310   0,				  /* tp_clear */
1311   0,				  /* tp_richcompare */
1312   0,				  /* tp_weaklistoffset */
1313   0,				  /* tp_iter */
1314   0,				  /* tp_iternext */
1315   breakpoint_object_methods,	  /* tp_methods */
1316   0,				  /* tp_members */
1317   breakpoint_object_getset,	  /* tp_getset */
1318   0,				  /* tp_base */
1319   0,				  /* tp_dict */
1320   0,				  /* tp_descr_get */
1321   0,				  /* tp_descr_set */
1322   0,				  /* tp_dictoffset */
1323   bppy_init,			  /* tp_init */
1324   0,				  /* tp_alloc */
1325 };
1326 
1327 void _initialize_py_breakpoint ();
1328 void
_initialize_py_breakpoint()1329 _initialize_py_breakpoint ()
1330 {
1331   add_setshow_boolean_cmd
1332       ("py-breakpoint", class_maintenance, &pybp_debug,
1333 	_("Set Python breakpoint debugging."),
1334 	_("Show Python breakpoint debugging."),
1335 	_("When on, Python breakpoint debugging is enabled."),
1336 	NULL,
1337 	show_pybp_debug,
1338 	&setdebuglist, &showdebuglist);
1339 }
1340