1 /* Python interface to inferior threads.
2 
3    Copyright (C) 2009-2024 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 "gdbthread.h"
21 #include "inferior.h"
22 #include "python-internal.h"
23 
24 extern PyTypeObject thread_object_type
25     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("thread_object");
26 
27 /* Require that INFERIOR be a valid inferior ID.  */
28 #define THPY_REQUIRE_VALID(Thread)                                    \
29   do {                                                                          \
30     if (!Thread->thread)                                              \
31       {                                                                         \
32           PyErr_SetString (PyExc_RuntimeError,                        \
33                                _("Thread no longer exists."));        \
34           return NULL;                                                          \
35       }                                                                         \
36   } while (0)
37 
38 gdbpy_ref<thread_object>
create_thread_object(struct thread_info * tp)39 create_thread_object (struct thread_info *tp)
40 {
41   gdbpy_ref<thread_object> thread_obj;
42 
43   gdbpy_ref<inferior_object> inf_obj = inferior_to_inferior_object (tp->inf);
44   if (inf_obj == NULL)
45     return NULL;
46 
47   thread_obj.reset (PyObject_New (thread_object, &thread_object_type));
48   if (thread_obj == NULL)
49     return NULL;
50 
51   thread_obj->thread = tp;
52   thread_obj->inf_obj = (PyObject *) inf_obj.release ();
53   thread_obj->dict = PyDict_New ();
54   if (thread_obj->dict == nullptr)
55     return nullptr;
56 
57   return thread_obj;
58 }
59 
60 static void
thpy_dealloc(PyObject * self)61 thpy_dealloc (PyObject *self)
62 {
63   thread_object *thr_obj = (thread_object *) self;
64 
65   gdb_assert (thr_obj->inf_obj != nullptr);
66 
67   Py_DECREF (thr_obj->inf_obj);
68   Py_XDECREF (thr_obj->dict);
69 
70   Py_TYPE (self)->tp_free (self);
71 }
72 
73 static PyObject *
thpy_get_name(PyObject * self,void * ignore)74 thpy_get_name (PyObject *self, void *ignore)
75 {
76   thread_object *thread_obj = (thread_object *) self;
77 
78   THPY_REQUIRE_VALID (thread_obj);
79 
80   const char *name = thread_name (thread_obj->thread);
81   if (name == NULL)
82     Py_RETURN_NONE;
83 
84   return PyUnicode_FromString (name);
85 }
86 
87 /* Return a string containing target specific additional information about
88    the state of the thread, or None, if there is no such additional
89    information.  */
90 
91 static PyObject *
thpy_get_details(PyObject * self,void * ignore)92 thpy_get_details (PyObject *self, void *ignore)
93 {
94   thread_object *thread_obj = (thread_object *) self;
95 
96   THPY_REQUIRE_VALID (thread_obj);
97 
98   /* GCC can't tell that extra_info will always be assigned after the
99      'catch', so initialize it.  */
100   const char *extra_info = nullptr;
101   try
102     {
103       extra_info = target_extra_thread_info (thread_obj->thread);
104     }
105   catch (const gdb_exception &except)
106     {
107       GDB_PY_HANDLE_EXCEPTION (except);
108     }
109   if (extra_info == nullptr)
110     Py_RETURN_NONE;
111 
112   return PyUnicode_FromString (extra_info);
113 }
114 
115 static int
thpy_set_name(PyObject * self,PyObject * newvalue,void * ignore)116 thpy_set_name (PyObject *self, PyObject *newvalue, void *ignore)
117 {
118   thread_object *thread_obj = (thread_object *) self;
119   gdb::unique_xmalloc_ptr<char> name;
120 
121   if (! thread_obj->thread)
122     {
123       PyErr_SetString (PyExc_RuntimeError, _("Thread no longer exists."));
124       return -1;
125     }
126 
127   if (newvalue == NULL)
128     {
129       PyErr_SetString (PyExc_TypeError,
130                            _("Cannot delete `name' attribute."));
131       return -1;
132     }
133   else if (newvalue == Py_None)
134     {
135       /* Nothing.  */
136     }
137   else if (! gdbpy_is_string (newvalue))
138     {
139       PyErr_SetString (PyExc_TypeError,
140                            _("The value of `name' must be a string."));
141       return -1;
142     }
143   else
144     {
145       name = python_string_to_host_string (newvalue);
146       if (! name)
147           return -1;
148     }
149 
150   thread_obj->thread->set_name (std::move (name));
151 
152   return 0;
153 }
154 
155 /* Getter for InferiorThread.num.  */
156 
157 static PyObject *
thpy_get_num(PyObject * self,void * closure)158 thpy_get_num (PyObject *self, void *closure)
159 {
160   thread_object *thread_obj = (thread_object *) self;
161 
162   THPY_REQUIRE_VALID (thread_obj);
163 
164   gdbpy_ref<> result
165     = gdb_py_object_from_longest (thread_obj->thread->per_inf_num);
166   return result.release ();
167 }
168 
169 /* Getter for InferiorThread.global_num.  */
170 
171 static PyObject *
thpy_get_global_num(PyObject * self,void * closure)172 thpy_get_global_num (PyObject *self, void *closure)
173 {
174   thread_object *thread_obj = (thread_object *) self;
175 
176   THPY_REQUIRE_VALID (thread_obj);
177 
178   gdbpy_ref<> result
179     = gdb_py_object_from_longest (thread_obj->thread->global_num);
180   return result.release ();
181 }
182 
183 /* Getter for InferiorThread.ptid  -> (pid, lwp, tid).
184    Returns a tuple with the thread's ptid components.  */
185 
186 static PyObject *
thpy_get_ptid(PyObject * self,void * closure)187 thpy_get_ptid (PyObject *self, void *closure)
188 {
189   thread_object *thread_obj = (thread_object *) self;
190 
191   THPY_REQUIRE_VALID (thread_obj);
192 
193   return gdbpy_create_ptid_object (thread_obj->thread->ptid);
194 }
195 
196 /* Implement gdb.InferiorThread.ptid_string attribute.  */
197 
198 static PyObject *
thpy_get_ptid_string(PyObject * self,void * closure)199 thpy_get_ptid_string (PyObject *self, void *closure)
200 {
201   thread_object *thread_obj = (thread_object *) self;
202   THPY_REQUIRE_VALID (thread_obj);
203   ptid_t ptid = thread_obj->thread->ptid;
204 
205   try
206     {
207       /* Select the correct inferior before calling a target_* function.  */
208       scoped_restore_current_thread restore_thread;
209       switch_to_inferior_no_thread (thread_obj->thread->inf);
210       std::string ptid_str = target_pid_to_str (ptid);
211       return PyUnicode_FromString (ptid_str.c_str ());
212     }
213   catch (const gdb_exception &except)
214     {
215       GDB_PY_HANDLE_EXCEPTION (except);
216     }
217 }
218 
219 /* Getter for InferiorThread.inferior -> Inferior.  */
220 
221 static PyObject *
thpy_get_inferior(PyObject * self,void * ignore)222 thpy_get_inferior (PyObject *self, void *ignore)
223 {
224   thread_object *thread_obj = (thread_object *) self;
225 
226   THPY_REQUIRE_VALID (thread_obj);
227   Py_INCREF (thread_obj->inf_obj);
228 
229   return thread_obj->inf_obj;
230 }
231 
232 /* Implementation of InferiorThread.switch ().
233    Makes this the GDB selected thread.  */
234 
235 static PyObject *
thpy_switch(PyObject * self,PyObject * args)236 thpy_switch (PyObject *self, PyObject *args)
237 {
238   thread_object *thread_obj = (thread_object *) self;
239 
240   THPY_REQUIRE_VALID (thread_obj);
241 
242   try
243     {
244       switch_to_thread (thread_obj->thread);
245     }
246   catch (const gdb_exception &except)
247     {
248       GDB_PY_HANDLE_EXCEPTION (except);
249     }
250 
251   Py_RETURN_NONE;
252 }
253 
254 /* Implementation of InferiorThread.is_stopped () -> Boolean.
255    Return whether the thread is stopped.  */
256 
257 static PyObject *
thpy_is_stopped(PyObject * self,PyObject * args)258 thpy_is_stopped (PyObject *self, PyObject *args)
259 {
260   thread_object *thread_obj = (thread_object *) self;
261 
262   THPY_REQUIRE_VALID (thread_obj);
263 
264   if (thread_obj->thread->state == THREAD_STOPPED)
265     Py_RETURN_TRUE;
266 
267   Py_RETURN_FALSE;
268 }
269 
270 /* Implementation of InferiorThread.is_running () -> Boolean.
271    Return whether the thread is running.  */
272 
273 static PyObject *
thpy_is_running(PyObject * self,PyObject * args)274 thpy_is_running (PyObject *self, PyObject *args)
275 {
276   thread_object *thread_obj = (thread_object *) self;
277 
278   THPY_REQUIRE_VALID (thread_obj);
279 
280   if (thread_obj->thread->state == THREAD_RUNNING)
281     Py_RETURN_TRUE;
282 
283   Py_RETURN_FALSE;
284 }
285 
286 /* Implementation of InferiorThread.is_exited () -> Boolean.
287    Return whether the thread is exited.  */
288 
289 static PyObject *
thpy_is_exited(PyObject * self,PyObject * args)290 thpy_is_exited (PyObject *self, PyObject *args)
291 {
292   thread_object *thread_obj = (thread_object *) self;
293 
294   THPY_REQUIRE_VALID (thread_obj);
295 
296   if (thread_obj->thread->state == THREAD_EXITED)
297     Py_RETURN_TRUE;
298 
299   Py_RETURN_FALSE;
300 }
301 
302 /* Implementation of gdb.InfThread.is_valid (self) -> Boolean.
303    Returns True if this inferior Thread object still exists
304    in GDB.  */
305 
306 static PyObject *
thpy_is_valid(PyObject * self,PyObject * args)307 thpy_is_valid (PyObject *self, PyObject *args)
308 {
309   thread_object *thread_obj = (thread_object *) self;
310 
311   if (! thread_obj->thread)
312     Py_RETURN_FALSE;
313 
314   Py_RETURN_TRUE;
315 }
316 
317 /* Implementation of gdb.InferiorThread.handle (self) -> handle. */
318 
319 static PyObject *
thpy_thread_handle(PyObject * self,PyObject * args)320 thpy_thread_handle (PyObject *self, PyObject *args)
321 {
322   thread_object *thread_obj = (thread_object *) self;
323   THPY_REQUIRE_VALID (thread_obj);
324 
325   gdb::array_view<const gdb_byte> hv;
326 
327   try
328     {
329       hv = target_thread_info_to_thread_handle (thread_obj->thread);
330     }
331   catch (const gdb_exception &except)
332     {
333       GDB_PY_HANDLE_EXCEPTION (except);
334     }
335 
336   if (hv.size () == 0)
337     {
338       PyErr_SetString (PyExc_RuntimeError, _("Thread handle not found."));
339       return NULL;
340     }
341 
342   PyObject *object = PyBytes_FromStringAndSize ((const char *) hv.data (),
343                                                             hv.size());
344   return object;
345 }
346 
347 /* Implement repr() for gdb.InferiorThread.  */
348 
349 static PyObject *
thpy_repr(PyObject * self)350 thpy_repr (PyObject *self)
351 {
352   thread_object *thread_obj = (thread_object *) self;
353 
354   if (thread_obj->thread == nullptr)
355     return gdb_py_invalid_object_repr (self);
356 
357   thread_info *thr = thread_obj->thread;
358   return PyUnicode_FromFormat ("<%s id=%s target-id=\"%s\">",
359                                      Py_TYPE (self)->tp_name,
360                                      print_full_thread_id (thr),
361                                      target_pid_to_str (thr->ptid).c_str ());
362 }
363 
364 /* Return a reference to a new Python object representing a ptid_t.
365    The object is a tuple containing (pid, lwp, tid). */
366 PyObject *
gdbpy_create_ptid_object(ptid_t ptid)367 gdbpy_create_ptid_object (ptid_t ptid)
368 {
369   int pid;
370   long lwp;
371   ULONGEST tid;
372   PyObject *ret;
373 
374   ret = PyTuple_New (3);
375   if (!ret)
376     return NULL;
377 
378   pid = ptid.pid ();
379   lwp = ptid.lwp ();
380   tid = ptid.tid ();
381 
382   gdbpy_ref<> pid_obj = gdb_py_object_from_longest (pid);
383   if (pid_obj == nullptr)
384     return nullptr;
385   gdbpy_ref<> lwp_obj = gdb_py_object_from_longest (lwp);
386   if (lwp_obj == nullptr)
387     return nullptr;
388   gdbpy_ref<> tid_obj = gdb_py_object_from_ulongest (tid);
389   if (tid_obj == nullptr)
390     return nullptr;
391 
392   /* Note that these steal references, hence the use of 'release'.  */
393   PyTuple_SET_ITEM (ret, 0, pid_obj.release ());
394   PyTuple_SET_ITEM (ret, 1, lwp_obj.release ());
395   PyTuple_SET_ITEM (ret, 2, tid_obj.release ());
396 
397   return ret;
398 }
399 
400 /* Implementation of gdb.selected_thread () -> gdb.InferiorThread.
401    Returns the selected thread object.  */
402 
403 PyObject *
gdbpy_selected_thread(PyObject * self,PyObject * args)404 gdbpy_selected_thread (PyObject *self, PyObject *args)
405 {
406   if (inferior_ptid != null_ptid)
407     return thread_to_thread_object (inferior_thread ()).release ();
408 
409   Py_RETURN_NONE;
410 }
411 
412 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
gdbpy_initialize_thread(void)413 gdbpy_initialize_thread (void)
414 {
415   if (PyType_Ready (&thread_object_type) < 0)
416     return -1;
417 
418   return gdb_pymodule_addobject (gdb_module, "InferiorThread",
419                                          (PyObject *) &thread_object_type);
420 }
421 
422 GDBPY_INITIALIZE_FILE (gdbpy_initialize_thread);
423 
424 
425 
426 static gdb_PyGetSetDef thread_object_getset[] =
427 {
428   { "__dict__", gdb_py_generic_dict, nullptr,
429     "The __dict__ for this thread.", &thread_object_type },
430   { "name", thpy_get_name, thpy_set_name,
431     "The name of the thread, as set by the user or the OS.", NULL },
432   { "details", thpy_get_details, NULL,
433     "A target specific string containing extra thread state details.",
434     NULL },
435   { "num", thpy_get_num, NULL,
436     "Per-inferior number of the thread, as assigned by GDB.", NULL },
437   { "global_num", thpy_get_global_num, NULL,
438     "Global number of the thread, as assigned by GDB.", NULL },
439   { "ptid", thpy_get_ptid, NULL, "ID of the thread, as assigned by the OS.",
440     NULL },
441   { "ptid_string", thpy_get_ptid_string, nullptr,
442     "A string representing ptid, as used by, for example, 'info threads'.",
443     nullptr },
444   { "inferior", thpy_get_inferior, NULL,
445     "The Inferior object this thread belongs to.", NULL },
446 
447   { NULL }
448 };
449 
450 static PyMethodDef thread_object_methods[] =
451 {
452   { "is_valid", thpy_is_valid, METH_NOARGS,
453     "is_valid () -> Boolean.\n\
454 Return true if this inferior thread is valid, false if not." },
455   { "switch", thpy_switch, METH_NOARGS,
456     "switch ()\n\
457 Makes this the GDB selected thread." },
458   { "is_stopped", thpy_is_stopped, METH_NOARGS,
459     "is_stopped () -> Boolean\n\
460 Return whether the thread is stopped." },
461   { "is_running", thpy_is_running, METH_NOARGS,
462     "is_running () -> Boolean\n\
463 Return whether the thread is running." },
464   { "is_exited", thpy_is_exited, METH_NOARGS,
465     "is_exited () -> Boolean\n\
466 Return whether the thread is exited." },
467   { "handle", thpy_thread_handle, METH_NOARGS,
468     "handle  () -> handle\n\
469 Return thread library specific handle for thread." },
470 
471   { NULL }
472 };
473 
474 PyTypeObject thread_object_type =
475 {
476   PyVarObject_HEAD_INIT (NULL, 0)
477   "gdb.InferiorThread",                   /*tp_name*/
478   sizeof (thread_object),       /*tp_basicsize*/
479   0,                                      /*tp_itemsize*/
480   thpy_dealloc,                           /*tp_dealloc*/
481   0,                                      /*tp_print*/
482   0,                                      /*tp_getattr*/
483   0,                                      /*tp_setattr*/
484   0,                                      /*tp_compare*/
485   thpy_repr,                              /*tp_repr*/
486   0,                                      /*tp_as_number*/
487   0,                                      /*tp_as_sequence*/
488   0,                                      /*tp_as_mapping*/
489   0,                                      /*tp_hash */
490   0,                                      /*tp_call*/
491   0,                                      /*tp_str*/
492   0,                                      /*tp_getattro*/
493   0,                                      /*tp_setattro*/
494   0,                                      /*tp_as_buffer*/
495   Py_TPFLAGS_DEFAULT,                     /*tp_flags*/
496   "GDB thread object",                    /* tp_doc */
497   0,                                      /* tp_traverse */
498   0,                                      /* tp_clear */
499   0,                                      /* tp_richcompare */
500   0,                                      /* tp_weaklistoffset */
501   0,                                      /* tp_iter */
502   0,                                      /* tp_iternext */
503   thread_object_methods,        /* tp_methods */
504   0,                                      /* tp_members */
505   thread_object_getset,                   /* tp_getset */
506   0,                                      /* tp_base */
507   0,                                      /* tp_dict */
508   0,                                      /* tp_descr_get */
509   0,                                      /* tp_descr_set */
510   offsetof (thread_object, dict), /* tp_dictoffset */
511   0,                                      /* tp_init */
512   0                                       /* tp_alloc */
513 };
514