Debian Codegraph @

libdrgn/python/object.c

raw
1 // Copyright (c) Meta Platforms, Inc. and affiliates.
2 // SPDX-License-Identifier: LGPL-2.1-or-later
3
4 #include <inttypes.h>
5 #include <math.h>
6
7 #include "drgnpy.h"
8 #include "../error.h"
9 #include "../object.h"
10 #include "../serialize.h"
11 #include "../type.h"
12 #include "../util.h"
13
14 static int DrgnObject_literal(struct drgn_object *res, PyObject *literal)
15 {
16 struct drgn_error *err;
17
18 if (PyBool_Check(literal)) {
19 err = drgn_object_bool_literal(res, literal == Py_True);
20 } else if (PyLong_Check(literal)) {
21 bool is_negative = PyLong_IsNegative(literal);
22 uint64_t uvalue;
23 if (is_negative) {
24 _cleanup_pydecref_ PyObject *negated =
25 PyNumber_Negative(literal);
26 if (!negated)
27 return -1;
28 if (PyLong_AsUInt64(negated, &uvalue))
29 return -1;
30 } else if (PyLong_AsUInt64(literal, &uvalue)) {
31 return -1;
32 }
33 err = drgn_object_integer_literal(res, uvalue);
34 if (!err && is_negative)
35 err = drgn_object_neg(res, res);
36 } else if (PyFloat_Check(literal)) {
37 err = drgn_object_float_literal(res,
38 PyFloat_AS_DOUBLE(literal));
39 } else {
40 return 1;
41 }
42 if (err) {
43 set_drgn_error(err);
44 return -1;
45 }
46 return 0;
47 }
48
49 static void *
50 py_long_to_bytes_for_object_type(PyObject *value_obj,
51 const struct drgn_object_type *type)
52 {
53 if (!PyNumber_Check(value_obj)) {
54 return set_error_type_name("'%s' value must be number",
55 drgn_object_type_qualified(type));
56 }
57 _cleanup_pydecref_ PyObject *long_obj = PyNumber_Long(value_obj);
58 if (!long_obj)
59 return NULL;
60 uint64_t size = drgn_value_size(type->bit_size);
61 _cleanup_free_ void *buf = malloc64(size);
62 if (!buf) {
63 PyErr_NoMemory();
64 return NULL;
65 }
66 #if PY_VERSION_HEX >= 0x030d00a4
67 Py_ssize_t r = PyLong_AsNativeBytes(long_obj, buf, size,
68 type->little_endian);
69 if (r < 0)
70 return NULL;
71 #else
72 // _PyLong_AsByteArray() still returns the least significant bytes on
73 // OverflowError unless the object is negative and is_signed is false.
74 // So, we always pass is_signed as true.
75 int r = _PyLong_AsByteArray((PyLongObject *)long_obj, buf, size,
76 type->little_endian, true);
77 if (r) {
78 PyObject *exc_type, *exc_value, *exc_traceback;
79 PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);
80 if (PyErr_GivenExceptionMatches(exc_type, PyExc_OverflowError)) {
81 Py_XDECREF(exc_traceback);
82 Py_XDECREF(exc_value);
83 Py_DECREF(exc_type);
84 } else {
85 PyErr_Restore(exc_type, exc_value, exc_traceback);
86 return NULL;
87 }
88 }
89 #endif
90 return_ptr(buf);
91 }
92
93 static int serialize_py_object(struct drgn_program *prog, char *buf,
94 uint64_t buf_bit_size, uint64_t bit_offset,
95 PyObject *value_obj,
96 const struct drgn_object_type *type);
97
98 static int serialize_compound_value(struct drgn_program *prog, char *buf,
99 uint64_t buf_bit_size, uint64_t bit_offset,
100 PyObject *value_obj,
101 const struct drgn_object_type *type)
102 {
103 struct drgn_error *err;
104
105 if (!PyMapping_Check(value_obj)) {
106 set_error_type_name("'%s' value must be dictionary or mapping",
107 drgn_object_type_qualified(type));
108 return -1;
109 }
110
111 _cleanup_pydecref_ PyObject *items = PyMapping_Items(value_obj);
112 if (!items)
113 return -1;
114
115 Py_ssize_t num_items = PyList_GET_SIZE(items);
116 for (Py_ssize_t i = 0; i < num_items; i++) {
117 PyObject *item = PyList_GET_ITEM(items, i);
118 if (!PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) {
119 PyErr_SetString(PyExc_TypeError, "invalid item");
120 return -1;
121 }
122 PyObject *key = PyTuple_GET_ITEM(item, 0);
123 if (!PyUnicode_Check(key)) {
124 PyErr_SetString(PyExc_TypeError,
125 "member key must be string");
126 return -1;
127 }
128 const char *member_name = PyUnicode_AsUTF8(key);
129 if (!member_name)
130 return -1;
131
132 struct drgn_type_member *member;
133 uint64_t member_bit_offset;
134 err = drgn_type_find_member(type->underlying_type, member_name,
135 &member, &member_bit_offset);
136 if (err) {
137 set_drgn_error(err);
138 return -1;
139 }
140 struct drgn_qualified_type member_qualified_type;
141 uint64_t member_bit_field_size;
142 err = drgn_member_type(member, &member_qualified_type,
143 &member_bit_field_size);
144 if (err) {
145 set_drgn_error(err);
146 return -1;
147 }
148
149 struct drgn_object_type member_type;
150 err = drgn_object_type(member_qualified_type,
151 member_bit_field_size, &member_type);
152 if (err)
153 return -1;
154 if (serialize_py_object(prog, buf, buf_bit_size,
155 bit_offset + member_bit_offset,
156 PyTuple_GET_ITEM(item, 1),
157 &member_type) == -1)
158 return -1;
159 }
160
161 return 0;
162 }
163
164 static int serialize_array_value(struct drgn_program *prog, char *buf,
165 uint64_t buf_bit_size, uint64_t bit_offset,
166 PyObject *value_obj,
167 const struct drgn_object_type *type)
168 {
169 struct drgn_error *err;
170
171 struct drgn_object_type element_type;
172 err = drgn_object_type(drgn_type_type(type->underlying_type), 0,
173 &element_type);
174 if (err) {
175 set_drgn_error(err);
176 return -1;
177 }
178
179 uint64_t length = drgn_type_length(type->underlying_type);
180 if (length > PY_SSIZE_T_MAX) {
181 PyErr_NoMemory();
182 return -1;
183 }
184
185 _cleanup_pydecref_ PyObject *seq = PySequence_Fast(value_obj, "");
186 if (!seq) {
187 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
188 set_error_type_name("'%s' value must be iterable",
189 drgn_object_type_qualified(type));
190 }
191 return -1;
192 }
193 size_t seq_length = PySequence_Fast_GET_SIZE(seq);
194 if (seq_length > length) {
195 PyErr_SetString(PyExc_ValueError,
196 "too many items in array value");
197 return -1;
198 }
199
200 for (size_t i = 0; i < seq_length; i++) {
201 if (serialize_py_object(prog, buf, buf_bit_size,
202 bit_offset + i * element_type.bit_size,
203 PySequence_Fast_GET_ITEM(seq, i),
204 &element_type) == -1)
205 return -1;
206 }
207
208 return 0;
209 }
210
211 static int serialize_py_object(struct drgn_program *prog, char *buf,
212 uint64_t buf_bit_size, uint64_t bit_offset,
213 PyObject *value_obj,
214 const struct drgn_object_type *type)
215 {
216 struct drgn_error *err;
217
218 uint64_t bit_end;
219 if (__builtin_add_overflow(bit_offset, type->bit_size, &bit_end) ||
220 bit_end > buf_bit_size) {
221 err = drgn_error_create(DRGN_ERROR_OUT_OF_BOUNDS,
222 "out of bounds of value");
223 set_drgn_error(err);
224 return -1;
225 }
226
227 switch (type->encoding) {
228 case DRGN_OBJECT_ENCODING_SIGNED:
229 case DRGN_OBJECT_ENCODING_UNSIGNED: {
230 if (!PyNumber_Check(value_obj)) {
231 set_error_type_name("'%s' value must be number",
232 drgn_object_type_qualified(type));
233 return -1;
234 }
235 _cleanup_pydecref_ PyObject *long_obj =
236 PyNumber_Long(value_obj);
237 if (!long_obj)
238 return -1;
239 unsigned long long lvalue =
240 PyLong_AsUnsignedLongLongMask(long_obj);
241 if (lvalue == (unsigned long long)-1 && PyErr_Occurred())
242 return -1;
243 union {
244 int64_t svalue;
245 uint64_t uvalue;
246 } tmp = { .uvalue = lvalue };
247 if (type->encoding == DRGN_OBJECT_ENCODING_SIGNED) {
248 tmp.svalue = truncate_signed(tmp.svalue,
249 type->bit_size);
250 } else {
251 tmp.uvalue = truncate_unsigned(tmp.uvalue,
252 type->bit_size);
253 }
254 serialize_bits(buf, bit_offset, tmp.uvalue, type->bit_size,
255 type->little_endian);
256 return 0;
257 }
258 case DRGN_OBJECT_ENCODING_SIGNED_BIG:
259 case DRGN_OBJECT_ENCODING_UNSIGNED_BIG: {
260 _cleanup_free_ void *tmp =
261 py_long_to_bytes_for_object_type(value_obj, type);
262 if (!tmp)
263 return -1;
264 int src_bit_offset = 0;
265 if (!type->little_endian)
266 src_bit_offset = -type->bit_size % 8;
267 copy_bits(buf + bit_offset / 8, bit_offset % 8, tmp,
268 src_bit_offset, type->bit_size, type->little_endian);
269 return 0;
270 }
271 case DRGN_OBJECT_ENCODING_FLOAT: {
272 if (!PyNumber_Check(value_obj)) {
273 set_error_type_name("'%s' value must be number",
274 drgn_object_type_qualified(type));
275 return -1;
276 }
277 double fvalue = PyFloat_AsDouble(value_obj);
278 if (fvalue == -1.0 && PyErr_Occurred())
279 return -1;
280 union {
281 uint64_t uvalue;
282 double fvalue64;
283 struct {
284 #if !HOST_LITTLE_ENDIAN
285 float pad;
286 #endif
287 float fvalue32;
288 };
289 } tmp;
290 if (type->bit_size == 64)
291 tmp.fvalue64 = fvalue;
292 else
293 tmp.fvalue32 = fvalue;
294 serialize_bits(buf, bit_offset, tmp.uvalue, type->bit_size,
295 type->little_endian);
296 return 0;
297 }
298 case DRGN_OBJECT_ENCODING_BUFFER:
299 switch (drgn_type_kind(type->underlying_type)) {
300 case DRGN_TYPE_STRUCT:
301 case DRGN_TYPE_UNION:
302 case DRGN_TYPE_CLASS:
303 return serialize_compound_value(prog, buf, buf_bit_size,
304 bit_offset, value_obj,
305 type);
306 case DRGN_TYPE_ARRAY:
307 return serialize_array_value(prog, buf, buf_bit_size,
308 bit_offset, value_obj,
309 type);
310 default:
311 break;
312 }
313 break;
314 default:
315 break;
316 }
317 UNREACHABLE();
318 }
319
320 static int buffer_object_from_value(struct drgn_object *res,
321 const struct drgn_object_type *type,
322 PyObject *value_obj)
323 {
324 uint64_t size = drgn_value_size(type->bit_size);
325 if (size > SIZE_MAX) {
326 PyErr_NoMemory();
327 return -1;
328 }
329 union drgn_value value;
330 char *buf;
331 if (size <= sizeof(value.ibuf)) {
332 buf = value.ibuf;
333 } else {
334 buf = malloc64(size);
335 if (!buf) {
336 PyErr_NoMemory();
337 return -1;
338 }
339 value.bufp = buf;
340 }
341 memset(buf, 0, size);
342
343 if (serialize_py_object(drgn_object_program(res), buf, type->bit_size,
344 0, value_obj, type) == -1) {
345 if (buf != value.ibuf)
346 free(buf);
347 return -1;
348 }
349
350 drgn_object_reinit(res, type, DRGN_OBJECT_VALUE);
351 res->value = value;
352 return 0;
353 }
354
355 static DrgnObject *DrgnObject_new(PyTypeObject *subtype, PyObject *args,
356 PyObject *kwds)
357 {
358 static char *keywords[] = {
359 "prog", "type", "value", "address", "absence_reason",
360 "bit_offset", "bit_field_size", NULL,
361 };
362 struct drgn_error *err;
363 Program *prog;
364 PyObject *type_obj = Py_None, *value_obj = Py_None;
365 struct index_arg address = { .allow_none = true, .is_none = true };
366 struct enum_arg absence_reason = {
367 .type = AbsenceReason_class,
368 // Sentinel value so we can tell when the argument was passed.
369 .value = ULONG_MAX,
370 };
371 struct index_arg bit_offset = { .allow_none = true, .is_none = true };
372 struct index_arg bit_field_size = { .allow_none = true, .is_none = true };
373 struct drgn_qualified_type qualified_type;
374 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!|OO$O&O&O&O&:Object",
375 keywords, &Program_type, &prog,
376 &type_obj, &value_obj, index_converter,
377 &address, enum_converter,
378 &absence_reason, index_converter,
379 &bit_offset, index_converter,
380 &bit_field_size))
381 return NULL;
382
383 if (Program_type_arg(prog, type_obj, true, &qualified_type) == -1)
384 return NULL;
385
386 if (!bit_field_size.is_none && bit_field_size.uvalue == 0) {
387 PyErr_SetString(PyExc_ValueError,
388 "bit field size cannot be zero");
389 return NULL;
390 }
391
392 _cleanup_pydecref_ DrgnObject *obj = DrgnObject_alloc(prog);
393 if (!obj)
394 return NULL;
395 if (!address.is_none
396 + (value_obj != Py_None)
397 + (absence_reason.value != ULONG_MAX) > 1) {
398 PyErr_Format(PyExc_ValueError,
399 "object cannot have %s and %s",
400 !address.is_none
401 ? (value_obj != Py_None
402 && absence_reason.value != ULONG_MAX)
403 ? "address, value," : "address" : "value",
404 absence_reason.value != ULONG_MAX
405 ? "absence reason" : "value");
406 return NULL;
407 } else if (!address.is_none) {
408 if (!qualified_type.type) {
409 PyErr_SetString(PyExc_ValueError,
410 "reference must have type");
411 return NULL;
412 }
413
414 err = drgn_object_set_reference(&obj->obj, qualified_type,
415 address.uvalue,
416 bit_offset.uvalue,
417 bit_field_size.uvalue);
418 } else if (value_obj != Py_None && !qualified_type.type) {
419 int ret;
420
421 if (!bit_offset.is_none) {
422 PyErr_SetString(PyExc_ValueError,
423 "literal cannot have bit offset");
424 return NULL;
425 }
426 if (!bit_field_size.is_none) {
427 PyErr_SetString(PyExc_ValueError,
428 "literal cannot be bit field");
429 return NULL;
430 }
431
432 ret = DrgnObject_literal(&obj->obj, value_obj);
433 if (ret == -1) {
434 return NULL;
435 } else if (ret) {
436 PyErr_Format(PyExc_TypeError,
437 "literal must be int, float, or bool, not '%s'",
438 Py_TYPE(value_obj)->tp_name);
439 return NULL;
440 }
441 err = NULL;
442 } else if (value_obj != Py_None) {
443 if (!bit_offset.is_none) {
444 PyErr_SetString(PyExc_ValueError,
445 "value cannot have bit offset");
446 return NULL;
447 }
448
449 struct drgn_object_type object_type;
450 err = drgn_object_type(qualified_type, bit_field_size.uvalue,
451 &object_type);
452 if (err)
453 return set_drgn_error(err);
454
455 SWITCH_ENUM(object_type.encoding) {
456 case DRGN_OBJECT_ENCODING_BUFFER:
457 if (buffer_object_from_value(&obj->obj, &object_type,
458 value_obj) == -1)
459 return NULL;
460 err = NULL;
461 break;
462 case DRGN_OBJECT_ENCODING_SIGNED:
463 case DRGN_OBJECT_ENCODING_UNSIGNED: {
464 if (!PyNumber_Check(value_obj)) {
465 return set_error_type_name("'%s' value must be number",
466 qualified_type);
467 }
468 _cleanup_pydecref_ PyObject *long_obj =
469 PyNumber_Long(value_obj);
470 if (!long_obj)
471 return NULL;
472 unsigned long long lvalue =
473 PyLong_AsUnsignedLongLongMask(long_obj);
474 if (lvalue == (unsigned long long)-1 && PyErr_Occurred())
475 return NULL;
476 union {
477 int64_t svalue;
478 uint64_t uvalue;
479 } tmp = { .uvalue = lvalue };
480 if (object_type.encoding == DRGN_OBJECT_ENCODING_SIGNED) {
481 err = drgn_object_set_signed_internal(&obj->obj,
482 &object_type,
483 tmp.svalue);
484 } else {
485 err = drgn_object_set_unsigned_internal(&obj->obj,
486 &object_type,
487 tmp.uvalue);
488 }
489 break;
490 }
491 case DRGN_OBJECT_ENCODING_SIGNED_BIG:
492 case DRGN_OBJECT_ENCODING_UNSIGNED_BIG: {
493 _cleanup_free_ void *tmp =
494 py_long_to_bytes_for_object_type(value_obj,
495 &object_type);
496 if (!tmp)
497 return NULL;
498 uint64_t src_bit_offset = 0;
499 if (!object_type.little_endian)
500 src_bit_offset = -object_type.bit_size % 8;
501 err = drgn_object_set_from_buffer_internal(&obj->obj,
502 &object_type,
503 tmp,
504 src_bit_offset);
505 break;
506 }
507 case DRGN_OBJECT_ENCODING_FLOAT: {
508 if (!PyNumber_Check(value_obj)) {
509 return set_error_type_name("'%s' value must be number",
510 qualified_type);
511 }
512 double fvalue = PyFloat_AsDouble(value_obj);
513 if (fvalue == -1.0 && PyErr_Occurred())
514 return NULL;
515 err = drgn_object_set_float_internal(&obj->obj,
516 &object_type,
517 fvalue);
518 break;
519 }
520 case DRGN_OBJECT_ENCODING_NONE:
521 case DRGN_OBJECT_ENCODING_INCOMPLETE_BUFFER:
522 case DRGN_OBJECT_ENCODING_INCOMPLETE_INTEGER:
523 err = drgn_error_incomplete_type("cannot create value with %s type",
524 qualified_type.type);
525 break;
526 default:
527 UNREACHABLE();
528 }
529 } else {
530 if (!qualified_type.type) {
531 PyErr_SetString(PyExc_ValueError,
532 "absent object must have type");
533 return NULL;
534 }
535 if (!bit_offset.is_none) {
536 PyErr_SetString(PyExc_ValueError,
537 "absent object cannot have bit offset");
538 return NULL;
539 }
540 err = drgn_object_set_absent(&obj->obj, qualified_type,
541 absence_reason.value == ULONG_MAX
542 ? DRGN_ABSENCE_REASON_OTHER
543 : absence_reason.value,
544 bit_field_size.uvalue);
545 }
546 if (err)
547 return set_drgn_error(err);
548 return_ptr(obj);
549 }
550
551 static void DrgnObject_dealloc(DrgnObject *self)
552 {
553 PyObject_GC_UnTrack(self);
554 Py_DECREF(DrgnObject_prog(self));
555 drgn_object_deinit(&self->obj);
556 Py_TYPE(self)->tp_free((PyObject *)self);
557 }
558
559 static PyObject *DrgnObject_value_impl(struct drgn_object *obj);
560
561 static PyObject *DrgnObject_compound_value(struct drgn_object *obj,
562 struct drgn_type *underlying_type)
563 {
564 struct drgn_error *err;
565
566 if (!drgn_type_is_complete(underlying_type)) {
567 PyErr_Format(PyExc_TypeError,
568 "cannot get value of incomplete %s",
569 drgn_type_kind_spelling[drgn_type_kind(underlying_type)]);
570 return NULL;
571 }
572
573 _cleanup_pydecref_ PyObject *dict = PyDict_New();
574 if (!dict)
575 return NULL;
576
577 DRGN_OBJECT(member, drgn_object_program(obj));
578 struct drgn_type_member *members = drgn_type_members(underlying_type);
579 size_t num_members = drgn_type_num_members(underlying_type);
580 for (size_t i = 0; i < num_members; i++) {
581 struct drgn_qualified_type member_type;
582 uint64_t member_bit_field_size;
583 err = drgn_member_type(&members[i], &member_type,
584 &member_bit_field_size);
585 if (err)
586 return set_drgn_error(err);
587
588 err = drgn_object_fragment(&member, obj, member_type,
589 members[i].bit_offset,
590 member_bit_field_size);
591 if (err)
592 return set_drgn_error(err);
593
594 _cleanup_pydecref_ PyObject *member_value =
595 DrgnObject_value_impl(&member);
596 if (!member_value)
597 return NULL;
598
599 if (members[i].name) {
600 if (PyDict_SetItemString(dict, members[i].name,
601 member_value))
602 return NULL;
603 } else {
604 if (PyDict_Update(dict, member_value))
605 return NULL;
606 }
607 }
608 return_ptr(dict);
609 }
610
611 static PyObject *DrgnObject_array_value(struct drgn_object *obj,
612 struct drgn_type *underlying_type)
613 {
614 struct drgn_error *err;
615
616 struct drgn_qualified_type element_type =
617 drgn_type_type(underlying_type);
618 uint64_t element_bit_size;
619 err = drgn_type_bit_size(element_type.type, &element_bit_size);
620 if (err)
621 return set_drgn_error(err);
622
623 uint64_t length = drgn_type_length(underlying_type);
624 if (length > PY_SSIZE_T_MAX) {
625 PyErr_NoMemory();
626 return NULL;
627 }
628
629 _cleanup_pydecref_ PyObject *list = PyList_New(length);
630 if (!list)
631 return NULL;
632
633 DRGN_OBJECT(element, drgn_object_program(obj));
634 for (uint64_t i = 0; i < length; i++) {
635 err = drgn_object_fragment(&element, obj, element_type,
636 i * element_bit_size, 0);
637 if (err)
638 return set_drgn_error(err);
639
640 PyObject *element_value = DrgnObject_value_impl(&element);
641 if (!element_value)
642 return NULL;
643 PyList_SET_ITEM(list, i, element_value);
644 }
645 return_ptr(list);
646 }
647
648 static PyObject *DrgnObject_value_impl(struct drgn_object *obj)
649 {
650 struct drgn_error *err;
651 struct drgn_type *underlying_type;
652
653 if (!drgn_object_encoding_is_complete(obj->encoding)) {
654 err = drgn_error_incomplete_type("cannot read object with %s type",
655 obj->type);
656 return set_drgn_error(err);
657 }
658
659 underlying_type = drgn_underlying_type(obj->type);
660 switch (obj->encoding) {
661 case DRGN_OBJECT_ENCODING_SIGNED: {
662 int64_t svalue;
663 err = drgn_object_read_signed(obj, &svalue);
664 if (err)
665 return set_drgn_error(err);
666 return PyLong_FromInt64(svalue);
667 }
668 case DRGN_OBJECT_ENCODING_UNSIGNED: {
669 uint64_t uvalue;
670 err = drgn_object_read_unsigned(obj, &uvalue);
671 if (err)
672 return set_drgn_error(err);
673 if (drgn_type_kind(underlying_type) == DRGN_TYPE_BOOL)
674 Py_RETURN_BOOL(uvalue);
675 else
676 return PyLong_FromUInt64(uvalue);
677 }
678 case DRGN_OBJECT_ENCODING_SIGNED_BIG:
679 case DRGN_OBJECT_ENCODING_UNSIGNED_BIG: {
680 union drgn_value value_mem;
681 const union drgn_value *value;
682 err = drgn_object_read_value(obj, &value_mem, &value);
683 if (err)
684 return set_drgn_error(err);
685 return _PyLong_FromByteArray((void *)value->bufp,
686 drgn_object_size(obj),
687 obj->little_endian,
688 obj->encoding
689 == DRGN_OBJECT_ENCODING_SIGNED_BIG);
690 }
691 case DRGN_OBJECT_ENCODING_FLOAT: {
692 double fvalue;
693
694 err = drgn_object_read_float(obj, &fvalue);
695 if (err)
696 return set_drgn_error(err);
697 return PyFloat_FromDouble(fvalue);
698 }
699 case DRGN_OBJECT_ENCODING_BUFFER:
700 switch (drgn_type_kind(underlying_type)) {
701 case DRGN_TYPE_STRUCT:
702 case DRGN_TYPE_UNION:
703 case DRGN_TYPE_CLASS:
704 return DrgnObject_compound_value(obj, underlying_type);
705 case DRGN_TYPE_ARRAY:
706 return DrgnObject_array_value(obj, underlying_type);
707 default:
708 break;
709 }
710 break;
711 default:
712 break;
713 }
714 UNREACHABLE();
715 }
716
717 static PyObject *DrgnObject_value(DrgnObject *self)
718 {
719 return DrgnObject_value_impl(&self->obj);
720 }
721
722 static PyObject *DrgnObject_string(DrgnObject *self)
723 {
724 struct drgn_error *err;
725 _cleanup_free_ char *str = NULL;
726 err = drgn_object_read_c_string(&self->obj, &str);
727 if (err)
728 return set_drgn_error(err);
729 return PyBytes_FromString(str);
730 }
731
732 static DrgnObject *DrgnObject_address_of(DrgnObject *self)
733 {
734 struct drgn_error *err;
735 _cleanup_pydecref_ DrgnObject *res =
736 DrgnObject_alloc(DrgnObject_prog(self));
737 if (!res)
738 return NULL;
739 err = drgn_object_address_of(&res->obj, &self->obj);
740 if (err)
741 return set_drgn_error(err);
742 return_ptr(res);
743 }
744
745 static DrgnObject *DrgnObject_read(DrgnObject *self)
746 {
747 struct drgn_error *err;
748 SWITCH_ENUM(self->obj.kind) {
749 case DRGN_OBJECT_VALUE:
750 Py_INCREF(self);
751 return self;
752 case DRGN_OBJECT_REFERENCE: {
753 _cleanup_pydecref_ DrgnObject *res =
754 DrgnObject_alloc(DrgnObject_prog(self));
755 if (!res)
756 return NULL;
757 err = drgn_object_read(&res->obj, &self->obj);
758 if (err)
759 return set_drgn_error(err);
760 return_ptr(res);
761 }
762 case DRGN_OBJECT_ABSENT:
763 return set_drgn_error(&drgn_error_object_absent);
764 default:
765 UNREACHABLE();
766 }
767 }
768
769 static PyObject *DrgnObject_to_bytes(DrgnObject *self)
770 {
771 struct drgn_error *err;
772 _cleanup_pydecref_ PyObject *buf =
773 PyBytes_FromStringAndSize(NULL, drgn_object_size(&self->obj));
774 if (!buf)
775 return NULL;
776 err = drgn_object_read_bytes(&self->obj, PyBytes_AS_STRING(buf));
777 if (err)
778 return set_drgn_error(err);
779 return_ptr(buf);
780 }
781
782 static DrgnObject *DrgnObject_from_bytes(PyTypeObject *type, PyObject *args,
783 PyObject *kwds)
784 {
785 static char *keywords[] = {
786 "prog", "type", "bytes", "bit_offset", "bit_field_size", NULL
787 };
788 struct drgn_error *err;
789 Program *prog;
790 PyObject *type_obj = Py_None;
791 Py_buffer bytes;
792 struct index_arg bit_offset = {};
793 struct index_arg bit_field_size = { .allow_none = true, .is_none = true };
794 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!Oy*|$O&O&:from_bytes_",
795 keywords, &Program_type, &prog,
796 &type_obj, &bytes, index_converter,
797 &bit_offset, index_converter,
798 &bit_field_size))
799 return NULL;
800
801 DrgnObject *res = NULL;
802 struct drgn_qualified_type qualified_type;
803 if (Program_type_arg(prog, type_obj, false, &qualified_type) == -1)
804 goto out;
805
806 if (!bit_field_size.is_none && bit_field_size.uvalue == 0) {
807 PyErr_SetString(PyExc_ValueError,
808 "bit field size cannot be zero");
809 goto out;
810 }
811
812 res = DrgnObject_alloc(prog);
813 if (!res)
814 goto out;
815
816 err = drgn_object_set_from_buffer(&res->obj, qualified_type, bytes.buf,
817 bytes.len, bit_offset.uvalue,
818 bit_field_size.uvalue);
819 if (err) {
820 set_drgn_error(err);
821 Py_DECREF(res);
822 res = NULL;
823 goto out;
824 }
825
826 out:
827 PyBuffer_Release(&bytes);
828 return res;
829 }
830
831 static int append_bit_offset(PyObject *parts, uint8_t bit_offset)
832 {
833 if (bit_offset == 0)
834 return 0;
835 return append_format(parts, ", bit_offset=%d", bit_offset);
836 }
837
838 static PyObject *DrgnObject_repr(DrgnObject *self)
839 {
840 struct drgn_error *err;
841 _cleanup_pydecref_ PyObject *parts = PyList_New(0);
842 if (!parts)
843 return NULL;
844
845 _cleanup_free_ char *type_name = NULL;
846 err = drgn_format_type_name(drgn_object_qualified_type(&self->obj),
847 &type_name);
848 if (err)
849 return set_drgn_error(err);
850 _cleanup_pydecref_ PyObject *tmp = PyUnicode_FromString(type_name);
851 if (!tmp)
852 return NULL;
853
854 if (append_format(parts, "Object(prog, %R", tmp) == -1)
855 return NULL;
856
857 SWITCH_ENUM(self->obj.kind) {
858 case DRGN_OBJECT_VALUE: {
859 if (append_string(parts, ", value=") == -1)
860 return NULL;
861 _cleanup_pydecref_ PyObject *value_obj = DrgnObject_value(self);
862 if (!value_obj)
863 return NULL;
864 _cleanup_pydecref_ PyObject *part;
865 if (drgn_type_kind(drgn_underlying_type(self->obj.type))
866 == DRGN_TYPE_POINTER)
867 part = PyNumber_ToBase(value_obj, 16);
868 else
869 part = PyObject_Repr(value_obj);
870 if (!part)
871 return NULL;
872 if (PyList_Append(parts, part) == -1)
873 return NULL;
874 break;
875 }
876 case DRGN_OBJECT_REFERENCE: {
877 char buf[17];
878 snprintf(buf, sizeof(buf), "%" PRIx64, self->obj.address);
879 if (append_format(parts, ", address=0x%s", buf) == -1 ||
880 append_bit_offset(parts, self->obj.bit_offset) == -1)
881 return NULL;
882 break;
883 }
884 case DRGN_OBJECT_ABSENT:
885 if (self->obj.absence_reason != DRGN_ABSENCE_REASON_OTHER) {
886 if (append_format(parts, ", absence_reason=") < 0
887 || append_attr_str(parts, (PyObject *)self,
888 "absence_reason_") < 0)
889 return NULL;
890 }
891 break;
892 default:
893 UNREACHABLE();
894 }
895
896 if (self->obj.is_bit_field &&
897 append_format(parts, ", bit_field_size=%llu",
898 (unsigned long long)self->obj.bit_size) == -1)
899 return NULL;
900
901 if (append_string(parts, ")") == -1)
902 return NULL;
903
904 return join_strings(parts);
905 }
906
907 static PyObject *DrgnObject_str(DrgnObject *self)
908 {
909 _cleanup_free_ char *str = NULL;
910 struct drgn_error *err = drgn_format_object(&self->obj, NULL, &str);
911 if (err)
912 return set_drgn_error(err);
913 return PyUnicode_FromString(str);
914 }
915
916 struct format_object_flag_arg {
917 enum drgn_format_object_flags *flags;
918 enum drgn_format_object_flags value;
919 };
920
921 static int format_object_flag_converter(PyObject *o, void *p)
922 {
923 struct format_object_flag_arg *arg = p;
924 int ret;
925
926 if (o == Py_None)
927 return 1;
928 ret = PyObject_IsTrue(o);
929 if (ret == -1)
930 return 0;
931 if (ret)
932 *arg->flags |= arg->value;
933 else
934 *arg->flags &= ~arg->value;
935 return 1;
936 }
937
938 static PyObject *DrgnObject_format(DrgnObject *self, PyObject *args,
939 PyObject *kwds)
940 {
941 #define FLAGS \
942 X(dereference, DRGN_FORMAT_OBJECT_DEREFERENCE) \
943 X(symbolize, DRGN_FORMAT_OBJECT_SYMBOLIZE) \
944 X(string, DRGN_FORMAT_OBJECT_STRING) \
945 X(char, DRGN_FORMAT_OBJECT_CHAR) \
946 X(type_name, DRGN_FORMAT_OBJECT_TYPE_NAME) \
947 X(member_type_names, DRGN_FORMAT_OBJECT_MEMBER_TYPE_NAMES) \
948 X(element_type_names, DRGN_FORMAT_OBJECT_ELEMENT_TYPE_NAMES) \
949 X(members_same_line, DRGN_FORMAT_OBJECT_MEMBERS_SAME_LINE) \
950 X(elements_same_line, DRGN_FORMAT_OBJECT_ELEMENTS_SAME_LINE) \
951 X(member_names, DRGN_FORMAT_OBJECT_MEMBER_NAMES) \
952 X(element_indices, DRGN_FORMAT_OBJECT_ELEMENT_INDICES) \
953 X(implicit_members, DRGN_FORMAT_OBJECT_IMPLICIT_MEMBERS) \
954 X(implicit_elements, DRGN_FORMAT_OBJECT_IMPLICIT_ELEMENTS)
955
956 static char *keywords[] = {
957 #define X(name, value) #name,
958 FLAGS
959 #undef X
960 "columns",
961 "integer_base",
962 NULL,
963 };
964 struct drgn_error *err;
965 PyObject *columns_obj = Py_None;
966 PyObject *integer_base_obj = Py_None;
967 struct drgn_format_object_options options = {
968 .columns = SIZE_MAX,
969 .flags = DRGN_FORMAT_OBJECT_PRETTY,
970 .integer_base = 10,
971 };
972 #define X(name, value) \
973 struct format_object_flag_arg name##_arg = { &options.flags, value };
974 FLAGS
975 #undef X
976
977 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|$"
978 #define X(name, value) "O&"
979 FLAGS
980 #undef X
981 "OO:format_", keywords,
982 #define X(name, value) format_object_flag_converter, &name##_arg,
983 FLAGS
984 #undef X
985 &columns_obj, &integer_base_obj))
986 return NULL;
987
988 if (columns_obj != Py_None) {
989 columns_obj = PyNumber_Index(columns_obj);
990 if (!columns_obj)
991 return NULL;
992 options.columns = PyLong_AsSize_t(columns_obj);
993 Py_DECREF(columns_obj);
994 if (options.columns == (size_t)-1 && PyErr_Occurred())
995 return NULL;
996 }
997
998 if (integer_base_obj != Py_None) {
999 int overflow;
1000 long integer_base = PyLong_AsLongAndOverflow(integer_base_obj,
1001 &overflow);
1002 if (integer_base == -1 && PyErr_Occurred())
1003 return NULL;
1004 if (overflow
1005 || integer_base < INT_MIN || integer_base > INT_MAX) {
1006 PyErr_SetString(PyExc_ValueError,
1007 "invalid integer base");
1008 return NULL;
1009 }
1010 options.integer_base = integer_base;
1011 }
1012
1013 _cleanup_free_ char *str = NULL;
1014 err = drgn_format_object(&self->obj, &options, &str);
1015 if (err)
1016 return set_drgn_error(err);
1017 return PyUnicode_FromString(str);
1018
1019 #undef FLAGS
1020 }
1021
1022 static Program *DrgnObject_get_prog(DrgnObject *self, void *arg)
1023 {
1024 Py_INCREF(DrgnObject_prog(self));
1025 return DrgnObject_prog(self);
1026 }
1027
1028 static PyObject *DrgnObject_get_type(DrgnObject *self, void *arg)
1029 {
1030 return DrgnType_wrap(drgn_object_qualified_type(&self->obj));
1031 }
1032
1033 static PyObject *DrgnObject_get_absent(DrgnObject *self, void *arg)
1034 {
1035 Py_RETURN_BOOL(self->obj.kind == DRGN_OBJECT_ABSENT);
1036 }
1037
1038 static PyObject *DrgnObject_get_absence_reason(DrgnObject *self, void *arg)
1039 {
1040 if (self->obj.kind != DRGN_OBJECT_ABSENT)
1041 Py_RETURN_NONE;
1042 return PyObject_CallFunction(AbsenceReason_class, "i",
1043 (int)self->obj.absence_reason);
1044 }
1045
1046 static PyObject *DrgnObject_get_address(DrgnObject *self, void *arg)
1047 {
1048 if (self->obj.kind == DRGN_OBJECT_REFERENCE)
1049 return PyLong_FromUInt64(self->obj.address);
1050 else
1051 Py_RETURN_NONE;
1052 }
1053
1054 static PyObject *DrgnObject_get_bit_offset(DrgnObject *self, void *arg)
1055 {
1056 SWITCH_ENUM(self->obj.kind) {
1057 case DRGN_OBJECT_REFERENCE:
1058 return PyLong_FromUInt8(self->obj.bit_offset);
1059 case DRGN_OBJECT_VALUE:
1060 case DRGN_OBJECT_ABSENT:
1061 Py_RETURN_NONE;
1062 default:
1063 UNREACHABLE();
1064 }
1065 }
1066
1067 static PyObject *DrgnObject_get_bit_field_size(DrgnObject *self, void *arg)
1068 {
1069 if (self->obj.is_bit_field)
1070 return PyLong_FromUInt64(self->obj.bit_size);
1071 else
1072 Py_RETURN_NONE;
1073 }
1074
1075 static int DrgnObject_binary_operand(PyObject *self, PyObject *other,
1076 struct drgn_object **obj,
1077 struct drgn_object *tmp)
1078 {
1079 if (PyObject_TypeCheck(self, &DrgnObject_type)) {
1080 *obj = &((DrgnObject *)self)->obj;
1081 return 0;
1082 } else {
1083 *obj = tmp;
1084 /* If self isn't a DrgnObject, then other must be. */
1085 drgn_object_init(tmp,
1086 drgn_object_program(&((DrgnObject *)other)->obj));
1087 return DrgnObject_literal(tmp, self);
1088 }
1089 }
1090
1091 #define DrgnObject_BINARY_OP(op) \
1092 static PyObject *DrgnObject_##op(PyObject *left, PyObject *right) \
1093 { \
1094 struct drgn_error *err; \
1095 struct drgn_object *lhs, lhs_tmp, *rhs, rhs_tmp; \
1096 DrgnObject *res = NULL; \
1097 int ret; \
1098 \
1099 ret = DrgnObject_binary_operand(left, right, &lhs, &lhs_tmp); \
1100 if (ret) \
1101 goto out; \
1102 ret = DrgnObject_binary_operand(right, left, &rhs, &rhs_tmp); \
1103 if (ret) \
1104 goto out_lhs; \
1105 \
1106 res = DrgnObject_alloc(container_of(drgn_object_program(lhs), Program, \
1107 prog)); \
1108 if (!res) { \
1109 ret = -1; \
1110 goto out_rhs; \
1111 } \
1112 \
1113 err = drgn_object_##op(&res->obj, lhs, rhs); \
1114 if (err) { \
1115 set_drgn_error(err); \
1116 Py_DECREF(res); \
1117 ret = -1; \
1118 goto out_rhs; \
1119 } \
1120 \
1121 out_rhs: \
1122 if (rhs == &rhs_tmp) \
1123 drgn_object_deinit(&rhs_tmp); \
1124 out_lhs: \
1125 if (lhs == &lhs_tmp) \
1126 drgn_object_deinit(&lhs_tmp); \
1127 out: \
1128 if (ret == -1) \
1129 return NULL; \
1130 else if (ret) \
1131 Py_RETURN_NOTIMPLEMENTED; \
1132 else \
1133 return (PyObject *)res; \
1134 }
1135 DrgnObject_BINARY_OP(add)
1136 DrgnObject_BINARY_OP(sub)
1137 DrgnObject_BINARY_OP(mul)
1138 DrgnObject_BINARY_OP(div)
1139 DrgnObject_BINARY_OP(mod)
1140 DrgnObject_BINARY_OP(lshift)
1141 DrgnObject_BINARY_OP(rshift)
1142 DrgnObject_BINARY_OP(and)
1143 DrgnObject_BINARY_OP(or)
1144 DrgnObject_BINARY_OP(xor)
1145 #undef DrgnObject_BINARY_OP
1146
1147 #define DrgnObject_UNARY_OP(op) \
1148 static DrgnObject *DrgnObject_##op(DrgnObject *self) \
1149 { \
1150 struct drgn_error *err; \
1151 _cleanup_pydecref_ DrgnObject *res = \
1152 DrgnObject_alloc(DrgnObject_prog(self)); \
1153 if (!res) \
1154 return NULL; \
1155 err = drgn_object_##op(&res->obj, &self->obj); \
1156 if (err) \
1157 return set_drgn_error(err); \
1158 return_ptr(res); \
1159 }
1160 DrgnObject_UNARY_OP(pos)
1161 DrgnObject_UNARY_OP(neg)
1162 DrgnObject_UNARY_OP(not)
1163 #undef DrgnObject_UNARY_OP
1164
1165 static int DrgnObject_bool(DrgnObject *self)
1166 {
1167 struct drgn_error *err;
1168 bool ret;
1169
1170 err = drgn_object_bool(&self->obj, &ret);
1171 if (err) {
1172 set_drgn_error(err);
1173 return -1;
1174 }
1175 return ret;
1176 }
1177
1178 static PyObject *DrgnObject_int(DrgnObject *self)
1179 {
1180 struct drgn_error *err;
1181 SWITCH_ENUM(self->obj.encoding) {
1182 case DRGN_OBJECT_ENCODING_SIGNED:
1183 case DRGN_OBJECT_ENCODING_UNSIGNED:
1184 case DRGN_OBJECT_ENCODING_SIGNED_BIG:
1185 case DRGN_OBJECT_ENCODING_UNSIGNED_BIG:
1186 return DrgnObject_value(self);
1187 case DRGN_OBJECT_ENCODING_FLOAT: {
1188 double fvalue;
1189 err = drgn_object_read_float(&self->obj, &fvalue);
1190 if (err)
1191 return set_drgn_error(err);
1192 return PyLong_FromDouble(fvalue);
1193 }
1194 case DRGN_OBJECT_ENCODING_BUFFER:
1195 case DRGN_OBJECT_ENCODING_NONE:
1196 case DRGN_OBJECT_ENCODING_INCOMPLETE_BUFFER:
1197 case DRGN_OBJECT_ENCODING_INCOMPLETE_INTEGER:
1198 return set_error_type_name("cannot convert '%s' to int",
1199 drgn_object_qualified_type(&self->obj));
1200 default:
1201 UNREACHABLE();
1202 }
1203 }
1204
1205 static PyObject *DrgnObject_float(DrgnObject *self)
1206 {
1207 struct drgn_error *err;
1208 SWITCH_ENUM(self->obj.encoding) {
1209 case DRGN_OBJECT_ENCODING_FLOAT: {
1210 double fvalue;
1211 err = drgn_object_read_float(&self->obj, &fvalue);
1212 if (err)
1213 return set_drgn_error(err);
1214 return PyFloat_FromDouble(fvalue);
1215 }
1216 case DRGN_OBJECT_ENCODING_SIGNED:
1217 case DRGN_OBJECT_ENCODING_UNSIGNED:
1218 case DRGN_OBJECT_ENCODING_SIGNED_BIG:
1219 case DRGN_OBJECT_ENCODING_UNSIGNED_BIG: {
1220 if (drgn_type_kind(drgn_underlying_type(self->obj.type))
1221 != DRGN_TYPE_POINTER) {
1222 _cleanup_pydecref_ PyObject *value =
1223 DrgnObject_value(self);
1224 if (!value)
1225 return NULL;
1226 return PyObject_CallFunctionObjArgs((PyObject *)&PyFloat_Type,
1227 value, NULL);
1228 }
1229 fallthrough;
1230 }
1231 case DRGN_OBJECT_ENCODING_BUFFER:
1232 case DRGN_OBJECT_ENCODING_NONE:
1233 case DRGN_OBJECT_ENCODING_INCOMPLETE_BUFFER:
1234 case DRGN_OBJECT_ENCODING_INCOMPLETE_INTEGER:
1235 return set_error_type_name("cannot convert '%s' to float",
1236 drgn_object_qualified_type(&self->obj));
1237 default:
1238 UNREACHABLE();
1239 }
1240 }
1241
1242 static PyObject *DrgnObject_index(DrgnObject *self)
1243 {
1244 SWITCH_ENUM(self->obj.encoding) {
1245 case DRGN_OBJECT_ENCODING_SIGNED:
1246 case DRGN_OBJECT_ENCODING_UNSIGNED:
1247 case DRGN_OBJECT_ENCODING_SIGNED_BIG:
1248 case DRGN_OBJECT_ENCODING_UNSIGNED_BIG:
1249 return DrgnObject_value(self);
1250 case DRGN_OBJECT_ENCODING_FLOAT:
1251 case DRGN_OBJECT_ENCODING_BUFFER:
1252 case DRGN_OBJECT_ENCODING_NONE:
1253 case DRGN_OBJECT_ENCODING_INCOMPLETE_BUFFER:
1254 case DRGN_OBJECT_ENCODING_INCOMPLETE_INTEGER:
1255 return set_error_type_name("'%s' object cannot be interpreted as an integer",
1256 drgn_object_qualified_type(&self->obj));
1257 default:
1258 UNREACHABLE();
1259 }
1260 }
1261
1262 static PyObject *DrgnObject_round(DrgnObject *self, PyObject *args,
1263 PyObject *kwds)
1264 {
1265 static char *keywords[] = {"ndigits", NULL};
1266 PyObject *ndigits = Py_None;
1267 if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:round", keywords,
1268 &ndigits))
1269 return NULL;
1270
1271 if (!drgn_type_is_arithmetic(self->obj.type)) {
1272 return set_error_type_name("cannot round '%s'",
1273 drgn_object_qualified_type(&self->obj));
1274 }
1275
1276 _cleanup_pydecref_ PyObject *value = DrgnObject_value(self);
1277 if (!value)
1278 return NULL;
1279
1280 if (ndigits == Py_None)
1281 return PyObject_CallMethod(value, "__round__", NULL);
1282
1283 _cleanup_pydecref_ PyObject *rounded_value =
1284 PyObject_CallMethod(value, "__round__", "O", ndigits);
1285 if (!rounded_value)
1286 return NULL;
1287
1288 _cleanup_pydecref_ PyObject *type = DrgnObject_get_type(self, NULL);
1289 if (!type)
1290 return NULL;
1291 return PyObject_CallFunctionObjArgs((PyObject *)&DrgnObject_type,
1292 DrgnObject_prog(self), type,
1293 rounded_value, NULL);
1294 }
1295
1296 #define DrgnObject_round_method(func) \
1297 static PyObject *DrgnObject_##func(DrgnObject *self) \
1298 { \
1299 if (!drgn_type_is_arithmetic(self->obj.type)) { \
1300 return set_error_type_name("cannot round '%s'", \
1301 drgn_object_qualified_type(&self->obj));\
1302 } \
1303 if (self->obj.encoding != DRGN_OBJECT_ENCODING_FLOAT) \
1304 return DrgnObject_value(self); \
1305 union drgn_value value_mem; \
1306 const union drgn_value *value; \
1307 struct drgn_error *err = \
1308 drgn_object_read_value(&self->obj, &value_mem, &value); \
1309 if (err) \
1310 return set_drgn_error(err); \
1311 PyObject *ret = PyLong_FromDouble(func(value->fvalue)); \
1312 drgn_object_deinit_value(&self->obj, value); \
1313 return ret; \
1314 }
1315 DrgnObject_round_method(trunc)
1316 DrgnObject_round_method(floor)
1317 DrgnObject_round_method(ceil)
1318
1319 static PyObject *DrgnObject_richcompare(PyObject *left, PyObject *right, int op)
1320 {
1321 struct drgn_error *err;
1322 struct drgn_object *lhs, lhs_tmp, *rhs, rhs_tmp;
1323 int ret, cmp;
1324
1325 ret = DrgnObject_binary_operand(left, right, &lhs, &lhs_tmp);
1326 if (ret)
1327 goto out;
1328 ret = DrgnObject_binary_operand(right, left, &rhs, &rhs_tmp);
1329 if (ret)
1330 goto out_lhs;
1331
1332 err = drgn_object_cmp(lhs, rhs, &cmp);
1333 if (err) {
1334 set_drgn_error(err);
1335 ret = -1;
1336 }
1337
1338 if (rhs == &rhs_tmp)
1339 drgn_object_deinit(&rhs_tmp);
1340 out_lhs:
1341 if (lhs == &lhs_tmp)
1342 drgn_object_deinit(&lhs_tmp);
1343 out:
1344 if (ret == -1)
1345 return NULL;
1346 else if (ret)
1347 Py_RETURN_NOTIMPLEMENTED;
1348 else
1349 Py_RETURN_RICHCOMPARE(cmp, 0, op);
1350 }
1351
1352 static DrgnObject *DrgnObject_member(DrgnObject *self, PyObject *args,
1353 PyObject *kwds)
1354 {
1355 static char *keywords[] = {"name", NULL};
1356 struct drgn_error *err;
1357 const char *name;
1358 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:member_", keywords,
1359 &name))
1360 return NULL;
1361
1362 _cleanup_pydecref_ DrgnObject *res =
1363 DrgnObject_alloc(DrgnObject_prog(self));
1364 if (!res)
1365 return NULL;
1366
1367 if (self->obj.encoding == DRGN_OBJECT_ENCODING_UNSIGNED) {
1368 err = drgn_object_member_dereference(&res->obj, &self->obj,
1369 name);
1370 } else {
1371 err = drgn_object_member(&res->obj, &self->obj, name);
1372 }
1373 if (err)
1374 return set_drgn_error(err);
1375 return_ptr(res);
1376 }
1377
1378 static DrgnObject *DrgnObject_subobject(DrgnObject *self, PyObject *args,
1379 PyObject *kwds)
1380 {
1381 static char *keywords[] = {"designator", NULL};
1382 struct drgn_error *err;
1383 const char *designator;
1384 if (!PyArg_ParseTupleAndKeywords(args, kwds, "s:subobject_", keywords,
1385 &designator))
1386 return NULL;
1387
1388 _cleanup_pydecref_ DrgnObject *res =
1389 DrgnObject_alloc(DrgnObject_prog(self));
1390 if (!res)
1391 return NULL;
1392 err = drgn_object_subobject(&res->obj, &self->obj, designator);
1393 if (err)
1394 return set_drgn_error(err);
1395 return_ptr(res);
1396 }
1397
1398 static PyObject *DrgnObject_getattro(DrgnObject *self, PyObject *attr_name)
1399 {
1400 struct drgn_error *err;
1401
1402 PyObject *attr = _PyObject_GenericGetAttrWithDict((PyObject *)self,
1403 attr_name, NULL, 1);
1404 if (attr || PyErr_Occurred())
1405 return attr;
1406
1407 const char *name = PyUnicode_AsUTF8(attr_name);
1408 if (!name)
1409 return NULL;
1410
1411 _cleanup_pydecref_ DrgnObject *res =
1412 DrgnObject_alloc(DrgnObject_prog(self));
1413 if (!res)
1414 return NULL;
1415
1416 if (self->obj.encoding == DRGN_OBJECT_ENCODING_UNSIGNED) {
1417 err = drgn_object_member_dereference(&res->obj, &self->obj,
1418 name);
1419 } else {
1420 err = drgn_object_member(&res->obj, &self->obj, name);
1421 }
1422 if (drgn_error_catch(&err, DRGN_ERROR_TYPE)) {
1423 // If the object doesn't have a compound type, raise a generic
1424 // AttributeError.
1425 return PyErr_Format(PyExc_AttributeError,
1426 "'%s' object has no attribute '%U'",
1427 Py_TYPE(self)->tp_name, attr_name);
1428 } else if (err && err->code == DRGN_ERROR_LOOKUP) {
1429 PyErr_SetString(PyExc_AttributeError, err->message);
1430 drgn_error_destroy(err);
1431 return NULL;
1432 } else if (err) {
1433 return set_drgn_error(err);
1434 }
1435 return (PyObject *)no_cleanup_ptr(res);
1436 }
1437
1438 static Py_ssize_t DrgnObject_length(DrgnObject *self)
1439 {
1440 struct drgn_type *underlying_type;
1441 uint64_t length;
1442
1443 underlying_type = drgn_underlying_type(self->obj.type);
1444 if (drgn_type_kind(underlying_type) != DRGN_TYPE_ARRAY ||
1445 !drgn_type_is_complete(underlying_type)) {
1446 set_error_type_name("'%s' has no len()",
1447 drgn_object_qualified_type(&self->obj));
1448 return -1;
1449 }
1450 length = drgn_type_length(underlying_type);
1451 if (length > PY_SSIZE_T_MAX) {
1452 PyErr_SetString(PyExc_OverflowError, "length is too large");
1453 return -1;
1454 }
1455 return length;
1456 }
1457
1458 static DrgnObject *DrgnObject_subscript_impl(DrgnObject *self,
1459 int64_t index)
1460 {
1461 struct drgn_error *err;
1462 _cleanup_pydecref_ DrgnObject *res =
1463 DrgnObject_alloc(DrgnObject_prog(self));
1464 if (!res)
1465 return NULL;
1466 err = drgn_object_subscript(&res->obj, &self->obj, index);
1467 if (err)
1468 return set_drgn_error(err);
1469 return_ptr(res);
1470 }
1471
1472 static DrgnObject *DrgnObject_subscript(DrgnObject *self, PyObject *item)
1473 {
1474 if (PyIndex_Check(item)) {
1475 int64_t index;
1476 if (PyLong_AsInt64(item, &index))
1477 return NULL;
1478 return DrgnObject_subscript_impl(self, index);
1479 } else if (PySlice_Check(item)) {
1480 PySliceObject *slice = (PySliceObject *)item;
1481 int64_t start, stop;
1482 if (slice->start == Py_None)
1483 start = 0;
1484 else if (PyLong_AsInt64(slice->start, &start))
1485 return NULL;
1486 if (slice->stop == Py_None) {
1487 struct drgn_type *underlying_type =
1488 drgn_underlying_type(self->obj.type);
1489 if (drgn_type_kind(underlying_type) != DRGN_TYPE_ARRAY
1490 || !drgn_type_is_complete(underlying_type)) {
1491 set_error_type_name("'%s' has no length; slice stop must be given",
1492 drgn_object_qualified_type(&self->obj));
1493 return NULL;
1494 }
1495 uint64_t length = drgn_type_length(underlying_type);
1496 if (length > INT64_MAX) {
1497 PyErr_SetString(PyExc_OverflowError,
1498 "length is too large");
1499 return NULL;
1500 }
1501 stop = length;
1502 } else if (PyLong_AsInt64(slice->stop, &stop)) {
1503 return NULL;
1504 }
1505 if (slice->step != Py_None) {
1506 Py_ssize_t step =
1507 PyNumber_AsSsize_t(slice->step,
1508 PyExc_OverflowError);
1509 if (step == -1 && PyErr_Occurred())
1510 return NULL;
1511 if (step != 1) {
1512 PyErr_SetString(PyExc_ValueError,
1513 "object slice step must be 1");
1514 return NULL;
1515 }
1516 }
1517 struct drgn_error *err;
1518 _cleanup_pydecref_ DrgnObject *res =
1519 DrgnObject_alloc(DrgnObject_prog(self));
1520 if (!res)
1521 return NULL;
1522 err = drgn_object_slice(&res->obj, &self->obj, start, stop);
1523 if (err)
1524 return set_drgn_error(err);
1525 return_ptr(res);
1526 } else {
1527 PyErr_Format(PyExc_TypeError,
1528 "object subscript must be integer or slice, not %.200s",
1529 Py_TYPE(item)->tp_name);
1530 return NULL;
1531 }
1532 }
1533
1534 static ObjectIterator *DrgnObject_iter_impl(DrgnObject *self, bool reversed)
1535 {
1536 struct drgn_type *underlying_type =
1537 drgn_underlying_type(self->obj.type);
1538 if (drgn_type_kind(underlying_type) != DRGN_TYPE_ARRAY ||
1539 !drgn_type_is_complete(underlying_type)) {
1540 set_error_type_name("'%s' is not iterable",
1541 drgn_object_qualified_type(&self->obj));
1542 return NULL;
1543 }
1544
1545 ObjectIterator *it = call_tp_alloc(ObjectIterator);
1546 if (!it)
1547 return NULL;
1548 it->obj = self;
1549 Py_INCREF(self);
1550 if (reversed) {
1551 it->index = drgn_type_length(underlying_type) - 1;
1552 it->end = -1;
1553 it->step = -1;
1554 } else {
1555 it->index = 0;
1556 it->end = drgn_type_length(underlying_type);
1557 it->step = 1;
1558 }
1559 return it;
1560 }
1561
1562 static ObjectIterator *DrgnObject_iter(DrgnObject *self)
1563 {
1564 return DrgnObject_iter_impl(self, false);
1565 }
1566
1567 static ObjectIterator *DrgnObject_reversed(DrgnObject *self)
1568 {
1569 return DrgnObject_iter_impl(self, true);
1570 }
1571
1572 static int add_to_dir(PyObject *dir, struct drgn_type *type)
1573 {
1574 struct drgn_error *err;
1575
1576 type = drgn_underlying_type(type);
1577 if (!drgn_type_has_members(type))
1578 return 0;
1579
1580 struct drgn_type_member *members = drgn_type_members(type);
1581 size_t num_members = drgn_type_num_members(type);
1582 for (size_t i = 0; i < num_members; i++) {
1583 struct drgn_type_member *member;
1584
1585 member = &members[i];
1586 if (member->name) {
1587 _cleanup_pydecref_ PyObject *str =
1588 PyUnicode_FromString(member->name);
1589 if (!str)
1590 return -1;
1591 if (PyList_Append(dir, str) == -1)
1592 return -1;
1593 } else {
1594 struct drgn_qualified_type member_type;
1595 err = drgn_member_type(member, &member_type, NULL);
1596 if (err) {
1597 set_drgn_error(err);
1598 return -1;
1599 }
1600 if (add_to_dir(dir, member_type.type) == -1)
1601 return -1;
1602 }
1603 }
1604 return 0;
1605 }
1606
1607 static PyObject *DrgnObject_dir(DrgnObject *self)
1608 {
1609 _Py_IDENTIFIER(__dir__);
1610 _cleanup_pydecref_ PyObject *method =
1611 _PyObject_GetAttrId((PyObject *)Py_TYPE(self)->tp_base,
1612 &PyId___dir__);
1613 if (!method)
1614 return NULL;
1615 _cleanup_pydecref_ PyObject *dir =
1616 PyObject_CallFunctionObjArgs(method, self, NULL);
1617 if (!dir)
1618 return NULL;
1619
1620 struct drgn_type *type = drgn_underlying_type(self->obj.type);
1621 if (drgn_type_kind(type) == DRGN_TYPE_POINTER)
1622 type = drgn_type_type(type).type;
1623 if (add_to_dir(dir, type) == -1)
1624 return NULL;
1625
1626 return_ptr(dir);
1627 }
1628
1629 static PyGetSetDef DrgnObject_getset[] = {
1630 {"prog_", (getter)DrgnObject_get_prog, NULL, drgn_Object_prog__DOC},
1631 {"type_", (getter)DrgnObject_get_type, NULL, drgn_Object_type__DOC},
1632 {"absent_", (getter)DrgnObject_get_absent, NULL,
1633 drgn_Object_absent__DOC},
1634 {"absence_reason_", (getter)DrgnObject_get_absence_reason, NULL,
1635 drgn_Object_absence_reason__DOC},
1636 {"address_", (getter)DrgnObject_get_address, NULL,
1637 drgn_Object_address__DOC},
1638 {"bit_offset_", (getter)DrgnObject_get_bit_offset, NULL,
1639 drgn_Object_bit_offset__DOC},
1640 {"bit_field_size_", (getter)DrgnObject_get_bit_field_size, NULL,
1641 drgn_Object_bit_field_size__DOC},
1642 {},
1643 };
1644
1645 static PyMethodDef DrgnObject_methods[] = {
1646 {"__getitem__", (PyCFunction)DrgnObject_subscript,
1647 METH_O | METH_COEXIST, drgn_Object___getitem___DOC},
1648 {"value_", (PyCFunction)DrgnObject_value, METH_NOARGS,
1649 drgn_Object_value__DOC},
1650 {"string_", (PyCFunction)DrgnObject_string, METH_NOARGS,
1651 drgn_Object_string__DOC},
1652 {"member_", (PyCFunction)DrgnObject_member,
1653 METH_VARARGS | METH_KEYWORDS, drgn_Object_member__DOC},
1654 {"subobject_", (PyCFunction)DrgnObject_subobject,
1655 METH_VARARGS | METH_KEYWORDS, drgn_Object_subobject__DOC},
1656 {"address_of_", (PyCFunction)DrgnObject_address_of, METH_NOARGS,
1657 drgn_Object_address_of__DOC},
1658 {"read_", (PyCFunction)DrgnObject_read, METH_NOARGS,
1659 drgn_Object_read__DOC},
1660 {"to_bytes_", (PyCFunction)DrgnObject_to_bytes, METH_NOARGS,
1661 drgn_Object_to_bytes__DOC},
1662 {"from_bytes_", (PyCFunction)DrgnObject_from_bytes,
1663 METH_CLASS | METH_VARARGS | METH_KEYWORDS,
1664 drgn_Object_from_bytes__DOC},
1665 {"format_", (PyCFunction)DrgnObject_format,
1666 METH_VARARGS | METH_KEYWORDS, drgn_Object_format__DOC},
1667 {"__reversed__", (PyCFunction)DrgnObject_reversed, METH_NOARGS},
1668 {"__round__", (PyCFunction)DrgnObject_round,
1669 METH_VARARGS | METH_KEYWORDS},
1670 {"__trunc__", (PyCFunction)DrgnObject_trunc, METH_NOARGS},
1671 {"__floor__", (PyCFunction)DrgnObject_floor, METH_NOARGS},
1672 {"__ceil__", (PyCFunction)DrgnObject_ceil, METH_NOARGS},
1673 {"__dir__", (PyCFunction)DrgnObject_dir, METH_NOARGS,
1674 "dir() implementation which includes structure, union, and class members."},
1675 {"_repr_pretty_", (PyCFunction)repr_pretty_from_str,
1676 METH_VARARGS | METH_KEYWORDS},
1677 {},
1678 };
1679
1680 static PyNumberMethods DrgnObject_as_number = {
1681 .nb_add = (binaryfunc)DrgnObject_add,
1682 .nb_subtract = (binaryfunc)DrgnObject_sub,
1683 .nb_multiply = (binaryfunc)DrgnObject_mul,
1684 .nb_remainder = (binaryfunc)DrgnObject_mod,
1685 .nb_negative = (unaryfunc)DrgnObject_neg,
1686 .nb_positive = (unaryfunc)DrgnObject_pos,
1687 .nb_bool = (inquiry)DrgnObject_bool,
1688 .nb_invert = (unaryfunc)DrgnObject_not,
1689 .nb_lshift = (binaryfunc)DrgnObject_lshift,
1690 .nb_rshift = (binaryfunc)DrgnObject_rshift,
1691 .nb_and = (binaryfunc)DrgnObject_and,
1692 .nb_xor = (binaryfunc)DrgnObject_xor,
1693 .nb_or = (binaryfunc)DrgnObject_or,
1694 .nb_int = (unaryfunc)DrgnObject_int,
1695 .nb_float = (unaryfunc)DrgnObject_float,
1696 .nb_true_divide = (binaryfunc)DrgnObject_div,
1697 .nb_index = (unaryfunc)DrgnObject_index,
1698 };
1699
1700 static PyMappingMethods DrgnObject_as_mapping = {
1701 .mp_length = (lenfunc)DrgnObject_length,
1702 .mp_subscript = (binaryfunc)DrgnObject_subscript,
1703 };
1704
1705 static int DrgnObject_traverse(DrgnObject *self, visitproc visit, void *arg)
1706 {
1707 Py_VISIT(DrgnObject_prog(self));
1708 return 0;
1709 }
1710
1711 PyTypeObject DrgnObject_type = {
1712 PyVarObject_HEAD_INIT(NULL, 0)
1713 .tp_name = "_drgn.Object",
1714 .tp_basicsize = sizeof(DrgnObject),
1715 .tp_dealloc = (destructor)DrgnObject_dealloc,
1716 .tp_repr = (reprfunc)DrgnObject_repr,
1717 .tp_as_number = &DrgnObject_as_number,
1718 .tp_as_mapping = &DrgnObject_as_mapping,
1719 .tp_str = (reprfunc)DrgnObject_str,
1720 .tp_getattro = (getattrofunc)DrgnObject_getattro,
1721 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1722 .tp_traverse = (traverseproc)DrgnObject_traverse,
1723 .tp_doc = drgn_Object_DOC,
1724 .tp_richcompare = DrgnObject_richcompare,
1725 .tp_iter = (getiterfunc)DrgnObject_iter,
1726 .tp_methods = DrgnObject_methods,
1727 .tp_getset = DrgnObject_getset,
1728 .tp_new = (newfunc)DrgnObject_new,
1729 };
1730
1731 PyObject *DrgnObject_NULL(PyObject *self, PyObject *args, PyObject *kwds)
1732 {
1733 static char *keywords[] = {"prog", "type", NULL};
1734 PyObject *prog_obj, *type_obj;
1735 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:NULL", keywords,
1736 &prog_obj, &type_obj))
1737 return NULL;
1738 return PyObject_CallFunction((PyObject *)&DrgnObject_type, "OOi",
1739 prog_obj, type_obj, 0);
1740 }
1741
1742 #define DrgnObject_CAST_OP(op) \
1743 DrgnObject *op(PyObject *self, PyObject *args, PyObject *kwds) \
1744 { \
1745 static char *keywords[] = {"type", "obj", NULL}; \
1746 struct drgn_error *err; \
1747 PyObject *type_obj; \
1748 DrgnObject *obj; \
1749 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO!:" #op, keywords, \
1750 &type_obj, &DrgnObject_type, &obj)) \
1751 return NULL; \
1752 \
1753 struct drgn_qualified_type qualified_type; \
1754 if (Program_type_arg(DrgnObject_prog(obj), type_obj, false, \
1755 &qualified_type) == -1) \
1756 return NULL; \
1757 \
1758 _cleanup_pydecref_ DrgnObject *res = \
1759 DrgnObject_alloc(DrgnObject_prog(obj)); \
1760 if (!res) \
1761 return NULL; \
1762 \
1763 err = drgn_object_##op(&res->obj, qualified_type, &obj->obj); \
1764 if (err) \
1765 return set_drgn_error(err); \
1766 return_ptr(res); \
1767 }
1768
1769 DrgnObject_CAST_OP(cast)
1770
1771 DrgnObject *implicit_convert(PyObject *self, PyObject *args, PyObject *kwds)
1772 {
1773 static char *keywords[] = {"type", "obj", "bit_field_size", NULL};
1774 struct drgn_error *err;
1775 PyObject *type_obj;
1776 DrgnObject *obj;
1777 struct index_arg bit_field_size = { .allow_none = true, .is_none = true };
1778 if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO!|$O&:implicit_convert",
1779 keywords, &type_obj, &DrgnObject_type,
1780 &obj, index_converter,
1781 &bit_field_size))
1782 return NULL;
1783
1784 if (!bit_field_size.is_none && bit_field_size.uvalue == 0) {
1785 PyErr_SetString(PyExc_ValueError,
1786 "bit field size cannot be zero");
1787 return NULL;
1788 }
1789
1790 struct drgn_qualified_type qualified_type;
1791 if (Program_type_arg(DrgnObject_prog(obj), type_obj, false,
1792 &qualified_type) == -1)
1793 return NULL;
1794
1795 _cleanup_pydecref_ DrgnObject *res =
1796 DrgnObject_alloc(DrgnObject_prog(obj));
1797 if (!res)
1798 return NULL;
1799
1800 err = drgn_object_implicit_convert(&res->obj, qualified_type,
1801 bit_field_size.uvalue, &obj->obj);
1802 if (err)
1803 return set_drgn_error(err);
1804 return_ptr(res);
1805 }
1806
1807 DrgnObject_CAST_OP(reinterpret)
1808
1809 #undef DrgnObject_CAST_OP
1810
1811 DrgnObject *DrgnObject_container_of(PyObject *self, PyObject *args,
1812 PyObject *kwds)
1813 {
1814 static char *keywords[] = {"ptr", "type", "member", NULL};
1815 struct drgn_error *err;
1816 DrgnObject *obj;
1817 PyObject *type_obj;
1818 struct drgn_qualified_type qualified_type;
1819 const char *member_designator;
1820 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!Os:container_of",
1821 keywords, &DrgnObject_type, &obj,
1822 &type_obj, &member_designator))
1823 return NULL;
1824
1825 if (Program_type_arg(DrgnObject_prog(obj), type_obj, false,
1826 &qualified_type) == -1)
1827 return NULL;
1828
1829 _cleanup_pydecref_ DrgnObject *res = DrgnObject_alloc(DrgnObject_prog(obj));
1830 if (!res)
1831 return NULL;
1832
1833 err = drgn_object_container_of(&res->obj, &obj->obj, qualified_type,
1834 member_designator);
1835 if (err)
1836 return set_drgn_error(err);
1837 return_ptr(res);
1838 }
1839
1840 static void ObjectIterator_dealloc(ObjectIterator *self)
1841 {
1842 PyObject_GC_UnTrack(self);
1843 Py_DECREF(self->obj);
1844 Py_TYPE(self)->tp_free((PyObject *)self);
1845 }
1846
1847 static int ObjectIterator_traverse(ObjectIterator *self, visitproc visit,
1848 void *arg)
1849 {
1850 Py_VISIT(self->obj);
1851 return 0;
1852 }
1853
1854 static DrgnObject *ObjectIterator_next(ObjectIterator *self)
1855 {
1856 if (self->index == self->end)
1857 return NULL;
1858 DrgnObject *ret = DrgnObject_subscript_impl(self->obj, self->index);
1859 if (ret)
1860 self->index += self->step;
1861 return ret;
1862 }
1863
1864 static PyObject *ObjectIterator_length_hint(ObjectIterator *self)
1865 {
1866 uint64_t length;
1867 if (self->step == 1)
1868 length = self->end - self->index;
1869 else
1870 length = self->index + 1;
1871 return PyLong_FromUInt64(length);
1872 }
1873
1874 static PyMethodDef ObjectIterator_methods[] = {
1875 {"__length_hint__", (PyCFunction)ObjectIterator_length_hint,
1876 METH_NOARGS},
1877 {},
1878 };
1879
1880 PyTypeObject ObjectIterator_type = {
1881 PyVarObject_HEAD_INIT(NULL, 0)
1882 .tp_name = "_drgn._ObjectIterator",
1883 .tp_basicsize = sizeof(ObjectIterator),
1884 .tp_dealloc = (destructor)ObjectIterator_dealloc,
1885 .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
1886 .tp_traverse = (traverseproc)ObjectIterator_traverse,
1887 .tp_iter = PyObject_SelfIter,
1888 .tp_iternext = (iternextfunc)ObjectIterator_next,
1889 .tp_methods = ObjectIterator_methods,
1890 };