array_t::at() returns a misaligned reference when the stride is not a multiple of alignof(T)

未关闭
#6,309 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 3 天内回复

@henryiii 已经在做这个了。

开始于 2026年11月25日。

  • #6311 来自 @henryiii —— 未关闭

评估

难度
4/5
预计耗时
3-5 天
新手友好度
35/100
Issue 类型
缺陷
描述清晰度
基本清楚
活跃度
活跃
技术栈
cpp, python
领域
api, data

调研方向

The misaligned reference comes from array_t::at() and mutable_at() in include/pybind11/numpy.h, around line 1526. Start with the element address calculation there, then run test_at_stride_not_multiple_of_itemsize under the UBSan CI job, which currently deselects it. Done means the test passes under UBSan without the deselect, and either a throw for misaligned elements or an alignment check at array creation has been chosen and implemented.

由索引模型根据 Issue 内容生成。

描述

🤖 AI text below 🤖

Since #6241, array_t<T>::at() and mutable_at() support strides that are not a multiple of sizeof(T). They return a T & to the element. If the stride is not a multiple of alignof(T), that reference is misaligned. This is undefined behavior. It works on x86 and arm64, but it can fail on platforms that require aligned access, and UBSan reports it:

include/pybind11/numpy.h:1526: runtime error: reference binding to misaligned address 0x00000a5cf433 for type 'const short unsigned int', which requires 2 byte alignment

Reproducer (from test_at_stride_not_multiple_of_itemsize):

packed = np.zeros(3, dtype=[("a", np.uint16), ("b", np.uint8)])
m.at_t(packed["a"], 1)  # stride 3, element 1 is at an odd address

A reference cannot point to a misaligned T. Possible fixes:

  • Throw when the element address is not aligned for T.
  • Throw when the array is not aligned (NPY_ARRAY_ALIGNED), possibly as a check when the array_t is created.

The UBSan CI job deselects this test until this is fixed.

主要语言
C++
星标
18k
派生
2.3k
平均合并
5 天 7 小时
30 天内合并 PR
53

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

pybind/pybind11 的其他 Issue

查看 pybind/pybind11 的全部 Issue

相似的 Issue

更多 C++ Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。