Skip to content

Commit 59da3a1

Browse files
JDevliegherekrishna2803
authored andcommitted
[lldb] Reimplement PythonObject::Dump using the limited API (llvm#152055)
This reimplements `PythonObject::Dump` using functions that are part of the limited API, instead of using `PyObject_Print`, which is not.
1 parent 816be6b commit 59da3a1

File tree

1 file changed

+25
-17
lines changed

1 file changed

+25
-17
lines changed

lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp

Lines changed: 25 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include "lldb/Utility/Log.h"
2121
#include "lldb/Utility/Stream.h"
2222

23+
#include "llvm/ADT/ScopeExit.h"
2324
#include "llvm/Support/Casting.h"
2425
#include "llvm/Support/ConvertUTF.h"
2526
#include "llvm/Support/Errno.h"
@@ -131,23 +132,30 @@ void StructuredPythonObject::Serialize(llvm::json::OStream &s) const {
131132
// PythonObject
132133

133134
void PythonObject::Dump(Stream &strm) const {
134-
if (m_py_obj) {
135-
FILE *file = llvm::sys::RetryAfterSignal(nullptr, ::tmpfile);
136-
if (file) {
137-
::PyObject_Print(m_py_obj, file, 0);
138-
const long length = ftell(file);
139-
if (length) {
140-
::rewind(file);
141-
std::vector<char> file_contents(length, '\0');
142-
const size_t length_read =
143-
::fread(file_contents.data(), 1, file_contents.size(), file);
144-
if (length_read > 0)
145-
strm.Write(file_contents.data(), length_read);
146-
}
147-
::fclose(file);
148-
}
149-
} else
150-
strm.PutCString("NULL");
135+
if (!m_py_obj) {
136+
strm << "NULL";
137+
return;
138+
}
139+
140+
PyObject *py_str = PyObject_Repr(m_py_obj);
141+
if (!py_str)
142+
return;
143+
144+
auto release_py_str = llvm::make_scope_exit([py_str] { Py_DECREF(py_str); });
145+
146+
PyObject *py_bytes = PyUnicode_AsEncodedString(py_str, "utf-8", "replace");
147+
if (!py_bytes)
148+
return;
149+
150+
auto release_py_bytes =
151+
llvm::make_scope_exit([py_bytes] { Py_DECREF(py_bytes); });
152+
153+
char *buffer = nullptr;
154+
Py_ssize_t length = 0;
155+
if (PyBytes_AsStringAndSize(py_bytes, &buffer, &length) == -1)
156+
return;
157+
158+
strm << llvm::StringRef(buffer, length);
151159
}
152160

153161
PyObjectType PythonObject::GetObjectType() const {

0 commit comments

Comments
 (0)