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
111 changes: 111 additions & 0 deletions graalpython/com.oracle.graal.python.test/src/tests/test_mmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,114 @@ def test_iter():
l.append(i)

assert l == [b'\x02', b'\x03', b'\x04']


def test_move():
m = mmap.mmap(-1, 6)
m[:] = b"abcdef"
assert m.move(1, 0, 4) is None
assert m[:] == b"aabcdf"
m[:] = b"abcdef"
m.move(0, 2, 4)
assert m[:] == b"cdefef"
m.move(3, 3, 3)
m.move(6, 0, 0)
assert m[:] == b"cdefef"
for args in [(-1, 0, 1), (0, -1, 1), (0, 0, -1), (0, 3, 4), (3, 0, 4), (7, 0, 0)]:
try:
m.move(*args)
except ValueError:
pass
else:
assert False, f"move{args} should raise ValueError"
m.close()
try:
m.move(0, 0, 1)
except ValueError:
pass
else:
assert False, "move on a closed mmap should raise ValueError"


def test_move_large_overlapping():
# larger than the copy buffer used by MoveNode, to exercise the chunked copy in both directions
size = 64 * 1024 * 3 + 17
data = bytes(i % 251 for i in range(size))
for dest, src in [(1, 0), (0, 1), (1000, 3), (3, 1000)]:
count = size - max(dest, src)
m = mmap.mmap(-1, size)
m[:] = data
m.move(dest, src, count)
assert m[:] == data[:dest] + data[src:src + count] + data[dest + count:]
m.close()


def test_move_readonly():
with tempfile.TemporaryDirectory() as tmpdir:
path = os.path.join(tmpdir, "move_readonly")
with open(path, "wb") as f:
f.write(b"abcdef")
with open(path, "rb") as f:
with mmap.mmap(f.fileno(), 6, access=mmap.ACCESS_READ) as m:
try:
m.move(1, 0, 4)
except TypeError:
pass
else:
assert False, "move on a readonly mmap should raise TypeError"
assert m[:] == b"abcdef"


def test_move_positional_only():
m = mmap.mmap(-1, 6)
m[:] = b"abcdef"
try:
m.move(dest=1, src=0, count=4)
except TypeError:
pass
else:
assert False, "move should not accept keyword arguments"
assert m[:] == b"abcdef"
m.close()


def test_move_closed_checked_before_arguments():
# CPython 3.13 checks the mapping before parsing the arguments (3.14+ converts them first)
m = mmap.mmap(-1, 6)
m.close()
try:
m.move(None, 0, 1)
except ValueError:
pass
else:
assert False, "move on a closed mmap should raise ValueError before converting the arguments"


def test_move_closed_by_index():
m = mmap.mmap(-1, 6)

class CloseOnIndex:
def __index__(self):
m.close()
return 0

try:
m.move(CloseOnIndex(), 1, 1)
except ValueError:
pass
else:
assert False, "move should raise ValueError when __index__ closes the mmap"


@unittest.skipUnless(hasattr(mmap, "PROT_WRITE"), "requires mmap.PROT_WRITE")
def test_move_write_only_mapping():
with tempfile.TemporaryDirectory() as tmpdir:
path = os.path.join(tmpdir, "move_write_only")
with open(path, "wb") as f:
f.write(b"abcdef")
with open(path, "r+b") as f:
with mmap.mmap(f.fileno(), 6, prot=mmap.PROT_WRITE) as m:
m.move(1, 0, 4)
m.flush()
with open(path, "rb") as f:
assert f.read() == b"aabcdf"
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ test.test_mmap.MmapTests.test_find_end @ darwin-arm64,linux-aarch64,linux-aarch6
test.test_mmap.MmapTests.test_flush_return_value @ darwin-arm64,win32-AMD64,win32-AMD64-github
test.test_mmap.MmapTests.test_length_0_large_offset @ darwin-arm64,linux-aarch64,linux-aarch64-github,linux-x86_64,linux-x86_64-github,win32-AMD64-github
test.test_mmap.MmapTests.test_length_0_offset @ darwin-arm64,linux-aarch64,linux-aarch64-github,linux-x86_64,linux-x86_64-github,win32-AMD64,win32-AMD64-github
test.test_mmap.MmapTests.test_move @ darwin-arm64,linux-aarch64,linux-aarch64-github,linux-x86_64,linux-x86_64-github,win32-AMD64,win32-AMD64-github
test.test_mmap.MmapTests.test_offset @ linux-aarch64,linux-aarch64-github,linux-x86_64,linux-x86_64-github,win32-AMD64,win32-AMD64-github
test.test_mmap.MmapTests.test_prot_readonly @ darwin-arm64,linux-aarch64,linux-aarch64-github,linux-x86_64,linux-x86_64-github,win32-AMD64,win32-AMD64-github
test.test_mmap.MmapTests.test_read_all @ darwin-arm64,linux-aarch64,linux-aarch64-github,linux-x86_64,linux-x86_64-github,win32-AMD64,win32-AMD64-github
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
import static com.oracle.graal.python.nodes.ErrorMessages.MMAP_INDICES_MUST_BE_INTEGER;
import static com.oracle.graal.python.nodes.ErrorMessages.MMAP_ITEM_VALUE_MUST_BE_AN_INT;
import static com.oracle.graal.python.nodes.ErrorMessages.MMAP_ITEM_VALUE_MUST_BE_IN_RANGE;
import static com.oracle.graal.python.nodes.ErrorMessages.MMAP_MOVE_OUT_OF_RANGE;
import static com.oracle.graal.python.nodes.ErrorMessages.MMAP_OBJECT_DOESNT_SUPPORT_ITEM_DELETION;
import static com.oracle.graal.python.nodes.ErrorMessages.MMAP_OBJECT_DOESNT_SUPPORT_SLICE_DELETION;
import static com.oracle.graal.python.nodes.ErrorMessages.MMAP_SLICE_ASSIGNMENT_IS_WRONG_SIZE;
Expand Down Expand Up @@ -125,6 +126,7 @@
import com.oracle.graal.python.nodes.function.PythonBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonBinaryClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonQuaternaryBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonQuaternaryClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonTernaryClinicBuiltinNode;
import com.oracle.graal.python.nodes.function.builtins.PythonUnaryBuiltinNode;
Expand Down Expand Up @@ -832,6 +834,76 @@ static int doIt(VirtualFrame frame, PMMap self, Object dataBuffer,
}
}

