Skip to content

Commit 54de8da

Browse files
committed
[lldb] Use Python Bytes instead of Buffer for Binary I/O (NFC)
Binary I/O (also called buffered I/O) expects bytes-like objects and produces bytes objects [1]. Switch from using a Python buffer to using Python bytes to read the data. This eliminates calls to functions that aren't part of the Python stable C API. [1] https://docs.python.org/3/library/io.html#binary-i-o
1 parent 147cfc8 commit 54de8da

File tree

1 file changed

+6
-40
lines changed

1 file changed

+6
-40
lines changed

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

Lines changed: 6 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1085,40 +1085,6 @@ class SimplePythonFile : public OwnedPythonFile<NativeFile> {
10851085
char SimplePythonFile::ID = 0;
10861086
} // namespace
10871087

1088-
namespace {
1089-
class PythonBuffer {
1090-
public:
1091-
PythonBuffer &operator=(const PythonBuffer &) = delete;
1092-
PythonBuffer(const PythonBuffer &) = delete;
1093-
1094-
static Expected<PythonBuffer> Create(PythonObject &obj,
1095-
int flags = PyBUF_SIMPLE) {
1096-
Py_buffer py_buffer = {};
1097-
PyObject_GetBuffer(obj.get(), &py_buffer, flags);
1098-
if (!py_buffer.obj)
1099-
return llvm::make_error<PythonException>();
1100-
return PythonBuffer(py_buffer);
1101-
}
1102-
1103-
PythonBuffer(PythonBuffer &&other) {
1104-
m_buffer = other.m_buffer;
1105-
other.m_buffer.obj = nullptr;
1106-
}
1107-
1108-
~PythonBuffer() {
1109-
if (m_buffer.obj)
1110-
PyBuffer_Release(&m_buffer);
1111-
}
1112-
1113-
Py_buffer &get() { return m_buffer; }
1114-
1115-
private:
1116-
// takes ownership of the buffer.
1117-
PythonBuffer(const Py_buffer &py_buffer) : m_buffer(py_buffer) {}
1118-
Py_buffer m_buffer;
1119-
};
1120-
} // namespace
1121-
11221088
// Shared methods between TextPythonFile and BinaryPythonFile
11231089
namespace {
11241090
class PythonIOFile : public OwnedPythonFile<File> {
@@ -1212,12 +1178,12 @@ class BinaryPythonFile : public PythonIOFile {
12121178
num_bytes = 0;
12131179
return Status();
12141180
}
1215-
auto pybuffer = PythonBuffer::Create(pybuffer_obj.get());
1216-
if (!pybuffer)
1217-
// Cloning since the wrapped exception may still reference the PyThread.
1218-
return Status::FromError(pybuffer.takeError()).Clone();
1219-
memcpy(buf, pybuffer.get().get().buf, pybuffer.get().get().len);
1220-
num_bytes = pybuffer.get().get().len;
1181+
PythonBytes pybytes(PyRefType::Borrowed, pybuffer_obj->get());
1182+
if (!pybytes)
1183+
return Status::FromErrorString("not a byte array");
1184+
llvm::ArrayRef<uint8_t> bytes = pybytes.GetBytes();
1185+
memcpy(buf, bytes.begin(), bytes.size());
1186+
num_bytes = bytes.size();
12211187
return Status();
12221188
}
12231189
};

0 commit comments

Comments
 (0)