[Go to site: main page, start]

LLDB mainline
PythonDataObjects.cpp
Go to the documentation of this file.
1//===-- PythonDataObjects.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "PythonDataObjects.h"
11
12#include "lldb/Host/File.h"
16#include "lldb/Utility/Log.h"
17#include "lldb/Utility/Stream.h"
18
19#include "llvm/ADT/ScopeExit.h"
20#include "llvm/Support/Casting.h"
21#include "llvm/Support/ConvertUTF.h"
22#include "llvm/Support/Errno.h"
23
24#include <cstdio>
25#include <variant>
26
27using namespace lldb_private;
28using namespace lldb;
29using namespace lldb_private::python;
30using llvm::cantFail;
31using llvm::Error;
32using llvm::Expected;
33using llvm::Twine;
34
35template <> Expected<bool> python::As<bool>(Expected<PythonObject> &&obj) {
36 if (!obj)
37 return obj.takeError();
38 return obj.get().IsTrue();
39}
40
41template <>
42Expected<long long> python::As<long long>(Expected<PythonObject> &&obj) {
43 if (!obj)
44 return obj.takeError();
45 return obj->AsLongLong();
46}
47
48template <>
49Expected<unsigned long long>
50python::As<unsigned long long>(Expected<PythonObject> &&obj) {
51 if (!obj)
52 return obj.takeError();
53 return obj->AsUnsignedLongLong();
54}
55
56template <>
57Expected<std::string> python::As<std::string>(Expected<PythonObject> &&obj) {
58 if (!obj)
59 return obj.takeError();
60 PyObject *str_obj = PyObject_Str(obj.get().get());
61 if (!str_obj)
62 return llvm::make_error<PythonException>();
63 auto str = Take<PythonString>(str_obj);
64 auto utf8 = str.AsUTF8();
65 if (!utf8)
66 return utf8.takeError();
67 return std::string(utf8.get());
68}
69
71 if (m_py_obj && Py_IsInitialized()) {
72 PyGILState_STATE state = PyGILState_Ensure();
73 Py_DECREF(m_py_obj);
74 PyGILState_Release(state);
75 }
76 m_py_obj = nullptr;
77}
78
79Expected<long long> PythonObject::AsLongLong() const {
80 if (!m_py_obj)
81 return nullDeref();
82 assert(!PyErr_Occurred());
83 long long r = PyLong_AsLongLong(m_py_obj);
84 if (PyErr_Occurred())
85 return exception();
86 return r;
87}
88
89Expected<unsigned long long> PythonObject::AsUnsignedLongLong() const {
90 if (!m_py_obj)
91 return nullDeref();
92 assert(!PyErr_Occurred());
93 long long r = PyLong_AsUnsignedLongLong(m_py_obj);
94 if (PyErr_Occurred())
95 return exception();
96 return r;
97}
98
99// wraps on overflow, instead of raising an error.
100Expected<unsigned long long> PythonObject::AsModuloUnsignedLongLong() const {
101 if (!m_py_obj)
102 return nullDeref();
103 assert(!PyErr_Occurred());
104 unsigned long long r = PyLong_AsUnsignedLongLongMask(m_py_obj);
105 // FIXME: We should fetch the exception message and hoist it.
106 if (PyErr_Occurred())
107 return exception();
108 return r;
109}
110
111void StructuredPythonObject::Serialize(llvm::json::OStream &s) const {
112 s.value(llvm::formatv("Python Obj: {0:X}", GetValue()).str());
113}
114
115// PythonObject
116
117void PythonObject::Dump(Stream &strm) const {
118 if (!m_py_obj) {
119 strm << "NULL";
120 return;
121 }
122
123 PyObject *py_str = PyObject_Repr(m_py_obj);
124 if (!py_str)
125 return;
126
127 llvm::scope_exit release_py_str([py_str] { Py_DECREF(py_str); });
128
129 PyObject *py_bytes = PyUnicode_AsEncodedString(py_str, "utf-8", "replace");
130 if (!py_bytes)
131 return;
132
133 llvm::scope_exit release_py_bytes([py_bytes] { Py_DECREF(py_bytes); });
134
135 char *buffer = nullptr;
136 Py_ssize_t length = 0;
137 if (PyBytes_AsStringAndSize(py_bytes, &buffer, &length) == -1)
138 return;
139
140 strm << llvm::StringRef(buffer, length);
141}
142
171
173 if (!m_py_obj)
174 return PythonString();
175 PyObject *repr = PyObject_Repr(m_py_obj);
176 if (!repr)
177 return PythonString();
178 return PythonString(PyRefType::Owned, repr);
179}
180
182 if (!m_py_obj)
183 return PythonString();
184 PyObject *str = PyObject_Str(m_py_obj);
185 if (!str)
186 return PythonString();
187 return PythonString(PyRefType::Owned, str);
188}
189
192 const PythonDictionary &dict) {
193 size_t dot_pos = name.find('.');
194 llvm::StringRef piece = name.substr(0, dot_pos);
195 PythonObject result = dict.GetItemForKey(PythonString(piece));
196 if (dot_pos == llvm::StringRef::npos) {
197 // There was no dot, we're done.
198 return result;
199 }
200
201 // There was a dot. The remaining portion of the name should be looked up in
202 // the context of the object that was found in the dictionary.
203 return result.ResolveName(name.substr(dot_pos + 1));
204}
205
206PythonObject PythonObject::ResolveName(llvm::StringRef name) const {
207 // Resolve the name in the context of the specified object. If, for example,
208 // `this` refers to a PyModule, then this will look for `name` in this
209 // module. If `this` refers to a PyType, then it will resolve `name` as an
210 // attribute of that type. If `this` refers to an instance of an object,
211 // then it will resolve `name` as the value of the specified field.
212 //
213 // This function handles dotted names so that, for example, if `m_py_obj`
214 // refers to the `sys` module, and `name` == "path.append", then it will find
215 // the function `sys.path.append`.
216
217 size_t dot_pos = name.find('.');
218 if (dot_pos == llvm::StringRef::npos) {
219 // No dots in the name, we should be able to find the value immediately as
220 // an attribute of `m_py_obj`.
221 return GetAttributeValue(name);
222 }
223
224 // Look up the first piece of the name, and resolve the rest as a child of
225 // that.
226 PythonObject parent = ResolveName(name.substr(0, dot_pos));
227 if (!parent.IsAllocated())
228 return PythonObject();
229
230 // Tail recursion.. should be optimized by the compiler
231 return parent.ResolveName(name.substr(dot_pos + 1));
232}
233
234bool PythonObject::HasAttribute(llvm::StringRef attr) const {
235 if (!IsValid())
236 return false;
237 PythonString py_attr(attr);
238 return !!PyObject_HasAttr(m_py_obj, py_attr.get());
239}
240
242 if (!IsValid())
243 return PythonObject();
244
245 PythonString py_attr(attr);
246 if (!PyObject_HasAttr(m_py_obj, py_attr.get()))
247 return PythonObject();
248
250 PyObject_GetAttr(m_py_obj, py_attr.get()));
251}
252
254 switch (GetObjectType()) {
264 if (std::holds_alternative<StructuredData::UnsignedIntegerSP>(int_sp))
265 return std::get<StructuredData::UnsignedIntegerSP>(int_sp);
266 if (std::holds_alternative<StructuredData::SignedIntegerSP>(int_sp))
267 return std::get<StructuredData::SignedIntegerSP>(int_sp);
268 return nullptr;
269 };
281 default:
284 }
285}
286
287// PythonString
288
289PythonBytes::PythonBytes(llvm::ArrayRef<uint8_t> bytes) { SetBytes(bytes); }
290
291PythonBytes::PythonBytes(const uint8_t *bytes, size_t length) {
292 SetBytes(llvm::ArrayRef<uint8_t>(bytes, length));
293}
294
295bool PythonBytes::Check(PyObject *py_obj) {
296 if (!py_obj)
297 return false;
298 return PyBytes_Check(py_obj);
299}
300
301llvm::ArrayRef<uint8_t> PythonBytes::GetBytes() const {
302 if (!IsValid())
303 return llvm::ArrayRef<uint8_t>();
304
305 Py_ssize_t size;
306 char *c;
307
308 PyBytes_AsStringAndSize(m_py_obj, &c, &size);
309 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
310}
311
312size_t PythonBytes::GetSize() const {
313 if (!IsValid())
314 return 0;
315 return PyBytes_Size(m_py_obj);
316}
317
318void PythonBytes::SetBytes(llvm::ArrayRef<uint8_t> bytes) {
319 const char *data = reinterpret_cast<const char *>(bytes.data());
320 *this = Take<PythonBytes>(PyBytes_FromStringAndSize(data, bytes.size()));
321}
322
325 Py_ssize_t size;
326 char *c;
327 PyBytes_AsStringAndSize(m_py_obj, &c, &size);
328 result->SetValue(std::string(c, size));
329 return result;
330}
331
332PythonByteArray::PythonByteArray(llvm::ArrayRef<uint8_t> bytes)
333 : PythonByteArray(bytes.data(), bytes.size()) {}
334
335PythonByteArray::PythonByteArray(const uint8_t *bytes, size_t length) {
336 const char *str = reinterpret_cast<const char *>(bytes);
337 *this = Take<PythonByteArray>(PyByteArray_FromStringAndSize(str, length));
338}
339
340bool PythonByteArray::Check(PyObject *py_obj) {
341 if (!py_obj)
342 return false;
343 return PyByteArray_Check(py_obj);
344}
345
346llvm::ArrayRef<uint8_t> PythonByteArray::GetBytes() const {
347 if (!IsValid())
348 return llvm::ArrayRef<uint8_t>();
349
350 char *c = PyByteArray_AsString(m_py_obj);
351 size_t size = GetSize();
352 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
353}
354
356 if (!IsValid())
357 return 0;
358
359 return PyByteArray_Size(m_py_obj);
360}
361
364 llvm::ArrayRef<uint8_t> bytes = GetBytes();
365 const char *str = reinterpret_cast<const char *>(bytes.data());
366 result->SetValue(std::string(str, bytes.size()));
367 return result;
368}
369
370// PythonString
371
372Expected<PythonString> PythonString::FromUTF8(llvm::StringRef string) {
373 PyObject *str = PyUnicode_FromStringAndSize(string.data(), string.size());
374 if (!str)
375 return llvm::make_error<PythonException>();
376 return Take<PythonString>(str);
377}
378
379PythonString::PythonString(llvm::StringRef string) { SetString(string); }
380
381bool PythonString::Check(PyObject *py_obj) {
382 if (!py_obj)
383 return false;
384
385 if (PyUnicode_Check(py_obj))
386 return true;
387 return false;
388}
389
390llvm::StringRef PythonString::GetString() const {
391 auto s = AsUTF8();
392 if (!s) {
393 llvm::consumeError(s.takeError());
394 return llvm::StringRef("");
395 }
396 return s.get();
397}
398
399Expected<llvm::StringRef> PythonString::AsUTF8() const {
400 if (!IsValid())
401 return nullDeref();
402
403 // PyUnicode_AsUTF8AndSize caches the UTF-8 representation of the string in
404 // the Unicode object, which makes it more efficient and ties the lifetime of
405 // the data to the Python string. However, it was only added to the Stable API
406 // in Python 3.10. Older versions that want to use the Stable API must use
407 // PyUnicode_AsUTF8String in combination with ConstString.
408#if defined(Py_LIMITED_API) && (Py_LIMITED_API < 0x030a0000)
409 PyObject *py_bytes = PyUnicode_AsUTF8String(m_py_obj);
410 if (!py_bytes)
411 return exception();
412 llvm::scope_exit release_py_str([py_bytes] { Py_DECREF(py_bytes); });
413 Py_ssize_t size = PyBytes_Size(py_bytes);
414 const char *str = PyBytes_AsString(py_bytes);
415
416 if (!str)
417 return exception();
418
419 return ConstString(str, size).GetStringRef();
420#else
421 Py_ssize_t size;
422 const char *str = PyUnicode_AsUTF8AndSize(m_py_obj, &size);
423
424 if (!str)
425 return exception();
426
427 return llvm::StringRef(str, size);
428#endif
429}
430
431size_t PythonString::GetSize() const {
432 if (IsValid())
433 return PyUnicode_GetLength(m_py_obj);
434 return 0;
435}
436
437void PythonString::SetString(llvm::StringRef string) {
438 auto s = FromUTF8(string);
439 if (!s) {
440 llvm::consumeError(s.takeError());
441 Reset();
442 } else {
443 *this = std::move(s.get());
444 }
445}
446
449 result->SetValue(GetString());
450 return result;
451}
452
453// PythonInteger
454
455PythonInteger::PythonInteger(int64_t value) { SetInteger(value); }
456
457bool PythonInteger::Check(PyObject *py_obj) {
458 if (!py_obj)
459 return false;
460
461 // Python 3 does not have PyInt_Check. There is only one type of integral
462 // value, long.
463 return PyLong_Check(py_obj);
464}
465
466void PythonInteger::SetInteger(int64_t value) {
467 *this = Take<PythonInteger>(PyLong_FromLongLong(value));
468}
469
475
478 StructuredData::UnsignedIntegerSP result = nullptr;
479 llvm::Expected<unsigned long long> value = AsUnsignedLongLong();
480 if (!value)
481 llvm::consumeError(value.takeError());
482 else
483 result = std::make_shared<StructuredData::UnsignedInteger>(value.get());
484
485 return result;
486}
487
490 StructuredData::SignedIntegerSP result = nullptr;
491 llvm::Expected<long long> value = AsLongLong();
492 if (!value)
493 llvm::consumeError(value.takeError());
494 else
495 result = std::make_shared<StructuredData::SignedInteger>(value.get());
496
497 return result;
498}
499
500// PythonBoolean
501
503
504bool PythonBoolean::Check(PyObject *py_obj) {
505 return py_obj ? PyBool_Check(py_obj) : false;
506}
507
509 return m_py_obj ? PyObject_IsTrue(m_py_obj) : false;
510}
511
512void PythonBoolean::SetValue(bool value) {
513 *this = Take<PythonBoolean>(PyBool_FromLong(value));
514}
515
521
522// PythonList
523
525 if (value == PyInitialValue::Empty)
526 *this = Take<PythonList>(PyList_New(0));
527}
528
530 *this = Take<PythonList>(PyList_New(list_size));
531}
532
533bool PythonList::Check(PyObject *py_obj) {
534 if (!py_obj)
535 return false;
536 return PyList_Check(py_obj);
537}
538
539uint32_t PythonList::GetSize() const {
540 if (IsValid())
541 return PyList_Size(m_py_obj);
542 return 0;
543}
544
546 if (IsValid())
547 return PythonObject(PyRefType::Borrowed, PyList_GetItem(m_py_obj, index));
548 return PythonObject();
549}
550
551void PythonList::SetItemAtIndex(uint32_t index, const PythonObject &object) {
552 if (IsAllocated() && object.IsValid()) {
553 // PyList_SetItem is documented to "steal" a reference, so we need to
554 // convert it to an owned reference by incrementing it.
555 Py_INCREF(object.get());
556 PyList_SetItem(m_py_obj, index, object.get());
557 }
558}
559
561 if (IsAllocated() && object.IsValid()) {
562 // `PyList_Append` does *not* steal a reference, so do not call `Py_INCREF`
563 // here like we do with `PyList_SetItem`.
564 PyList_Append(m_py_obj, object.get());
565 }
566}
567
570 uint32_t count = GetSize();
571 for (uint32_t i = 0; i < count; ++i) {
573 result->AddItem(obj.CreateStructuredObject());
574 }
575 return result;
576}
577
578// PythonTuple
579
581 if (value == PyInitialValue::Empty)
582 *this = Take<PythonTuple>(PyTuple_New(0));
583}
584
586 *this = Take<PythonTuple>(PyTuple_New(tuple_size));
587}
588
589PythonTuple::PythonTuple(std::initializer_list<PythonObject> objects) {
590 m_py_obj = PyTuple_New(objects.size());
591
592 uint32_t idx = 0;
593 for (auto object : objects) {
594 if (object.IsValid())
595 SetItemAtIndex(idx, object);
596 idx++;
597 }
598}
599
600PythonTuple::PythonTuple(std::initializer_list<PyObject *> objects) {
601 m_py_obj = PyTuple_New(objects.size());
602
603 uint32_t idx = 0;
604 for (auto py_object : objects) {
605 PythonObject object(PyRefType::Borrowed, py_object);
606 if (object.IsValid())
607 SetItemAtIndex(idx, object);
608 idx++;
609 }
610}
611
612bool PythonTuple::Check(PyObject *py_obj) {
613 if (!py_obj)
614 return false;
615 return PyTuple_Check(py_obj);
616}
617
618uint32_t PythonTuple::GetSize() const {
619 if (IsValid())
620 return PyTuple_Size(m_py_obj);
621 return 0;
622}
623
625 if (IsValid())
626 return PythonObject(PyRefType::Borrowed, PyTuple_GetItem(m_py_obj, index));
627 return PythonObject();
628}
629
630void PythonTuple::SetItemAtIndex(uint32_t index, const PythonObject &object) {
631 if (IsAllocated() && object.IsValid()) {
632 // PyTuple_SetItem is documented to "steal" a reference, so we need to
633 // convert it to an owned reference by incrementing it.
634 Py_INCREF(object.get());
635 PyTuple_SetItem(m_py_obj, index, object.get());
636 }
637}
638
641 uint32_t count = GetSize();
642 for (uint32_t i = 0; i < count; ++i) {
644 result->AddItem(obj.CreateStructuredObject());
645 }
646 return result;
647}
648
649// PythonDictionary
650
655
656bool PythonDictionary::Check(PyObject *py_obj) {
657 if (!py_obj)
658 return false;
659
660 return PyDict_Check(py_obj);
661}
662
663bool PythonDictionary::HasKey(const llvm::Twine &key) const {
664 if (!IsValid())
665 return false;
666
667 PythonString key_object(key.isSingleStringRef() ? key.getSingleStringRef()
668 : key.str());
669
670 if (int res = PyDict_Contains(m_py_obj, key_object.get()) > 0)
671 return res;
672
673 PyErr_Print();
674 return false;
675}
676
678 if (IsValid())
679 return PyDict_Size(m_py_obj);
680 return 0;
681}
682
688
690 auto item = GetItem(key);
691 if (!item) {
692 llvm::consumeError(item.takeError());
693 return PythonObject();
694 }
695 return std::move(item.get());
696}
697
698Expected<PythonObject>
700 if (!IsValid() || !key.IsValid())
701 return nullDeref();
702 PyObject *o = PyDict_GetItemWithError(m_py_obj, key.get());
703 if (PyErr_Occurred())
704 return exception();
705 if (!o)
706 return keyError();
707 return Retain<PythonObject>(o);
708}
709
710Expected<PythonObject> PythonDictionary::GetItem(const Twine &key) const {
711 if (!IsValid())
712 return nullDeref();
713 PyObject *o = PyDict_GetItemString(m_py_obj, NullTerminated(key));
714 if (PyErr_Occurred())
715 return exception();
716 if (!o)
717 return keyError();
718 return Retain<PythonObject>(o);
719}
720
722 const PythonObject &value) const {
723 if (!IsValid() || !value.IsValid())
724 return nullDeref();
725 int r = PyDict_SetItem(m_py_obj, key.get(), value.get());
726 if (r < 0)
727 return exception();
728 return Error::success();
729}
730
731Error PythonDictionary::SetItem(const Twine &key,
732 const PythonObject &value) const {
733 if (!IsValid() || !value.IsValid())
734 return nullDeref();
735 int r = PyDict_SetItemString(m_py_obj, NullTerminated(key), value.get());
736 if (r < 0)
737 return exception();
738 return Error::success();
739}
740
742 const PythonObject &value) {
743 Error error = SetItem(key, value);
744 if (error)
745 llvm::consumeError(std::move(error));
746}
747
751 PythonList keys(GetKeys());
752 uint32_t num_keys = keys.GetSize();
753 for (uint32_t i = 0; i < num_keys; ++i) {
754 PythonObject key = keys.GetItemAtIndex(i);
755 PythonObject value = GetItemForKey(key);
756 StructuredData::ObjectSP structured_value = value.CreateStructuredObject();
757 result->AddItem(key.Str().GetString(), structured_value);
758 }
759 return result;
760}
761
763
765
766PythonModule PythonModule::AddModule(llvm::StringRef module) {
767 std::string str = module.str();
768 return PythonModule(PyRefType::Borrowed, PyImport_AddModule(str.c_str()));
769}
770
771Expected<PythonModule> PythonModule::Import(const Twine &name) {
772 PyObject *mod = PyImport_ImportModule(NullTerminated(name));
773 if (!mod)
774 return exception();
775 return Take<PythonModule>(mod);
776}
777
778Expected<PythonObject> PythonModule::Get(const Twine &name) {
779 if (!IsValid())
780 return nullDeref();
781 PyObject *dict = PyModule_GetDict(m_py_obj);
782 if (!dict)
783 return exception();
784 PyObject *item = PyDict_GetItemString(dict, NullTerminated(name));
785 if (!item)
786 return exception();
787 return Retain<PythonObject>(item);
788}
789
790bool PythonModule::Check(PyObject *py_obj) {
791 if (!py_obj)
792 return false;
793
794 return PyModule_Check(py_obj);
795}
796
798 if (!IsValid())
799 return PythonDictionary();
800 return Retain<PythonDictionary>(PyModule_GetDict(m_py_obj));
801}
802
803bool PythonCallable::Check(PyObject *py_obj) {
804 if (!py_obj)
805 return false;
806
807 PythonObject python_obj(PyRefType::Borrowed, py_obj);
808
809 // Handle staticmethod/classmethod descriptors by extracting the
810 // `__func__` attribute.
811 if (python_obj.HasAttribute("__func__")) {
812 PythonObject function_obj = python_obj.GetAttributeValue("__func__");
813 if (!function_obj.IsAllocated())
814 return false;
815 return PyCallable_Check(function_obj.release());
816 }
817
818 return PyCallable_Check(py_obj);
819}
820
821static const char get_arg_info_script[] = R"(
822from inspect import signature, Parameter, ismethod
823from collections import namedtuple
824ArgInfo = namedtuple('ArgInfo', ['count', 'has_varargs'])
825def main(f):
826 count = 0
827 varargs = False
828 for parameter in signature(f).parameters.values():
829 kind = parameter.kind
830 if kind in (Parameter.POSITIONAL_ONLY,
831 Parameter.POSITIONAL_OR_KEYWORD):
832 count += 1
833 elif kind == Parameter.VAR_POSITIONAL:
834 varargs = True
835 elif kind in (Parameter.KEYWORD_ONLY,
836 Parameter.VAR_KEYWORD):
837 pass
838 else:
839 raise Exception(f'unknown parameter kind: {kind}')
840 return ArgInfo(count, varargs)
841)";
842
843// inspect.signature() is deeply recursive and expensive in C-stack terms;
844// reentrant scripted callbacks dispatched through GetArgInfo() can turn
845// that into a fatal stack overflow instead of a catchable Python
846// RecursionError. GetArgInfo() never calls this itself; callers fall back
847// to it explicitly when they need to handle callables its cheaper,
848// attribute-only approach can't (e.g. builtins).
849Expected<PythonCallable::ArgInfo>
851 PythonCallable::ArgInfo result = {};
852 // no need to synchronize access to this global, we already have the GIL
853 static PythonScript get_arg_info(get_arg_info_script);
854 Expected<PythonObject> pyarginfo = get_arg_info(callable);
855 if (!pyarginfo)
856 return pyarginfo.takeError();
857 long long count =
858 cantFail(As<long long>(pyarginfo.get().GetAttribute("count")));
859 bool has_varargs =
860 cantFail(As<bool>(pyarginfo.get().GetAttribute("has_varargs")));
861 result.max_positional_args =
862 has_varargs ? PythonCallable::ArgInfo::UNBOUNDED : count;
863 return result;
864}
865
866// GetArgInfo()'s branches, top to bottom (`func` is what each branch ends up
867// introspecting; the final step is always func.__code__.co_argcount/co_flags):
868//
869// callable
870// |-- has __self__ -> func = __func__ (bound method;
871// | fails for slot wrappers, e.g. (1).__add__)
872// |-- has __code__ already -> func = callable (plain function)
873// `-- neither
874// |-- is a class
875// | |-- __init__ has __code__ -> func = __init__
876// | `-- else: check __new__ too (object.__init__ is lenient about
877// | extra args once __new__ is overridden)
878// | |-- __new__ has __code__ -> func = __new__
879// | `-- else -> ArgInfo{0} (object's defaults)
880// `-- is an instance
881// `-- func = __call__ (unwrap __func__ if bound)
882// `-- no __code__ -> error (e.g. a builtin)
883Expected<PythonCallable::ArgInfo> PythonCallable::GetArgInfo() const {
884 if (!IsValid())
885 return nullDeref();
886
887 PythonObject func = *this;
888 bool implicit_first_arg = false;
889 if (HasAttribute("__self__")) {
890 implicit_first_arg = true;
891 Expected<PythonObject> func_or_err = GetAttribute("__func__");
892 if (!func_or_err)
893 return func_or_err.takeError();
894 func = *func_or_err;
895 } else if (!HasAttribute("__code__")) {
896 implicit_first_arg = true;
897 if (PyType_Check(m_py_obj)) {
898 Expected<PythonObject> init_or_err = GetAttribute("__init__");
899 if (!init_or_err)
900 return init_or_err.takeError();
901 func = *init_or_err;
902 if (!func.HasAttribute("__code__")) {
903 // __init__ is still object.__init__. A class may customize
904 // __new__ instead and leave __init__ untouched, which makes
905 // object.__init__ lenient about extra arguments -- so check
906 // __new__ too before concluding there are none.
907 Expected<PythonObject> new_or_err = GetAttribute("__new__");
908 if (!new_or_err)
909 return new_or_err.takeError();
910 func = *new_or_err;
911 if (!func.HasAttribute("__code__"))
912 return ArgInfo{0};
913 }
914 } else {
915 Expected<PythonObject> call_or_err = GetAttribute("__call__");
916 if (!call_or_err)
917 return call_or_err.takeError();
918 func = *call_or_err;
919 if (func.HasAttribute("__self__")) {
920 Expected<PythonObject> inner_or_err = func.GetAttribute("__func__");
921 if (!inner_or_err)
922 return inner_or_err.takeError();
923 func = *inner_or_err;
924 }
925 if (!func.HasAttribute("__code__"))
926 return llvm::createStringError("__call__ has no __code__");
927 }
928 }
929
930 Expected<PythonObject> code_or_err = func.GetAttribute("__code__");
931 if (!code_or_err)
932 return code_or_err.takeError();
933 PythonObject code = *code_or_err;
934
935 Expected<long long> argcount =
936 As<long long>(code.GetAttribute("co_argcount"));
937 if (!argcount)
938 return argcount.takeError();
939 Expected<long long> flags = As<long long>(code.GetAttribute("co_flags"));
940 if (!flags)
941 return flags.takeError();
942
943 ArgInfo result = {};
944 // Mirrors CPython's CO_VARARGS from <code.h>, which isn't reliably
945 // visible across the Python versions/platforms this file builds against.
946 constexpr long long kCoFlagVarArgs = 0x04;
947 if (*flags & kCoFlagVarArgs) {
949 } else {
950 long long count = *argcount - (implicit_first_arg ? 1 : 0);
951 result.max_positional_args = count > 0 ? static_cast<unsigned>(count) : 0;
952 }
953 return result;
954}
955
956constexpr unsigned
957 PythonCallable::ArgInfo::UNBOUNDED; // FIXME delete after c++17
958
960 return PythonObject(PyRefType::Owned, PyObject_CallObject(m_py_obj, nullptr));
961}
962
964PythonCallable::operator()(std::initializer_list<PyObject *> args) {
965 PythonTuple arg_tuple(args);
967 PyObject_CallObject(m_py_obj, arg_tuple.get()));
968}
969
971PythonCallable::operator()(std::initializer_list<PythonObject> args) {
972 PythonTuple arg_tuple(args);
974 PyObject_CallObject(m_py_obj, arg_tuple.get()));
975}
976
977bool PythonFile::Check(PyObject *py_obj) {
978 if (!py_obj)
979 return false;
980 // In Python 3, there is no `PyFile_Check`, and in fact PyFile is not even a
981 // first-class object type anymore. `PyFile_FromFd` is just a thin wrapper
982 // over `io.open()`, which returns some object derived from `io.IOBase`. As a
983 // result, the only way to detect a file in Python 3 is to check whether it
984 // inherits from `io.IOBase`.
985 auto io_module = PythonModule::Import("io");
986 if (!io_module) {
987 llvm::consumeError(io_module.takeError());
988 return false;
989 }
990 auto iobase = io_module.get().Get("IOBase");
991 if (!iobase) {
992 llvm::consumeError(iobase.takeError());
993 return false;
994 }
995 int r = PyObject_IsInstance(py_obj, iobase.get().get());
996 if (r < 0) {
997 llvm::consumeError(exception()); // clear the exception and log it.
998 return false;
999 }
1000 return !!r;
1001}
1002
1003const char *PythonException::toCString() const {
1004 if (!m_repr_bytes)
1005 return "unknown exception";
1006 return PyBytes_AsString(m_repr_bytes);
1007}
1008
1010 assert(PyErr_Occurred());
1012 PyErr_Fetch(&m_exception_type, &m_exception, &m_traceback);
1013 PyErr_NormalizeException(&m_exception_type, &m_exception, &m_traceback);
1014 PyErr_Clear();
1015 if (m_exception) {
1016 PyObject *repr = PyObject_Repr(m_exception);
1017 if (repr) {
1018 m_repr_bytes = PyUnicode_AsEncodedString(repr, "utf-8", nullptr);
1019 if (!m_repr_bytes) {
1020 PyErr_Clear();
1021 }
1022 Py_XDECREF(repr);
1023 } else {
1024 PyErr_Clear();
1025 }
1026 }
1028 if (caller)
1029 LLDB_LOGF(log, "%s failed with exception: %s", caller, toCString());
1030 else
1031 LLDB_LOGF(log, "python exception: %s", toCString());
1032}
1035 PyErr_Restore(m_exception_type, m_exception, m_traceback);
1036 } else {
1037 PyErr_SetString(PyExc_Exception, toCString());
1038 }
1040}
1041
1043 Py_XDECREF(m_exception_type);
1044 Py_XDECREF(m_exception);
1045 Py_XDECREF(m_traceback);
1046 Py_XDECREF(m_repr_bytes);
1047}
1048
1049void PythonException::log(llvm::raw_ostream &OS) const { OS << toCString(); }
1050
1052 return llvm::inconvertibleErrorCode();
1053}
1054
1055bool PythonException::Matches(PyObject *exc) const {
1056 return PyErr_GivenExceptionMatches(m_exception_type, exc);
1057}
1058
1059const char read_exception_script[] = R"(
1060import sys
1061from traceback import print_exception
1062from io import StringIO
1063def main(exc_type, exc_value, tb):
1064 f = StringIO()
1065 print_exception(exc_type, exc_value, tb, file=f)
1066 return f.getvalue()
1067)";
1068
1070
1071 if (!m_traceback)
1072 return toCString();
1073
1074 // no need to synchronize access to this global, we already have the GIL
1075 static PythonScript read_exception(read_exception_script);
1076
1077 Expected<std::string> backtrace = As<std::string>(
1078 read_exception(m_exception_type, m_exception, m_traceback));
1079
1080 if (!backtrace) {
1081 std::string message =
1082 std::string(toCString()) + "\n" +
1083 "Traceback unavailable, an error occurred while reading it:\n";
1084 return (message + llvm::toString(backtrace.takeError()));
1085 }
1086
1087 return std::move(backtrace.get());
1088}
1089
1090char PythonException::ID = 0;
1091
1092llvm::Expected<File::OpenOptions>
1094 auto options = File::OpenOptions(0);
1095 auto readable = As<bool>(obj.CallMethod("readable"));
1096 if (!readable)
1097 return readable.takeError();
1098 auto writable = As<bool>(obj.CallMethod("writable"));
1099 if (!writable)
1100 return writable.takeError();
1101 if (readable.get() && writable.get())
1102 options |= File::eOpenOptionReadWrite;
1103 else if (writable.get())
1104 options |= File::eOpenOptionWriteOnly;
1105 else if (readable.get())
1106 options |= File::eOpenOptionReadOnly;
1107 return options;
1108}
1109
1110// Base class template for python files. All it knows how to do
1111// is hold a reference to the python object and close or flush it
1112// when the File is closed.
1113namespace {
1114template <typename Base> class OwnedPythonFile : public Base {
1115public:
1116 template <typename... Args>
1117 OwnedPythonFile(const PythonFile &file, bool borrowed, Args... args)
1118 : Base(args...), m_py_obj(file), m_borrowed(borrowed) {
1119 assert(m_py_obj);
1120 }
1121
1122 ~OwnedPythonFile() override {
1123 assert(m_py_obj);
1124 GIL takeGIL;
1125 Close();
1126 // we need to ensure the python object is released while we still
1127 // hold the GIL
1128 m_py_obj.Reset();
1129 }
1130
1131 bool IsPythonSideValid() const {
1132 GIL takeGIL;
1133 auto closed = As<bool>(m_py_obj.GetAttribute("closed"));
1134 if (!closed) {
1135 llvm::consumeError(closed.takeError());
1136 return false;
1137 }
1138 return !closed.get();
1139 }
1140
1141 bool IsValid() const override {
1142 return IsPythonSideValid() && Base::IsValid();
1143 }
1144
1145 Status Close() override {
1146 assert(m_py_obj);
1147 Status py_error, base_error;
1148 GIL takeGIL;
1149 if (!m_borrowed) {
1150 auto r = m_py_obj.CallMethod("close");
1151 if (!r)
1152 py_error = Status::FromError(r.takeError());
1153 }
1154 base_error = Base::Close();
1155 // Cloning since the wrapped exception may still reference the PyThread.
1156 if (py_error.Fail())
1157 return py_error.Clone();
1158 return base_error.Clone();
1159 };
1160
1161 PyObject *GetPythonObject() const {
1162 assert(m_py_obj.IsValid());
1163 return m_py_obj.get();
1164 }
1165
1166 static bool classof(const File *file) = delete;
1167
1168protected:
1169 PythonFile m_py_obj;
1170 bool m_borrowed;
1171};
1172} // namespace
1173
1174// A SimplePythonFile is a OwnedPythonFile that just does all I/O as
1175// a NativeFile
1176namespace {
1177class SimplePythonFile : public OwnedPythonFile<NativeFile> {
1178public:
1179 SimplePythonFile(const PythonFile &file, bool borrowed, int fd,
1180 File::OpenOptions options)
1181 : OwnedPythonFile(file, borrowed, fd, options, false) {}
1182
1183 static char ID;
1184 bool isA(const void *classID) const override {
1185 return classID == &ID || NativeFile::isA(classID);
1186 }
1187 static bool classof(const File *file) { return file->isA(&ID); }
1188};
1189char SimplePythonFile::ID = 0;
1190} // namespace
1191
1192// Shared methods between TextPythonFile and BinaryPythonFile
1193namespace {
1194class PythonIOFile : public OwnedPythonFile<File> {
1195public:
1196 PythonIOFile(const PythonFile &file, bool borrowed)
1197 : OwnedPythonFile(file, borrowed) {}
1198
1199 ~PythonIOFile() override { Close(); }
1200
1201 bool IsValid() const override { return IsPythonSideValid(); }
1202
1203 Status Close() override {
1204 assert(m_py_obj);
1205 GIL takeGIL;
1206 if (m_borrowed)
1207 return Flush();
1208 auto r = m_py_obj.CallMethod("close");
1209 if (!r)
1210 // Cloning since the wrapped exception may still reference the PyThread.
1211 return Status::FromError(r.takeError()).Clone();
1212 return Status();
1213 }
1214
1215 Status Flush() override {
1216 GIL takeGIL;
1217 auto r = m_py_obj.CallMethod("flush");
1218 if (!r)
1219 // Cloning since the wrapped exception may still reference the PyThread.
1220 return Status::FromError(r.takeError()).Clone();
1221 return Status();
1222 }
1223
1224 Expected<File::OpenOptions> GetOptions() const override {
1225 GIL takeGIL;
1226 return GetOptionsForPyObject(m_py_obj);
1227 }
1228
1229 static char ID;
1230 bool isA(const void *classID) const override {
1231 return classID == &ID || File::isA(classID);
1232 }
1233 static bool classof(const File *file) { return file->isA(&ID); }
1234};
1235char PythonIOFile::ID = 0;
1236} // namespace
1237
1238namespace {
1239class BinaryPythonFile : public PythonIOFile {
1240protected:
1241 int m_descriptor;
1242
1243public:
1244 BinaryPythonFile(int fd, const PythonFile &file, bool borrowed)
1245 : PythonIOFile(file, borrowed),
1246 m_descriptor(File::DescriptorIsValid(fd) ? fd
1247 : File::kInvalidDescriptor) {}
1248
1249 int GetDescriptor() const override { return m_descriptor; }
1250
1251 Status Write(const void *buf, size_t &num_bytes) override {
1252 GIL takeGIL;
1253 PyObject *pybuffer_p = PyMemoryView_FromMemory(
1254 const_cast<char *>((const char *)buf), num_bytes, PyBUF_READ);
1255 if (!pybuffer_p)
1256 // Cloning since the wrapped exception may still reference the PyThread.
1257 return Status::FromError(llvm::make_error<PythonException>()).Clone();
1258 auto pybuffer = Take<PythonObject>(pybuffer_p);
1259 num_bytes = 0;
1260 auto bytes_written = As<long long>(m_py_obj.CallMethod("write", pybuffer));
1261 if (!bytes_written)
1262 return Status::FromError(bytes_written.takeError());
1263 if (bytes_written.get() < 0)
1264 return Status::FromErrorString(
1265 ".write() method returned a negative number!");
1266 static_assert(sizeof(long long) >= sizeof(size_t), "overflow");
1267 num_bytes = bytes_written.get();
1268 return Status();
1269 }
1270
1271 Status Read(void *buf, size_t &num_bytes) override {
1272 GIL takeGIL;
1273 static_assert(sizeof(long long) >= sizeof(size_t), "overflow");
1274 auto pybuffer_obj =
1275 m_py_obj.CallMethod("read", (unsigned long long)num_bytes);
1276 if (!pybuffer_obj)
1277 // Cloning since the wrapped exception may still reference the PyThread.
1278 return Status::FromError(pybuffer_obj.takeError()).Clone();
1279 num_bytes = 0;
1280 if (pybuffer_obj.get().IsNone()) {
1281 // EOF
1282 num_bytes = 0;
1283 return Status();
1284 }
1285 PythonBytes pybytes(PyRefType::Borrowed, pybuffer_obj->get());
1286 if (!pybytes)
1287 return Status::FromError(llvm::make_error<PythonException>());
1288 llvm::ArrayRef<uint8_t> bytes = pybytes.GetBytes();
1289 memcpy(buf, bytes.begin(), bytes.size());
1290 num_bytes = bytes.size();
1291 return Status();
1292 }
1293};
1294} // namespace
1295
1296namespace {
1297class TextPythonFile : public PythonIOFile {
1298protected:
1299 int m_descriptor;
1300
1301public:
1302 TextPythonFile(int fd, const PythonFile &file, bool borrowed)
1303 : PythonIOFile(file, borrowed),
1304 m_descriptor(File::DescriptorIsValid(fd) ? fd
1305 : File::kInvalidDescriptor) {}
1306
1307 int GetDescriptor() const override { return m_descriptor; }
1308
1309 Status Write(const void *buf, size_t &num_bytes) override {
1310 GIL takeGIL;
1311 auto pystring =
1312 PythonString::FromUTF8(llvm::StringRef((const char *)buf, num_bytes));
1313 if (!pystring)
1314 return Status::FromError(pystring.takeError());
1315 num_bytes = 0;
1316 auto bytes_written =
1317 As<long long>(m_py_obj.CallMethod("write", pystring.get()));
1318 if (!bytes_written)
1319 // Cloning since the wrapped exception may still reference the PyThread.
1320 return Status::FromError(bytes_written.takeError()).Clone();
1321 if (bytes_written.get() < 0)
1322 return Status::FromErrorString(
1323 ".write() method returned a negative number!");
1324 static_assert(sizeof(long long) >= sizeof(size_t), "overflow");
1325 num_bytes = bytes_written.get();
1326 return Status();
1327 }
1328
1329 Status Read(void *buf, size_t &num_bytes) override {
1330 GIL takeGIL;
1331 size_t num_chars = num_bytes / 6;
1332 size_t orig_num_bytes = num_bytes;
1333 num_bytes = 0;
1334 if (orig_num_bytes < 6) {
1335 return Status::FromErrorString(
1336 "can't read less than 6 bytes from a utf8 text stream");
1337 }
1338 auto pystring = As<PythonString>(
1339 m_py_obj.CallMethod("read", (unsigned long long)num_chars));
1340 if (!pystring)
1341 // Cloning since the wrapped exception may still reference the PyThread.
1342 return Status::FromError(pystring.takeError()).Clone();
1343 if (pystring.get().IsNone()) {
1344 // EOF
1345 return Status();
1346 }
1347 auto stringref = pystring.get().AsUTF8();
1348 if (!stringref)
1349 // Cloning since the wrapped exception may still reference the PyThread.
1350 return Status::FromError(stringref.takeError()).Clone();
1351 num_bytes = stringref.get().size();
1352 memcpy(buf, stringref.get().begin(), num_bytes);
1353 return Status();
1354 }
1355};
1356} // namespace
1357
1358llvm::Expected<FileSP> PythonFile::ConvertToFile(bool borrowed) {
1359 if (!IsValid())
1360 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1361 "invalid PythonFile");
1362
1363 int fd = PyObject_AsFileDescriptor(m_py_obj);
1364 if (fd < 0) {
1365 PyErr_Clear();
1367 }
1368 auto options = GetOptionsForPyObject(*this);
1369 if (!options)
1370 return options.takeError();
1371
1376 // LLDB and python will not share I/O buffers. We should probably
1377 // flush the python buffers now.
1378 auto r = CallMethod("flush");
1379 if (!r)
1380 return r.takeError();
1381 }
1382
1383 FileSP file_sp;
1384 if (borrowed) {
1385 // In this case we don't need to retain the python
1386 // object at all.
1387 file_sp = std::make_shared<NativeFile>(fd, options.get(), false);
1388 } else {
1389 file_sp = std::static_pointer_cast<File>(
1390 std::make_shared<SimplePythonFile>(*this, borrowed, fd, options.get()));
1391 }
1392 if (!file_sp->IsValid())
1393 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1394 "invalid File");
1395
1396 return file_sp;
1397}
1398
1399llvm::Expected<FileSP>
1401
1402 assert(!PyErr_Occurred());
1403
1404 if (!IsValid())
1405 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1406 "invalid PythonFile");
1407
1408 int fd = PyObject_AsFileDescriptor(m_py_obj);
1409 if (fd < 0) {
1410 PyErr_Clear();
1412 }
1413
1414 auto io_module = PythonModule::Import("io");
1415 if (!io_module)
1416 return io_module.takeError();
1417 auto textIOBase = io_module.get().Get("TextIOBase");
1418 if (!textIOBase)
1419 return textIOBase.takeError();
1420 auto rawIOBase = io_module.get().Get("RawIOBase");
1421 if (!rawIOBase)
1422 return rawIOBase.takeError();
1423 auto bufferedIOBase = io_module.get().Get("BufferedIOBase");
1424 if (!bufferedIOBase)
1425 return bufferedIOBase.takeError();
1426
1427 FileSP file_sp;
1428
1429 auto isTextIO = IsInstance(textIOBase.get());
1430 if (!isTextIO)
1431 return isTextIO.takeError();
1432 if (isTextIO.get())
1433 file_sp = std::static_pointer_cast<File>(
1434 std::make_shared<TextPythonFile>(fd, *this, borrowed));
1435
1436 auto isRawIO = IsInstance(rawIOBase.get());
1437 if (!isRawIO)
1438 return isRawIO.takeError();
1439 auto isBufferedIO = IsInstance(bufferedIOBase.get());
1440 if (!isBufferedIO)
1441 return isBufferedIO.takeError();
1442
1443 if (isRawIO.get() || isBufferedIO.get()) {
1444 file_sp = std::static_pointer_cast<File>(
1445 std::make_shared<BinaryPythonFile>(fd, *this, borrowed));
1446 }
1447
1448 if (!file_sp)
1449 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1450 "python file is neither text nor binary");
1451
1452 if (!file_sp->IsValid())
1453 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1454 "invalid File");
1455
1456 return file_sp;
1457}
1458
1459Expected<PythonFile> PythonFile::FromFile(File &file, const char *mode) {
1460 if (!file.IsValid())
1461 return llvm::createStringError(llvm::inconvertibleErrorCode(),
1462 "invalid file");
1463
1464 if (auto *simple = llvm::dyn_cast<SimplePythonFile>(&file))
1465 return Retain<PythonFile>(simple->GetPythonObject());
1466 if (auto *pythonio = llvm::dyn_cast<PythonIOFile>(&file))
1467 return Retain<PythonFile>(pythonio->GetPythonObject());
1468
1469 if (!mode) {
1470 auto m = file.GetOpenMode();
1471 if (!m)
1472 return m.takeError();
1473 mode = m.get();
1474 }
1475
1476 PyObject *file_obj;
1477 file_obj = PyFile_FromFd(file.GetDescriptor(), nullptr, mode, -1, nullptr,
1478 "ignore", nullptr, /*closefd=*/0);
1479
1480 if (!file_obj)
1481 return exception();
1482
1483 return Take<PythonFile>(file_obj);
1484}
1485
1487 if (function.IsValid())
1488 return Error::success();
1489
1491 auto builtins = PythonModule::BuiltinsModule();
1492 if (Error error = globals.SetItem("__builtins__", builtins))
1493 return error;
1494 PyObject *o = RunString(script, Py_file_input, globals.get(), globals.get());
1495 if (!o)
1496 return exception();
1498 auto f = As<PythonCallable>(globals.GetItem("main"));
1499 if (!f)
1500 return f.takeError();
1501 function = std::move(f.get());
1502
1503 return Error::success();
1504}
1505
1506llvm::Expected<PythonObject>
1507python::runStringOneLine(const llvm::Twine &string,
1508 const PythonDictionary &globals,
1509 const PythonDictionary &locals) {
1510 if (!globals.IsValid() || !locals.IsValid())
1511 return nullDeref();
1512
1513 PyObject *code =
1514 Py_CompileString(NullTerminated(string), "<string>", Py_eval_input);
1515 if (!code) {
1516 PyErr_Clear();
1517 code =
1518 Py_CompileString(NullTerminated(string), "<string>", Py_single_input);
1519 }
1520 if (!code)
1521 return exception();
1522 auto code_ref = Take<PythonObject>(code);
1523
1524 PyObject *result = PyEval_EvalCode(code, globals.get(), locals.get());
1525
1526 if (!result)
1527 return exception();
1528
1529 return Take<PythonObject>(result);
1530}
1531
1532llvm::Expected<PythonObject>
1533python::runStringMultiLine(const llvm::Twine &string,
1534 const PythonDictionary &globals,
1535 const PythonDictionary &locals) {
1536 if (!globals.IsValid() || !locals.IsValid())
1537 return nullDeref();
1538 PyObject *result = RunString(NullTerminated(string), Py_file_input,
1539 globals.get(), locals.get());
1540 if (!result)
1541 return exception();
1542 return Take<PythonObject>(result);
1543}
1544
1545PyObject *lldb_private::python::RunString(const char *str, int start,
1546 PyObject *globals, PyObject *locals) {
1547 const char *filename = "<string>";
1548
1549 // Compile the string into a code object.
1550 PyObject *code = Py_CompileString(str, filename, start);
1551 if (!code)
1552 return nullptr;
1553
1554 // Execute the code object.
1555 PyObject *result = PyEval_EvalCode(code, globals, locals);
1556
1557 // Clean up the code object.
1558 Py_DECREF(code);
1559
1560 return result;
1561}
1562
1564 PyObject *main_module = PyImport_AddModule("__main__");
1565 if (!main_module)
1566 return -1;
1567
1568 PyObject *globals = PyModule_GetDict(main_module);
1569 if (!globals)
1570 return -1;
1571
1572 PyObject *result = RunString(str, Py_file_input, globals, globals);
1573 if (!result)
1574 return -1;
1575
1576 return 0;
1577}
static llvm::raw_ostream & error(Stream &strm)
static char ID
#define LLDB_LOGF(log,...)
Definition Log.h:389
static const char get_arg_info_script[]
llvm::Expected< File::OpenOptions > GetOptionsForPyObject(const PythonObject &obj)
const char read_exception_script[]
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
virtual bool isA(const void *classID) const
Definition FileBase.h:363
static int kInvalidDescriptor
Definition FileBase.h:36
virtual int GetDescriptor() const
Get underlying OS file descriptor for this file, or kInvalidDescriptor.
Definition File.cpp:119
llvm::Expected< const char * > GetOpenMode() const
Definition FileBase.h:321
bool IsValid() const override
IsValid.
Definition File.cpp:106
bool isA(const void *classID) const override
Definition FilePosix.h:38
Status Clone() const
Don't call this function in new code.
Definition Status.h:174
bool Fail() const
Test for error condition.
Definition Status.cpp:293
A stream class that can stream formatted output to a file.
Definition Stream.h:28
std::shared_ptr< UnsignedInteger > UnsignedIntegerSP
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< String > StringSP
std::shared_ptr< Array > ArraySP
std::shared_ptr< Boolean > BooleanSP
std::shared_ptr< SignedInteger > SignedIntegerSP
std::variant< UnsignedIntegerSP, SignedIntegerSP > IntegerSP
StructuredData::BooleanSP CreateStructuredBoolean() const
static bool Check(PyObject *py_obj)
StructuredData::StringSP CreateStructuredString() const
llvm::ArrayRef< uint8_t > GetBytes() const
static bool Check(PyObject *py_obj)
PythonByteArray(llvm::ArrayRef< uint8_t > bytes)
static bool Check(PyObject *py_obj)
StructuredData::StringSP CreateStructuredString() const
void SetBytes(llvm::ArrayRef< uint8_t > stringbytes)
PythonBytes(llvm::ArrayRef< uint8_t > bytes)
llvm::ArrayRef< uint8_t > GetBytes() const
static llvm::Expected< ArgInfo > GetArgInfoFromInspectSignature(const PythonCallable &callable)
llvm::Expected< ArgInfo > GetArgInfo() const
static bool Check(PyObject *py_obj)
StructuredData::DictionarySP CreateStructuredDictionary() const
llvm::Expected< PythonObject > GetItem(const PythonObject &key) const
bool HasKey(const llvm::Twine &key) const
PythonObject GetItemForKey(const PythonObject &key) const
llvm::Error SetItem(const PythonObject &key, const PythonObject &value) const
void SetItemForKey(const PythonObject &key, const PythonObject &value)
std::error_code convertToErrorCode() const override
void log(llvm::raw_ostream &OS) const override
PythonException(const char *caller=nullptr)
llvm::Expected< lldb::FileSP > ConvertToFileForcingUseOfScriptingIOMethods(bool borrowed=false)
llvm::Expected< lldb::FileSP > ConvertToFile(bool borrowed=false)
static bool Check(PyObject *py_obj)
static llvm::Expected< PythonFile > FromFile(File &file, const char *mode=nullptr)
StructuredData::SignedIntegerSP CreateStructuredSignedInteger() const
static bool Check(PyObject *py_obj)
StructuredData::UnsignedIntegerSP CreateStructuredUnsignedInteger() const
StructuredData::IntegerSP CreateStructuredInteger() const
PythonObject GetItemAtIndex(uint32_t index) const
void AppendItem(const PythonObject &object)
static bool Check(PyObject *py_obj)
void SetItemAtIndex(uint32_t index, const PythonObject &object)
StructuredData::ArraySP CreateStructuredArray() const
static PythonModule AddModule(llvm::StringRef module)
llvm::Expected< PythonObject > Get(const llvm::Twine &name)
static bool Check(PyObject *py_obj)
static llvm::Expected< PythonModule > Import(const llvm::Twine &name)
PythonObject ResolveName(llvm::StringRef name) const
llvm::Expected< long long > AsLongLong() const
StructuredData::ObjectSP CreateStructuredObject() const
llvm::Expected< unsigned long long > AsModuloUnsignedLongLong() const
PythonObject GetAttributeValue(llvm::StringRef attribute) const
static PythonObject ResolveNameWithDictionary(llvm::StringRef name, const PythonDictionary &dict)
llvm::Expected< unsigned long long > AsUnsignedLongLong() const
llvm::Expected< bool > IsInstance(const PythonObject &cls)
llvm::Expected< PythonObject > GetAttribute(const llvm::Twine &name) const
bool HasAttribute(llvm::StringRef attribute) const
llvm::Expected< PythonObject > CallMethod(const char *name, const T &... t) const
llvm::Expected< llvm::StringRef > AsUTF8() const
void SetString(llvm::StringRef string)
StructuredData::StringSP CreateStructuredString() const
static bool Check(PyObject *py_obj)
static llvm::Expected< PythonString > FromUTF8(llvm::StringRef string)
StructuredData::ArraySP CreateStructuredArray() const
void SetItemAtIndex(uint32_t index, const PythonObject &object)
PythonObject GetItemAtIndex(uint32_t index) const
static bool Check(PyObject *py_obj)
void Serialize(llvm::json::OStream &s) const override
#define PyBUF_READ
Definition lldb-python.h:59
llvm::Expected< unsigned long long > As< unsigned long long >(llvm::Expected< PythonObject > &&obj)
llvm::Error exception(const char *s=nullptr)
llvm::Expected< std::string > As< std::string >(llvm::Expected< PythonObject > &&obj)
PyObject * RunString(const char *str, int start, PyObject *globals, PyObject *locals)
T Retain(PyObject *obj)
llvm::Expected< T > As(llvm::Expected< PythonObject > &&obj)
llvm::Expected< PythonObject > runStringMultiLine(const llvm::Twine &string, const PythonDictionary &globals, const PythonDictionary &locals)
int RunSimpleString(const char *str)
llvm::Expected< long long > As< long long >(llvm::Expected< PythonObject > &&obj)
llvm::Expected< bool > As< bool >(llvm::Expected< PythonObject > &&obj)
llvm::Expected< PythonObject > runStringOneLine(const llvm::Twine &string, const PythonDictionary &globals, const PythonDictionary &locals)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< lldb_private::File > FileSP