From e9f627c5090901814507978f1e6be29864716c91 Mon Sep 17 00:00:00 2001 From: Mark Jan van Kampen Date: Thu, 13 Mar 2025 08:46:57 -0700 Subject: [PATCH] fix: contains check segfaults on empty map (#20446) Fixes #19624 Closes #20446 COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/20446 from mjvankampen:fix/segfault-empty-map ea872030c89e510174e382b0125c4c0086c53df5 PiperOrigin-RevId: 736519479 --- python/google/protobuf/internal/well_known_types_test.py | 5 +++++ python/message.c | 1 + 2 files changed, 6 insertions(+) diff --git a/python/google/protobuf/internal/well_known_types_test.py b/python/google/protobuf/internal/well_known_types_test.py index 1a6a97c1c6dbb..22f74acb813ad 100644 --- a/python/google/protobuf/internal/well_known_types_test.py +++ b/python/google/protobuf/internal/well_known_types_test.py @@ -683,6 +683,11 @@ def testDurationSub(self, old_time, time_delta, expected_sec, expected_nano): class StructTest(unittest.TestCase): + def testEmptyDict(self): + # in operator for empty initialized struct + msg = well_known_types_test_pb2.WKTMessage(optional_struct={}) + self.assertNotIn('key', msg.optional_struct) + def testStruct(self): struct = struct_pb2.Struct() self.assertIsInstance(struct, collections_abc.Mapping) diff --git a/python/message.c b/python/message.c index 5ad1b06ebbd92..8e60aaaab4364 100644 --- a/python/message.c +++ b/python/message.c @@ -1103,6 +1103,7 @@ static PyObject* PyUpb_Message_Contains(PyObject* _self, PyObject* arg) { upb_Message* msg = PyUpb_Message_GetMsg(self); const upb_FieldDef* f = upb_MessageDef_FindFieldByName(msgdef, "fields"); const upb_Map* map = upb_Message_GetFieldByDef(msg, f).map_val; + if (!map || upb_Map_Size(map) == 0) Py_RETURN_FALSE; const upb_MessageDef* entry_m = upb_FieldDef_MessageSubDef(f); const upb_FieldDef* key_f = upb_MessageDef_Field(entry_m, 0); upb_MessageValue u_key;