[Mlir-commits] [mlir] [MLIR] Fix thread safety of the deleter in PyDenseResourceElementsAttribute (PR #124832)

llvmlistbot at llvm.org llvmlistbot at llvm.org
Tue Jan 28 12:30:33 PST 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-mlir

Author: Fabian Tschopp (naibaf7)

<details>
<summary>Changes</summary>

In general, `PyDenseResourceElementsAttribute` can get deleted at any time and any thread, where unlike the `getFromBuffer` call, the Python interpreter may not be initialized and the GIL may not be held.

This PR fixes segfaults caused by `PyBuffer_Release` when the GIL is not being held by the thread calling the deleter.

---
Full diff: https://github.com/llvm/llvm-project/pull/124832.diff


1 Files Affected:

- (modified) mlir/lib/Bindings/Python/IRAttributes.cpp (+3) 


``````````diff
diff --git a/mlir/lib/Bindings/Python/IRAttributes.cpp b/mlir/lib/Bindings/Python/IRAttributes.cpp
index 7bc21a31c3c84c..142b6eca11c438 100644
--- a/mlir/lib/Bindings/Python/IRAttributes.cpp
+++ b/mlir/lib/Bindings/Python/IRAttributes.cpp
@@ -1468,7 +1468,10 @@ class PyDenseResourceElementsAttribute
     // The userData is a Py_buffer* that the deleter owns.
     auto deleter = [](void *userData, const void *data, size_t size,
                       size_t align) {
+      if (!Py_IsInitialized())
+        Py_Initialize();
       Py_buffer *ownedView = static_cast<Py_buffer *>(userData);
+      nb::gil_scoped_acquire gil;
       PyBuffer_Release(ownedView);
       delete ownedView;
     };

``````````

</details>


https://github.com/llvm/llvm-project/pull/124832


More information about the Mlir-commits mailing list