From 8614247167fe7e628836af9b87c4355881e0b1bf Mon Sep 17 00:00:00 2001
From: Rhys-T <108157737+Rhys-T@users.noreply.github.com>
Date: Mon, 17 Mar 2025 15:06:05 -0400
Subject: [PATCH] Add workaround for tagged pointers on Android 12

Based on the corresponding OpenJDK patch at:
https://github.com/termux/termux-packages/blob/3ca825e40d7cf2f456ac5d5fd7b1a1693470081d/packages/openjdk-21/0022-Add-workaround-for-tagged-pointers-on-Android-12.patch

Co-authored-by: Tee KOBAYASHI <xtkoba@gmail.com>
Co-authored-by: dev-bz <32380878+dev-bz@users.noreply.github.com>
---
 system/vl.c | 28 ++++++++++++++++++++++++++++
 1 file changed, 28 insertions(+)

diff --git a/system/vl.c b/system/vl.c
index ec93988..0d0942a 100644
--- a/system/vl.c
+++ b/system/vl.c
@@ -140,6 +140,32 @@
 #include "qemu/guest-random.h"
 #include "qemu/keyval.h"
 
+#ifdef __TERMUX__
+#include <stdbool.h>
+#include <dlfcn.h>
+static void android_disable_tags() {
+    void *lib_handle = dlopen("libc.so", RTLD_LAZY);
+    if (lib_handle) {
+        if (android_get_device_api_level() >= 31) {
+            int (*mallopt_func)(int, int) = dlsym(lib_handle, "mallopt");
+            if (mallopt_func) {
+                mallopt_func(M_BIONIC_SET_HEAP_TAGGING_LEVEL, 0);
+            }
+            return;
+        }
+        /* android_get_device_api_level() < 31 */
+        bool (*android_mallopt)(int opcode, void* arg, size_t arg_size) = dlsym(lib_handle, "android_mallopt");
+        if (android_mallopt) {
+            int android_malloc_tag_level = 0;
+            android_mallopt(8, &android_malloc_tag_level, sizeof(android_malloc_tag_level));
+        }
+        dlclose(lib_handle);
+    }
+}
+#else
+static void android_disable_tags(){}
+#endif
+
 #define MAX_VIRTIO_CONSOLES 1
 
 typedef struct BlockdevOptionsQueueEntry {
@@ -2848,6 +2874,8 @@ void qemu_init(int argc, char **argv)
     bool userconfig = true;
     FILE *vmstate_dump_file = NULL;
 
+    android_disable_tags();
+
     qemu_add_opts(&qemu_drive_opts);
     qemu_add_drive_opts(&qemu_legacy_drive_opts);
     qemu_add_drive_opts(&qemu_common_drive_opts);
-- 
2.24.3 (Apple Git-128)

