[Bug][TOPI] `topi.scanop` (`cumsum` / `cumprod`) performs out-of-bounds write/read on empty tensors

Aperta Adatta ai principianti
#21,125 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 3 giorni

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
82/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
python
Ambito
backend, compilers

Direzione di ricerca

Inizia in python/tvm/topi/scan.py, nel body per lane di topi.scanop, poi esamina i test di scan vicini per i tensori vuoti e il comportamento esclusivo rispetto a quello inclusivo. Riproduci il caso con un asse di scan di lunghezza zero e verifica che il kernel non acceda ad alcun buffer e restituisca un tensore vuoto della stessa forma.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

needs-triage type: bug
Expected behavior

Calling topi.cumsum or topi.cumprod (or relax.op.cumsum / relax.op.cumprod) on a valid 0-element tensor whose scan axis has length 0 (e.g., shape=(0,) or (2, 0, 4)) should perform zero memory accesses and return an empty tensor of the same shape.

Actual behavior

topi.scanop unconditionally writes out_buf[base_idx] (and reads data_buf[base_idx] when exclusive=False) even when cumsum_axis_len == 0, causing an out-of-bounds heap write (and OOB read for exclusive=False) on 0-byte buffers.

In python/tvm/topi/scan.py (lines 120–134 on main 84657c01):

with T.parallel(0, axis_mul_before * axis_mul_after) as fused:
    i = fused // axis_mul_after
    j = fused % axis_mul_after
    base_idx = i * cumsum_axis_len * axis_mul_after + j
    if exclusive:
        T.tensor_store(
            out_buf, T.tensor_indices(out_buf, base_idx), cast(identity_value, dtype)
        )
    else:
        T.tensor_store(
            out_buf,
            T.tensor_indices(out_buf, base_idx),
            maybe_cast(data_buf[T.tensor_indices(data_buf, base_idx)]),
        )
    with T.serial(0, cumsum_axis_len - 1) as _k:
        ...

When N == 0, T.parallel(0, axis_mul_before * axis_mul_after) still executes with base_idx = 0, writing 8 bytes (int64) past the end of the 0-byte out_buf (or axis_mul_after * sizeof(dtype) bytes for multi-dimensional shapes like (2, 0, 4)).

Environment
  • TVM: 0.27.0 (7b5acb32bd271342a24130f4ef439ff6c2e52c6c)
  • Upstream status: verified still unfixed on apache/tvm main (84657c01e5d3672cfd299bd3d5c77bff3888a1a9, 2026-12-02)
  • OS: Linux x86_64
Steps to reproduce
import ctypes
import numpy as np
import tvm
from tvm import te, topi

N = te.var("N", dtype="int64")
A = te.placeholder((N,), name="A", dtype="int64")
B = topi.cumsum(A, axis=0, exclusive=True)
print(tvm.IRModule.from_expr(te.create_prim_func([A, B])).script())
fn = tvm.compile(te.create_prim_func([A, B]), target="llvm")

# Map a PROT_NONE page and pass it as a valid 0-element (0-byte) int64 tensor.
# A sound 0-length kernel performs 0 memory accesses; scanop writes out_buf[0] = 0 -> SIGSEGV.
libc = ctypes.CDLL("libc.so.6")
libc.mmap.restype = ctypes.c_void_p
libc.mmap.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_long]
addr = libc.mmap(None, 4096, 0, 0x22, -1, 0)

class ZeroElemView:
    def __init__(self, ptr):
        self.__array_interface__ = {"shape": (0,), "typestr": "<i8", "data": (ptr, False), "version": 3}

a_np = np.asarray(ZeroElemView(addr))
b_np = np.asarray(ZeroElemView(addr))
fn(tvm.runtime.from_dlpack(a_np), tvm.runtime.from_dlpack(b_np))  # SIGSEGV (-11)

Using topi.nn.relu(A) as a control with the exact same ZeroElemView(addr) succeeds with exit code 0, whereas cumsum(exclusive=True), cumsum(exclusive=False), and cumprod(exclusive=True) all crash with SIGSEGV (-11).

Suggested fix

Guard the per-lane body inside T.parallel in python/tvm/topi/scan.py with with T.If(cumsum_axis_len > 0): with T.Then(): ... (or guard the entire parallel loop with cumsum_axis_len > 0).

Lingua principale
Python
Stelle
13.9k
Fork
4.1k
Merge medio
4g 22h
PR unite (30g)
22

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di apache/tvm

Tutte le issue di apache/tvm

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.