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 return PyBytes_Check(py_obj);
228 void PythonBytes::Reset(PyRefType type, PyObject *py_obj) {
229 // Grab the desired reference type so that if we end up rejecting `py_obj` it
230 // still gets decremented if necessary.
231 PythonObject result(type, py_obj);
233 if (!PythonBytes::Check(py_obj)) {
234 PythonObject::Reset();
238 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
239 // overflow since it calls back into the virtual implementation.
240 PythonObject::Reset(PyRefType::Borrowed, result.get());
243 llvm::ArrayRef<uint8_t> PythonBytes::GetBytes() const {
245 return llvm::ArrayRef<uint8_t>();
250 PyBytes_AsStringAndSize(m_py_obj, &c, &size);
251 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
254 size_t PythonBytes::GetSize() const {
257 return PyBytes_Size(m_py_obj);
260 void PythonBytes::SetBytes(llvm::ArrayRef<uint8_t> bytes) {
261 const char *data = reinterpret_cast<const char *>(bytes.data());
262 PyObject *py_bytes = PyBytes_FromStringAndSize(data, bytes.size());
263 PythonObject::Reset(PyRefType::Owned, py_bytes);
266 StructuredData::StringSP PythonBytes::CreateStructuredString() const {
267 StructuredData::StringSP result(new StructuredData::String);
270 PyBytes_AsStringAndSize(m_py_obj, &c, &size);
271 result->SetValue(std::string(c, size));
275 PythonByteArray::PythonByteArray(llvm::ArrayRef<uint8_t> bytes)
276 : PythonByteArray(bytes.data(), bytes.size()) {}
278 PythonByteArray::PythonByteArray(const uint8_t *bytes, size_t length) {
279 const char *str = reinterpret_cast<const char *>(bytes);
280 Reset(PyRefType::Owned, PyByteArray_FromStringAndSize(str, length));
283 PythonByteArray::PythonByteArray(PyRefType type, PyObject *o) {
287 PythonByteArray::PythonByteArray(const PythonBytes &object)
288 : PythonObject(object) {}
290 PythonByteArray::~PythonByteArray() {}
292 bool PythonByteArray::Check(PyObject *py_obj) {
295 return PyByteArray_Check(py_obj);
298 void PythonByteArray::Reset(PyRefType type, PyObject *py_obj) {
299 // Grab the desired reference type so that if we end up rejecting `py_obj` it
300 // still gets decremented if necessary.
301 PythonObject result(type, py_obj);
303 if (!PythonByteArray::Check(py_obj)) {
304 PythonObject::Reset();
308 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
309 // overflow since it calls back into the virtual implementation.
310 PythonObject::Reset(PyRefType::Borrowed, result.get());
313 llvm::ArrayRef<uint8_t> PythonByteArray::GetBytes() const {
315 return llvm::ArrayRef<uint8_t>();
317 char *c = PyByteArray_AsString(m_py_obj);
318 size_t size = GetSize();
319 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
322 size_t PythonByteArray::GetSize() const {
326 return PyByteArray_Size(m_py_obj);
329 StructuredData::StringSP PythonByteArray::CreateStructuredString() const {
330 StructuredData::StringSP result(new StructuredData::String);
331 llvm::ArrayRef<uint8_t> bytes = GetBytes();
332 const char *str = reinterpret_cast<const char *>(bytes.data());
333 result->SetValue(std::string(str, bytes.size()));
337 //----------------------------------------------------------------------
339 //----------------------------------------------------------------------
341 PythonString::PythonString(PyRefType type, PyObject *py_obj) : PythonObject() {
342 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a string
345 PythonString::PythonString(const PythonString &object) : PythonObject(object) {}
347 PythonString::PythonString(llvm::StringRef string) : PythonObject() {
351 PythonString::PythonString(const char *string) : PythonObject() {
352 SetString(llvm::StringRef(string));
355 PythonString::PythonString() : PythonObject() {}
357 PythonString::~PythonString() {}
359 bool PythonString::Check(PyObject *py_obj) {
363 if (PyUnicode_Check(py_obj))
365 #if PY_MAJOR_VERSION < 3
366 if (PyString_Check(py_obj))
372 void PythonString::Reset(PyRefType type, PyObject *py_obj) {
373 // Grab the desired reference type so that if we end up rejecting `py_obj` it
374 // still gets decremented if necessary.
375 PythonObject result(type, py_obj);
377 if (!PythonString::Check(py_obj)) {
378 PythonObject::Reset();
381 #if PY_MAJOR_VERSION < 3
382 // In Python 2, Don't store PyUnicode objects directly, because we need
383 // access to their underlying character buffers which Python 2 doesn't
385 if (PyUnicode_Check(py_obj))
386 result.Reset(PyRefType::Owned, PyUnicode_AsUTF8String(result.get()));
388 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
389 // overflow since it calls back into the virtual implementation.
390 PythonObject::Reset(PyRefType::Borrowed, result.get());
393 llvm::StringRef PythonString::GetString() const {
395 return llvm::StringRef();
400 #if PY_MAJOR_VERSION >= 3
401 data = PyUnicode_AsUTF8AndSize(m_py_obj, &size);
404 PyString_AsStringAndSize(m_py_obj, &c, &size);
407 return llvm::StringRef(data, size);
410 size_t PythonString::GetSize() const {
412 #if PY_MAJOR_VERSION >= 3
413 return PyUnicode_GetSize(m_py_obj);
415 return PyString_Size(m_py_obj);
421 void PythonString::SetString(llvm::StringRef string) {
422 #if PY_MAJOR_VERSION >= 3
423 PyObject *unicode = PyUnicode_FromStringAndSize(string.data(), string.size());
424 PythonObject::Reset(PyRefType::Owned, unicode);
426 PyObject *str = PyString_FromStringAndSize(string.data(), string.size());
427 PythonObject::Reset(PyRefType::Owned, str);
431 StructuredData::StringSP PythonString::CreateStructuredString() const {
432 StructuredData::StringSP result(new StructuredData::String);
433 result->SetValue(GetString());
437 //----------------------------------------------------------------------
439 //----------------------------------------------------------------------
441 PythonInteger::PythonInteger() : PythonObject() {}
443 PythonInteger::PythonInteger(PyRefType type, PyObject *py_obj)
445 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a integer type
448 PythonInteger::PythonInteger(const PythonInteger &object)
449 : PythonObject(object) {}
451 PythonInteger::PythonInteger(int64_t value) : PythonObject() {
455 PythonInteger::~PythonInteger() {}
457 bool PythonInteger::Check(PyObject *py_obj) {
461 #if PY_MAJOR_VERSION >= 3
462 // Python 3 does not have PyInt_Check. There is only one type of integral
464 return PyLong_Check(py_obj);
466 return PyLong_Check(py_obj) || PyInt_Check(py_obj);
470 void PythonInteger::Reset(PyRefType type, PyObject *py_obj) {
471 // Grab the desired reference type so that if we end up rejecting `py_obj` it
472 // still gets decremented if necessary.
473 PythonObject result(type, py_obj);
475 if (!PythonInteger::Check(py_obj)) {
476 PythonObject::Reset();
480 #if PY_MAJOR_VERSION < 3
481 // Always store this as a PyLong, which makes interoperability between Python
482 // 2.x and Python 3.x easier. This is only necessary in 2.x, since 3.x
483 // doesn't even have a PyInt.
484 if (PyInt_Check(py_obj)) {
485 // Since we converted the original object to a different type, the new
486 // object is an owned object regardless of the ownership semantics
487 // requested by the user.
488 result.Reset(PyRefType::Owned, PyLong_FromLongLong(PyInt_AsLong(py_obj)));
492 assert(PyLong_Check(result.get()) &&
493 "Couldn't get a PyLong from this PyObject");
495 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
496 // overflow since it calls back into the virtual implementation.
497 PythonObject::Reset(PyRefType::Borrowed, result.get());
500 int64_t PythonInteger::GetInteger() const {
502 assert(PyLong_Check(m_py_obj) &&
503 "PythonInteger::GetInteger has a PyObject that isn't a PyLong");
506 int64_t result = PyLong_AsLongLongAndOverflow(m_py_obj, &overflow);
508 // We got an integer that overflows, like 18446744072853913392L we can't
509 // use PyLong_AsLongLong() as it will return 0xffffffffffffffff. If we
510 // use the unsigned long long it will work as expected.
511 const uint64_t uval = PyLong_AsUnsignedLongLong(m_py_obj);
512 result = static_cast<int64_t>(uval);
519 void PythonInteger::SetInteger(int64_t value) {
520 PythonObject::Reset(PyRefType::Owned, PyLong_FromLongLong(value));
523 StructuredData::IntegerSP PythonInteger::CreateStructuredInteger() const {
524 StructuredData::IntegerSP result(new StructuredData::Integer);
525 result->SetValue(GetInteger());
529 //----------------------------------------------------------------------
531 //----------------------------------------------------------------------
533 PythonList::PythonList(PyInitialValue value) : PythonObject() {
534 if (value == PyInitialValue::Empty)
535 Reset(PyRefType::Owned, PyList_New(0));
538 PythonList::PythonList(int list_size) : PythonObject() {
539 Reset(PyRefType::Owned, PyList_New(list_size));
542 PythonList::PythonList(PyRefType type, PyObject *py_obj) : PythonObject() {
543 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a list
546 PythonList::PythonList(const PythonList &list) : PythonObject(list) {}
548 PythonList::~PythonList() {}
550 bool PythonList::Check(PyObject *py_obj) {
553 return PyList_Check(py_obj);
556 void PythonList::Reset(PyRefType type, PyObject *py_obj) {
557 // Grab the desired reference type so that if we end up rejecting `py_obj` it
558 // still gets decremented if necessary.
559 PythonObject result(type, py_obj);
561 if (!PythonList::Check(py_obj)) {
562 PythonObject::Reset();
566 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
567 // overflow since it calls back into the virtual implementation.
568 PythonObject::Reset(PyRefType::Borrowed, result.get());
571 uint32_t PythonList::GetSize() const {
573 return PyList_GET_SIZE(m_py_obj);
577 PythonObject PythonList::GetItemAtIndex(uint32_t index) const {
579 return PythonObject(PyRefType::Borrowed, PyList_GetItem(m_py_obj, index));
580 return PythonObject();
583 void PythonList::SetItemAtIndex(uint32_t index, const PythonObject &object) {
584 if (IsAllocated() && object.IsValid()) {
585 // PyList_SetItem is documented to "steal" a reference, so we need to
586 // convert it to an owned reference by incrementing it.
587 Py_INCREF(object.get());
588 PyList_SetItem(m_py_obj, index, object.get());
592 void PythonList::AppendItem(const PythonObject &object) {
593 if (IsAllocated() && object.IsValid()) {
594 // `PyList_Append` does *not* steal a reference, so do not call `Py_INCREF`
595 // here like we do with `PyList_SetItem`.
596 PyList_Append(m_py_obj, object.get());
600 StructuredData::ArraySP PythonList::CreateStructuredArray() const {
601 StructuredData::ArraySP result(new StructuredData::Array);
602 uint32_t count = GetSize();
603 for (uint32_t i = 0; i < count; ++i) {
604 PythonObject obj = GetItemAtIndex(i);
605 result->AddItem(obj.CreateStructuredObject());
610 //----------------------------------------------------------------------
612 //----------------------------------------------------------------------
614 PythonTuple::PythonTuple(PyInitialValue value) : PythonObject() {
615 if (value == PyInitialValue::Empty)
616 Reset(PyRefType::Owned, PyTuple_New(0));
619 PythonTuple::PythonTuple(int tuple_size) : PythonObject() {
620 Reset(PyRefType::Owned, PyTuple_New(tuple_size));
623 PythonTuple::PythonTuple(PyRefType type, PyObject *py_obj) : PythonObject() {
624 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a tuple
627 PythonTuple::PythonTuple(const PythonTuple &tuple) : PythonObject(tuple) {}
629 PythonTuple::PythonTuple(std::initializer_list<PythonObject> objects) {
630 m_py_obj = PyTuple_New(objects.size());
633 for (auto object : objects) {
634 if (object.IsValid())
635 SetItemAtIndex(idx, object);
640 PythonTuple::PythonTuple(std::initializer_list<PyObject *> objects) {
641 m_py_obj = PyTuple_New(objects.size());
644 for (auto py_object : objects) {
645 PythonObject object(PyRefType::Borrowed, py_object);
646 if (object.IsValid())
647 SetItemAtIndex(idx, object);
652 PythonTuple::~PythonTuple() {}
654 bool PythonTuple::Check(PyObject *py_obj) {
657 return PyTuple_Check(py_obj);
660 void PythonTuple::Reset(PyRefType type, PyObject *py_obj) {
661 // Grab the desired reference type so that if we end up rejecting `py_obj` it
662 // still gets decremented if necessary.
663 PythonObject result(type, py_obj);
665 if (!PythonTuple::Check(py_obj)) {
666 PythonObject::Reset();
670 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
671 // overflow since it calls back into the virtual implementation.
672 PythonObject::Reset(PyRefType::Borrowed, result.get());
675 uint32_t PythonTuple::GetSize() const {
677 return PyTuple_GET_SIZE(m_py_obj);
681 PythonObject PythonTuple::GetItemAtIndex(uint32_t index) const {
683 return PythonObject(PyRefType::Borrowed, PyTuple_GetItem(m_py_obj, index));
684 return PythonObject();
687 void PythonTuple::SetItemAtIndex(uint32_t index, const PythonObject &object) {
688 if (IsAllocated() && object.IsValid()) {
689 // PyTuple_SetItem is documented to "steal" a reference, so we need to
690 // convert it to an owned reference by incrementing it.
691 Py_INCREF(object.get());
692 PyTuple_SetItem(m_py_obj, index, object.get());
696 StructuredData::ArraySP PythonTuple::CreateStructuredArray() const {
697 StructuredData::ArraySP result(new StructuredData::Array);
698 uint32_t count = GetSize();
699 for (uint32_t i = 0; i < count; ++i) {
700 PythonObject obj = GetItemAtIndex(i);
701 result->AddItem(obj.CreateStructuredObject());
706 //----------------------------------------------------------------------
708 //----------------------------------------------------------------------
710 PythonDictionary::PythonDictionary(PyInitialValue value) : PythonObject() {
711 if (value == PyInitialValue::Empty)
712 Reset(PyRefType::Owned, PyDict_New());
715 PythonDictionary::PythonDictionary(PyRefType type, PyObject *py_obj)
717 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a dictionary
720 PythonDictionary::PythonDictionary(const PythonDictionary &object)
721 : PythonObject(object) {}
723 PythonDictionary::~PythonDictionary() {}
725 bool PythonDictionary::Check(PyObject *py_obj) {
729 return PyDict_Check(py_obj);
732 void PythonDictionary::Reset(PyRefType type, PyObject *py_obj) {
733 // Grab the desired reference type so that if we end up rejecting `py_obj` it
734 // still gets decremented if necessary.
735 PythonObject result(type, py_obj);
737 if (!PythonDictionary::Check(py_obj)) {
738 PythonObject::Reset();
742 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
743 // overflow since it calls back into the virtual implementation.
744 PythonObject::Reset(PyRefType::Borrowed, result.get());
747 uint32_t PythonDictionary::GetSize() const {
749 return PyDict_Size(m_py_obj);
753 PythonList PythonDictionary::GetKeys() const {
755 return PythonList(PyRefType::Owned, PyDict_Keys(m_py_obj));
756 return PythonList(PyInitialValue::Invalid);
759 PythonObject PythonDictionary::GetItemForKey(const PythonObject &key) const {
760 if (IsAllocated() && key.IsValid())
761 return PythonObject(PyRefType::Borrowed,
762 PyDict_GetItem(m_py_obj, key.get()));
763 return PythonObject();
766 void PythonDictionary::SetItemForKey(const PythonObject &key,
767 const PythonObject &value) {
768 if (IsAllocated() && key.IsValid() && value.IsValid())
769 PyDict_SetItem(m_py_obj, key.get(), value.get());
772 StructuredData::DictionarySP
773 PythonDictionary::CreateStructuredDictionary() const {
774 StructuredData::DictionarySP result(new StructuredData::Dictionary);
775 PythonList keys(GetKeys());
776 uint32_t num_keys = keys.GetSize();
777 for (uint32_t i = 0; i < num_keys; ++i) {
778 PythonObject key = keys.GetItemAtIndex(i);
779 PythonObject value = GetItemForKey(key);
780 StructuredData::ObjectSP structured_value = value.CreateStructuredObject();
781 result->AddItem(key.Str().GetString(), structured_value);
786 PythonModule::PythonModule() : PythonObject() {}
788 PythonModule::PythonModule(PyRefType type, PyObject *py_obj) {
789 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a module
792 PythonModule::PythonModule(const PythonModule &dict) : PythonObject(dict) {}
794 PythonModule::~PythonModule() {}
796 PythonModule PythonModule::BuiltinsModule() {
797 #if PY_MAJOR_VERSION >= 3
798 return AddModule("builtins");
800 return AddModule("__builtin__");
804 PythonModule PythonModule::MainModule() { return AddModule("__main__"); }
806 PythonModule PythonModule::AddModule(llvm::StringRef module) {
807 std::string str = module.str();
808 return PythonModule(PyRefType::Borrowed, PyImport_AddModule(str.c_str()));
811 PythonModule PythonModule::ImportModule(llvm::StringRef module) {
812 std::string str = module.str();
813 return PythonModule(PyRefType::Owned, PyImport_ImportModule(str.c_str()));
816 bool PythonModule::Check(PyObject *py_obj) {
820 return PyModule_Check(py_obj);
823 void PythonModule::Reset(PyRefType type, PyObject *py_obj) {
824 // Grab the desired reference type so that if we end up rejecting `py_obj` it
825 // still gets decremented if necessary.
826 PythonObject result(type, py_obj);
828 if (!PythonModule::Check(py_obj)) {
829 PythonObject::Reset();
833 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
834 // overflow since it calls back into the virtual implementation.
835 PythonObject::Reset(PyRefType::Borrowed, result.get());
838 PythonDictionary PythonModule::GetDictionary() const {
839 return PythonDictionary(PyRefType::Borrowed, PyModule_GetDict(m_py_obj));
842 PythonCallable::PythonCallable() : PythonObject() {}
844 PythonCallable::PythonCallable(PyRefType type, PyObject *py_obj) {
845 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a callable
848 PythonCallable::PythonCallable(const PythonCallable &callable)
849 : PythonObject(callable) {}
851 PythonCallable::~PythonCallable() {}
853 bool PythonCallable::Check(PyObject *py_obj) {
857 return PyCallable_Check(py_obj);
860 void PythonCallable::Reset(PyRefType type, PyObject *py_obj) {
861 // Grab the desired reference type so that if we end up rejecting `py_obj` it
862 // still gets decremented if necessary.
863 PythonObject result(type, py_obj);
865 if (!PythonCallable::Check(py_obj)) {
866 PythonObject::Reset();
870 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
871 // overflow since it calls back into the virtual implementation.
872 PythonObject::Reset(PyRefType::Borrowed, result.get());
875 PythonCallable::ArgInfo PythonCallable::GetNumArguments() const {
876 ArgInfo result = {0, false, false, false};
880 PyObject *py_func_obj = m_py_obj;
881 if (PyMethod_Check(py_func_obj)) {
882 py_func_obj = PyMethod_GET_FUNCTION(py_func_obj);
883 PythonObject im_self = GetAttributeValue("im_self");
884 if (im_self.IsValid() && !im_self.IsNone())
885 result.is_bound_method = true;
887 // see if this is a callable object with an __call__ method
888 if (!PyFunction_Check(py_func_obj)) {
889 PythonObject __call__ = GetAttributeValue("__call__");
890 if (__call__.IsValid()) {
891 auto __callable__ = __call__.AsType<PythonCallable>();
892 if (__callable__.IsValid()) {
893 py_func_obj = PyMethod_GET_FUNCTION(__callable__.get());
894 PythonObject im_self = GetAttributeValue("im_self");
895 if (im_self.IsValid() && !im_self.IsNone())
896 result.is_bound_method = true;
905 PyCodeObject *code = (PyCodeObject *)PyFunction_GET_CODE(py_func_obj);
909 result.count = code->co_argcount;
910 result.has_varargs = !!(code->co_flags & CO_VARARGS);
911 result.has_kwargs = !!(code->co_flags & CO_VARKEYWORDS);
915 PythonObject PythonCallable::operator()() {
916 return PythonObject(PyRefType::Owned, PyObject_CallObject(m_py_obj, nullptr));
919 PythonObject PythonCallable::
920 operator()(std::initializer_list<PyObject *> args) {
921 PythonTuple arg_tuple(args);
922 return PythonObject(PyRefType::Owned,
923 PyObject_CallObject(m_py_obj, arg_tuple.get()));
926 PythonObject PythonCallable::
927 operator()(std::initializer_list<PythonObject> args) {
928 PythonTuple arg_tuple(args);
929 return PythonObject(PyRefType::Owned,
930 PyObject_CallObject(m_py_obj, arg_tuple.get()));
933 PythonFile::PythonFile() : PythonObject() {}
935 PythonFile::PythonFile(File &file, const char *mode) { Reset(file, mode); }
937 PythonFile::PythonFile(const char *path, const char *mode) {
938 lldb_private::File file;
939 FileSystem::Instance().Open(file, FileSpec(path), GetOptionsFromMode(mode));
943 PythonFile::PythonFile(PyRefType type, PyObject *o) { Reset(type, o); }
945 PythonFile::~PythonFile() {}
947 bool PythonFile::Check(PyObject *py_obj) {
948 #if PY_MAJOR_VERSION < 3
949 return PyFile_Check(py_obj);
951 // In Python 3, there is no `PyFile_Check`, and in fact PyFile is not even a
952 // first-class object type anymore. `PyFile_FromFd` is just a thin wrapper
953 // over `io.open()`, which returns some object derived from `io.IOBase`. As a
954 // result, the only way to detect a file in Python 3 is to check whether it
955 // inherits from `io.IOBase`. Since it is possible for non-files to also
956 // inherit from `io.IOBase`, we additionally verify that it has the `fileno`
957 // attribute, which should guarantee that it is backed by the file system.
958 PythonObject io_module(PyRefType::Owned, PyImport_ImportModule("io"));
959 PythonDictionary io_dict(PyRefType::Borrowed,
960 PyModule_GetDict(io_module.get()));
961 PythonObject io_base_class = io_dict.GetItemForKey(PythonString("IOBase"));
963 PythonObject object_type(PyRefType::Owned, PyObject_Type(py_obj));
965 if (1 != PyObject_IsSubclass(object_type.get(), io_base_class.get()))
967 if (!object_type.HasAttribute("fileno"))
974 void PythonFile::Reset(PyRefType type, PyObject *py_obj) {
975 // Grab the desired reference type so that if we end up rejecting `py_obj` it
976 // still gets decremented if necessary.
977 PythonObject result(type, py_obj);
979 if (!PythonFile::Check(py_obj)) {
980 PythonObject::Reset();
984 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
985 // overflow since it calls back into the virtual implementation.
986 PythonObject::Reset(PyRefType::Borrowed, result.get());
989 void PythonFile::Reset(File &file, const char *mode) {
990 if (!file.IsValid()) {
995 char *cmode = const_cast<char *>(mode);
996 #if PY_MAJOR_VERSION >= 3
997 Reset(PyRefType::Owned, PyFile_FromFd(file.GetDescriptor(), nullptr, cmode,
998 -1, nullptr, "ignore", nullptr, 0));
1000 // Read through the Python source, doesn't seem to modify these strings
1001 Reset(PyRefType::Owned,
1002 PyFile_FromFile(file.GetStream(), const_cast<char *>(""), cmode,
1007 uint32_t PythonFile::GetOptionsFromMode(llvm::StringRef mode) {
1011 return llvm::StringSwitch<uint32_t>(mode.str())
1012 .Case("r", File::eOpenOptionRead)
1013 .Case("w", File::eOpenOptionWrite)
1014 .Case("a", File::eOpenOptionWrite | File::eOpenOptionAppend |
1015 File::eOpenOptionCanCreate)
1016 .Case("r+", File::eOpenOptionRead | File::eOpenOptionWrite)
1017 .Case("w+", File::eOpenOptionRead | File::eOpenOptionWrite |
1018 File::eOpenOptionCanCreate | File::eOpenOptionTruncate)
1019 .Case("a+", File::eOpenOptionRead | File::eOpenOptionWrite |
1020 File::eOpenOptionAppend | File::eOpenOptionCanCreate)
1024 bool PythonFile::GetUnderlyingFile(File &file) const {
1029 // We don't own the file descriptor returned by this function, make sure the
1030 // File object knows about that.
1031 file.SetDescriptor(PyObject_AsFileDescriptor(m_py_obj), false);
1032 PythonString py_mode = GetAttributeValue("mode").AsType<PythonString>();
1033 file.SetOptions(PythonFile::GetOptionsFromMode(py_mode.GetString()));
1034 return file.IsValid();