@Builtin(name = "move", minNumOfPositionalArgs = 4, numOfPositionalOnlyArgs = 4, parameterNames = {"$self", "dest", "src", "count"})
@GenerateNodeFactory
abstract static class MoveNode extends PythonQuaternaryBuiltinNode {
private static final int BUFFER_SIZE = 64 * 1024;

@Specialization
static Object move(VirtualFrame frame, PMMap self, Object destObj, Object srcObj, Object countObj,
@Bind Node inliningTarget,
@Bind PythonContext context,
@Cached LongIndexConverterNode indexConverter,
@Cached PConstructAndRaiseNode.Lazy constructAndRaiseNode,
@Cached PRaiseNode raiseNode) {
// Like CPython: check validity before converting the arguments, and again after the
// conversion, because __index__ can run arbitrary code that closes the mapping.
if (self.isClosed()) {
throw raiseNode.raise(inliningTarget, ValueError, MMAP_CLOSED_OR_INVALID);
}
Comment on lines +851 to +853

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Check for a closed mapping before converting move arguments

PythonQuaternaryClinicBuiltinNode converts the arguments before MoveNode.move checks self.isClosed(). On a closed map, m.move(None, 0, 1) therefore raises TypeError, while CPython 3.13 raises ValueError without inspecting the arguments. Check for closure before conversion and keep the check after conversion because __index__ can run Python code and close the mapping.

long dest = indexConverter.executeLong(frame, destObj);
long src = indexConverter.executeLong(frame, srcObj);
long count = indexConverter.executeLong(frame, countObj);
if (!self.isWriteable()) {
throw raiseNode.raise(inliningTarget, TypeError, MMAP_CANNOT_MODIFY_READONLY_MEMORY);
}
long len = self.getLength();
if (dest < 0 || src < 0 || count < 0 || len - dest < count || len - src < count) {
throw raiseNode.raise(inliningTarget, ValueError, MMAP_MOVE_OUT_OF_RANGE);
}
if (self.isClosed()) {
throw raiseNode.raise(inliningTarget, ValueError, MMAP_CLOSED_OR_INVALID);
}
if (count == 0 || dest == src) {
return PNone.NONE;
}
PosixSupport posixSupport = context.getPosixSupport();
Object handle = self.getPosixSupportHandle();
/*
* Equivalent of memmove: copy through an intermediate buffer in chunks. If the
* destination is after the source, copy from the end so that overlapping source bytes
* are read before they are overwritten.
*/
byte[] buffer = new byte[(int) Math.min(count, BUFFER_SIZE)];
try {
if (dest < src) {
for (long off = 0; off < count; off += buffer.length) {
int n = (int) Math.min(buffer.length, count - off);
copyChunk(inliningTarget, posixSupport, handle, src + off, dest + off, buffer, n, raiseNode);
}
} else {
for (long end = count; end > 0; end -= buffer.length) {
int n = (int) Math.min(buffer.length, end);
long off = end - n;
copyChunk(inliningTarget, posixSupport, handle, src + off, dest + off, buffer, n, raiseNode);
}
}
} catch (PosixException e) {
throw constructAndRaiseNode.get(inliningTarget).raiseOSErrorFromPosixException(frame, e);
}
return PNone.NONE;
}

private static void copyChunk(Node inliningTarget, PosixSupport posixSupport, Object handle, long from, long to, byte[] buffer, int n, PRaiseNode raiseNode)
throws PosixException {
int nread = posixSupport.mmapReadBytes(handle, from, buffer, n);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Support moves on write-only file mappings in the Java backend

With --python.PosixModuleBackend=java, a file mapping created with prot=mmap.PROT_WRITE passes the writability check, but copyChunk reads from a write-only channel and leaks NonReadableChannelException. The same move succeeds on CPython 3.13 on Linux x86-64. Give the Java backend a way to read the source bytes for move, and translate unsupported channel access into a Python exception.

if (nread != n) {
throw raiseNode.raise(inliningTarget, PythonBuiltinClassType.SystemError, MMAP_CHANGED_LENGTH);
}
posixSupport.mmapWriteBytes(handle, to, buffer, n);
Comment on lines +899 to +903

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Handle short transfers when moving bytes on Java-backed maps

A SeekableByteChannel can transfer fewer bytes than requested without reaching EOF or encountering an I/O failure. copyChunk treats a short read as a changed mapping length, and EmulatedPosixSupport.mmapWriteBytes treats a short write as EIO after partially updating the destination. Fill each chunk before writing it and retry short writes from the remaining buffer offset, with explicit handling for EOF and zero progress.

}
}

