1 //===-- PythonDataObjects.cpp -----------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifdef LLDB_DISABLE_PYTHON
12 // Python is disabled in this build
16 #include "PythonDataObjects.h"
17 #include "ScriptInterpreterPython.h"
19 #include "lldb/Host/File.h"
20 #include "lldb/Host/FileSystem.h"
21 #include "lldb/Interpreter/ScriptInterpreter.h"
22 #include "lldb/Utility/Stream.h"
24 #include "llvm/Support/ConvertUTF.h"
28 #include "llvm/ADT/StringSwitch.h"
30 using namespace lldb_private;
33 void StructuredPythonObject::Dump(Stream &s, bool pretty_print) const {
34 s << "Python Obj: 0x" << GetValue();
37 //----------------------------------------------------------------------
39 //----------------------------------------------------------------------
41 void PythonObject::Dump(Stream &strm) const {
43 FILE *file = ::tmpfile();
45 ::PyObject_Print(m_py_obj, file, 0);
46 const long length = ftell(file);
49 std::vector<char> file_contents(length, '\0');
50 const size_t length_read =
51 ::fread(file_contents.data(), 1, file_contents.size(), file);
53 strm.Write(file_contents.data(), length_read);
58 strm.PutCString("NULL");
61 PyObjectType PythonObject::GetObjectType() const {
63 return PyObjectType::None;
65 if (PythonModule::Check(m_py_obj))
66 return PyObjectType::Module;
67 if (PythonList::Check(m_py_obj))
68 return PyObjectType::List;
69 if (PythonTuple::Check(m_py_obj))
70 return PyObjectType::Tuple;
71 if (PythonDictionary::Check(m_py_obj))
72 return PyObjectType::Dictionary;
73 if (PythonString::Check(m_py_obj))
74 return PyObjectType::String;
75 #if PY_MAJOR_VERSION >= 3
76 if (PythonBytes::Check(m_py_obj))
77 return PyObjectType::Bytes;
79 if (PythonByteArray::Check(m_py_obj))
80 return PyObjectType::ByteArray;
81 if (PythonInteger::Check(m_py_obj))
82 return PyObjectType::Integer;
83 if (PythonFile::Check(m_py_obj))
84 return PyObjectType::File;
85 if (PythonCallable::Check(m_py_obj))
86 return PyObjectType::Callable;
87 return PyObjectType::Unknown;
90 PythonString PythonObject::Repr() const {
92 return PythonString();
93 PyObject *repr = PyObject_Repr(m_py_obj);
95 return PythonString();
96 return PythonString(PyRefType::Owned, repr);
99 PythonString PythonObject::Str() const {
101 return PythonString();
102 PyObject *str = PyObject_Str(m_py_obj);
104 return PythonString();
105 return PythonString(PyRefType::Owned, str);
109 PythonObject::ResolveNameWithDictionary(llvm::StringRef name,
110 const PythonDictionary &dict) {
111 size_t dot_pos = name.find_first_of('.');
112 llvm::StringRef piece = name.substr(0, dot_pos);
113 PythonObject result = dict.GetItemForKey(PythonString(piece));
114 if (dot_pos == llvm::StringRef::npos) {
115 // There was no dot, we're done.
119 // There was a dot. The remaining portion of the name should be looked up in
120 // the context of the object that was found in the dictionary.
121 return result.ResolveName(name.substr(dot_pos + 1));
124 PythonObject PythonObject::ResolveName(llvm::StringRef name) const {
125 // Resolve the name in the context of the specified object. If, for example,
126 // `this` refers to a PyModule, then this will look for `name` in this
127 // module. If `this` refers to a PyType, then it will resolve `name` as an
128 // attribute of that type. If `this` refers to an instance of an object,
129 // then it will resolve `name` as the value of the specified field.
131 // This function handles dotted names so that, for example, if `m_py_obj`
132 // refers to the `sys` module, and `name` == "path.append", then it will find
133 // the function `sys.path.append`.
135 size_t dot_pos = name.find_first_of('.');
136 if (dot_pos == llvm::StringRef::npos) {
137 // No dots in the name, we should be able to find the value immediately as
138 // an attribute of `m_py_obj`.
139 return GetAttributeValue(name);
142 // Look up the first piece of the name, and resolve the rest as a child of
144 PythonObject parent = ResolveName(name.substr(0, dot_pos));
145 if (!parent.IsAllocated())
146 return PythonObject();
148 // Tail recursion.. should be optimized by the compiler
149 return parent.ResolveName(name.substr(dot_pos + 1));
152 bool PythonObject::HasAttribute(llvm::StringRef attr) const {
155 PythonString py_attr(attr);
156 return !!PyObject_HasAttr(m_py_obj, py_attr.get());
159 PythonObject PythonObject::GetAttributeValue(llvm::StringRef attr) const {
161 return PythonObject();
163 PythonString py_attr(attr);
164 if (!PyObject_HasAttr(m_py_obj, py_attr.get()))
165 return PythonObject();
167 return PythonObject(PyRefType::Owned,
168 PyObject_GetAttr(m_py_obj, py_attr.get()));
171 bool PythonObject::IsNone() const { return m_py_obj == Py_None; }
173 bool PythonObject::IsValid() const { return m_py_obj != nullptr; }
175 bool PythonObject::IsAllocated() const { return IsValid() && !IsNone(); }
177 StructuredData::ObjectSP PythonObject::CreateStructuredObject() const {
178 switch (GetObjectType()) {
179 case PyObjectType::Dictionary:
180 return PythonDictionary(PyRefType::Borrowed, m_py_obj)
181 .CreateStructuredDictionary();
182 case PyObjectType::Integer:
183 return PythonInteger(PyRefType::Borrowed, m_py_obj)
184 .CreateStructuredInteger();
185 case PyObjectType::List:
186 return PythonList(PyRefType::Borrowed, m_py_obj).CreateStructuredArray();
187 case PyObjectType::String:
188 return PythonString(PyRefType::Borrowed, m_py_obj).CreateStructuredString();
189 case PyObjectType::Bytes:
190 return PythonBytes(PyRefType::Borrowed, m_py_obj).CreateStructuredString();
191 case PyObjectType::ByteArray:
192 return PythonByteArray(PyRefType::Borrowed, m_py_obj)
193 .CreateStructuredString();
194 case PyObjectType::None:
195 return StructuredData::ObjectSP();
197 return StructuredData::ObjectSP(new StructuredPythonObject(m_py_obj));
201 //----------------------------------------------------------------------
203 //----------------------------------------------------------------------
204 PythonBytes::PythonBytes() : PythonObject() {}
206 PythonBytes::PythonBytes(llvm::ArrayRef<uint8_t> bytes) : PythonObject() {
210 PythonBytes::PythonBytes(const uint8_t *bytes, size_t length) : PythonObject() {
211 SetBytes(llvm::ArrayRef<uint8_t>(bytes, length));
214 PythonBytes::PythonBytes(PyRefType type, PyObject *py_obj) : PythonObject() {
215 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a string
218 PythonBytes::PythonBytes(const PythonBytes &object) : PythonObject(object) {}
220 PythonBytes::~PythonBytes() {}
222 bool PythonBytes::Check(PyObject *py_obj) {
225 if (PyBytes_Check(py_obj))
230 void PythonBytes::Reset(PyRefType type, PyObject *py_obj) {
231 // Grab the desired reference type so that if we end up rejecting `py_obj` it
232 // still gets decremented if necessary.
233 PythonObject result(type, py_obj);
235 if (!PythonBytes::Check(py_obj)) {
236 PythonObject::Reset();
240 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
241 // overflow since it calls back into the virtual implementation.
242 PythonObject::Reset(PyRefType::Borrowed, result.get());
245 llvm::ArrayRef<uint8_t> PythonBytes::GetBytes() const {
247 return llvm::ArrayRef<uint8_t>();
252 PyBytes_AsStringAndSize(m_py_obj, &c, &size);
253 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
256 size_t PythonBytes::GetSize() const {
259 return PyBytes_Size(m_py_obj);
262 void PythonBytes::SetBytes(llvm::ArrayRef<uint8_t> bytes) {
263 const char *data = reinterpret_cast<const char *>(bytes.data());
264 PyObject *py_bytes = PyBytes_FromStringAndSize(data, bytes.size());
265 PythonObject::Reset(PyRefType::Owned, py_bytes);
268 StructuredData::StringSP PythonBytes::CreateStructuredString() const {
269 StructuredData::StringSP result(new StructuredData::String);
272 PyBytes_AsStringAndSize(m_py_obj, &c, &size);
273 result->SetValue(std::string(c, size));
277 PythonByteArray::PythonByteArray(llvm::ArrayRef<uint8_t> bytes)
278 : PythonByteArray(bytes.data(), bytes.size()) {}
280 PythonByteArray::PythonByteArray(const uint8_t *bytes, size_t length) {
281 const char *str = reinterpret_cast<const char *>(bytes);
282 Reset(PyRefType::Owned, PyByteArray_FromStringAndSize(str, length));
285 PythonByteArray::PythonByteArray(PyRefType type, PyObject *o) {
289 PythonByteArray::PythonByteArray(const PythonBytes &object)
290 : PythonObject(object) {}
292 PythonByteArray::~PythonByteArray() {}
294 bool PythonByteArray::Check(PyObject *py_obj) {
297 if (PyByteArray_Check(py_obj))
302 void PythonByteArray::Reset(PyRefType type, PyObject *py_obj) {
303 // Grab the desired reference type so that if we end up rejecting `py_obj` it
304 // still gets decremented if necessary.
305 PythonObject result(type, py_obj);
307 if (!PythonByteArray::Check(py_obj)) {
308 PythonObject::Reset();
312 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
313 // overflow since it calls back into the virtual implementation.
314 PythonObject::Reset(PyRefType::Borrowed, result.get());
317 llvm::ArrayRef<uint8_t> PythonByteArray::GetBytes() const {
319 return llvm::ArrayRef<uint8_t>();
321 char *c = PyByteArray_AsString(m_py_obj);
322 size_t size = GetSize();
323 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
326 size_t PythonByteArray::GetSize() const {
330 return PyByteArray_Size(m_py_obj);
333 StructuredData::StringSP PythonByteArray::CreateStructuredString() const {
334 StructuredData::StringSP result(new StructuredData::String);
335 llvm::ArrayRef<uint8_t> bytes = GetBytes();
336 const char *str = reinterpret_cast<const char *>(bytes.data());
337 result->SetValue(std::string(str, bytes.size()));
341 //----------------------------------------------------------------------
343 //----------------------------------------------------------------------
345 PythonString::PythonString(PyRefType type, PyObject *py_obj) : PythonObject() {
346 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a string
349 PythonString::PythonString(const PythonString &object) : PythonObject(object) {}
351 PythonString::PythonString(llvm::StringRef string) : PythonObject() {
355 PythonString::PythonString(const char *string) : PythonObject() {
356 SetString(llvm::StringRef(string));
359 PythonString::PythonString() : PythonObject() {}
361 PythonString::~PythonString() {}
363 bool PythonString::Check(PyObject *py_obj) {
367 if (PyUnicode_Check(py_obj))
369 #if PY_MAJOR_VERSION < 3
370 if (PyString_Check(py_obj))
376 void PythonString::Reset(PyRefType type, PyObject *py_obj) {
377 // Grab the desired reference type so that if we end up rejecting `py_obj` it
378 // still gets decremented if necessary.
379 PythonObject result(type, py_obj);
381 if (!PythonString::Check(py_obj)) {
382 PythonObject::Reset();
385 #if PY_MAJOR_VERSION < 3
386 // In Python 2, Don't store PyUnicode objects directly, because we need
387 // access to their underlying character buffers which Python 2 doesn't
389 if (PyUnicode_Check(py_obj))
390 result.Reset(PyRefType::Owned, PyUnicode_AsUTF8String(result.get()));
392 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
393 // overflow since it calls back into the virtual implementation.
394 PythonObject::Reset(PyRefType::Borrowed, result.get());
397 llvm::StringRef PythonString::GetString() const {
399 return llvm::StringRef();
404 #if PY_MAJOR_VERSION >= 3
405 data = PyUnicode_AsUTF8AndSize(m_py_obj, &size);
408 PyString_AsStringAndSize(m_py_obj, &c, &size);
411 return llvm::StringRef(data, size);
414 size_t PythonString::GetSize() const {
416 #if PY_MAJOR_VERSION >= 3
417 return PyUnicode_GetSize(m_py_obj);
419 return PyString_Size(m_py_obj);
425 void PythonString::SetString(llvm::StringRef string) {
426 #if PY_MAJOR_VERSION >= 3
427 PyObject *unicode = PyUnicode_FromStringAndSize(string.data(), string.size());
428 PythonObject::Reset(PyRefType::Owned, unicode);
430 PyObject *str = PyString_FromStringAndSize(string.data(), string.size());
431 PythonObject::Reset(PyRefType::Owned, str);
435 StructuredData::StringSP PythonString::CreateStructuredString() const {
436 StructuredData::StringSP result(new StructuredData::String);
437 result->SetValue(GetString());
441 //----------------------------------------------------------------------
443 //----------------------------------------------------------------------
445 PythonInteger::PythonInteger() : PythonObject() {}
447 PythonInteger::PythonInteger(PyRefType type, PyObject *py_obj)
449 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a integer type
452 PythonInteger::PythonInteger(const PythonInteger &object)
453 : PythonObject(object) {}
455 PythonInteger::PythonInteger(int64_t value) : PythonObject() {
459 PythonInteger::~PythonInteger() {}
461 bool PythonInteger::Check(PyObject *py_obj) {
465 #if PY_MAJOR_VERSION >= 3
466 // Python 3 does not have PyInt_Check. There is only one type of integral
468 return PyLong_Check(py_obj);
470 return PyLong_Check(py_obj) || PyInt_Check(py_obj);
474 void PythonInteger::Reset(PyRefType type, PyObject *py_obj) {
475 // Grab the desired reference type so that if we end up rejecting `py_obj` it
476 // still gets decremented if necessary.
477 PythonObject result(type, py_obj);
479 if (!PythonInteger::Check(py_obj)) {
480 PythonObject::Reset();
484 #if PY_MAJOR_VERSION < 3
485 // Always store this as a PyLong, which makes interoperability between Python
486 // 2.x and Python 3.x easier. This is only necessary in 2.x, since 3.x
487 // doesn't even have a PyInt.
488 if (PyInt_Check(py_obj)) {
489 // Since we converted the original object to a different type, the new
490 // object is an owned object regardless of the ownership semantics
491 // requested by the user.
492 result.Reset(PyRefType::Owned, PyLong_FromLongLong(PyInt_AsLong(py_obj)));
496 assert(PyLong_Check(result.get()) &&
497 "Couldn't get a PyLong from this PyObject");
499 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
500 // overflow since it calls back into the virtual implementation.
501 PythonObject::Reset(PyRefType::Borrowed, result.get());
504 int64_t PythonInteger::GetInteger() const {
506 assert(PyLong_Check(m_py_obj) &&
507 "PythonInteger::GetInteger has a PyObject that isn't a PyLong");
510 int64_t result = PyLong_AsLongLongAndOverflow(m_py_obj, &overflow);
512 // We got an integer that overflows, like 18446744072853913392L we can't
513 // use PyLong_AsLongLong() as it will return 0xffffffffffffffff. If we
514 // use the unsigned long long it will work as expected.
515 const uint64_t uval = PyLong_AsUnsignedLongLong(m_py_obj);
516 result = static_cast<int64_t>(uval);
523 void PythonInteger::SetInteger(int64_t value) {
524 PythonObject::Reset(PyRefType::Owned, PyLong_FromLongLong(value));
527 StructuredData::IntegerSP PythonInteger::CreateStructuredInteger() const {
528 StructuredData::IntegerSP result(new StructuredData::Integer);
529 result->SetValue(GetInteger());
533 //----------------------------------------------------------------------
535 //----------------------------------------------------------------------
537 PythonList::PythonList(PyInitialValue value) : PythonObject() {
538 if (value == PyInitialValue::Empty)
539 Reset(PyRefType::Owned, PyList_New(0));
542 PythonList::PythonList(int list_size) : PythonObject() {
543 Reset(PyRefType::Owned, PyList_New(list_size));
546 PythonList::PythonList(PyRefType type, PyObject *py_obj) : PythonObject() {
547 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a list
550 PythonList::PythonList(const PythonList &list) : PythonObject(list) {}
552 PythonList::~PythonList() {}
554 bool PythonList::Check(PyObject *py_obj) {
557 return PyList_Check(py_obj);
560 void PythonList::Reset(PyRefType type, PyObject *py_obj) {
561 // Grab the desired reference type so that if we end up rejecting `py_obj` it
562 // still gets decremented if necessary.
563 PythonObject result(type, py_obj);
565 if (!PythonList::Check(py_obj)) {
566 PythonObject::Reset();
570 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
571 // overflow since it calls back into the virtual implementation.
572 PythonObject::Reset(PyRefType::Borrowed, result.get());
575 uint32_t PythonList::GetSize() const {
577 return PyList_GET_SIZE(m_py_obj);
581 PythonObject PythonList::GetItemAtIndex(uint32_t index) const {
583 return PythonObject(PyRefType::Borrowed, PyList_GetItem(m_py_obj, index));
584 return PythonObject();
587 void PythonList::SetItemAtIndex(uint32_t index, const PythonObject &object) {
588 if (IsAllocated() && object.IsValid()) {
589 // PyList_SetItem is documented to "steal" a reference, so we need to
590 // convert it to an owned reference by incrementing it.
591 Py_INCREF(object.get());
592 PyList_SetItem(m_py_obj, index, object.get());
596 void PythonList::AppendItem(const PythonObject &object) {
597 if (IsAllocated() && object.IsValid()) {
598 // `PyList_Append` does *not* steal a reference, so do not call `Py_INCREF`
599 // here like we do with `PyList_SetItem`.
600 PyList_Append(m_py_obj, object.get());
604 StructuredData::ArraySP PythonList::CreateStructuredArray() const {
605 StructuredData::ArraySP result(new StructuredData::Array);
606 uint32_t count = GetSize();
607 for (uint32_t i = 0; i < count; ++i) {
608 PythonObject obj = GetItemAtIndex(i);
609 result->AddItem(obj.CreateStructuredObject());
614 //----------------------------------------------------------------------
616 //----------------------------------------------------------------------
618 PythonTuple::PythonTuple(PyInitialValue value) : PythonObject() {
619 if (value == PyInitialValue::Empty)
620 Reset(PyRefType::Owned, PyTuple_New(0));
623 PythonTuple::PythonTuple(int tuple_size) : PythonObject() {
624 Reset(PyRefType::Owned, PyTuple_New(tuple_size));
627 PythonTuple::PythonTuple(PyRefType type, PyObject *py_obj) : PythonObject() {
628 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a tuple
631 PythonTuple::PythonTuple(const PythonTuple &tuple) : PythonObject(tuple) {}
633 PythonTuple::PythonTuple(std::initializer_list<PythonObject> objects) {
634 m_py_obj = PyTuple_New(objects.size());
637 for (auto object : objects) {
638 if (object.IsValid())
639 SetItemAtIndex(idx, object);
644 PythonTuple::PythonTuple(std::initializer_list<PyObject *> objects) {
645 m_py_obj = PyTuple_New(objects.size());
648 for (auto py_object : objects) {
649 PythonObject object(PyRefType::Borrowed, py_object);
650 if (object.IsValid())
651 SetItemAtIndex(idx, object);
656 PythonTuple::~PythonTuple() {}
658 bool PythonTuple::Check(PyObject *py_obj) {
661 return PyTuple_Check(py_obj);
664 void PythonTuple::Reset(PyRefType type, PyObject *py_obj) {
665 // Grab the desired reference type so that if we end up rejecting `py_obj` it
666 // still gets decremented if necessary.
667 PythonObject result(type, py_obj);
669 if (!PythonTuple::Check(py_obj)) {
670 PythonObject::Reset();
674 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
675 // overflow since it calls back into the virtual implementation.
676 PythonObject::Reset(PyRefType::Borrowed, result.get());
679 uint32_t PythonTuple::GetSize() const {
681 return PyTuple_GET_SIZE(m_py_obj);
685 PythonObject PythonTuple::GetItemAtIndex(uint32_t index) const {
687 return PythonObject(PyRefType::Borrowed, PyTuple_GetItem(m_py_obj, index));
688 return PythonObject();
691 void PythonTuple::SetItemAtIndex(uint32_t index, const PythonObject &object) {
692 if (IsAllocated() && object.IsValid()) {
693 // PyTuple_SetItem is documented to "steal" a reference, so we need to
694 // convert it to an owned reference by incrementing it.
695 Py_INCREF(object.get());
696 PyTuple_SetItem(m_py_obj, index, object.get());
700 StructuredData::ArraySP PythonTuple::CreateStructuredArray() const {
701 StructuredData::ArraySP result(new StructuredData::Array);
702 uint32_t count = GetSize();
703 for (uint32_t i = 0; i < count; ++i) {
704 PythonObject obj = GetItemAtIndex(i);
705 result->AddItem(obj.CreateStructuredObject());
710 //----------------------------------------------------------------------
712 //----------------------------------------------------------------------
714 PythonDictionary::PythonDictionary(PyInitialValue value) : PythonObject() {
715 if (value == PyInitialValue::Empty)
716 Reset(PyRefType::Owned, PyDict_New());
719 PythonDictionary::PythonDictionary(PyRefType type, PyObject *py_obj)
721 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a dictionary
724 PythonDictionary::PythonDictionary(const PythonDictionary &object)
725 : PythonObject(object) {}
727 PythonDictionary::~PythonDictionary() {}
729 bool PythonDictionary::Check(PyObject *py_obj) {
733 return PyDict_Check(py_obj);
736 void PythonDictionary::Reset(PyRefType type, PyObject *py_obj) {
737 // Grab the desired reference type so that if we end up rejecting `py_obj` it
738 // still gets decremented if necessary.
739 PythonObject result(type, py_obj);
741 if (!PythonDictionary::Check(py_obj)) {
742 PythonObject::Reset();
746 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
747 // overflow since it calls back into the virtual implementation.
748 PythonObject::Reset(PyRefType::Borrowed, result.get());
751 uint32_t PythonDictionary::GetSize() const {
753 return PyDict_Size(m_py_obj);
757 PythonList PythonDictionary::GetKeys() const {
759 return PythonList(PyRefType::Owned, PyDict_Keys(m_py_obj));
760 return PythonList(PyInitialValue::Invalid);
763 PythonObject PythonDictionary::GetItemForKey(const PythonObject &key) const {
764 if (IsAllocated() && key.IsValid())
765 return PythonObject(PyRefType::Borrowed,
766 PyDict_GetItem(m_py_obj, key.get()));
767 return PythonObject();
770 void PythonDictionary::SetItemForKey(const PythonObject &key,
771 const PythonObject &value) {
772 if (IsAllocated() && key.IsValid() && value.IsValid())
773 PyDict_SetItem(m_py_obj, key.get(), value.get());
776 StructuredData::DictionarySP
777 PythonDictionary::CreateStructuredDictionary() const {
778 StructuredData::DictionarySP result(new StructuredData::Dictionary);
779 PythonList keys(GetKeys());
780 uint32_t num_keys = keys.GetSize();
781 for (uint32_t i = 0; i < num_keys; ++i) {
782 PythonObject key = keys.GetItemAtIndex(i);
783 PythonObject value = GetItemForKey(key);
784 StructuredData::ObjectSP structured_value = value.CreateStructuredObject();
785 result->AddItem(key.Str().GetString(), structured_value);
790 PythonModule::PythonModule() : PythonObject() {}
792 PythonModule::PythonModule(PyRefType type, PyObject *py_obj) {
793 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a module
796 PythonModule::PythonModule(const PythonModule &dict) : PythonObject(dict) {}
798 PythonModule::~PythonModule() {}
800 PythonModule PythonModule::BuiltinsModule() {
801 #if PY_MAJOR_VERSION >= 3
802 return AddModule("builtins");
804 return AddModule("__builtin__");
808 PythonModule PythonModule::MainModule() { return AddModule("__main__"); }
810 PythonModule PythonModule::AddModule(llvm::StringRef module) {
811 std::string str = module.str();
812 return PythonModule(PyRefType::Borrowed, PyImport_AddModule(str.c_str()));
815 PythonModule PythonModule::ImportModule(llvm::StringRef module) {
816 std::string str = module.str();
817 return PythonModule(PyRefType::Owned, PyImport_ImportModule(str.c_str()));
820 bool PythonModule::Check(PyObject *py_obj) {
824 return PyModule_Check(py_obj);
827 void PythonModule::Reset(PyRefType type, PyObject *py_obj) {
828 // Grab the desired reference type so that if we end up rejecting `py_obj` it
829 // still gets decremented if necessary.
830 PythonObject result(type, py_obj);
832 if (!PythonModule::Check(py_obj)) {
833 PythonObject::Reset();
837 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
838 // overflow since it calls back into the virtual implementation.
839 PythonObject::Reset(PyRefType::Borrowed, result.get());
842 PythonDictionary PythonModule::GetDictionary() const {
843 return PythonDictionary(PyRefType::Borrowed, PyModule_GetDict(m_py_obj));
846 PythonCallable::PythonCallable() : PythonObject() {}
848 PythonCallable::PythonCallable(PyRefType type, PyObject *py_obj) {
849 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a callable
852 PythonCallable::PythonCallable(const PythonCallable &callable)
853 : PythonObject(callable) {}
855 PythonCallable::~PythonCallable() {}
857 bool PythonCallable::Check(PyObject *py_obj) {
861 return PyCallable_Check(py_obj);
864 void PythonCallable::Reset(PyRefType type, PyObject *py_obj) {
865 // Grab the desired reference type so that if we end up rejecting `py_obj` it
866 // still gets decremented if necessary.
867 PythonObject result(type, py_obj);
869 if (!PythonCallable::Check(py_obj)) {
870 PythonObject::Reset();
874 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
875 // overflow since it calls back into the virtual implementation.
876 PythonObject::Reset(PyRefType::Borrowed, result.get());
879 PythonCallable::ArgInfo PythonCallable::GetNumArguments() const {
880 ArgInfo result = {0, false, false, false};
884 PyObject *py_func_obj = m_py_obj;
885 if (PyMethod_Check(py_func_obj)) {
886 py_func_obj = PyMethod_GET_FUNCTION(py_func_obj);
887 PythonObject im_self = GetAttributeValue("im_self");
888 if (im_self.IsValid() && !im_self.IsNone())
889 result.is_bound_method = true;
891 // see if this is a callable object with an __call__ method
892 if (!PyFunction_Check(py_func_obj)) {
893 PythonObject __call__ = GetAttributeValue("__call__");
894 if (__call__.IsValid()) {
895 auto __callable__ = __call__.AsType<PythonCallable>();
896 if (__callable__.IsValid()) {
897 py_func_obj = PyMethod_GET_FUNCTION(__callable__.get());
898 PythonObject im_self = GetAttributeValue("im_self");
899 if (im_self.IsValid() && !im_self.IsNone())
900 result.is_bound_method = true;
909 PyCodeObject *code = (PyCodeObject *)PyFunction_GET_CODE(py_func_obj);
913 result.count = code->co_argcount;
914 result.has_varargs = !!(code->co_flags & CO_VARARGS);
915 result.has_kwargs = !!(code->co_flags & CO_VARKEYWORDS);
919 PythonObject PythonCallable::operator()() {
920 return PythonObject(PyRefType::Owned, PyObject_CallObject(m_py_obj, nullptr));
923 PythonObject PythonCallable::
924 operator()(std::initializer_list<PyObject *> args) {
925 PythonTuple arg_tuple(args);
926 return PythonObject(PyRefType::Owned,
927 PyObject_CallObject(m_py_obj, arg_tuple.get()));
930 PythonObject PythonCallable::
931 operator()(std::initializer_list<PythonObject> args) {
932 PythonTuple arg_tuple(args);
933 return PythonObject(PyRefType::Owned,
934 PyObject_CallObject(m_py_obj, arg_tuple.get()));
937 PythonFile::PythonFile() : PythonObject() {}
939 PythonFile::PythonFile(File &file, const char *mode) { Reset(file, mode); }
941 PythonFile::PythonFile(const char *path, const char *mode) {
942 lldb_private::File file(path, GetOptionsFromMode(mode));
946 PythonFile::PythonFile(PyRefType type, PyObject *o) { Reset(type, o); }
948 PythonFile::~PythonFile() {}
950 bool PythonFile::Check(PyObject *py_obj) {
951 #if PY_MAJOR_VERSION < 3
952 return PyFile_Check(py_obj);
954 // In Python 3, there is no `PyFile_Check`, and in fact PyFile is not even a
955 // first-class object type anymore. `PyFile_FromFd` is just a thin wrapper
956 // over `io.open()`, which returns some object derived from `io.IOBase`. As a
957 // result, the only way to detect a file in Python 3 is to check whether it
958 // inherits from `io.IOBase`. Since it is possible for non-files to also
959 // inherit from `io.IOBase`, we additionally verify that it has the `fileno`
960 // attribute, which should guarantee that it is backed by the file system.
961 PythonObject io_module(PyRefType::Owned, PyImport_ImportModule("io"));
962 PythonDictionary io_dict(PyRefType::Borrowed,
963 PyModule_GetDict(io_module.get()));
964 PythonObject io_base_class = io_dict.GetItemForKey(PythonString("IOBase"));
966 PythonObject object_type(PyRefType::Owned, PyObject_Type(py_obj));
968 if (1 != PyObject_IsSubclass(object_type.get(), io_base_class.get()))
970 if (!object_type.HasAttribute("fileno"))
977 void PythonFile::Reset(PyRefType type, PyObject *py_obj) {
978 // Grab the desired reference type so that if we end up rejecting `py_obj` it
979 // still gets decremented if necessary.
980 PythonObject result(type, py_obj);
982 if (!PythonFile::Check(py_obj)) {
983 PythonObject::Reset();
987 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
988 // overflow since it calls back into the virtual implementation.
989 PythonObject::Reset(PyRefType::Borrowed, result.get());
992 void PythonFile::Reset(File &file, const char *mode) {
993 if (!file.IsValid()) {
998 char *cmode = const_cast<char *>(mode);
999 #if PY_MAJOR_VERSION >= 3
1000 Reset(PyRefType::Owned, PyFile_FromFd(file.GetDescriptor(), nullptr, cmode,
1001 -1, nullptr, "ignore", nullptr, 0));
1003 // Read through the Python source, doesn't seem to modify these strings
1004 Reset(PyRefType::Owned,
1005 PyFile_FromFile(file.GetStream(), const_cast<char *>(""), cmode,
1010 uint32_t PythonFile::GetOptionsFromMode(llvm::StringRef mode) {
1014 return llvm::StringSwitch<uint32_t>(mode.str())
1015 .Case("r", File::eOpenOptionRead)
1016 .Case("w", File::eOpenOptionWrite)
1017 .Case("a", File::eOpenOptionWrite | File::eOpenOptionAppend |
1018 File::eOpenOptionCanCreate)
1019 .Case("r+", File::eOpenOptionRead | File::eOpenOptionWrite)
1020 .Case("w+", File::eOpenOptionRead | File::eOpenOptionWrite |
1021 File::eOpenOptionCanCreate | File::eOpenOptionTruncate)
1022 .Case("a+", File::eOpenOptionRead | File::eOpenOptionWrite |
1023 File::eOpenOptionAppend | File::eOpenOptionCanCreate)
1027 bool PythonFile::GetUnderlyingFile(File &file) const {
1032 // We don't own the file descriptor returned by this function, make sure the
1033 // File object knows about that.
1034 file.SetDescriptor(PyObject_AsFileDescriptor(m_py_obj), false);
1035 PythonString py_mode = GetAttributeValue("mode").AsType<PythonString>();
1036 file.SetOptions(PythonFile::GetOptionsFromMode(py_mode.GetString()));
1037 return file.IsValid();