BUG: flatiter[True] reads and writes past the end of the array buffer
メンテナーはふだん 1 日以内に返信
まだ誰も着手していません。
- #33083 @lazerg による — マージされずにクローズ
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 35/100
調査の方向性
Read numpy/_core/src/multiarray/iterators.c, especially iter_subscript and iter_ass_subscript, and inspect the existing test at numpy/_core/tests/test_indexing.py:1513. Reproduce the issue with the provided script, then add regression coverage for indexing after iteration and empty arrays. Done means reads and writes stay within bounds and the regression tests pass; a linked pull request is already open.
索引モデルが issue の本文から書いたものです。
説明
Describe the issue:
a.flat[True] can read and write memory outside the array. NumPy gives a DeprecationWarning and then does the read or the write.
Background. a.flat returns a numpy.flatiter. You can loop over it (for x in a.flat) and you can index it (a.flat[3]). While you loop, the iterator keeps a C pointer, dataptr, to the current element. When the loop ends, dataptr points one element past the end of the buffer.
Cause. Every index type except a 0-d boolean first calls PyArray_ITER_RESET, which moves dataptr back to element 0. Then it checks the index against the size. The 0-d boolean branch runs before that reset and has no size check. It reads or writes one element at the current dataptr.
Read, in iter_subscript:
https://github.com/numpy/numpy/blob/7ed6cf76b27d66e6354f8d6cedafd1e06cda741e/numpy/_core/src/multiarray/iterators.c#L556-L579
Write, in iter_ass_subscript:
https://github.com/numpy/numpy/blob/7ed6cf76b27d66e6354f8d6cedafd1e06cda741e/numpy/_core/src/multiarray/iterators.c#L830-L844
flowchart TD
call["it[index] or it[index] = value"] --> prep["prepare_index_noarray() sorts the index by type"]
prep --> kind{"Is the index a 0-d boolean?<br/>True, False, np.array(True)"}
kind -- "no: int, slice, list, array" --> reset["PyArray_ITER_RESET<br/>dataptr goes back to element 0"]
reset --> bounds["check the index against the size"]
bounds --> good["read or write the element"]
kind -- "yes, True" --> warn["DeprecationWarning"]
warn --> bad["read or write at the current dataptr<br/>no reset, no size check"]
classDef bug fill:#F6D3BF,stroke:#D55E00,color:#1A1A1A
class bad bug
This gives three wrong results:
- After
next(it),it[True]returnsa[1]. It should returna[0], the same asit[0]. The existing test atnumpy/_core/tests/test_indexing.py:1513expects element 0, but it uses a new iterator, so it passes. - After the loop ends,
it[True]reads 8 bytes past the end of the buffer ofa.it[True] = vwrites 8 bytes there. - An empty array still gets a 1-byte buffer.
e.flat[True]reads or writese.itemsizebytes from the start of that buffer.e.flat[0]correctly raisesIndexError: index 0 is out of bounds for size 0.
When it started. Problem 1 and the read in problem 2 are new in NumPy 2.4. Before #28590, iter_subscript called PyArray_ITER_RESET before its PyBool_Check branch. #28590 put the new HAS_0D_BOOL branch above the reset. The write in problem 2 and both parts of problem 3 also fail on 2.3.5.
"Segfault" in this table means a crash under macOS Guard Malloc, which puts the end of each allocation at the edge of a page.
| 2.3.5 | 2.5.4 | nightly 2.6.0.dev0+git20261013.acf3017 | |
|---|---|---|---|
it[True] after next(it) |
0 |
1 |
1 |
it[True] after the loop |
0, no crash |
segfault | segfault |
it[True] = v after the loop |
segfault | segfault | segfault |
e.flat[True], empty S64 array |
segfault | segfault | segfault |
e.flat[True] = v, empty S64 array |
segfault | segfault | segfault |
Related: #17175 is about the odd results of boolean indexing on flatiter. A note at its top says the deprecation can be finalized. It does not mention reads or writes outside the buffer.
Reproduce the code example:
import warnings
import numpy as np
# flat[True] gives a DeprecationWarning since NumPy 2.4. Hide it to keep the output short.
warnings.simplefilter("ignore", DeprecationWarning)
a = np.arange(4)
it = a.flat
print(it[True]) # 0: correct, the first element
next(it)
print(it[True], it[0]) # 1 0: it[True] should be 0, the same as it[0]
for _ in it: # run the iterator to the end
pass
print(it[True]) # reads 8 bytes past the end of the buffer of `a`
it[True] = 12345 # writes 8 bytes past the end of the buffer of `a`
e = np.empty(0, dtype="S64")
print(e.flat[True]) # reads 64 bytes from the 1-byte buffer of an empty array
e.flat[True] = b"x" * 64 # writes 64 bytes into that 1-byte buffer
print("finished without an error")
Error message:
# Normal run, NumPy 2.5.4. No error. Line 3 is 5, but `a` holds only 0 to 3.
# Line 4 is heap memory. The values change from run to run.
0
1 0
5
b'\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00\x00\x04'
finished without an error
Backtraces under macOS Guard Malloc (NumPy 2.5.4 wheel from PyPI)
The script below is the middle part of the reproducer. It uses np.arange(4) because 32 bytes is a multiple of 16, so Guard Malloc puts the end of the buffer on a page edge.
import sys, warnings
import numpy as np
warnings.simplefilter("ignore", DeprecationWarning)
a = np.arange(4) # 32 bytes, so Guard Malloc puts the end of the buffer on a page edge
it = a.flat
for _ in it:
pass
print("loop done", flush=True)
if sys.argv[1] == "read":
print(it[True])
else:
it[True] = 12345
print("no crash", flush=True)
$ PYTHONMALLOC=malloc DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib python -u flatiter_true_crash.py read
loop done
[exit code 139]
$ PYTHONMALLOC=malloc DYLD_INSERT_LIBRARIES=/usr/lib/libgmalloc.dylib python -u flatiter_true_crash.py write
loop done
[exit code 139]
The same two runs under lldb, with the same two environment variables:
# read
* thread #2, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x80302f8000)
* frame #0: 0x00000070c957c0a8 _multiarray_umath.cpython-313-darwin.so`LONG_copyswap + 4
frame #1: 0x00000070c96c8268 _multiarray_umath.cpython-313-darwin.so`PyArray_Scalar + 628
frame #2: 0x00000070c9698e7c _multiarray_umath.cpython-313-darwin.so`iter_subscript + 596
frame #3: 0x00000001007ce9cc Python`_PyEval_EvalFrameDefault + 9508
frame #4: 0x00000001007cc22c Python`PyEval_EvalCode + 200
frame #5: 0x000000010083bfa4 Python`run_eval_code_obj + 104
# write
* thread #2, queue = 'com.apple.main-thread', stop reason = EXC_BAD_ACCESS (code=1, address=0x80432fc000)
* frame #0: 0x00000070dc577fa4 _multiarray_umath.cpython-313-darwin.so`LONG_setitem + 448
frame #1: 0x00000070dc695d9c _multiarray_umath.cpython-313-darwin.so`iter_ass_subscript + 424
frame #2: 0x00000001007d247c Python`_PyEval_EvalFrameDefault + 24532
frame #3: 0x00000001007cc22c Python`PyEval_EvalCode + 200
frame #4: 0x000000010083bfa4 Python`run_eval_code_obj + 104
frame #5: 0x000000010083b8f8 Python`run_mod + 168
Both fault addresses are at the start of a memory page. Guard Malloc puts an unmapped page right after each buffer, so each fault is at the first byte past the end of the buffer.
Python and NumPy Versions:
2.5.4
3.13.11 (main, Dec 5 2025, 16:06:33) [Clang 17.0.0 (clang-1700.6.3.2)]
The same results on NumPy 2.6.0.dev0+git20261013.acf3017 (nightly wheel) and on 2.3.5, as in the table above.
Runtime Environment:
[{'numpy_version': '2.5.4',
'python': '3.13.11 (main, Dec 5 2025, 16:06:33) [Clang 17.0.0 '
'(clang-1700.6.3.2)]',
'uname': uname_result(system='Darwin', node='<redacted>', release='27.0.0', version='Darwin Kernel Version 27.0.0: Tue Aug 11 21:20:40 PDT 2026; root:xnu-13432.1.9~1/RELEASE_ARM64_T6020', machine='arm64')},
{'simd_extensions': {'baseline': ['NEON', 'NEON_FP16', 'NEON_VFPV4', 'ASIMD'],
'found': ['ASIMDHP', 'ASIMDDP'],
'not_found': ['ASIMDFHM']}},
{'ignore_floating_point_errors_in_matmul': True}]
How does this issue affect you or how did you find it:
Possible fixes (not tested):
- Finalize the 2.4 deprecation, so a 0-d boolean index raises
IndexError. That removes both branches. - If the deprecation must stay for now, treat
Trueas the integer index 0. MovePyArray_ITER_RESET(self)above the 0-d boolean branch in both functions. RaiseIndexErrorwhenself->size == 0.
A regression test could run the iterator to the end, then check that it[True] == a[0], and check that np.empty(0).flat[True] raises IndexError.
- 主要言語
- Python
- スター
- 33.5k
- フォーク
- 13.1k
- 平均マージ
- 1日 19時間
- マージ済み PR(30日)
- 143
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
numpy/numpy のほかの issue
-
00 - Bug component: numpy.linalg
難易度 2/5 1〜3時間 初心者へのやさしさ 75/100
メンテナーはふだん 1 日以内に返信
-
00 - Bug
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
メンテナーはふだん 1 日以内に返信
-
00 - Bug
難易度 2/5 1〜3時間 初心者へのやさしさ 70/100
numpy/numpy#33422 · コメント 6 件 ·
メンテナーはふだん 1 日以内に返信
-
BUG: f2py treats a backslash as an escape inside character literals対応中かも @HaoZeke が 17 日前に担当しました。 オープン00 - Bug component: numpy.f2py
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
numpy/numpy#33220 · コメント 2 件 · 担当者 1 名 ·
メンテナーはふだん 1 日以内に返信
-
DOC: use CITATION.cff file format for citation information対応中かも @JaroCamphuijsen が 58 日前に担当しました。 オープン04 - Documentation
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
numpy/numpy#32817 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
似ている issue
-
難易度 1/5 1時間未満 初心者へのやさしさ 72/100
521xueweihan/HelloGitHub#4543 ·
-
難易度 2/5 1〜3時間 初心者へのやさしさ 83/100
emeryberger/CSrankings#15700 ·
メンテナーはふだん 2 日以内に返信
-
Bug | 工作不正常 Triage | 待检查
難易度 2/5 1〜3時間 初心者へのやさしさ 77/100
OneDragon-Anything/ZenlessZoneZero-OneDragon#3084 ·
メンテナーはふだん 1 日以内に返信
-
Task select patterns with uppercase letters never match対応中かも @manobhisriram が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 76/100
メンテナーはふだん 1 日以内に返信