Read EI_DATA from the executable descriptor before selecting the CPU and
loading the image. This also covers binfmt open-binary execution and an
explicitly selected CPU model.

Reject invalid ELF byte-order encodings without using the invoked
emulator name to select an ABI.

Signed-off-by: Philippe Mathieu-Daudé <[email protected]>
---
 linux-user/main.c | 26 ++++++++++++++++++++++++++
 1 file changed, 26 insertions(+)

diff --git a/linux-user/main.c b/linux-user/main.c
index 2f0c0a50c8a4..71718f974f6b 100644
--- a/linux-user/main.c
+++ b/linux-user/main.c
@@ -22,6 +22,7 @@
 #include "qemu/units.h"
 #include "qemu/accel.h"
 #include "qemu/version.h"
+#include "elf.h"
 #include <sys/syscall.h>
 #include <sys/resource.h>
 #include <sys/shm.h>
@@ -769,6 +770,31 @@ int main(int argc, char **argv, char **envp)
         }
     }
 
+#ifdef TARGET_RUNTIME_ENDIAN
+    {
+        unsigned char ident[EI_NIDENT];
+        ssize_t len = pread(execfd, ident, sizeof(ident), 0);
+
+        if (len < 0) {
+            error_report("Error reading %s: %s", exec_path, strerror(errno));
+            exit(EXIT_FAILURE);
+        }
+        if (len == sizeof(ident) && memcmp(ident, ELFMAG, SELFMAG) == 0) {
+            switch (ident[EI_DATA]) {
+            case ELFDATA2LSB:
+                target_set_big_endian(false);
+                break;
+            case ELFDATA2MSB:
+                target_set_big_endian(true);
+                break;
+            default:
+                error_report("%s: Invalid ELF byte order", exec_path);
+                exit(EXIT_FAILURE);
+            }
+        }
+    }
+#endif
+
     /* Resolve executable file name to full path name */
     /* Keep how we started the program in exec_path, e.g. "./my_program" */
     /* Store real path in real_exec_path, e.g. "/usr/local/bin/my_program" */
-- 
2.55.0

Reply via email to