[Stable-10.1.4 31/74] linux-user: fix mremap errors for invalid ranges

Michael Tokarev posted 74 patches 1 week ago
[Stable-10.1.4 31/74] linux-user: fix mremap errors for invalid ranges
Posted by Michael Tokarev 1 week ago
From: Matthew Lugg <mlugg@mlugg.co.uk>

If an address range given to `mremap` is invalid (exceeds addressing
bounds on the guest), we were previously returning `ENOMEM`, which is
not correct. The manpage and the Linux kernel implementation both agree
that if `old_addr`/`old_size` refer to an invalid address, `EFAULT` is
returned, and if `new_addr`/`new_size` refer to an invalid address,
`EINVAL` is returned.

Signed-off-by: Matthew Lugg <mlugg@mlugg.co.uk>
Signed-off-by: Richard Henderson <richard.henderson@linaro.org>
Message-ID: <20251117170954.31451-3-mlugg@mlugg.co.uk>
(cherry picked from commit 2422884ec5a12037d2378f45ca1411d3f37c7081)
Signed-off-by: Michael Tokarev <mjt@tls.msk.ru>

diff --git a/linux-user/mmap.c b/linux-user/mmap.c
index 7a5f7c3660..131c6374bc 100644
--- a/linux-user/mmap.c
+++ b/linux-user/mmap.c
@@ -1109,12 +1109,15 @@ abi_long target_mremap(abi_ulong old_addr, abi_ulong old_size,
     int prot;
     void *host_addr;
 
-    if (!guest_range_valid_untagged(old_addr, old_size) ||
-        ((flags & MREMAP_FIXED) &&
+    if (((flags & MREMAP_FIXED) &&
          !guest_range_valid_untagged(new_addr, new_size)) ||
         ((flags & MREMAP_MAYMOVE) == 0 &&
          !guest_range_valid_untagged(old_addr, new_size))) {
-        errno = ENOMEM;
+        errno = EINVAL;
+        return -1;
+    }
+    if (!guest_range_valid_untagged(old_addr, old_size)) {
+        errno = EFAULT;
         return -1;
     }
 
-- 
2.47.3