[PATCH v3] linux-user: retry ignored ELF load hints for PIE executables

Artemii Mashanov posted 1 patch 4 days, 6 hours ago
linux-user/elfload.c          | 24 +++++++++++++++++-------
tests/tcg/aarch64/brk-pie.c   | 28 ++++++++++++++++++++++++++++
tests/tcg/aarch64/meson.build |  1 +
tests/tcg/meson.build         |  8 +++++---
4 files changed, 51 insertions(+), 10 deletions(-)
create mode 100644 tests/tcg/aarch64/brk-pie.c
[PATCH v3] linux-user: retry ignored ELF load hints for PIE executables
Posted by Artemii Mashanov 4 days, 6 hours ago
On x86_64 hosts that cannot map the preferred AArch64 ET_DYN base,
mmap() may place the main image near QEMU's host mappings, causing
subsequent brk growth to fail.

Retry with lower page-aligned hints for main ET_DYN images without
reserved guest address space. Add an AArch64 static PIE regression
for heap growth, memory access and restoration of the original break.
Allow individual TCG tests to select static PIE linking.

Resolves: https://gitlab.com/qemu-project/qemu/-/issues/4645
Signed-off-by: Artemii Mashanov <ralerrdirsardx@gmail.com>
---
 linux-user/elfload.c          | 24 +++++++++++++++++-------
 tests/tcg/aarch64/brk-pie.c   | 28 ++++++++++++++++++++++++++++
 tests/tcg/aarch64/meson.build |  1 +
 tests/tcg/meson.build         |  8 +++++---
 4 files changed, 51 insertions(+), 10 deletions(-)
 create mode 100644 tests/tcg/aarch64/brk-pie.c

diff --git a/linux-user/elfload.c b/linux-user/elfload.c
index c188fa0..f45326a 100644
--- a/linux-user/elfload.c
+++ b/linux-user/elfload.c
@@ -934,7 +934,7 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
 {
     g_autofree struct elf_phdr *phdr = NULL;
     PGBRange range = { -1, 0 };
-    abi_ulong load_addr, load_bias, error, align;
+    abi_ulong load_addr, load_bias, error, align, mmap_hint;
     size_t reserve_size, align_size;
     int i, prot_exec;
     Error *err = NULL;
@@ -1073,12 +1073,22 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
         align_size += align - 1;
     }
 
