Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion Lib/multiprocessing/shared_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,13 @@ def __init__(self, sequence=None, *, name=None):
self._types_mapping[type(item)]
if not isinstance(item, (str, bytes))
else self._types_mapping[type(item)] % (
self._alignment * ((len(self._encode_value(item)) - 1) // self._alignment + 1),
# An empty str/bytes still needs one alignment unit of
# storage: a zero-length slot would overlap the next
# item (or the metadata area), and __setitem__() could
# then silently overwrite it with a fixed-size value.
max(self._alignment,
self._alignment * ((len(self._encode_value(item)) - 1)
// self._alignment + 1)),
)
for item in sequence
]
Expand Down
21 changes: 21 additions & 0 deletions Lib/test/_test_multiprocessing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5254,6 +5254,27 @@ def test_shared_memory_ShareableList_basics(self):
finally:
empty_sl.shm.unlink()

def test_shared_memory_ShareableList_empty_items(self):
# An empty str or bytes still needs a slot of its own: a zero-length
# slot overlaps the next item (or the metadata area), so storing a
# fixed-size value into it used to overwrite the following item, or
# to corrupt the packing formats and raise struct.error.
sl = shared_memory.ShareableList(['', b'', 42])
self.addCleanup(sl.shm.unlink)
try:
self.assertEqual(sl.format, '8s8sq')
self.assertEqual(list(sl), ['', b'', 42])
sl[0] = 7
sl[1] = 8
self.assertEqual(list(sl), [7, 8, 42])
sl[2] = ''
self.assertEqual(list(sl), [7, 8, ''])
# A trailing empty item must not run into the metadata area.
sl[2] = 3
self.assertEqual(list(sl), [7, 8, 3])
finally:
sl.shm.close()

def test_shared_memory_ShareableList_unpackable_value(self):
# Values of a supported type that cannot be packed must not leave
# the newly created shared memory block behind.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix a zero-length slot for an empty :class:`str` or :class:`bytes` in
:class:`multiprocessing.shared_memory.ShareableList`.
Loading