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