]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/python/py-inferior.c
gdb: centralize "[Thread ...exited]" notifications
[thirdparty/binutils-gdb.git] / gdb / python / py-inferior.c
CommitLineData
595939de
PM
1/* Python interface to inferiors.
2
213516ef 3 Copyright (C) 2009-2023 Free Software Foundation, Inc.
595939de
PM
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"
2c473def 21#include "auto-load.h"
595939de
PM
22#include "gdbcore.h"
23#include "gdbthread.h"
24#include "inferior.h"
20c168b5 25#include "objfiles.h"
76727919 26#include "observable.h"
595939de
PM
27#include "python-internal.h"
28#include "arch-utils.h"
29#include "language.h"
268a13a5 30#include "gdbsupport/gdb_signals.h"
505500db
SW
31#include "py-event.h"
32#include "py-stopevent.h"
75ec0982 33#include "progspace-and-thread.h"
40b355f2 34#include <unordered_map>
595939de 35
40b355f2
LS
36using thread_map_t
37 = std::unordered_map<thread_info *, gdbpy_ref<thread_object>>;
595939de 38
00431a78 39struct inferior_object
595939de
PM
40{
41 PyObject_HEAD
42
43 /* The inferior we represent. */
44 struct inferior *inferior;
45
40b355f2 46 /* thread_object instances under this inferior. This owns a
595939de 47 reference to each object it contains. */
40b355f2 48 thread_map_t *threads;
00431a78 49};
595939de 50
e36122e9 51extern PyTypeObject inferior_object_type
62eec1a5 52 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("inferior_object");
595939de 53
08b8a139
TT
54/* Deleter to clean up when an inferior is removed. */
55struct infpy_deleter
56{
57 void operator() (inferior_object *obj)
58 {
08b8a139
TT
59 if (!gdb_python_initialized)
60 return;
61
62 gdbpy_enter enter_py;
63 gdbpy_ref<inferior_object> inf_obj (obj);
64
65 inf_obj->inferior = NULL;
66
40b355f2 67 delete inf_obj->threads;
08b8a139
TT
68 }
69};
70
71static const registry<inferior>::key<inferior_object, infpy_deleter>
72 infpy_inf_data_key;
595939de 73
595939de
PM
74/* Require that INFERIOR be a valid inferior ID. */
75#define INFPY_REQUIRE_VALID(Inferior) \
76 do { \
77 if (!Inferior->inferior) \
78 { \
79 PyErr_SetString (PyExc_RuntimeError, \
80 _("Inferior no longer exists.")); \
81 return NULL; \
82 } \
83 } while (0)
84
505500db 85static void
313f3b21 86python_on_normal_stop (struct bpstat *bs, int print_frame)
505500db 87{
2ea28649 88 enum gdb_signal stop_signal;
505500db 89
0646da15
TT
90 if (!gdb_python_initialized)
91 return;
92
151bb4a5
PA
93 if (inferior_ptid == null_ptid)
94 return;
505500db 95
1edb66d8 96 stop_signal = inferior_thread ()->stop_signal ();
505500db 97
1da5d0e6 98 gdbpy_enter enter_py;
505500db
SW
99
100 if (emit_stop_event (bs, stop_signal) < 0)
101 gdbpy_print_stack ();
505500db
SW
102}
103
104static void
105python_on_resume (ptid_t ptid)
106{
0646da15
TT
107 if (!gdb_python_initialized)
108 return;
109
1da5d0e6 110 gdbpy_enter enter_py (target_gdbarch ());
505500db
SW
111
112 if (emit_continue_event (ptid) < 0)
113 gdbpy_print_stack ();
505500db
SW
114}
115
162078c8
NB
116/* Callback, registered as an observer, that notifies Python listeners
117 when an inferior function call is about to be made. */
118
119static void
120python_on_inferior_call_pre (ptid_t thread, CORE_ADDR address)
121{
1da5d0e6 122 gdbpy_enter enter_py (target_gdbarch ());
162078c8
NB
123
124 if (emit_inferior_call_event (INFERIOR_CALL_PRE, thread, address) < 0)
125 gdbpy_print_stack ();
162078c8
NB
126}
127
128/* Callback, registered as an observer, that notifies Python listeners
129 when an inferior function call has completed. */
130
131static void
132python_on_inferior_call_post (ptid_t thread, CORE_ADDR address)
133{
1da5d0e6 134 gdbpy_enter enter_py (target_gdbarch ());
162078c8
NB
135
136 if (emit_inferior_call_event (INFERIOR_CALL_POST, thread, address) < 0)
137 gdbpy_print_stack ();
162078c8
NB
138}
139
140/* Callback, registered as an observer, that notifies Python listeners
141 when a part of memory has been modified by user action (eg via a
142 'set' command). */
143
144static void
145python_on_memory_change (struct inferior *inferior, CORE_ADDR addr, ssize_t len, const bfd_byte *data)
146{
1da5d0e6 147 gdbpy_enter enter_py (target_gdbarch ());
162078c8
NB
148
149 if (emit_memory_changed_event (addr, len) < 0)
150 gdbpy_print_stack ();
162078c8
NB
151}
152
153/* Callback, registered as an observer, that notifies Python listeners
154 when a register has been modified by user action (eg via a 'set'
155 command). */
156
157static void
bd2b40ac 158python_on_register_change (frame_info_ptr frame, int regnum)
162078c8 159{
1da5d0e6 160 gdbpy_enter enter_py (target_gdbarch ());
162078c8
NB
161
162 if (emit_register_changed_event (frame, regnum) < 0)
163 gdbpy_print_stack ();
162078c8
NB
164}
165
505500db
SW
166static void
167python_inferior_exit (struct inferior *inf)
168{
8cf64490 169 const LONGEST *exit_code = NULL;
505500db 170
0646da15
TT
171 if (!gdb_python_initialized)
172 return;
173
1da5d0e6 174 gdbpy_enter enter_py (target_gdbarch ());
505500db 175
8cf64490
TT
176 if (inf->has_exit_code)
177 exit_code = &inf->exit_code;
505500db 178
cb6be26b 179 if (emit_exited_event (exit_code, inf) < 0)
505500db 180 gdbpy_print_stack ();
505500db
SW
181}
182
20c168b5 183/* Callback used to notify Python listeners about new objfiles loaded in the
4ffbba72
DE
184 inferior. OBJFILE may be NULL which means that the objfile list has been
185 cleared (emptied). */
20c168b5
KP
186
187static void
188python_new_objfile (struct objfile *objfile)
189{
0646da15
TT
190 if (!gdb_python_initialized)
191 return;
192
07bc7329 193 gdbpy_enter enter_py (objfile != NULL
08feed99 194 ? objfile->arch ()
1da5d0e6 195 : target_gdbarch ());
20c168b5 196
4ffbba72
DE
197 if (objfile == NULL)
198 {
199 if (emit_clear_objfiles_event () < 0)
200 gdbpy_print_stack ();
201 }
202 else
203 {
204 if (emit_new_objfile_event (objfile) < 0)
205 gdbpy_print_stack ();
206 }
20c168b5
KP
207}
208
0b4fe76f
TT
209/* Emit a Python event when an objfile is about to be removed. */
210
211static void
212python_free_objfile (struct objfile *objfile)
213{
214 if (!gdb_python_initialized)
215 return;
216
217 gdbpy_enter enter_py (objfile->arch ());
218
219 if (emit_free_objfile_event (objfile) < 0)
220 gdbpy_print_stack ();
221}
222
754eadd1 223/* Return a reference to the Python object of type Inferior
595939de 224 representing INFERIOR. If the object has already been created,
754eadd1
PM
225 return it and increment the reference count, otherwise, create it.
226 Return NULL on failure. */
00431a78 227
61fd3e73 228gdbpy_ref<inferior_object>
595939de
PM
229inferior_to_inferior_object (struct inferior *inferior)
230{
231 inferior_object *inf_obj;
232
08b8a139 233 inf_obj = infpy_inf_data_key.get (inferior);
595939de
PM
234 if (!inf_obj)
235 {
595939de
PM
236 inf_obj = PyObject_New (inferior_object, &inferior_object_type);
237 if (!inf_obj)
61fd3e73 238 return NULL;
595939de
PM
239
240 inf_obj->inferior = inferior;
40b355f2 241 inf_obj->threads = new thread_map_t ();
595939de 242
72bc1d24
SM
243 /* PyObject_New initializes the new object with a refcount of 1. This
244 counts for the reference we are keeping in the inferior data. */
08b8a139 245 infpy_inf_data_key.set (inferior, inf_obj);
595939de 246 }
72bc1d24
SM
247
248 /* We are returning a new reference. */
61fd3e73
TT
249 gdb_assert (inf_obj != nullptr);
250 return gdbpy_ref<inferior_object>::new_reference (inf_obj);
595939de
PM
251}
252
7c96f8c1
TT
253/* Called when a new inferior is created. Notifies any Python event
254 listeners. */
255static void
256python_new_inferior (struct inferior *inf)
257{
258 if (!gdb_python_initialized)
259 return;
260
1da5d0e6 261 gdbpy_enter enter_py;
7c96f8c1
TT
262
263 if (evregpy_no_listeners_p (gdb_py_events.new_inferior))
264 return;
265
61fd3e73 266 gdbpy_ref<inferior_object> inf_obj = inferior_to_inferior_object (inf);
7c96f8c1
TT
267 if (inf_obj == NULL)
268 {
269 gdbpy_print_stack ();
270 return;
271 }
272
d98fc15b 273 gdbpy_ref<> event = create_event_object (&new_inferior_event_object_type);
7c96f8c1 274 if (event == NULL
00431a78
PA
275 || evpy_add_attribute (event.get (), "inferior",
276 (PyObject *) inf_obj.get ()) < 0
7c96f8c1
TT
277 || evpy_emit_event (event.get (), gdb_py_events.new_inferior) < 0)
278 gdbpy_print_stack ();
279}
280
281/* Called when an inferior is removed. Notifies any Python event
282 listeners. */
283static void
284python_inferior_deleted (struct inferior *inf)
285{
286 if (!gdb_python_initialized)
287 return;
288
1da5d0e6 289 gdbpy_enter enter_py;
7c96f8c1
TT
290
291 if (evregpy_no_listeners_p (gdb_py_events.inferior_deleted))
292 return;
293
61fd3e73 294 gdbpy_ref<inferior_object> inf_obj = inferior_to_inferior_object (inf);
7c96f8c1
TT
295 if (inf_obj == NULL)
296 {
297 gdbpy_print_stack ();
298 return;
299 }
300
d98fc15b 301 gdbpy_ref<> event = create_event_object (&inferior_deleted_event_object_type);
7c96f8c1 302 if (event == NULL
00431a78
PA
303 || evpy_add_attribute (event.get (), "inferior",
304 (PyObject *) inf_obj.get ()) < 0
7c96f8c1
TT
305 || evpy_emit_event (event.get (), gdb_py_events.inferior_deleted) < 0)
306 gdbpy_print_stack ();
307}
308
db1337cc 309gdbpy_ref<>
00431a78 310thread_to_thread_object (thread_info *thr)
595939de 311{
61fd3e73 312 gdbpy_ref<inferior_object> inf_obj = inferior_to_inferior_object (thr->inf);
9205649a 313 if (inf_obj == NULL)
754eadd1
PM
314 return NULL;
315
40b355f2
LS
316 auto thread_it = inf_obj->threads->find (thr);
317 if (thread_it != inf_obj->threads->end ())
318 return gdbpy_ref<>::new_reference
319 ((PyObject *) (thread_it->second.get ()));
595939de 320
4a137fec
TT
321 PyErr_SetString (PyExc_SystemError,
322 _("could not find gdb thread object"));
595939de
PM
323 return NULL;
324}
325
326static void
327add_thread_object (struct thread_info *tp)
328{
595939de 329 inferior_object *inf_obj;
595939de 330
0646da15
TT
331 if (!gdb_python_initialized)
332 return;
333
1da5d0e6 334 gdbpy_enter enter_py;
595939de 335
05b08ac1
TT
336 gdbpy_ref<thread_object> thread_obj = create_thread_object (tp);
337 if (thread_obj == NULL)
595939de
PM
338 {
339 gdbpy_print_stack ();
595939de
PM
340 return;
341 }
342
343 inf_obj = (inferior_object *) thread_obj->inf_obj;
344
40b355f2
LS
345 auto ins_result = inf_obj->threads->emplace
346 (thread_map_t::value_type (tp, std::move (thread_obj)));
595939de 347
40b355f2
LS
348 if (!ins_result.second)
349 return;
7c96f8c1
TT
350
351 if (evregpy_no_listeners_p (gdb_py_events.new_thread))
352 return;
353
40b355f2
LS
354 gdbpy_ref<> event = create_thread_event_object
355 (&new_thread_event_object_type,
356 (PyObject *) ins_result.first->second.get ());
357
7c96f8c1
TT
358 if (event == NULL
359 || evpy_emit_event (event.get (), gdb_py_events.new_thread) < 0)
360 gdbpy_print_stack ();
595939de
PM
361}
362
363static void
9d7d58e7
PA
364delete_thread_object (thread_info *tp,
365 gdb::optional<ULONGEST> /* exit_code */,
366 bool /* silent */)
595939de 367{
0646da15
TT
368 if (!gdb_python_initialized)
369 return;
370
1da5d0e6 371 gdbpy_enter enter_py;
595939de 372
61fd3e73 373 gdbpy_ref<inferior_object> inf_obj = inferior_to_inferior_object (tp->inf);
88b6faea 374 if (inf_obj == NULL)
07bc7329 375 return;
595939de 376
28ab5960
SF
377 if (emit_thread_exit_event (tp) < 0)
378 gdbpy_print_stack ();
379
40b355f2
LS
380 auto it = inf_obj->threads->find (tp);
381 if (it != inf_obj->threads->end ())
382 {
383 /* Some python code can still hold a reference to the thread_object
384 instance. Make sure to remove the link to the associated
385 thread_info object as it will be freed soon. This makes the python
386 object invalid (i.e. gdb.InfThread.is_valid returns False). */
387 it->second->thread = nullptr;
388 inf_obj->threads->erase (it);
389 }
595939de
PM
390}
391
392static PyObject *
393infpy_threads (PyObject *self, PyObject *args)
394{
40b355f2 395 int i = 0;
595939de
PM
396 inferior_object *inf_obj = (inferior_object *) self;
397 PyObject *tuple;
398
399 INFPY_REQUIRE_VALID (inf_obj);
400
a70b8144 401 try
492d29ea
PA
402 {
403 update_thread_list ();
404 }
230d2906 405 catch (const gdb_exception &except)
492d29ea
PA
406 {
407 GDB_PY_HANDLE_EXCEPTION (except);
408 }
f66713d2 409
40b355f2 410 tuple = PyTuple_New (inf_obj->threads->size ());
595939de
PM
411 if (!tuple)
412 return NULL;
413
40b355f2 414 for (const thread_map_t::value_type &entry : *inf_obj->threads)
595939de 415 {
40b355f2 416 PyObject *thr = (PyObject *) entry.second.get ();
05b08ac1
TT
417 Py_INCREF (thr);
418 PyTuple_SET_ITEM (tuple, i, thr);
40b355f2 419 i = i + 1;
595939de
PM
420 }
421
422 return tuple;
423}
424
425static PyObject *
426infpy_get_num (PyObject *self, void *closure)
427{
428 inferior_object *inf = (inferior_object *) self;
429
430 INFPY_REQUIRE_VALID (inf);
431
062534d4 432 return gdb_py_object_from_longest (inf->inferior->num).release ();
595939de
PM
433}
434
0e3b7c25
AB
435/* Return the gdb.TargetConnection object for this inferior, or None if a
436 connection does not exist. */
437
438static PyObject *
439infpy_get_connection (PyObject *self, void *closure)
440{
441 inferior_object *inf = (inferior_object *) self;
442
443 INFPY_REQUIRE_VALID (inf);
444
445 process_stratum_target *target = inf->inferior->process_target ();
446 return target_to_connection_object (target).release ();
447}
448
55789354
TBA
449/* Return the connection number of the given inferior, or None if a
450 connection does not exist. */
451
452static PyObject *
453infpy_get_connection_num (PyObject *self, void *closure)
454{
455 inferior_object *inf = (inferior_object *) self;
456
457 INFPY_REQUIRE_VALID (inf);
458
459 process_stratum_target *target = inf->inferior->process_target ();
460 if (target == nullptr)
461 Py_RETURN_NONE;
462
8b9c48b2 463 return gdb_py_object_from_longest (target->connection_number).release ();
55789354
TBA
464}
465
595939de
PM
466static PyObject *
467infpy_get_pid (PyObject *self, void *closure)
468{
469 inferior_object *inf = (inferior_object *) self;
470
471 INFPY_REQUIRE_VALID (inf);
472
062534d4 473 return gdb_py_object_from_longest (inf->inferior->pid).release ();
595939de
PM
474}
475
476static PyObject *
477infpy_get_was_attached (PyObject *self, void *closure)
478{
479 inferior_object *inf = (inferior_object *) self;
480
481 INFPY_REQUIRE_VALID (inf);
482 if (inf->inferior->attach_flag)
483 Py_RETURN_TRUE;
484 Py_RETURN_FALSE;
485}
486
a40bf0c2
SM
487/* Getter of gdb.Inferior.progspace. */
488
489static PyObject *
490infpy_get_progspace (PyObject *self, void *closure)
491{
492 inferior_object *inf = (inferior_object *) self;
493
494 INFPY_REQUIRE_VALID (inf);
495
496 program_space *pspace = inf->inferior->pspace;
497 gdb_assert (pspace != nullptr);
498
3c7aa307 499 return pspace_to_pspace_object (pspace).release ();
a40bf0c2
SM
500}
501
595939de
PM
502/* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
503 Returns a tuple of all inferiors. */
504PyObject *
505gdbpy_inferiors (PyObject *unused, PyObject *unused2)
506{
7780f186 507 gdbpy_ref<> list (PyList_New (0));
f59fe7f8 508 if (list == NULL)
595939de
PM
509 return NULL;
510
d9bc85b6
SM
511 for (inferior *inf : all_inferiors ())
512 {
513 gdbpy_ref<inferior_object> inferior = inferior_to_inferior_object (inf);
514
515 if (inferior == NULL)
516 continue;
517
518 if (PyList_Append (list.get (), (PyObject *) inferior.get ()) != 0)
519 return NULL;
520 }
27ca1a5b 521
f59fe7f8 522 return PyList_AsTuple (list.get ());
595939de
PM
523}
524
525/* Membuf and memory manipulation. */
526
2678e2af 527/* Implementation of Inferior.read_memory (address, length).
595939de 528 Returns a Python buffer object with LENGTH bytes of the inferior's
8dc78533
JK
529 memory at ADDRESS. Both arguments are integers. Returns NULL on error,
530 with a python exception set. */
595939de
PM
531static PyObject *
532infpy_read_memory (PyObject *self, PyObject *args, PyObject *kw)
533{
75ec0982 534 inferior_object *inf = (inferior_object *) self;
595939de 535 CORE_ADDR addr, length;
075c55e0 536 gdb::unique_xmalloc_ptr<gdb_byte> buffer;
625f7b1c 537 PyObject *addr_obj, *length_obj;
2adadf51 538 static const char *keywords[] = { "address", "length", NULL };
595939de 539
75ec0982
TT
540 INFPY_REQUIRE_VALID (inf);
541
2adadf51
PA
542 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "OO", keywords,
543 &addr_obj, &length_obj))
595939de
PM
544 return NULL;
545
b86af38a
TT
546 if (get_addr_from_python (addr_obj, &addr) < 0
547 || get_addr_from_python (length_obj, &length) < 0)
548 return NULL;
549
a70b8144 550 try
595939de 551 {
75ec0982
TT
552 /* Use this scoped-restore because we want to be able to read
553 memory from an unwinder. */
554 scoped_restore_current_inferior_for_memory restore_inferior
6d30ada8 555 (inf->inferior);
75ec0982 556
075c55e0 557 buffer.reset ((gdb_byte *) xmalloc (length));
595939de 558
075c55e0 559 read_memory (addr, buffer.get (), length);
595939de 560 }
230d2906 561 catch (const gdb_exception &except)
595939de 562 {
595939de
PM
563 GDB_PY_HANDLE_EXCEPTION (except);
564 }
565
595939de 566
625f7b1c 567 return gdbpy_buffer_to_membuf (std::move (buffer), addr, length);
595939de
PM
568}
569
2678e2af 570/* Implementation of Inferior.write_memory (address, buffer [, length]).
595939de
PM
571 Writes the contents of BUFFER (a Python object supporting the read
572 buffer protocol) at ADDRESS in the inferior's memory. Write LENGTH
573 bytes from BUFFER, or its entire contents if the argument is not
8dc78533
JK
574 provided. The function returns nothing. Returns NULL on error, with
575 a python exception set. */
595939de
PM
576static PyObject *
577infpy_write_memory (PyObject *self, PyObject *args, PyObject *kw)
578{
75ec0982 579 inferior_object *inf = (inferior_object *) self;
cc06b668 580 struct gdb_exception except;
ddd49eee 581 Py_ssize_t buf_len;
7c543f7b 582 const gdb_byte *buffer;
595939de
PM
583 CORE_ADDR addr, length;
584 PyObject *addr_obj, *length_obj = NULL;
2adadf51 585 static const char *keywords[] = { "address", "buffer", "length", NULL };
9a27f2c6 586 Py_buffer pybuf;
595939de 587
75ec0982
TT
588 INFPY_REQUIRE_VALID (inf);
589
2adadf51
PA
590 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords,
591 &addr_obj, &pybuf, &length_obj))
9a27f2c6 592 return NULL;
595939de 593
6ca62222 594 Py_buffer_up buffer_up (&pybuf);
7c543f7b 595 buffer = (const gdb_byte *) pybuf.buf;
9a27f2c6 596 buf_len = pybuf.len;
595939de 597
b86af38a 598 if (get_addr_from_python (addr_obj, &addr) < 0)
6ca62222 599 return nullptr;
b86af38a
TT
600
601 if (!length_obj)
602 length = buf_len;
603 else if (get_addr_from_python (length_obj, &length) < 0)
6ca62222 604 return nullptr;
b86af38a 605
a70b8144 606 try
595939de 607 {
75ec0982
TT
608 /* It's probably not too important to avoid invalidating the
609 frame cache when writing memory, but this scoped-restore is
610 still used here, just to keep the code similar to other code
611 in this file. */
612 scoped_restore_current_inferior_for_memory restore_inferior
6d30ada8 613 (inf->inferior);
75ec0982 614
7c543f7b 615 write_memory_with_notification (addr, buffer, length);
595939de 616 }
94aeb44b 617 catch (gdb_exception &ex)
492d29ea 618 {
94aeb44b 619 except = std::move (ex);
492d29ea 620 }
492d29ea 621
595939de
PM
622 GDB_PY_HANDLE_EXCEPTION (except);
623
595939de
PM
624 Py_RETURN_NONE;
625}
626
595939de 627/* Implementation of
75ec0982 628 Inferior.search_memory (address, length, pattern). ADDRESS is the
595939de
PM
629 address to start the search. LENGTH specifies the scope of the
630 search from ADDRESS. PATTERN is the pattern to search for (and
631 must be a Python object supporting the buffer protocol).
632 Returns a Python Long object holding the address where the pattern
8dc78533
JK
633 was located, or if the pattern was not found, returns None. Returns NULL
634 on error, with a python exception set. */
595939de
PM
635static PyObject *
636infpy_search_memory (PyObject *self, PyObject *args, PyObject *kw)
637{
75ec0982 638 inferior_object *inf = (inferior_object *) self;
cc06b668 639 struct gdb_exception except;
595939de 640 CORE_ADDR start_addr, length;
2adadf51 641 static const char *keywords[] = { "address", "length", "pattern", NULL };
9a27f2c6 642 PyObject *start_addr_obj, *length_obj;
595939de 643 Py_ssize_t pattern_size;
7c543f7b 644 const gdb_byte *buffer;
595939de
PM
645 CORE_ADDR found_addr;
646 int found = 0;
9a27f2c6 647 Py_buffer pybuf;
595939de 648
75ec0982
TT
649 INFPY_REQUIRE_VALID (inf);
650
2adadf51
PA
651 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords,
652 &start_addr_obj, &length_obj,
653 &pybuf))
9a27f2c6
PK
654 return NULL;
655
6ca62222 656 Py_buffer_up buffer_up (&pybuf);
7c543f7b 657 buffer = (const gdb_byte *) pybuf.buf;
9a27f2c6 658 pattern_size = pybuf.len;
595939de 659
b86af38a 660 if (get_addr_from_python (start_addr_obj, &start_addr) < 0)
6ca62222 661 return nullptr;
256458bc 662
b86af38a 663 if (get_addr_from_python (length_obj, &length) < 0)
6ca62222 664 return nullptr;
9a27f2c6 665
b86af38a
TT
666 if (!length)
667 {
668 PyErr_SetString (PyExc_ValueError,
669 _("Search range is empty."));
6ca62222 670 return nullptr;
b86af38a
TT
671 }
672 /* Watch for overflows. */
673 else if (length > CORE_ADDR_MAX
674 || (start_addr + length - 1) < start_addr)
675 {
676 PyErr_SetString (PyExc_ValueError,
677 _("The search range is too large."));
6ca62222 678 return nullptr;
595939de 679 }
595939de 680
a70b8144 681 try
595939de 682 {
75ec0982
TT
683 /* It's probably not too important to avoid invalidating the
684 frame cache when searching memory, but this scoped-restore is
685 still used here, just to keep the code similar to other code
686 in this file. */
687 scoped_restore_current_inferior_for_memory restore_inferior
6d30ada8 688 (inf->inferior);
75ec0982 689
595939de
PM
690 found = target_search_memory (start_addr, length,
691 buffer, pattern_size,
692 &found_addr);
693 }
94aeb44b 694 catch (gdb_exception &ex)
492d29ea 695 {
94aeb44b 696 except = std::move (ex);
492d29ea 697 }
492d29ea 698
b86af38a 699 GDB_PY_HANDLE_EXCEPTION (except);
9a27f2c6 700
595939de 701 if (found)
b017825f 702 return gdb_py_object_from_ulongest (found_addr).release ();
595939de
PM
703 else
704 Py_RETURN_NONE;
705}
706
29703da4
PM
707/* Implementation of gdb.Inferior.is_valid (self) -> Boolean.
708 Returns True if this inferior object still exists in GDB. */
709
710static PyObject *
711infpy_is_valid (PyObject *self, PyObject *args)
712{
713 inferior_object *inf = (inferior_object *) self;
714
715 if (! inf->inferior)
716 Py_RETURN_FALSE;
717
718 Py_RETURN_TRUE;
719}
720
2b0c8b01 721/* Implementation of gdb.Inferior.thread_from_handle (self, handle)
dda83cd7 722 -> gdb.InferiorThread. */
fbbe5337 723
7d221512 724static PyObject *
fbbe5337
KB
725infpy_thread_from_thread_handle (PyObject *self, PyObject *args, PyObject *kw)
726{
db1337cc 727 PyObject *handle_obj;
fbbe5337 728 inferior_object *inf_obj = (inferior_object *) self;
2b0c8b01 729 static const char *keywords[] = { "handle", NULL };
fbbe5337
KB
730
731 INFPY_REQUIRE_VALID (inf_obj);
732
733 if (! gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords, &handle_obj))
734 return NULL;
735
50a82723
KB
736 const gdb_byte *bytes;
737 size_t bytes_len;
738 Py_buffer_up buffer_up;
739 Py_buffer py_buf;
740
741 if (PyObject_CheckBuffer (handle_obj)
742 && PyObject_GetBuffer (handle_obj, &py_buf, PyBUF_SIMPLE) == 0)
743 {
744 buffer_up.reset (&py_buf);
745 bytes = (const gdb_byte *) py_buf.buf;
746 bytes_len = py_buf.len;
747 }
748 else if (gdbpy_is_value_object (handle_obj))
749 {
750 struct value *val = value_object_to_value (handle_obj);
efaf1ae0 751 bytes = val->contents_all ().data ();
d0c97917 752 bytes_len = val->type ()->length ();
50a82723
KB
753 }
754 else
fbbe5337
KB
755 {
756 PyErr_SetString (PyExc_TypeError,
2b0c8b01 757 _("Argument 'handle' must be a thread handle object."));
fbbe5337
KB
758
759 return NULL;
760 }
db1337cc 761
a70b8144 762 try
db1337cc
TT
763 {
764 struct thread_info *thread_info;
db1337cc 765
50a82723 766 thread_info = find_thread_by_handle
dda83cd7 767 (gdb::array_view<const gdb_byte> (bytes, bytes_len),
50a82723 768 inf_obj->inferior);
db1337cc 769 if (thread_info != NULL)
4a137fec 770 return thread_to_thread_object (thread_info).release ();
db1337cc 771 }
230d2906 772 catch (const gdb_exception &except)
fbbe5337 773 {
db1337cc 774 GDB_PY_HANDLE_EXCEPTION (except);
fbbe5337
KB
775 }
776
4a137fec 777 Py_RETURN_NONE;
fbbe5337
KB
778}
779
add5ded5
TT
780/* Implementation of gdb.Inferior.architecture. */
781
782static PyObject *
783infpy_architecture (PyObject *self, PyObject *args)
784{
785 inferior_object *inf = (inferior_object *) self;
786
787 INFPY_REQUIRE_VALID (inf);
788
789 return gdbarch_to_arch_object (inf->inferior->gdbarch);
790}
791
1256af7d
SM
792/* Implement repr() for gdb.Inferior. */
793
794static PyObject *
795infpy_repr (PyObject *obj)
796{
797 inferior_object *self = (inferior_object *) obj;
798 inferior *inf = self->inferior;
799
800 if (inf == nullptr)
5aee4587 801 return PyUnicode_FromString ("<gdb.Inferior (invalid)>");
1256af7d 802
5aee4587
SM
803 return PyUnicode_FromFormat ("<gdb.Inferior num=%d, pid=%d>",
804 inf->num, inf->pid);
1256af7d
SM
805}
806
31531132
TT
807/* Implement clear_env. */
808
809static PyObject *
810infpy_clear_env (PyObject *obj)
811{
812 inferior_object *self = (inferior_object *) obj;
813
814 INFPY_REQUIRE_VALID (self);
815
816 self->inferior->environment.clear ();
817 Py_RETURN_NONE;
818}
819
820/* Implement set_env. */
821
822static PyObject *
823infpy_set_env (PyObject *obj, PyObject *args, PyObject *kw)
824{
825 inferior_object *self = (inferior_object *) obj;
826 INFPY_REQUIRE_VALID (self);
827
828 const char *name, *val;
829 static const char *keywords[] = { "name", "value", nullptr };
830
831 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "ss", keywords,
832 &name, &val))
833 return nullptr;
834
835 self->inferior->environment.set (name, val);
836 Py_RETURN_NONE;
837}
838
839/* Implement unset_env. */
840
841static PyObject *
842infpy_unset_env (PyObject *obj, PyObject *args, PyObject *kw)
843{
844 inferior_object *self = (inferior_object *) obj;
845 INFPY_REQUIRE_VALID (self);
846
847 const char *name;
848 static const char *keywords[] = { "name", nullptr };
849 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s", keywords, &name))
850 return nullptr;
851
852 self->inferior->environment.unset (name);
853 Py_RETURN_NONE;
854}
855
856/* Getter for "arguments". */
857
858static PyObject *
859infpy_get_args (PyObject *self, void *closure)
860{
861 inferior_object *inf = (inferior_object *) self;
862
863 INFPY_REQUIRE_VALID (inf);
864
865 const std::string &args = inf->inferior->args ();
866 if (args.empty ())
867 Py_RETURN_NONE;
868
869 return host_string_to_python_string (args.c_str ()).release ();
870}
871
872/* Setter for "arguments". */
873
874static int
875infpy_set_args (PyObject *self, PyObject *value, void *closure)
876{
877 inferior_object *inf = (inferior_object *) self;
878
879 if (!inf->inferior)
880 {
881 PyErr_SetString (PyExc_RuntimeError, _("Inferior no longer exists."));
882 return -1;
883 }
884
885 if (value == nullptr)
886 {
887 PyErr_SetString (PyExc_TypeError,
888 _("Cannot delete 'arguments' attribute."));
889 return -1;
890 }
891
892 if (gdbpy_is_string (value))
893 {
894 gdb::unique_xmalloc_ptr<char> str = python_string_to_host_string (value);
895 if (str == nullptr)
896 return -1;
897 inf->inferior->set_args (std::string (str.get ()));
898 }
899 else if (PySequence_Check (value))
900 {
901 std::vector<gdb::unique_xmalloc_ptr<char>> args;
902 Py_ssize_t len = PySequence_Size (value);
903 if (len == -1)
904 return -1;
905 for (Py_ssize_t i = 0; i < len; ++i)
906 {
907 gdbpy_ref<> item (PySequence_ITEM (value, i));
908 if (item == nullptr)
909 return -1;
910 gdb::unique_xmalloc_ptr<char> str
911 = python_string_to_host_string (item.get ());
912 if (str == nullptr)
913 return -1;
914 args.push_back (std::move (str));
915 }
916 std::vector<char *> argvec;
917 for (const auto &arg : args)
918 argvec.push_back (arg.get ());
919 gdb::array_view<char * const> view (argvec.data (), argvec.size ());
920 inf->inferior->set_args (view);
921 }
922 else
923 {
924 PyErr_SetString (PyExc_TypeError,
925 _("string or sequence required for 'arguments'"));
926 return -1;
927 }
928 return 0;
929}
930
931/* Getter for "main_name". */
932
933static PyObject *
934infpy_get_main_name (PyObject *self, void *closure)
935{
936 inferior_object *inf = (inferior_object *) self;
937
938 INFPY_REQUIRE_VALID (inf);
939
940 const char *name = nullptr;
941 try
942 {
943 /* This is unfortunate but the implementation of main_name can
75ec0982
TT
944 reach into memory. It's probably not too important to avoid
945 invalidating the frame cache here, but this scoped-restore is
946 still used, just to keep the code similar to other code in
947 this file. */
948 scoped_restore_current_inferior_for_memory restore_inferior
6d30ada8 949 (inf->inferior);
31531132
TT
950
951 name = main_name ();
952 }
953 catch (const gdb_exception &except)
954 {
955 /* We can just ignore this. */
956 }
957
958 if (name == nullptr)
959 Py_RETURN_NONE;
960
961 return host_string_to_python_string (name).release ();
962}
fbbe5337 963
754eadd1
PM
964static void
965infpy_dealloc (PyObject *obj)
966{
967 inferior_object *inf_obj = (inferior_object *) obj;
754eadd1 968
cb6e6bb8
AB
969 /* The inferior itself holds a reference to this Python object, which
970 will keep the reference count of this object above zero until GDB
971 deletes the inferior and py_free_inferior is called.
972
973 Once py_free_inferior has been called then the link between this
974 Python object and the inferior is set to nullptr, and then the
975 reference count on this Python object is decremented.
976
977 The result of all this is that the link between this Python object and
978 the inferior should always have been set to nullptr before this
979 function is called. */
980 gdb_assert (inf_obj->inferior == nullptr);
754eadd1 981
2e953aca 982 Py_TYPE (obj)->tp_free (obj);
754eadd1 983}
595939de 984
2aa48337
KP
985/* Implementation of gdb.selected_inferior() -> gdb.Inferior.
986 Returns the current inferior object. */
987
988PyObject *
989gdbpy_selected_inferior (PyObject *self, PyObject *args)
990{
61fd3e73
TT
991 return ((PyObject *)
992 inferior_to_inferior_object (current_inferior ()).release ());
2aa48337
KP
993}
994
3965bff5 995static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
595939de
PM
996gdbpy_initialize_inferior (void)
997{
998 if (PyType_Ready (&inferior_object_type) < 0)
999633ed 999 return -1;
595939de 1000
aa36459a
TT
1001 if (gdb_pymodule_addobject (gdb_module, "Inferior",
1002 (PyObject *) &inferior_object_type) < 0)
999633ed 1003 return -1;
595939de 1004
c90e7d63
SM
1005 gdb::observers::new_thread.attach (add_thread_object, "py-inferior");
1006 gdb::observers::thread_exit.attach (delete_thread_object, "py-inferior");
1007 gdb::observers::normal_stop.attach (python_on_normal_stop, "py-inferior");
1008 gdb::observers::target_resumed.attach (python_on_resume, "py-inferior");
1009 gdb::observers::inferior_call_pre.attach (python_on_inferior_call_pre,
1010 "py-inferior");
1011 gdb::observers::inferior_call_post.attach (python_on_inferior_call_post,
1012 "py-inferior");
1013 gdb::observers::memory_changed.attach (python_on_memory_change,
1014 "py-inferior");
1015 gdb::observers::register_changed.attach (python_on_register_change,
1016 "py-inferior");
1017 gdb::observers::inferior_exit.attach (python_inferior_exit, "py-inferior");
2c473def
MW
1018 /* Need to run after auto-load's new_objfile observer, so that
1019 auto-loaded pretty-printers are available. */
1020 gdb::observers::new_objfile.attach
1021 (python_new_objfile, "py-inferior",
1022 { &auto_load_new_objfile_observer_token });
0b4fe76f 1023 gdb::observers::free_objfile.attach (python_free_objfile, "py-inferior");
c90e7d63
SM
1024 gdb::observers::inferior_added.attach (python_new_inferior, "py-inferior");
1025 gdb::observers::inferior_removed.attach (python_inferior_deleted,
1026 "py-inferior");
595939de 1027
625f7b1c 1028 return 0;
595939de
PM
1029}
1030
3965bff5
AB
1031GDBPY_INITIALIZE_FILE (gdbpy_initialize_inferior);
1032
1033\f
1034
0d1f4ceb 1035static gdb_PyGetSetDef inferior_object_getset[] =
595939de 1036{
31531132
TT
1037 { "arguments", infpy_get_args, infpy_set_args,
1038 "Arguments to this program.", nullptr },
595939de 1039 { "num", infpy_get_num, NULL, "ID of inferior, as assigned by GDB.", NULL },
0e3b7c25
AB
1040 { "connection", infpy_get_connection, NULL,
1041 "The gdb.TargetConnection for this inferior.", NULL },
55789354
TBA
1042 { "connection_num", infpy_get_connection_num, NULL,
1043 "ID of inferior's connection, as assigned by GDB.", NULL },
595939de
PM
1044 { "pid", infpy_get_pid, NULL, "PID of inferior, as assigned by the OS.",
1045 NULL },
1046 { "was_attached", infpy_get_was_attached, NULL,
1047 "True if the inferior was created using 'attach'.", NULL },
a40bf0c2 1048 { "progspace", infpy_get_progspace, NULL, "Program space of this inferior" },
31531132
TT
1049 { "main_name", infpy_get_main_name, nullptr,
1050 "Name of 'main' function, if known.", nullptr },
595939de
PM
1051 { NULL }
1052};
1053
1054static PyMethodDef inferior_object_methods[] =
1055{
29703da4
PM
1056 { "is_valid", infpy_is_valid, METH_NOARGS,
1057 "is_valid () -> Boolean.\n\
1058Return true if this inferior is valid, false if not." },
595939de
PM
1059 { "threads", infpy_threads, METH_NOARGS,
1060 "Return all the threads of this inferior." },
1061 { "read_memory", (PyCFunction) infpy_read_memory,
1062 METH_VARARGS | METH_KEYWORDS,
1063 "read_memory (address, length) -> buffer\n\
1064Return a buffer object for reading from the inferior's memory." },
1065 { "write_memory", (PyCFunction) infpy_write_memory,
1066 METH_VARARGS | METH_KEYWORDS,
1067 "write_memory (address, buffer [, length])\n\
1068Write the given buffer object to the inferior's memory." },
1069 { "search_memory", (PyCFunction) infpy_search_memory,
1070 METH_VARARGS | METH_KEYWORDS,
1071 "search_memory (address, length, pattern) -> long\n\
1072Return a long with the address of a match, or None." },
2b0c8b01 1073 /* thread_from_thread_handle is deprecated. */
fbbe5337
KB
1074 { "thread_from_thread_handle", (PyCFunction) infpy_thread_from_thread_handle,
1075 METH_VARARGS | METH_KEYWORDS,
1076 "thread_from_thread_handle (handle) -> gdb.InferiorThread.\n\
2b0c8b01
KB
1077Return thread object corresponding to thread handle.\n\
1078This method is deprecated - use thread_from_handle instead." },
1079 { "thread_from_handle", (PyCFunction) infpy_thread_from_thread_handle,
1080 METH_VARARGS | METH_KEYWORDS,
1081 "thread_from_handle (handle) -> gdb.InferiorThread.\n\
fbbe5337 1082Return thread object corresponding to thread handle." },
add5ded5
TT
1083 { "architecture", (PyCFunction) infpy_architecture, METH_NOARGS,
1084 "architecture () -> gdb.Architecture\n\
1085Return architecture of this inferior." },
31531132
TT
1086 { "clear_env", (PyCFunction) infpy_clear_env, METH_NOARGS,
1087 "clear_env () -> None\n\
1088Clear environment of this inferior." },
1089 { "set_env", (PyCFunction) infpy_set_env, METH_VARARGS | METH_KEYWORDS,
1090 "set_env (name, value) -> None\n\
1091Set an environment variable of this inferior." },
1092 { "unset_env", (PyCFunction) infpy_unset_env, METH_VARARGS | METH_KEYWORDS,
1093 "unset_env (name) -> None\n\
1094Unset an environment of this inferior." },
595939de
PM
1095 { NULL }
1096};
1097
e36122e9 1098PyTypeObject inferior_object_type =
595939de 1099{
9a27f2c6 1100 PyVarObject_HEAD_INIT (NULL, 0)
595939de
PM
1101 "gdb.Inferior", /* tp_name */
1102 sizeof (inferior_object), /* tp_basicsize */
1103 0, /* tp_itemsize */
754eadd1 1104 infpy_dealloc, /* tp_dealloc */
595939de
PM
1105 0, /* tp_print */
1106 0, /* tp_getattr */
1107 0, /* tp_setattr */
1108 0, /* tp_compare */
1256af7d 1109 infpy_repr, /* tp_repr */
595939de
PM
1110 0, /* tp_as_number */
1111 0, /* tp_as_sequence */
1112 0, /* tp_as_mapping */
1113 0, /* tp_hash */
1114 0, /* tp_call */
1115 0, /* tp_str */
1116 0, /* tp_getattro */
1117 0, /* tp_setattro */
1118 0, /* tp_as_buffer */
0b233e34 1119 Py_TPFLAGS_DEFAULT, /* tp_flags */
595939de
PM
1120 "GDB inferior object", /* tp_doc */
1121 0, /* tp_traverse */
1122 0, /* tp_clear */
1123 0, /* tp_richcompare */
1124 0, /* tp_weaklistoffset */
1125 0, /* tp_iter */
1126 0, /* tp_iternext */
1127 inferior_object_methods, /* tp_methods */
1128 0, /* tp_members */
1129 inferior_object_getset, /* tp_getset */
1130 0, /* tp_base */
1131 0, /* tp_dict */
1132 0, /* tp_descr_get */
1133 0, /* tp_descr_set */
1134 0, /* tp_dictoffset */
1135 0, /* tp_init */
1136 0 /* tp_alloc */
1137};