Skip to content

Commit 2fc9229

Browse files
committed
Fix unsafe "block" implementation in test_eigen.cpp
1 parent 6a0e8ca commit 2fc9229

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

tests/test_eigen.cpp

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -201,7 +201,14 @@ TEST_SUBMODULE(eigen, m) {
201201
int start_row,
202202
int start_col,
203203
int block_rows,
204-
int block_cols) { return x.block(start_row, start_col, block_rows, block_cols); });
204+
int block_cols) {
205+
// In case x is a copy made in the type_caster for Eigen::Ref
206+
// (https://pybind11.readthedocs.io/en/stable/advanced/cast/eigen.html#pass-by-reference),
207+
// returning the Eigen::Ref returned by x.block() will lead to heap-use-after-free,
208+
// because the block references the copy, which is destroyed when this function
209+
// returns. Therefore the block needs to be returned by value.
210+
return Eigen::MatrixXd{x.block(start_row, start_col, block_rows, block_cols)};
211+
});
205212

206213
// test_eigen_return_references, test_eigen_keepalive
207214
// return value referencing/copying tests:

tests/test_eigen.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -223,7 +223,6 @@ def test_nonunit_stride_to_python():
223223
for i in range(-5, 7):
224224
assert np.all(m.diagonal_n(ref, i) == ref.diagonal(i)), f"m.diagonal_n({i})"
225225

226-
return # TODO(rwgk): Fix ASAN failure.
227226
assert np.all(m.block(ref, 2, 1, 3, 3) == ref[2:5, 1:4])
228227
assert np.all(m.block(ref, 1, 4, 4, 2) == ref[1:, 4:])
229228
assert np.all(m.block(ref, 1, 4, 3, 2) == ref[1:4, 4:])

0 commit comments

Comments
 (0)