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 "lldb-python.h"
17 #include "PythonDataObjects.h"
18 #include "ScriptInterpreterPython.h"
20 #include "lldb/Core/Stream.h"
21 #include "lldb/Host/File.h"
22 #include "lldb/Host/FileSystem.h"
23 #include "lldb/Interpreter/ScriptInterpreter.h"
25 #include "llvm/Support/ConvertUTF.h"
29 #include "llvm/ADT/StringSwitch.h"
31 using namespace lldb_private;
35 StructuredPythonObject::Dump(Stream &s) const
37 s << "Python Obj: 0x" << GetValue();
40 //----------------------------------------------------------------------
42 //----------------------------------------------------------------------
45 PythonObject::Dump(Stream &strm) const
49 FILE *file = ::tmpfile();
52 ::PyObject_Print (m_py_obj, file, 0);
53 const long length = ftell (file);
57 std::vector<char> file_contents (length,'\0');
58 const size_t length_read = ::fread (file_contents.data(), 1, file_contents.size(), file);
60 strm.Write (file_contents.data(), length_read);
66 strm.PutCString ("NULL");
70 PythonObject::GetObjectType() const
73 return PyObjectType::None;
75 if (PythonModule::Check(m_py_obj))
76 return PyObjectType::Module;
77 if (PythonList::Check(m_py_obj))
78 return PyObjectType::List;
79 if (PythonTuple::Check(m_py_obj))
80 return PyObjectType::Tuple;
81 if (PythonDictionary::Check(m_py_obj))
82 return PyObjectType::Dictionary;
83 if (PythonString::Check(m_py_obj))
84 return PyObjectType::String;
85 #if PY_MAJOR_VERSION >= 3
86 if (PythonBytes::Check(m_py_obj))
87 return PyObjectType::Bytes;
89 if (PythonByteArray::Check(m_py_obj))
90 return PyObjectType::ByteArray;
91 if (PythonInteger::Check(m_py_obj))
92 return PyObjectType::Integer;
93 if (PythonFile::Check(m_py_obj))
94 return PyObjectType::File;
95 if (PythonCallable::Check(m_py_obj))
96 return PyObjectType::Callable;
97 return PyObjectType::Unknown;
101 PythonObject::Repr() const
104 return PythonString();
105 PyObject *repr = PyObject_Repr(m_py_obj);
107 return PythonString();
108 return PythonString(PyRefType::Owned, repr);
112 PythonObject::Str() const
115 return PythonString();
116 PyObject *str = PyObject_Str(m_py_obj);
118 return PythonString();
119 return PythonString(PyRefType::Owned, str);
123 PythonObject::ResolveNameWithDictionary(llvm::StringRef name, const PythonDictionary &dict)
125 size_t dot_pos = name.find_first_of('.');
126 llvm::StringRef piece = name.substr(0, dot_pos);
127 PythonObject result = dict.GetItemForKey(PythonString(piece));
128 if (dot_pos == llvm::StringRef::npos)
130 // There was no dot, we're done.
134 // There was a dot. The remaining portion of the name should be looked up in
135 // the context of the object that was found in the dictionary.
136 return result.ResolveName(name.substr(dot_pos + 1));
140 PythonObject::ResolveName(llvm::StringRef name) const
142 // Resolve the name in the context of the specified object. If,
143 // for example, `this` refers to a PyModule, then this will look for
144 // `name` in this module. If `this` refers to a PyType, then it will
145 // resolve `name` as an attribute of that type. If `this` refers to
146 // an instance of an object, then it will resolve `name` as the value
147 // of the specified field.
149 // This function handles dotted names so that, for example, if `m_py_obj`
150 // refers to the `sys` module, and `name` == "path.append", then it
151 // will find the function `sys.path.append`.
153 size_t dot_pos = name.find_first_of('.');
154 if (dot_pos == llvm::StringRef::npos)
156 // No dots in the name, we should be able to find the value immediately
157 // as an attribute of `m_py_obj`.
158 return GetAttributeValue(name);
161 // Look up the first piece of the name, and resolve the rest as a child of that.
162 PythonObject parent = ResolveName(name.substr(0, dot_pos));
163 if (!parent.IsAllocated())
164 return PythonObject();
166 // Tail recursion.. should be optimized by the compiler
167 return parent.ResolveName(name.substr(dot_pos + 1));
171 PythonObject::HasAttribute(llvm::StringRef attr) const
175 PythonString py_attr(attr);
176 return !!PyObject_HasAttr(m_py_obj, py_attr.get());
180 PythonObject::GetAttributeValue(llvm::StringRef attr) const
183 return PythonObject();
185 PythonString py_attr(attr);
186 if (!PyObject_HasAttr(m_py_obj, py_attr.get()))
187 return PythonObject();
189 return PythonObject(PyRefType::Owned,
190 PyObject_GetAttr(m_py_obj, py_attr.get()));
194 PythonObject::IsNone() const
196 return m_py_obj == Py_None;
200 PythonObject::IsValid() const
202 return m_py_obj != nullptr;
206 PythonObject::IsAllocated() const
208 return IsValid() && !IsNone();
211 StructuredData::ObjectSP
212 PythonObject::CreateStructuredObject() const
214 switch (GetObjectType())
216 case PyObjectType::Dictionary:
217 return PythonDictionary(PyRefType::Borrowed, m_py_obj).CreateStructuredDictionary();
218 case PyObjectType::Integer:
219 return PythonInteger(PyRefType::Borrowed, m_py_obj).CreateStructuredInteger();
220 case PyObjectType::List:
221 return PythonList(PyRefType::Borrowed, m_py_obj).CreateStructuredArray();
222 case PyObjectType::String:
223 return PythonString(PyRefType::Borrowed, m_py_obj).CreateStructuredString();
224 case PyObjectType::Bytes:
225 return PythonBytes(PyRefType::Borrowed, m_py_obj).CreateStructuredString();
226 case PyObjectType::ByteArray:
227 return PythonByteArray(PyRefType::Borrowed, m_py_obj).CreateStructuredString();
228 case PyObjectType::None:
229 return StructuredData::ObjectSP();
231 return StructuredData::ObjectSP(new StructuredPythonObject(m_py_obj));
235 //----------------------------------------------------------------------
237 //----------------------------------------------------------------------
238 PythonBytes::PythonBytes() : PythonObject()
242 PythonBytes::PythonBytes(llvm::ArrayRef<uint8_t> bytes) : PythonObject()
247 PythonBytes::PythonBytes(const uint8_t *bytes, size_t length) : PythonObject()
249 SetBytes(llvm::ArrayRef<uint8_t>(bytes, length));
252 PythonBytes::PythonBytes(PyRefType type, PyObject *py_obj) : PythonObject()
254 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a string
257 PythonBytes::PythonBytes(const PythonBytes &object) : PythonObject(object)
261 PythonBytes::~PythonBytes()
266 PythonBytes::Check(PyObject *py_obj)
270 if (PyBytes_Check(py_obj))
276 PythonBytes::Reset(PyRefType type, PyObject *py_obj)
278 // Grab the desired reference type so that if we end up rejecting
279 // `py_obj` it still gets decremented if necessary.
280 PythonObject result(type, py_obj);
282 if (!PythonBytes::Check(py_obj))
284 PythonObject::Reset();
288 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
289 // back into the virtual implementation.
290 PythonObject::Reset(PyRefType::Borrowed, result.get());
293 llvm::ArrayRef<uint8_t>
294 PythonBytes::GetBytes() const
297 return llvm::ArrayRef<uint8_t>();
302 PyBytes_AsStringAndSize(m_py_obj, &c, &size);
303 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
307 PythonBytes::GetSize() const
311 return PyBytes_Size(m_py_obj);
315 PythonBytes::SetBytes(llvm::ArrayRef<uint8_t> bytes)
317 const char *data = reinterpret_cast<const char *>(bytes.data());
318 PyObject *py_bytes = PyBytes_FromStringAndSize(data, bytes.size());
319 PythonObject::Reset(PyRefType::Owned, py_bytes);
322 StructuredData::StringSP
323 PythonBytes::CreateStructuredString() const
325 StructuredData::StringSP result(new StructuredData::String);
328 PyBytes_AsStringAndSize(m_py_obj, &c, &size);
329 result->SetValue(std::string(c, size));
333 PythonByteArray::PythonByteArray(llvm::ArrayRef<uint8_t> bytes) : PythonByteArray(bytes.data(), bytes.size())
337 PythonByteArray::PythonByteArray(const uint8_t *bytes, size_t length)
339 const char *str = reinterpret_cast<const char *>(bytes);
340 Reset(PyRefType::Owned, PyByteArray_FromStringAndSize(str, length));
343 PythonByteArray::PythonByteArray(PyRefType type, PyObject *o)
348 PythonByteArray::PythonByteArray(const PythonBytes &object) : PythonObject(object)
352 PythonByteArray::~PythonByteArray()
357 PythonByteArray::Check(PyObject *py_obj)
361 if (PyByteArray_Check(py_obj))
367 PythonByteArray::Reset(PyRefType type, PyObject *py_obj)
369 // Grab the desired reference type so that if we end up rejecting
370 // `py_obj` it still gets decremented if necessary.
371 PythonObject result(type, py_obj);
373 if (!PythonByteArray::Check(py_obj))
375 PythonObject::Reset();
379 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
380 // back into the virtual implementation.
381 PythonObject::Reset(PyRefType::Borrowed, result.get());
384 llvm::ArrayRef<uint8_t>
385 PythonByteArray::GetBytes() const
388 return llvm::ArrayRef<uint8_t>();
390 char *c = PyByteArray_AsString(m_py_obj);
391 size_t size = GetSize();
392 return llvm::ArrayRef<uint8_t>(reinterpret_cast<uint8_t *>(c), size);
396 PythonByteArray::GetSize() const
401 return PyByteArray_Size(m_py_obj);
404 StructuredData::StringSP
405 PythonByteArray::CreateStructuredString() const
407 StructuredData::StringSP result(new StructuredData::String);
408 llvm::ArrayRef<uint8_t> bytes = GetBytes();
409 const char *str = reinterpret_cast<const char *>(bytes.data());
410 result->SetValue(std::string(str, bytes.size()));
414 //----------------------------------------------------------------------
416 //----------------------------------------------------------------------
418 PythonString::PythonString(PyRefType type, PyObject *py_obj)
421 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a string
424 PythonString::PythonString(const PythonString &object)
425 : PythonObject(object)
429 PythonString::PythonString(llvm::StringRef string)
435 PythonString::PythonString(const char *string)
438 SetString(llvm::StringRef(string));
441 PythonString::PythonString()
446 PythonString::~PythonString ()
451 PythonString::Check(PyObject *py_obj)
456 if (PyUnicode_Check(py_obj))
458 #if PY_MAJOR_VERSION < 3
459 if (PyString_Check(py_obj))
466 PythonString::Reset(PyRefType type, PyObject *py_obj)
468 // Grab the desired reference type so that if we end up rejecting
469 // `py_obj` it still gets decremented if necessary.
470 PythonObject result(type, py_obj);
472 if (!PythonString::Check(py_obj))
474 PythonObject::Reset();
477 #if PY_MAJOR_VERSION < 3
478 // In Python 2, Don't store PyUnicode objects directly, because we need
479 // access to their underlying character buffers which Python 2 doesn't
481 if (PyUnicode_Check(py_obj))
482 result.Reset(PyRefType::Owned, PyUnicode_AsUTF8String(result.get()));
484 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
485 // back into the virtual implementation.
486 PythonObject::Reset(PyRefType::Borrowed, result.get());
490 PythonString::GetString() const
493 return llvm::StringRef();
498 #if PY_MAJOR_VERSION >= 3
499 c = PyUnicode_AsUTF8AndSize(m_py_obj, &size);
501 PyString_AsStringAndSize(m_py_obj, &c, &size);
503 return llvm::StringRef(c, size);
507 PythonString::GetSize() const
511 #if PY_MAJOR_VERSION >= 3
512 return PyUnicode_GetSize(m_py_obj);
514 return PyString_Size(m_py_obj);
521 PythonString::SetString (llvm::StringRef string)
523 #if PY_MAJOR_VERSION >= 3
524 PyObject *unicode = PyUnicode_FromStringAndSize(string.data(), string.size());
525 PythonObject::Reset(PyRefType::Owned, unicode);
527 PyObject *str = PyString_FromStringAndSize(string.data(), string.size());
528 PythonObject::Reset(PyRefType::Owned, str);
532 StructuredData::StringSP
533 PythonString::CreateStructuredString() const
535 StructuredData::StringSP result(new StructuredData::String);
536 result->SetValue(GetString());
540 //----------------------------------------------------------------------
542 //----------------------------------------------------------------------
544 PythonInteger::PythonInteger()
550 PythonInteger::PythonInteger(PyRefType type, PyObject *py_obj)
553 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a integer type
556 PythonInteger::PythonInteger(const PythonInteger &object)
557 : PythonObject(object)
561 PythonInteger::PythonInteger(int64_t value)
568 PythonInteger::~PythonInteger ()
573 PythonInteger::Check(PyObject *py_obj)
578 #if PY_MAJOR_VERSION >= 3
579 // Python 3 does not have PyInt_Check. There is only one type of
580 // integral value, long.
581 return PyLong_Check(py_obj);
583 return PyLong_Check(py_obj) || PyInt_Check(py_obj);
588 PythonInteger::Reset(PyRefType type, PyObject *py_obj)
590 // Grab the desired reference type so that if we end up rejecting
591 // `py_obj` it still gets decremented if necessary.
592 PythonObject result(type, py_obj);
594 if (!PythonInteger::Check(py_obj))
596 PythonObject::Reset();
600 #if PY_MAJOR_VERSION < 3
601 // Always store this as a PyLong, which makes interoperability between
602 // Python 2.x and Python 3.x easier. This is only necessary in 2.x,
603 // since 3.x doesn't even have a PyInt.
604 if (PyInt_Check(py_obj))
606 // Since we converted the original object to a different type, the new
607 // object is an owned object regardless of the ownership semantics requested
609 result.Reset(PyRefType::Owned, PyLong_FromLongLong(PyInt_AsLong(py_obj)));
613 assert(PyLong_Check(result.get()) && "Couldn't get a PyLong from this PyObject");
615 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
616 // back into the virtual implementation.
617 PythonObject::Reset(PyRefType::Borrowed, result.get());
621 PythonInteger::GetInteger() const
625 assert(PyLong_Check(m_py_obj) && "PythonInteger::GetInteger has a PyObject that isn't a PyLong");
627 return PyLong_AsLongLong(m_py_obj);
633 PythonInteger::SetInteger(int64_t value)
635 PythonObject::Reset(PyRefType::Owned, PyLong_FromLongLong(value));
638 StructuredData::IntegerSP
639 PythonInteger::CreateStructuredInteger() const
641 StructuredData::IntegerSP result(new StructuredData::Integer);
642 result->SetValue(GetInteger());
646 //----------------------------------------------------------------------
648 //----------------------------------------------------------------------
650 PythonList::PythonList(PyInitialValue value)
653 if (value == PyInitialValue::Empty)
654 Reset(PyRefType::Owned, PyList_New(0));
657 PythonList::PythonList(int list_size)
660 Reset(PyRefType::Owned, PyList_New(list_size));
663 PythonList::PythonList(PyRefType type, PyObject *py_obj)
666 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a list
669 PythonList::PythonList(const PythonList &list)
674 PythonList::~PythonList ()
679 PythonList::Check(PyObject *py_obj)
683 return PyList_Check(py_obj);
687 PythonList::Reset(PyRefType type, PyObject *py_obj)
689 // Grab the desired reference type so that if we end up rejecting
690 // `py_obj` it still gets decremented if necessary.
691 PythonObject result(type, py_obj);
693 if (!PythonList::Check(py_obj))
695 PythonObject::Reset();
699 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
700 // back into the virtual implementation.
701 PythonObject::Reset(PyRefType::Borrowed, result.get());
705 PythonList::GetSize() const
708 return PyList_GET_SIZE(m_py_obj);
713 PythonList::GetItemAtIndex(uint32_t index) const
716 return PythonObject(PyRefType::Borrowed, PyList_GetItem(m_py_obj, index));
717 return PythonObject();
721 PythonList::SetItemAtIndex(uint32_t index, const PythonObject &object)
723 if (IsAllocated() && object.IsValid())
725 // PyList_SetItem is documented to "steal" a reference, so we need to
726 // convert it to an owned reference by incrementing it.
727 Py_INCREF(object.get());
728 PyList_SetItem(m_py_obj, index, object.get());
733 PythonList::AppendItem(const PythonObject &object)
735 if (IsAllocated() && object.IsValid())
737 // `PyList_Append` does *not* steal a reference, so do not call `Py_INCREF`
738 // here like we do with `PyList_SetItem`.
739 PyList_Append(m_py_obj, object.get());
743 StructuredData::ArraySP
744 PythonList::CreateStructuredArray() const
746 StructuredData::ArraySP result(new StructuredData::Array);
747 uint32_t count = GetSize();
748 for (uint32_t i = 0; i < count; ++i)
750 PythonObject obj = GetItemAtIndex(i);
751 result->AddItem(obj.CreateStructuredObject());
756 //----------------------------------------------------------------------
758 //----------------------------------------------------------------------
760 PythonTuple::PythonTuple(PyInitialValue value)
763 if (value == PyInitialValue::Empty)
764 Reset(PyRefType::Owned, PyTuple_New(0));
767 PythonTuple::PythonTuple(int tuple_size)
770 Reset(PyRefType::Owned, PyTuple_New(tuple_size));
773 PythonTuple::PythonTuple(PyRefType type, PyObject *py_obj)
776 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a tuple
779 PythonTuple::PythonTuple(const PythonTuple &tuple)
780 : PythonObject(tuple)
784 PythonTuple::PythonTuple(std::initializer_list<PythonObject> objects)
786 m_py_obj = PyTuple_New(objects.size());
789 for (auto object : objects)
791 if (object.IsValid())
792 SetItemAtIndex(idx, object);
797 PythonTuple::PythonTuple(std::initializer_list<PyObject*> objects)
799 m_py_obj = PyTuple_New(objects.size());
802 for (auto py_object : objects)
804 PythonObject object(PyRefType::Borrowed, py_object);
805 if (object.IsValid())
806 SetItemAtIndex(idx, object);
811 PythonTuple::~PythonTuple()
816 PythonTuple::Check(PyObject *py_obj)
820 return PyTuple_Check(py_obj);
824 PythonTuple::Reset(PyRefType type, PyObject *py_obj)
826 // Grab the desired reference type so that if we end up rejecting
827 // `py_obj` it still gets decremented if necessary.
828 PythonObject result(type, py_obj);
830 if (!PythonTuple::Check(py_obj))
832 PythonObject::Reset();
836 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
837 // back into the virtual implementation.
838 PythonObject::Reset(PyRefType::Borrowed, result.get());
842 PythonTuple::GetSize() const
845 return PyTuple_GET_SIZE(m_py_obj);
850 PythonTuple::GetItemAtIndex(uint32_t index) const
853 return PythonObject(PyRefType::Borrowed, PyTuple_GetItem(m_py_obj, index));
854 return PythonObject();
858 PythonTuple::SetItemAtIndex(uint32_t index, const PythonObject &object)
860 if (IsAllocated() && object.IsValid())
862 // PyTuple_SetItem is documented to "steal" a reference, so we need to
863 // convert it to an owned reference by incrementing it.
864 Py_INCREF(object.get());
865 PyTuple_SetItem(m_py_obj, index, object.get());
869 StructuredData::ArraySP
870 PythonTuple::CreateStructuredArray() const
872 StructuredData::ArraySP result(new StructuredData::Array);
873 uint32_t count = GetSize();
874 for (uint32_t i = 0; i < count; ++i)
876 PythonObject obj = GetItemAtIndex(i);
877 result->AddItem(obj.CreateStructuredObject());
882 //----------------------------------------------------------------------
884 //----------------------------------------------------------------------
886 PythonDictionary::PythonDictionary(PyInitialValue value)
889 if (value == PyInitialValue::Empty)
890 Reset(PyRefType::Owned, PyDict_New());
893 PythonDictionary::PythonDictionary(PyRefType type, PyObject *py_obj)
896 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a dictionary
899 PythonDictionary::PythonDictionary(const PythonDictionary &object)
900 : PythonObject(object)
904 PythonDictionary::~PythonDictionary ()
909 PythonDictionary::Check(PyObject *py_obj)
914 return PyDict_Check(py_obj);
918 PythonDictionary::Reset(PyRefType type, PyObject *py_obj)
920 // Grab the desired reference type so that if we end up rejecting
921 // `py_obj` it still gets decremented if necessary.
922 PythonObject result(type, py_obj);
924 if (!PythonDictionary::Check(py_obj))
926 PythonObject::Reset();
930 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
931 // back into the virtual implementation.
932 PythonObject::Reset(PyRefType::Borrowed, result.get());
936 PythonDictionary::GetSize() const
939 return PyDict_Size(m_py_obj);
944 PythonDictionary::GetKeys() const
947 return PythonList(PyRefType::Owned, PyDict_Keys(m_py_obj));
948 return PythonList(PyInitialValue::Invalid);
952 PythonDictionary::GetItemForKey(const PythonObject &key) const
954 if (IsAllocated() && key.IsValid())
955 return PythonObject(PyRefType::Borrowed, PyDict_GetItem(m_py_obj, key.get()));
956 return PythonObject();
960 PythonDictionary::SetItemForKey(const PythonObject &key, const PythonObject &value)
962 if (IsAllocated() && key.IsValid() && value.IsValid())
963 PyDict_SetItem(m_py_obj, key.get(), value.get());
966 StructuredData::DictionarySP
967 PythonDictionary::CreateStructuredDictionary() const
969 StructuredData::DictionarySP result(new StructuredData::Dictionary);
970 PythonList keys(GetKeys());
971 uint32_t num_keys = keys.GetSize();
972 for (uint32_t i = 0; i < num_keys; ++i)
974 PythonObject key = keys.GetItemAtIndex(i);
975 PythonObject value = GetItemForKey(key);
976 StructuredData::ObjectSP structured_value = value.CreateStructuredObject();
977 result->AddItem(key.Str().GetString(), structured_value);
982 PythonModule::PythonModule() : PythonObject()
986 PythonModule::PythonModule(PyRefType type, PyObject *py_obj)
988 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a module
991 PythonModule::PythonModule(const PythonModule &dict) : PythonObject(dict)
995 PythonModule::~PythonModule()
1000 PythonModule::BuiltinsModule()
1002 #if PY_MAJOR_VERSION >= 3
1003 return AddModule("builtins");
1005 return AddModule("__builtin__");
1010 PythonModule::MainModule()
1012 return AddModule("__main__");
1016 PythonModule::AddModule(llvm::StringRef module)
1018 std::string str = module.str();
1019 return PythonModule(PyRefType::Borrowed, PyImport_AddModule(str.c_str()));
1024 PythonModule::ImportModule(llvm::StringRef module)
1026 std::string str = module.str();
1027 return PythonModule(PyRefType::Owned, PyImport_ImportModule(str.c_str()));
1031 PythonModule::Check(PyObject *py_obj)
1036 return PyModule_Check(py_obj);
1040 PythonModule::Reset(PyRefType type, PyObject *py_obj)
1042 // Grab the desired reference type so that if we end up rejecting
1043 // `py_obj` it still gets decremented if necessary.
1044 PythonObject result(type, py_obj);
1046 if (!PythonModule::Check(py_obj))
1048 PythonObject::Reset();
1052 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
1053 // back into the virtual implementation.
1054 PythonObject::Reset(PyRefType::Borrowed, result.get());
1058 PythonModule::GetDictionary() const
1060 return PythonDictionary(PyRefType::Borrowed, PyModule_GetDict(m_py_obj));
1063 PythonCallable::PythonCallable() : PythonObject()
1067 PythonCallable::PythonCallable(PyRefType type, PyObject *py_obj)
1069 Reset(type, py_obj); // Use "Reset()" to ensure that py_obj is a callable
1072 PythonCallable::PythonCallable(const PythonCallable &callable)
1073 : PythonObject(callable)
1077 PythonCallable::~PythonCallable()
1082 PythonCallable::Check(PyObject *py_obj)
1087 return PyCallable_Check(py_obj);
1091 PythonCallable::Reset(PyRefType type, PyObject *py_obj)
1093 // Grab the desired reference type so that if we end up rejecting
1094 // `py_obj` it still gets decremented if necessary.
1095 PythonObject result(type, py_obj);
1097 if (!PythonCallable::Check(py_obj))
1099 PythonObject::Reset();
1103 // Calling PythonObject::Reset(const PythonObject&) will lead to stack overflow since it calls
1104 // back into the virtual implementation.
1105 PythonObject::Reset(PyRefType::Borrowed, result.get());
1109 PythonCallable::ArgInfo
1110 PythonCallable::GetNumArguments() const
1112 ArgInfo result = { 0, false, false, false };
1116 PyObject *py_func_obj = m_py_obj;
1117 if (PyMethod_Check(py_func_obj))
1119 py_func_obj = PyMethod_GET_FUNCTION(py_func_obj);
1120 PythonObject im_self = GetAttributeValue("im_self");
1121 if (im_self.IsValid() && !im_self.IsNone())
1122 result.is_bound_method = true;
1126 // see if this is a callable object with an __call__ method
1127 if (!PyFunction_Check(py_func_obj))
1129 PythonObject __call__ = GetAttributeValue("__call__");
1130 if (__call__.IsValid())
1132 auto __callable__ = __call__.AsType<PythonCallable>();
1133 if (__callable__.IsValid())
1135 py_func_obj = PyMethod_GET_FUNCTION(__callable__.get());
1136 PythonObject im_self = GetAttributeValue("im_self");
1137 if (im_self.IsValid() && !im_self.IsNone())
1138 result.is_bound_method = true;
1147 PyCodeObject* code = (PyCodeObject*)PyFunction_GET_CODE(py_func_obj);
1151 result.count = code->co_argcount;
1152 result.has_varargs = !!(code->co_flags & CO_VARARGS);
1153 result.has_kwargs = !!(code->co_flags & CO_VARKEYWORDS);
1158 PythonCallable::operator ()()
1160 return PythonObject(PyRefType::Owned,
1161 PyObject_CallObject(m_py_obj, nullptr));
1165 PythonCallable::operator ()(std::initializer_list<PyObject*> args)
1167 PythonTuple arg_tuple(args);
1168 return PythonObject(PyRefType::Owned,
1169 PyObject_CallObject(m_py_obj, arg_tuple.get()));
1173 PythonCallable::operator ()(std::initializer_list<PythonObject> args)
1175 PythonTuple arg_tuple(args);
1176 return PythonObject(PyRefType::Owned,
1177 PyObject_CallObject(m_py_obj, arg_tuple.get()));
1180 PythonFile::PythonFile()
1185 PythonFile::PythonFile(File &file, const char *mode)
1190 PythonFile::PythonFile(const char *path, const char *mode)
1192 lldb_private::File file(path, GetOptionsFromMode(mode));
1196 PythonFile::PythonFile(PyRefType type, PyObject *o)
1201 PythonFile::~PythonFile()
1206 PythonFile::Check(PyObject *py_obj)
1208 #if PY_MAJOR_VERSION < 3
1209 return PyFile_Check(py_obj);
1211 // In Python 3, there is no `PyFile_Check`, and in fact PyFile is not even a
1212 // first-class object type anymore. `PyFile_FromFd` is just a thin wrapper
1213 // over `io.open()`, which returns some object derived from `io.IOBase`.
1214 // As a result, the only way to detect a file in Python 3 is to check whether
1215 // it inherits from `io.IOBase`. Since it is possible for non-files to also
1216 // inherit from `io.IOBase`, we additionally verify that it has the `fileno`
1217 // attribute, which should guarantee that it is backed by the file system.
1218 PythonObject io_module(PyRefType::Owned, PyImport_ImportModule("io"));
1219 PythonDictionary io_dict(PyRefType::Borrowed, PyModule_GetDict(io_module.get()));
1220 PythonObject io_base_class = io_dict.GetItemForKey(PythonString("IOBase"));
1222 PythonObject object_type(PyRefType::Owned, PyObject_Type(py_obj));
1224 if (1 != PyObject_IsSubclass(object_type.get(), io_base_class.get()))
1226 if (!object_type.HasAttribute("fileno"))
1234 PythonFile::Reset(PyRefType type, PyObject *py_obj)
1236 // Grab the desired reference type so that if we end up rejecting
1237 // `py_obj` it still gets decremented if necessary.
1238 PythonObject result(type, py_obj);
1240 if (!PythonFile::Check(py_obj))
1242 PythonObject::Reset();
1246 // Calling PythonObject::Reset(const PythonObject&) will lead to stack
1247 // overflow since it calls back into the virtual implementation.
1248 PythonObject::Reset(PyRefType::Borrowed, result.get());
1252 PythonFile::Reset(File &file, const char *mode)
1254 if (!file.IsValid())
1260 char *cmode = const_cast<char *>(mode);
1261 #if PY_MAJOR_VERSION >= 3
1262 Reset(PyRefType::Owned,
1263 PyFile_FromFd(file.GetDescriptor(), nullptr, cmode, -1, nullptr, "ignore", nullptr, 0));
1265 // Read through the Python source, doesn't seem to modify these strings
1266 Reset(PyRefType::Owned,
1267 PyFile_FromFile(file.GetStream(), const_cast<char *>(""), cmode, nullptr));
1272 PythonFile::GetOptionsFromMode(llvm::StringRef mode)
1277 return llvm::StringSwitch<uint32_t>(mode.str().c_str())
1278 .Case("r", File::eOpenOptionRead)
1279 .Case("w", File::eOpenOptionWrite)
1280 .Case("a", File::eOpenOptionWrite|File::eOpenOptionAppend|File::eOpenOptionCanCreate)
1281 .Case("r+", File::eOpenOptionRead|File::eOpenOptionWrite)
1282 .Case("w+", File::eOpenOptionRead|File::eOpenOptionWrite|File::eOpenOptionCanCreate|File::eOpenOptionTruncate)
1283 .Case("a+", File::eOpenOptionRead|File::eOpenOptionWrite|File::eOpenOptionAppend|File::eOpenOptionCanCreate)
1288 PythonFile::GetUnderlyingFile(File &file) const
1294 // We don't own the file descriptor returned by this function, make sure the
1295 // File object knows about that.
1296 file.SetDescriptor(PyObject_AsFileDescriptor(m_py_obj), false);
1297 PythonString py_mode = GetAttributeValue("mode").AsType<PythonString>();
1298 file.SetOptions(PythonFile::GetOptionsFromMode(py_mode.GetString()));
1299 return file.IsValid();