From 96ded83d2c06de50194300c5925ce7cb250f92b4 Mon Sep 17 00:00:00 2001 From: Ryan Heard Date: Wed, 11 Nov 2026 09:42:13 -0500 Subject: [PATCH] [mypyc] Fix OverflowError when a native `__hash__` returns a large int --- mypyc/codegen/emitwrapper.py | 21 ++++++++++----- mypyc/lib-rt/CPy.h | 1 + mypyc/lib-rt/generic_ops.c | 17 ++++++++++++ mypyc/test-data/run-dunders.test | 46 ++++++++++++++++++++++++++++++++ 4 files changed, 78 insertions(+), 7 deletions(-) diff --git a/mypyc/codegen/emitwrapper.py b/mypyc/codegen/emitwrapper.py index e21d919265329..92d32937872d9 100644 --- a/mypyc/codegen/emitwrapper.py +++ b/mypyc/codegen/emitwrapper.py @@ -607,7 +607,7 @@ def generate_get_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: def generate_hash_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: """Generates a wrapper for native __hash__ methods.""" name = f"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}" - emitter.emit_line(f"static Py_ssize_t {name}(PyObject *self) {{") + emitter.emit_line(f"static Py_hash_t {name}(PyObject *self) {{") emitter.emit_line( "{}retval = {}{}{}(self);".format( emitter.ctype_spaced(fn.ret_type), @@ -618,13 +618,20 @@ def generate_hash_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str: ) emitter.emit_error_check("retval", fn.ret_type, "return -1;") if is_int_rprimitive(fn.ret_type): - emitter.emit_line("Py_ssize_t val = CPyTagged_AsSsize_t(retval);") + emitter.emit_line("if (likely(CPyTagged_CheckShort(retval))) {") + # A short int always fits in Py_hash_t, but -1 is reserved for errors + emitter.emit_line("Py_hash_t val = CPyTagged_ShortAsSsize_t(retval);") + emitter.emit_line("return val == -1 ? -2 : val;") + emitter.emit_line("}") + emitter.emit_line("Py_hash_t val = CPy_HashFromResult(CPyTagged_LongAsObject(retval));") + emitter.emit_dec_ref("retval", fn.ret_type) else: - emitter.emit_line("Py_ssize_t val = PyLong_AsSsize_t(retval);") - emitter.emit_dec_ref("retval", fn.ret_type) - emitter.emit_line("if (PyErr_Occurred()) return -1;") - # We can't return -1 from a hash function.. - emitter.emit_line("if (val == -1) return -2;") + # CPy_HashFromResult() takes an object, so box other unboxed types such as i64 + emitter.emit_box("retval", "retbox", fn.ret_type, declare_dest=True) + if fn.ret_type.is_unboxed: + emitter.emit_line("if (unlikely(retbox == NULL)) return -1;") + emitter.emit_line("Py_hash_t val = CPy_HashFromResult(retbox);") + emitter.emit_dec_ref("retbox", object_rprimitive) emitter.emit_line("return val;") emitter.emit_line("}") diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index d4bd2d8938ce1..9dca9623a80b3 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -893,6 +893,7 @@ static void CPy_LogGetAttr(const char *method, PyObject *obj, PyObject *attr) { PyObject_GetAttr((obj), (attr))) CPyTagged CPyObject_Hash(PyObject *o); +Py_hash_t CPy_HashFromResult(PyObject *res); // Default identity-based hash (same as object.__hash__), used as tp_hash static inline Py_hash_t CPy_DefaultHash(PyObject *o) { diff --git a/mypyc/lib-rt/generic_ops.c b/mypyc/lib-rt/generic_ops.c index 09e6df362343a..d421b53ebf0ad 100644 --- a/mypyc/lib-rt/generic_ops.c +++ b/mypyc/lib-rt/generic_ops.c @@ -20,6 +20,23 @@ CPyTagged CPyObject_Hash(PyObject *o) { } } +// Convert the result of a __hash__ method to a hash value like slot_tp_hash in +// CPython: an int that doesn't fit in Py_hash_t is hashed again, so any int is a +// valid result. Return -1 with an exception set if res isn't an int. +Py_hash_t CPy_HashFromResult(PyObject *res) { + if (unlikely(!PyLong_Check(res))) { + PyErr_SetString(PyExc_TypeError, "__hash__ method should return an integer"); + return -1; + } + Py_hash_t h = PyLong_AsSsize_t(res); + if (h == -1 && PyErr_Occurred()) { + PyErr_Clear(); + h = PyLong_Type.tp_hash(res); + } + // -1 is reserved for errors + return h == -1 ? -2 : h; +} + PyObject *CPyObject_GetAttr3(PyObject *v, PyObject *name, PyObject *defl) { PyObject *result; diff --git a/mypyc/test-data/run-dunders.test b/mypyc/test-data/run-dunders.test index ad9cd46bfd6c1..4f932b684c8da 100644 --- a/mypyc/test-data/run-dunders.test +++ b/mypyc/test-data/run-dunders.test @@ -1477,6 +1477,52 @@ def test_explicit_hash() -> None: assert hash(EqHash()) == 5 assert hash(EqHashSub()) == 5 +[case testDundersHashResult] +# hash() converts the value returned by __hash__ like in Python +from typing import Any + +from mypy_extensions import i64 +from testutil import assertRaises + +class Hash: + def __init__(self, h: int) -> None: + self.h = h + + def __hash__(self) -> int: + return self.h + +class HashAny: + def __init__(self, h: Any) -> None: + self.h = h + + def __hash__(self) -> Any: + return self.h + +class HashI64: + def __hash__(self) -> i64: + return -1 + +def test_hash_result() -> None: + # These fit in Py_hash_t on 32-bit and 64-bit platforms + for h in [0, 7, -2, 2**30, -(2**31)]: + assert hash(Hash(h)) == h + assert hash(HashAny(h)) == h + # -1 is reserved for errors + assert hash(Hash(-1)) == -2 + assert hash(HashAny(-1)) == -2 + assert hash(HashI64()) == -2 + # These don't fit in Py_hash_t on any platform, so they are hashed again + for h in [2**63, -(2**63) - 1, 2**64 + 5, -(2**100)]: + assert hash(Hash(h)) == hash(h) + assert hash(HashAny(h)) == hash(h) + # A long int that fits in Py_hash_t on 64-bit platforms, but not on 32-bit ones + assert hash(Hash(2**62)) in (2**62, hash(2**62)) + assert hash(HashAny(2**62)) in (2**62, hash(2**62)) + assert hash(HashAny(True)) == 1 + for x in ["x", 1.0, None]: + with assertRaises(TypeError, "__hash__ method should return an integer"): + hash(HashAny(x)) + [case testDundersImplicitNeWithNarrowRhs] class Accepted: pass