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