-    load_addr = target_mmap(load_addr, align_size, PROT_NONE,
-                            MAP_PRIVATE | MAP_ANON | MAP_NORESERVE |
-                            (ehdr->e_type == ET_EXEC ? MAP_FIXED_NOREPLACE : 0),
-                            -1, 0);
-    if (load_addr == -1) {
-        goto exit_mmap;
+    mmap_hint = load_addr;
+    for (;;) {
+        load_addr = target_mmap(mmap_hint, align_size, PROT_NONE,
+                                MAP_PRIVATE | MAP_ANON | MAP_NORESERVE |
+                                (ehdr->e_type == ET_EXEC
+                                 ? MAP_FIXED_NOREPLACE : 0),
+                                -1, 0);
+        if (load_addr == -1) {
+            goto exit_mmap;
+        }
+        if (ehdr->e_type != ET_DYN || pinterp_name == NULL || reserved_va ||
+            load_addr == mmap_hint || mmap_hint == 0) {
+            break;
+        }
+        target_munmap(load_addr, align_size);
+        mmap_hint = (mmap_hint / 2) & TARGET_PAGE_MASK;
     }
 
     if (align_size != reserve_size) {
diff --git a/tests/tcg/aarch64/brk-pie.c b/tests/tcg/aarch64/brk-pie.c
new file mode 100644
index 0000000..a3736ad
--- /dev/null
+++ b/tests/tcg/aarch64/brk-pie.c
@@ -0,0 +1,28 @@
+/* SPDX-License-Identifier: GPL-2.0-or-later */
+
+#define _DEFAULT_SOURCE
+#include <assert.h>
+#include <unistd.h>
+
+int main(void)
+{
+    enum { SIZE = 64 * 1024 };
+    void *initial = sbrk(0);
+    /* Keep heap accesses observable to the compiler. */
+    volatile unsigned char *heap = initial;
+
+    assert(initial != (void *)-1);
+    assert(sbrk(SIZE) == initial);
+    assert(sbrk(0) == (char *)initial + SIZE);
+
+    for (unsigned int i = 0; i < SIZE; i++) {
+        heap[i] = i;
+    }
+    for (unsigned int i = 0; i < SIZE; i++) {
+        assert(heap[i] == (unsigned char)i);
+    }
+
+    assert(sbrk(-SIZE) == (char *)initial + SIZE);
+    assert(sbrk(0) == initial);
+    return 0;
+}
diff --git a/tests/tcg/aarch64/meson.build b/tests/tcg/aarch64/meson.build
index 2033356..a9a21c5 100644
--- a/tests/tcg/aarch64/meson.build
+++ b/tests/tcg/aarch64/meson.build
@@ -8,6 +8,7 @@ tests += tcg_tests['multiarch-linux-user']['tests']
 # Base architecture tests
 tests += {
   '../arm/fcvt.c': {'cflags': '-lm', 'expected_output': 'fcvt.ref'},
+  'brk-pie.c': {'pie': true},
   'pcalign-a64.c': {},
   'lse2-fault.c': {},
   'test-2248.c': {},
diff --git a/tests/tcg/meson.build b/tests/tcg/meson.build
index 01c0aaf..32e09a1 100644
--- a/tests/tcg/meson.build
+++ b/tests/tcg/meson.build
@@ -35,6 +35,7 @@ tcg_tests = {}
 #           'exe_name': ['provide an alternative binary name'],
 #           'test_name': ['provide an alternative test name'],
 #           'cflags': ['additional cflags to compile test', ...],
+#           'pie': bool,  # compile executable as PIE, default to false
 #           'depends': [meson_dependency, ...],
 #           'cc_feat': 'feature name, must be present in cc_feat_cflags',
 #           'qemu_args': ['qemu command line flags', ...],
@@ -324,8 +325,8 @@ foreach target, plan: tcg_tests
       # return a clear error if user misspell a setup entry
       foreach key, _ : setup
         allowed = ['exe_name', 'env_var', 'expected_output', 'cc_feat', 'cflags',
-                   'depends', 'gdb_feat', 'gdb_test', 'plugin_test', 'protocol',
-                   'qemu_args', 'test_name', 'wrapper']
+                   'depends', 'gdb_feat', 'gdb_test', 'pie', 'plugin_test',
+                   'protocol', 'qemu_args', 'test_name', 'wrapper']
         if key not in allowed
           error('unknown tcg setup entry \'' + key + '\' for test ' + src +
                 ' (possible: [' + ', '.join(allowed) + '])')
@@ -438,10 +439,11 @@ foreach target, plan: tcg_tests
 
       # build executable if needed
       if exe_name not in built_tests
+        static_flag = setup.get('pie', false) ? '-static-pie' : '-static'
         exe = custom_target(exe_name + '.test',
                             input: file,
                             command: [cc, '@INPUT@',
-                                      '-o', '@OUTPUT@', '-static',
+                                      '-o', '@OUTPUT@', static_flag,
                                       '-MMD', '-MF', '@DEPFILE@',
                                       '-Wall', '-Werror',
                                       '-O0', '-g', '-fno-strict-aliasing',

Interdiff against v2:
  diff --git a/tests/tcg/multiarch/linux/brk-pie.c b/tests/tcg/aarch64/brk-pie.c
  similarity index 100%
  rename from tests/tcg/multiarch/linux/brk-pie.c
  rename to tests/tcg/aarch64/brk-pie.c
  diff --git a/tests/tcg/aarch64/meson.build b/tests/tcg/aarch64/meson.build
  index e3aeb81..a9a21c5 100644
  --- a/tests/tcg/aarch64/meson.build
  +++ b/tests/tcg/aarch64/meson.build
  @@ -8,7 +8,7 @@ tests += tcg_tests['multiarch-linux-user']['tests']
   # Base architecture tests
   tests += {
     '../arm/fcvt.c': {'cflags': '-lm', 'expected_output': 'fcvt.ref'},
  -  '../multiarch/linux/brk-pie.c': {'pie': true},
  +  'brk-pie.c': {'pie': true},
     'pcalign-a64.c': {},
     'lse2-fault.c': {},
     'test-2248.c': {},
-- 
2.56.1
Re: [PATCH v3] linux-user: retry ignored ELF load hints for PIE executables
Posted by Richard Henderson 3 days, 22 hours ago
On 12/2/26 05:54, Artemii Mashanov wrote:
> On x86_64 hosts that cannot map the preferred AArch64 ET_DYN base,
> mmap() may place the main image near QEMU's host mappings, causing
> subsequent brk growth to fail.
> 
> Retry with lower page-aligned hints for main ET_DYN images without
> reserved guest address space. Add an AArch64 static PIE regression
> for heap growth, memory access and restoration of the original break.
> Allow individual TCG tests to select static PIE linking.
> 
> Resolves: https://gitlab.com/qemu-project/qemu/-/issues/4645
> Signed-off-by: Artemii Mashanov <ralerrdirsardx@gmail.com>
> ---
>   linux-user/elfload.c          | 24 +++++++++++++++++-------
>   tests/tcg/aarch64/brk-pie.c   | 28 ++++++++++++++++++++++++++++
>   tests/tcg/aarch64/meson.build |  1 +
>   tests/tcg/meson.build         |  8 +++++---
>   4 files changed, 51 insertions(+), 10 deletions(-)
>   create mode 100644 tests/tcg/aarch64/brk-pie.c
> 
> diff --git a/linux-user/elfload.c b/linux-user/elfload.c
> index c188fa0..f45326a 100644
> --- a/linux-user/elfload.c
> +++ b/linux-user/elfload.c
> @@ -934,7 +934,7 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
>   {
>       g_autofree struct elf_phdr *phdr = NULL;
>       PGBRange range = { -1, 0 };
> -    abi_ulong load_addr, load_bias, error, align;
> +    abi_ulong load_addr, load_bias, error, align, mmap_hint;
>       size_t reserve_size, align_size;
>       int i, prot_exec;
>       Error *err = NULL;
> @@ -1073,12 +1073,22 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
>           align_size += align - 1;
>       }
>   
> -    load_addr = target_mmap(load_addr, align_size, PROT_NONE,
> -                            MAP_PRIVATE | MAP_ANON | MAP_NORESERVE |
> -                            (ehdr->e_type == ET_EXEC ? MAP_FIXED_NOREPLACE : 0),
> -                            -1, 0);
> -    if (load_addr == -1) {
> -        goto exit_mmap;
> +    mmap_hint = load_addr;
> +    for (;;) {
> +        load_addr = target_mmap(mmap_hint, align_size, PROT_NONE,
> +                                MAP_PRIVATE | MAP_ANON | MAP_NORESERVE |
> +                                (ehdr->e_type == ET_EXEC
> +                                 ? MAP_FIXED_NOREPLACE : 0),
> +                                -1, 0);
> +        if (load_addr == -1) {
> +            goto exit_mmap;
> +        }
> +        if (ehdr->e_type != ET_DYN || pinterp_name == NULL || reserved_va ||
> +            load_addr == mmap_hint || mmap_hint == 0) {
> +            break;
> +        }
> +        target_munmap(load_addr, align_size);
> +        mmap_hint = (mmap_hint / 2) & TARGET_PAGE_MASK;

This makes no sense.

There's no need for a loop.  You can choose the "correct" value straight 
away.

(1) ET_EXEC of course requires exactly load_addr.

(2) ET_DYN *could* be always 0, allowing the kernel to select the 
address, but...

(3) ET_DYN *should* be load_addr if we can allow that, to support 
prelink.  We can do so when:

(3a) reserved_va has already has split the address space
(3b) load_addr isn't "near" brk.

Therefore this becomes

     mmap_hint = load_addr;
     if (ehdr->e_type == ET_DYN
         && !reserved_va
         && !near_brk(load_addr) {
         mmap_hint = 0;
     }
     load_addr = target_mmap(load_addr, align_size, PROT_NONE,
                             MAP_PRIVATE | MAP_ANON | MAP_NORESERVE |
                             (ehdr->e_type == ET_EXEC ?
                              MAP_FIXED_NOREPLACE : 0),
                             -1, 0);

Writing the near_brk() predicate is an left as an exercise for the 
reader.  Note that we already have tests vs brk in 
common-user/probe-guest-base.c for very similar reasons, so there's room 
to rearrange and share code.


r~
Re: [PATCH v3] linux-user: retry ignored ELF load hints for PIE executables
Posted by Richard Henderson 3 days, 22 hours ago
On 12/2/26 14:18, Richard Henderson wrote:
> On 12/2/26 05:54, Artemii Mashanov wrote:
>> On x86_64 hosts that cannot map the preferred AArch64 ET_DYN base,

Finally, please quit sending new patches as replies to old patches.
This breaks tooling that uses lore.kernel.org.


r~
Re: [PATCH v3] linux-user: retry ignored ELF load hints for PIE executables
Posted by Pierrick Bouvier 3 days, 23 hours ago
On 12/2/2026 5:54 AM, Artemii Mashanov wrote:
> On x86_64 hosts that cannot map the preferred AArch64 ET_DYN base,
> mmap() may place the main image near QEMU's host mappings, causing
> subsequent brk growth to fail.
> 
> Retry with lower page-aligned hints for main ET_DYN images without
> reserved guest address space. Add an AArch64 static PIE regression
> for heap growth, memory access and restoration of the original break.
> Allow individual TCG tests to select static PIE linking.
> 
> Resolves: https://gitlab.com/qemu-project/qemu/-/issues/4645
> Signed-off-by: Artemii Mashanov <ralerrdirsardx@gmail.com>
> ---
>  linux-user/elfload.c          | 24 +++++++++++++++++-------
>  tests/tcg/aarch64/brk-pie.c   | 28 ++++++++++++++++++++++++++++
>  tests/tcg/aarch64/meson.build |  1 +
>  tests/tcg/meson.build         |  8 +++++---
>  4 files changed, 51 insertions(+), 10 deletions(-)
>  create mode 100644 tests/tcg/aarch64/brk-pie.c
> 
> diff --git a/linux-user/elfload.c b/linux-user/elfload.c
> index c188fa0..f45326a 100644
> --- a/linux-user/elfload.c
> +++ b/linux-user/elfload.c
> @@ -934,7 +934,7 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
>  {
>      g_autofree struct elf_phdr *phdr = NULL;
>      PGBRange range = { -1, 0 };
> -    abi_ulong load_addr, load_bias, error, align;
> +    abi_ulong load_addr, load_bias, error, align, mmap_hint;
>      size_t reserve_size, align_size;
>      int i, prot_exec;
>      Error *err = NULL;
> @@ -1073,12 +1073,22 @@ static void load_elf_image(const char *image_name, const ImageSource *src,
>          align_size += align - 1;
>      }
>  
> -    load_addr = target_mmap(load_addr, align_size, PROT_NONE,
> -                            MAP_PRIVATE | MAP_ANON | MAP_NORESERVE |
> -                            (ehdr->e_type == ET_EXEC ? MAP_FIXED_NOREPLACE : 0),
> -                            -1, 0);
> -    if (load_addr == -1) {
> -        goto exit_mmap;
> +    mmap_hint = load_addr;
> +    for (;;) {
> +        load_addr = target_mmap(mmap_hint, align_size, PROT_NONE,
> +                                MAP_PRIVATE | MAP_ANON | MAP_NORESERVE |
> +                                (ehdr->e_type == ET_EXEC
> +                                 ? MAP_FIXED_NOREPLACE : 0),
> +                                -1, 0);
> +        if (load_addr == -1) {
> +            goto exit_mmap;
> +        }
> +        if (ehdr->e_type != ET_DYN || pinterp_name == NULL || reserved_va ||
> +            load_addr == mmap_hint || mmap_hint == 0) {
> +            break;
> +        }
> +        target_munmap(load_addr, align_size);
> +        mmap_hint = (mmap_hint / 2) & TARGET_PAGE_MASK;
>      }
>  
>      if (align_size != reserve_size) {
> diff --git a/tests/tcg/aarch64/brk-pie.c b/tests/tcg/aarch64/brk-pie.c
> new file mode 100644
> index 0000000..a3736ad
> --- /dev/null
> +++ b/tests/tcg/aarch64/brk-pie.c
> @@ -0,0 +1,28 @@
> +/* SPDX-License-Identifier: GPL-2.0-or-later */
> +
> +#define _DEFAULT_SOURCE
> +#include <assert.h>
> +#include <unistd.h>
> +
> +int main(void)
> +{
> +    enum { SIZE = 64 * 1024 };
> +    void *initial = sbrk(0);
> +    /* Keep heap accesses observable to the compiler. */
> +    volatile unsigned char *heap = initial;
> +
> +    assert(initial != (void *)-1);
> +    assert(sbrk(SIZE) == initial);
> +    assert(sbrk(0) == (char *)initial + SIZE);
> +
> +    for (unsigned int i = 0; i < SIZE; i++) {
> +        heap[i] = i;
> +    }
> +    for (unsigned int i = 0; i < SIZE; i++) {
> +        assert(heap[i] == (unsigned char)i);
> +    }
> +
> +    assert(sbrk(-SIZE) == (char *)initial + SIZE);
> +    assert(sbrk(0) == initial);
> +    return 0;
> +}
> diff --git a/tests/tcg/aarch64/meson.build b/tests/tcg/aarch64/meson.build
> index 2033356..a9a21c5 100644
> --- a/tests/tcg/aarch64/meson.build
> +++ b/tests/tcg/aarch64/meson.build
> @@ -8,6 +8,7 @@ tests += tcg_tests['multiarch-linux-user']['tests']
>  # Base architecture tests
>  tests += {
>    '../arm/fcvt.c': {'cflags': '-lm', 'expected_output': 'fcvt.ref'},
> +  'brk-pie.c': {'pie': true},
>    'pcalign-a64.c': {},
>    'lse2-fault.c': {},
>    'test-2248.c': {},
> diff --git a/tests/tcg/meson.build b/tests/tcg/meson.build
> index 01c0aaf..32e09a1 100644
> --- a/tests/tcg/meson.build
> +++ b/tests/tcg/meson.build
> @@ -35,6 +35,7 @@ tcg_tests = {}
>  #           'exe_name': ['provide an alternative binary name'],
>  #           'test_name': ['provide an alternative test name'],
>  #           'cflags': ['additional cflags to compile test', ...],
> +#           'pie': bool,  # compile executable as PIE, default to false
>  #           'depends': [meson_dependency, ...],
>  #           'cc_feat': 'feature name, must be present in cc_feat_cflags',
>  #           'qemu_args': ['qemu command line flags', ...],
> @@ -324,8 +325,8 @@ foreach target, plan: tcg_tests
>        # return a clear error if user misspell a setup entry
>        foreach key, _ : setup
>          allowed = ['exe_name', 'env_var', 'expected_output', 'cc_feat', 'cflags',
> -                   'depends', 'gdb_feat', 'gdb_test', 'plugin_test', 'protocol',
> -                   'qemu_args', 'test_name', 'wrapper']
> +                   'depends', 'gdb_feat', 'gdb_test', 'pie', 'plugin_test',
> +                   'protocol', 'qemu_args', 'test_name', 'wrapper']
>          if key not in allowed
>            error('unknown tcg setup entry \'' + key + '\' for test ' + src +
>                  ' (possible: [' + ', '.join(allowed) + '])')
> @@ -438,10 +439,11 @@ foreach target, plan: tcg_tests
>  
>        # build executable if needed
>        if exe_name not in built_tests
> +        static_flag = setup.get('pie', false) ? '-static-pie' : '-static'
>          exe = custom_target(exe_name + '.test',
>                              input: file,
>                              command: [cc, '@INPUT@',
> -                                      '-o', '@OUTPUT@', '-static',
> +                                      '-o', '@OUTPUT@', static_flag,
>                                        '-MMD', '-MF', '@DEPFILE@',
>                                        '-Wall', '-Werror',
>                                        '-O0', '-g', '-fno-strict-aliasing',
>

It looks good to me.

Reviewed-by: Pierrick Bouvier <pierrick.bouvier@oss.qualcomm.com>
Tested-by: Pierrick Bouvier <pierrick.bouvier@oss.qualcomm.com>

Tested the added test (with/without the code change), and also all our
CI is passing with it.

@Helge: does it sound good to you?

Regards,
Pierrick