@Builtin(name = "seek", parameterNames = {"$self", "dist", "how"})
@ArgumentClinic(name = "dist", conversion = ClinicConversion.LongIndex)
@ArgumentClinic(name = "how", conversion = ClinicConversion.Int)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,7 @@ public abstract class ErrorMessages {
public static final TruffleString MMAP_ITEM_VALUE_MUST_BE_AN_INT = tsLiteral("mmap item value must be an int");
public static final TruffleString MMAP_ITEM_VALUE_MUST_BE_IN_RANGE = tsLiteral("mmap item value must be in range(0, 256)");
public static final TruffleString MMAP_SLICE_ASSIGNMENT_IS_WRONG_SIZE = tsLiteral("mmap slice assignment is wrong size");
public static final TruffleString MMAP_MOVE_OUT_OF_RANGE = tsLiteral("source, destination, or count out of range");

// zlib errors
public static final TruffleString WHILE_FLUSHING = tsLiteral("while flushing");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2824,15 +2824,20 @@ public void close() {

@Override
public int read(ByteBuffer dst) {
if (cur >= data.length) {
return -1;
}
int nread = Math.min(dst.remaining(), data.length - cur);
dst.put(data, cur, nread);
cur += nread;
return nread;
}

@Override
public int write(ByteBuffer src) {
int nwrite = Math.min(src.remaining(), data.length - cur);
src.get(data, cur, nwrite);
cur += nwrite;
return nwrite;
}

Expand Down Expand Up @@ -2901,6 +2906,9 @@ private static Set<StandardOpenOption> mmapProtToOptions(int prot) throws PosixE
options.add(StandardOpenOption.READ);
}
if ((prot & PROT_WRITE.value) != 0) {
// Writable mappings are also readable on the supported platforms (and mmap requires a
// file descriptor open for reading anyway), so that e.g. mmap.move() can read them.
options.add(StandardOpenOption.READ);
options.add(StandardOpenOption.WRITE);
}
if ((prot & PROT_EXEC.value) != 0) {
Expand Down Expand Up @@ -2949,9 +2957,21 @@ public int mmapReadBytes(Object mmap, long index, byte[] bytes, int length) thro

private static int readBytes(MMapHandle handle, long index, ByteBuffer readingBuffer) throws PosixException {
try {
handle.channel.position(index + handle.offset);
return handle.channel.read(readingBuffer);
} catch (IOException e) {
SeekableByteChannel channel = handle.channel;
channel.position(index + handle.offset);
// A channel may transfer fewer bytes than requested: keep reading until the buffer is
// full, the end of the channel is reached, or no progress is made.
int total = 0;
while (readingBuffer.hasRemaining()) {
int n = channel.read(readingBuffer);
if (n <= 0) {
break;
}
total += n;
}
return total;
} catch (Exception e) {
// Catching generic Exception to also cover NonReadableChannelException
throw posixException(OSErrorEnum.fromException(e));
}
}
Expand All @@ -2963,17 +2983,24 @@ public void mmapWriteBytes(Object mmap, long index, byte[] bytes, int length) th
throw posixException(OSErrorEnum.EACCES);
}
MMapHandle handle = (MMapHandle) mmap;
ByteBuffer buffer = ByteBuffer.wrap(bytes, 0, length);
try {
SeekableByteChannel channel = handle.channel;
channel.position(handle.offset + index);
int written = channel.write(ByteBuffer.wrap(bytes, 0, length));
if (written != length) {
throw posixException(OSErrorEnum.EIO);
// A channel may transfer fewer bytes than requested: retry with the remaining bytes
// until everything is written or no progress is made.
while (buffer.hasRemaining()) {
if (channel.write(buffer) <= 0) {
break;
}
}
} catch (Exception e) {
// Catching generic Exception to also cover NonWritableChannelException
throw posixException(OSErrorEnum.fromException(e));
}
if (buffer.hasRemaining()) {
throw posixException(OSErrorEnum.EIO);
}
}

@Override
Expand Down