linux-user: maybe_do_fake_open does not handle relative paths properly

Host environment

  • Operating system:

    Linux

  • OS/kernel version:

    Linux/all

  • Architecture:

    All

  • QEMU flavor:

    qemu-ARCH(,-static)

  • QEMU version:

    master

  • QEMU command line:

    ./qemu-ARCH(-static) some-ARCH-rootfs/usr/bin/ps

Emulated/Virtualized environment

  • Operating system:

    Linux

  • OS/kernel version:

    Linux/All

  • Architecture:

    All

Description of problem

qemu user does not properly resolve relative paths in fake open handler

Steps to reproduce

  1. Run something like "ps" under strace+qemu-ARCH(,-static)
  2. Observe e.g. openat dirfd pointing to /proc, path = SOMEPID/cmdline with SOMEPID matching the qemu-ARCH(,-static) PID.
  3. "ps" shows itself as qemu-ARCH(,-static)

Additional information

Potential fix:

diff --git a/linux-user/syscall.c b/linux-user/syscall.c
index cfa68dfbdb..30004e1bac 100644
--- a/linux-user/syscall.c
+++ b/linux-user/syscall.c
@@ -8826,6 +8826,30 @@ static int open_net_route(CPUArchState *cpu_env, int fd)
 }
 #endif
 
+static char *realpathat(int dirfd,
+                        const char *rel_path,
+                        char *resolved_path)
+{
+    int fd;
+    char proc_path[64];
+    char *result;
+
+    if (rel_path[0] == '/') {
+        return realpath(rel_path, resolved_path);
+    }
+
+    fd = openat(dirfd, rel_path, O_PATH | O_CLOEXEC);
+    if (fd == -1) {
+        return NULL;
+    }
+
+    snprintf(proc_path, sizeof(proc_path), "/proc/self/fd/%d", fd);
+    result = realpath(proc_path, resolved_path);
+    close(fd);
+
+    return result;
+}
+
 static int maybe_do_fake_open(CPUArchState *cpu_env, int dirfd,
                               const char *fname, int flags, mode_t mode,
                               int openat2_resolve, bool safe)
@@ -8857,7 +8881,7 @@ static int maybe_do_fake_open(CPUArchState *cpu_env, int dirfd,
     };
 
     /* if this is a file from /proc/ filesystem, expand full name */
-    proc_name = realpath(fname, NULL);
+    proc_name = realpathat(dirfd, fname, NULL);
     if (proc_name && strncmp(proc_name, "/proc/", 6) == 0) {
         pathname = proc_name;
     } else {
Edited by Frajo