SDL_ttf: release: apply updates from SDL3 repo

From cb303d4eb7838122b04b2d6f41c45faff0598374 Mon Sep 17 00:00:00 2001
From: Anonymous Maarten <[EMAIL REDACTED]>
Date: Thu, 6 Nov 2025 03:32:32 +0100
Subject: [PATCH] release: apply updates from SDL3 repo

- test Android elf alignment for x86_64/aarch64
- disable test cmake support of frameworks inside xcframework

[ci skip]
---
 .github/workflows/release.yml                 |  57 +++++++-
 .../resources/CMake/SDL3_ttfConfig.cmake      |  37 +++--
 .../CMake/SDL3_ttfConfigVersion.cmake         |  34 ++++-
 .../share/cmake/SDL3_ttf/SDL3_ttfConfig.cmake |   6 +-
 .../SDL3_ttf/SDL3_ttfConfigVersion.cmake      |   7 +-
 build-scripts/build-release.py                |   6 +-
 build-scripts/check_elf_alignment.sh          | 127 ++++++++++++++++++
 7 files changed, 247 insertions(+), 27 deletions(-)
 create mode 100755 build-scripts/check_elf_alignment.sh

diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 29f76572..a9778f3c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -264,6 +264,15 @@ jobs:
               -B build_darwin
           cmake --build build_darwin --config Release --verbose
 
+          cmake -S "${{ steps.src.outputs.path }}/cmake/test"               \
+              -DTEST_SHARED=TRUE                                            \
+              -DTEST_STATIC=FALSE                                           \
+              -DCMAKE_PREFIX_PATH="${{ steps.mount.outputs.mount-point }}/SDL3_ttf.xcframework/macos-arm64_x86_64;${{ steps.deps-mount.outputs.path }}/SDL3.xcframework/macos-arm64_x86_64" \
+              -DCMAKE_SYSTEM_NAME=Darwin                                    \
+              -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64"                      \
+              -B build_darwin2
+          cmake --build build_darwin2 --config Release --verbose
+
       - name: 'CMake (configure + build) iOS'
         run: |
           cmake -S "${{ steps.src.outputs.path }}/cmake/test"               \
@@ -275,6 +284,15 @@ jobs:
               -Werror=dev                                                   \
               -B build_ios
           cmake --build build_ios --config Release --verbose
+
+          cmake -S "${{ steps.src.outputs.path }}/cmake/test"               \
+              -DTEST_SHARED=TRUE                                            \
+              -DTEST_STATIC=FALSE                                           \
+              -DCMAKE_PREFIX_PATH="${{ steps.mount.outputs.mount-point }}/SDL3_ttf.xcframework/ios-arm64;${{ steps.deps-mount.outputs.path }}/SDL3.xcframework/ios-arm64" \
+              -DCMAKE_SYSTEM_NAME=iOS                                       \
+              -DCMAKE_OSX_ARCHITECTURES="arm64"                             \
+              -B build_ios2
+          cmake --build build_ios2 --config Release --verbose
       - name: 'CMake (configure + build) tvOS'
         run: |
           cmake -S "${{ steps.src.outputs.path }}/cmake/test"               \
@@ -286,6 +304,15 @@ jobs:
               -Werror=dev                                                   \
               -B build_tvos
           cmake --build build_tvos --config Release --verbose
+
+          cmake -S "${{ steps.src.outputs.path }}/cmake/test"               \
+              -DTEST_SHARED=TRUE                                            \
+              -DTEST_STATIC=FALSE                                           \
+              -DCMAKE_PREFIX_PATH="${{ steps.mount.outputs.mount-point }}/SDL3_ttf.xcframework/tvos-arm64;${{ steps.deps-mount.outputs.path }}/SDL3.xcframework/tvos-arm64" \
+              -DCMAKE_SYSTEM_NAME=tvOS                                      \
+              -DCMAKE_OSX_ARCHITECTURES="arm64"                             \
+              -B build_tvos2
+          cmake --build build_tvos2 --config Release --verbose
       - name: 'CMake (configure + build) iOS simulator'
         run: |
           sysroot=$(xcodebuild -version -sdk iphonesimulator Path)
@@ -300,6 +327,16 @@ jobs:
               -Werror=dev                                                   \
               -B build_ios_simulator
           cmake --build build_ios_simulator --config Release --verbose
+
+          cmake -S "${{ steps.src.outputs.path }}/cmake/test"               \
+              -DTEST_SHARED=TRUE                                            \
+              -DTEST_STATIC=FALSE                                           \
+              -DCMAKE_PREFIX_PATH="${{ steps.mount.outputs.mount-point }}/SDL3_ttf.xcframework/ios-arm64_x86_64-simulator;${{ steps.deps-mount.outputs.path }}/SDL3.xcframework/ios-arm64_x86_64-simulator" \
+              -DCMAKE_SYSTEM_NAME=iOS                                       \
+              -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64"                      \
+              -DCMAKE_OSX_SYSROOT="${sysroot}"                              \
+              -B build_ios_simulator2
+          cmake --build build_ios_simulator2 --config Release --verbose
       - name: 'CMake (configure + build) tvOS simulator'
         run: |
           sysroot=$(xcodebuild -version -sdk appletvsimulator Path)
@@ -314,6 +351,16 @@ jobs:
               -Werror=dev                                                   \
               -B build_tvos_simulator
           cmake --build build_tvos_simulator --config Release --verbose
+
+          cmake -S "${{ steps.src.outputs.path }}/cmake/test"               \
+              -DTEST_SHARED=TRUE                                            \
+              -DTEST_STATIC=FALSE                                           \
+              -DCMAKE_PREFIX_PATH="${{ steps.mount.outputs.mount-point }}/SDL3_ttf.xcframework/tvos-arm64_x86_64-simulator;${{ steps.deps-mount.outputs.path }}/SDL3.xcframework/tvos-arm64_x86_64-simulator" \
+              -DCMAKE_SYSTEM_NAME=tvOS                                      \
+              -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64"                      \
+              -DCMAKE_OSX_SYSROOT="${sysroot}"                              \
+              -B build_tvos_simulator2
+          cmake --build build_tvos_simulator2 --config Release --verbose
   msvc:
     needs: [src]
     runs-on: windows-2025
@@ -570,7 +617,7 @@ jobs:
           mkdir -p /tmp/deps-mingw/cmake
           mkdir -p /tmp/deps-mingw/i686-w64-mingw32
           mkdir -p /tmp/deps-mingw/x86_64-w64-mingw32
-          
+
           mkdir -p /tmp/deps-mingw-extract/sdl3
           tar -C /tmp/deps-mingw-extract/sdl3 -v -x -f "${{ steps.deps.outputs.dep-path }}/SDL3-devel-${{ steps.deps.outputs.dep-sdl-version }}-mingw.tar.gz"
           make -C /tmp/deps-mingw-extract/sdl3/SDL3-${{ steps.deps.outputs.dep-sdl-version }} install-all DESTDIR=/tmp/deps-mingw
@@ -629,6 +676,7 @@ jobs:
         with:
           sparse-checkout: 'build-scripts/build-release.py'
       - name: 'Setup Android NDK'
+        id: setup-ndk
         uses: nttld/setup-ndk@v1
         with:
           local-cache: false
@@ -663,6 +711,8 @@ jobs:
         run: |
           python build-scripts/build-release.py \
             --actions download android \
+            --android-api 21 \
+            --android-ndk-home "${{ steps.setup-ndk.outputs.ndk-path }}" \
             --commit ${{ inputs.commit }} \
             --root "${{ steps.tar.outputs.path }}" \
             --github \
@@ -728,6 +778,11 @@ jobs:
         run: |
           sudo apt-get update -y
           sudo apt-get install -y ninja-build
+      - name: 'Verify alignment of libSDL3_ttf.so (arm64-v8a/x86_64)'
+        run: |
+          set -e
+          ${{ steps.src.outputs.path }}/build-scripts/check_elf_alignment.sh ${{ steps.sdk.outputs.prefix }}/lib/arm64-v8a/libSDL3_ttf.so
+          ${{ steps.src.outputs.path }}/build-scripts/check_elf_alignment.sh ${{ steps.sdk.outputs.prefix }}/lib/x86_64/libSDL3_ttf.so
       - name: 'CMake (configure + build) x86, x64, arm32, arm64'
         run: |
           android_abis="x86 x86_64 armeabi-v7a arm64-v8a"
diff --git a/Xcode/pkg-support/resources/CMake/SDL3_ttfConfig.cmake b/Xcode/pkg-support/resources/CMake/SDL3_ttfConfig.cmake
index 826269f9..f5da253b 100644
--- a/Xcode/pkg-support/resources/CMake/SDL3_ttfConfig.cmake
+++ b/Xcode/pkg-support/resources/CMake/SDL3_ttfConfig.cmake
@@ -2,7 +2,7 @@
 # This file is meant to be placed in Resources/CMake of a SDL3_ttf framework
 
 # INTERFACE_LINK_OPTIONS needs CMake 3.12
-cmake_minimum_required(VERSION 3.12...3.28)
+cmake_minimum_required(VERSION 3.12...4.0)
 
 include(FeatureSummary)
 set_package_properties(SDL3_ttf PROPERTIES
@@ -28,15 +28,29 @@ set(SDLTTF_VENDORED TRUE)
 set(SDLTTF_HARFBUZZ TRUE)
 set(SDLTTF_FREETYPE TRUE)
 
-# Compute the installation prefix relative to this file.
-set(_sdl3_ttf_framework_path "${CMAKE_CURRENT_LIST_DIR}")                                   # > /SDL3_ttf.framework/Resources/CMake/
-get_filename_component(_sdl3_ttf_framework_path "${_sdl3_ttf_framework_path}" REALPATH)     # > /SDL3_ttf.framework/Versions/Current/Resources/CMake
-get_filename_component(_sdl3_ttf_framework_path "${_sdl3_ttf_framework_path}" REALPATH)     # > /SDL3_ttf.framework/Versions/A/Resources/CMake/
-get_filename_component(_sdl3_ttf_framework_path "${_sdl3_ttf_framework_path}" PATH)         # > /SDL3_ttf.framework/Versions/A/Resources/
-get_filename_component(_sdl3_ttf_framework_path "${_sdl3_ttf_framework_path}" PATH)         # > /SDL3_ttf.framework/Versions/A/
-get_filename_component(_sdl3_ttf_framework_path "${_sdl3_ttf_framework_path}" PATH)         # > /SDL3_ttf.framework/Versions/
-get_filename_component(_sdl3_ttf_framework_path "${_sdl3_ttf_framework_path}" PATH)         # > /SDL3_ttf.framework/
-get_filename_component(_sdl3_ttf_framework_parent_path "${_sdl3_ttf_framework_path}" PATH)  # > /
+# Compute the installation prefix relative to this file:
+# search upwards for the .framework directory
+set(_current_path "${CMAKE_CURRENT_LIST_DIR}")
+get_filename_component(_current_path "${_current_path}" REALPATH)
+set(_sdl3_ttf_framework_path "")
+
+while(NOT _sdl3_ttf_framework_path)
+    if(IS_DIRECTORY "${_current_path}" AND "${_current_path}" MATCHES "/SDL3_ttf\\.framework$")
+        set(_sdl3_ttf_framework_path "${_current_path}")
+        break()
+    endif()
+    get_filename_component(_next_current_path "${_current_path}" DIRECTORY)
+    if("${_current_path}" STREQUAL "${_next_current_path}")
+        break()
+    endif()
+    set(_current_path "${_next_current_path}")
+endwhile()
+unset(_current_path)
+unset(_next_current_path)
+
+if(NOT _sdl3_ttf_framework_path)
+    message(FATAL_ERROR "Could not find SDL3_ttf.framework root from ${CMAKE_CURRENT_LIST_DIR}")
+endif()
 
 # All targets are created, even when some might not be requested though COMPONENTS.
 # This is done for compatibility with CMake generated SDL3_ttf-target.cmake files.
@@ -46,7 +60,7 @@ if(NOT TARGET SDL3_ttf::SDL3_ttf-shared)
     set_target_properties(SDL3_ttf::SDL3_ttf-shared
         PROPERTIES
             FRAMEWORK "TRUE"
-            IMPORTED_LOCATION "${_sdl_ttf_framework_path}/SDL3_ttf"
+            IMPORTED_LOCATION "${_sdl3_ttf_framework_path}/SDL3_ttf"
             COMPATIBLE_INTERFACE_BOOL "SDL3_SHARED"
             INTERFACE_SDL3_SHARED "ON"
             COMPATIBLE_INTERFACE_STRING "SDL_VERSION"
@@ -58,7 +72,6 @@ set(SDL3_ttf_SDL3_ttf-shared_FOUND TRUE)
 set(SDL3_ttf_SDL3_ttf-static_FOUND FALSE)
 
 unset(_sdl3_ttf_framework_path)
-unset(_sdl3_ttf_framework_parent_path)
 
 set(SDL3_ttf_SDL3_ttf_FOUND FALSE)
 if(SDL3_ttf_SDL3_ttf-shared_FOUND OR SDL3_ttf_SDL3_ttf-static_FOUND)
diff --git a/Xcode/pkg-support/resources/CMake/SDL3_ttfConfigVersion.cmake b/Xcode/pkg-support/resources/CMake/SDL3_ttfConfigVersion.cmake
index 3602d9d0..bc859e17 100644
--- a/Xcode/pkg-support/resources/CMake/SDL3_ttfConfigVersion.cmake
+++ b/Xcode/pkg-support/resources/CMake/SDL3_ttfConfigVersion.cmake
@@ -1,14 +1,26 @@
 # based on the files generated by CMake's write_basic_package_version_file
 
 # SDL3_ttf CMake version configuration file:
-# This file is meant to be placed in Resources/CMake of a SDL3_ttf framework
+# This file is meant to be placed in Resources/CMake of a SDL3_ttf framework for macOS,
+# or in the CMake directory of a SDL3_ttf framework for iOS / tvOS / visionOS.
 
-if(NOT EXISTS "${CMAKE_CURRENT_LIST_DIR}/../../Headers/SDL_ttf.h")
-    message(AUTHOR_WARNING "Could not find SDL_ttf.h. This script is meant to be placed in the Resources/CMake directory of SDL3_ttf.framework")
+cmake_minimum_required(VERSION 3.12...4.0)
+
+# Find SDL_ttf.h.h
+set(_sdl_ttf_h_path "")
+if(EXISTS "${CMAKE_CURRENT_LIST_DIR}/../../Headers/SDL_ttf.h")
+    set(_sdl_ttf_h_path "${CMAKE_CURRENT_LIST_DIR}/../../Headers/SDL_ttf.h")
+elseif(EXISTS "${CMAKE_CURRENT_LIST_DIR}/../Headers/SDL_ttf.h")
+    set(_sdl_ttf_h_path "${CMAKE_CURRENT_LIST_DIR}/../Headers/SDL_ttf.h")
+endif()
+
+if(NOT _sdl_ttf_h_path)
+    message(AUTHOR_WARNING "Could not find SDL_ttf.h. This script is meant to be placed in the Resources/CMake directory or the CMake directory of SDL3_ttf.framework.")
+    set(PACKAGE_VERSION_UNSUITABLE TRUE)
     return()
 endif()
 
-file(READ "${CMAKE_CURRENT_LIST_DIR}/../../Headers/SDL_ttf.h" _sdl_ttf_h)
+file(READ "${_sdl_ttf_h_path}" _sdl_ttf_h)
 string(REGEX MATCH "#define[ \t]+SDL_TTF_MAJOR_VERSION[ \t]+([0-9]+)" _sdl_major_re "${_sdl_ttf_h}")
 set(_sdl_major "${CMAKE_MATCH_1}")
 string(REGEX MATCH "#define[ \t]+SDL_TTF_MINOR_VERSION[ \t]+([0-9]+)" _sdl_minor_re "${_sdl_ttf_h}")
@@ -19,9 +31,19 @@ if(_sdl_major_re AND _sdl_minor_re AND _sdl_micro_re)
     set(PACKAGE_VERSION "${_sdl_major}.${_sdl_minor}.${_sdl_micro}")
 else()
     message(AUTHOR_WARNING "Could not extract version from SDL_ttf.h.")
+    set(PACKAGE_VERSION_UNSUITABLE TRUE)
     return()
 endif()
 
+unset(_sdl_ttf_h)
+unset(_sdl_ttf_h_path)
+unset(_sdl_major_re)
+unset(_sdl_major)
+unset(_sdl_minor_re)
+unset(_sdl_minor)
+unset(_sdl_micro_re)
+unset(_sdl_micro)
+
 if(PACKAGE_FIND_VERSION_RANGE)
     # Package version must be in the requested version range
     if ((PACKAGE_FIND_VERSION_RANGE_MIN STREQUAL "INCLUDE" AND PACKAGE_VERSION VERSION_LESS PACKAGE_FIND_VERSION_MIN)
@@ -42,7 +64,7 @@ else()
     endif()
 endif()
 
-# if the using project doesn't have CMAKE_SIZEOF_VOID_P set, fail.
-if("${CMAKE_SIZEOF_VOID_P}" STREQUAL "")
+# The SDL3_ttf.xcframework only contains 64-bit archives
+if(NOT "${CMAKE_SIZEOF_VOID_P}" EQUAL "8")
     set(PACKAGE_VERSION_UNSUITABLE TRUE)
 endif()
diff --git a/Xcode/pkg-support/share/cmake/SDL3_ttf/SDL3_ttfConfig.cmake b/Xcode/pkg-support/share/cmake/SDL3_ttf/SDL3_ttfConfig.cmake
index 4e2e81dc..41930c8b 100644
--- a/Xcode/pkg-support/share/cmake/SDL3_ttf/SDL3_ttfConfig.cmake
+++ b/Xcode/pkg-support/share/cmake/SDL3_ttf/SDL3_ttfConfig.cmake
@@ -2,12 +2,12 @@
 # This file is meant to be placed in share/cmake/SDL3_ttf, next to SDL3_ttf.xcframework
 
 # INTERFACE_LINK_OPTIONS needs CMake 3.12
-cmake_minimum_required(VERSION 3.12...3.28)
+cmake_minimum_required(VERSION 3.12...4.0)
 
 include(FeatureSummary)
 set_package_properties(SDL3_ttf PROPERTIES
-        URL "https://www.libsdl.org/projects/SDL_ttf/"
-        DESCRIPTION "Support for TrueType (.ttf) font files with Simple Directmedia Layer"
+    URL "https://www.libsdl.org/projects/SDL_ttf/"
+    DESCRIPTION "Support for TrueType (.ttf) font files with Simple Directmedia Layer"
 )
 
 # Copied from `configure_package_config_file`
diff --git a/Xcode/pkg-support/share/cmake/SDL3_ttf/SDL3_ttfConfigVersion.cmake b/Xcode/pkg-support/share/cmake/SDL3_ttf/SDL3_ttfConfigVersion.cmake
index fc74f9ab..34f4e61a 100644
--- a/Xcode/pkg-support/share/cmake/SDL3_ttf/SDL3_ttfConfigVersion.cmake
+++ b/Xcode/pkg-support/share/cmake/SDL3_ttf/SDL3_ttfConfigVersion.cmake
@@ -3,7 +3,7 @@
 # SDL CMake version configuration file:
 # This file is meant to be placed in share/cmake/SDL3_ttf, next to SDL3_ttf.xcframework
 
-cmake_minimum_required(VERSION 3.12...3.28)
+cmake_minimum_required(VERSION 3.12...4.0)
 
 get_filename_component(_sdl3_ttf_xcframework_parent_path "${CMAKE_CURRENT_LIST_DIR}" REALPATH)                  # /share/cmake/SDL3_ttf/
 get_filename_component(_sdl3_ttf_xcframework_parent_path "${_sdl3_ttf_xcframework_parent_path}" REALPATH)       # /share/cmake/SDL3_ttf/
@@ -15,7 +15,8 @@ set(_sdl3_ttf_framework "${_sdl3_ttf_xcframework}/macos-arm64_x86_64/SDL3_ttf.fr
 set(_sdl3_ttf_version_h "${_sdl3_ttf_framework}/Headers/SDL_ttf.h")                                             # /SDL3_ttf.xcframework/macos-arm64_x86_64/SDL3_ttf.framework/Headers/SDL_ttf.h
 
 if(NOT EXISTS "${_sdl3_ttf_version_h}")
-    message(AUTHOR_WARNING "Cannot not find ${_sdl3_ttf_framework}. This script is meant to be placed in share/cmake/SDL3, next to SDL3.xcframework")
+    message(AUTHOR_WARNING "Cannot not find ${_sdl3_ttf_framework}. This script is meant to be placed in share/cmake/SDL3_ttf, next to SDL3_ttf.xcframework")
+    set(PACKAGE_VERSION_UNSUITABLE TRUE)
     return()
 endif()
 
@@ -36,6 +37,7 @@ if(_sdl_major_re AND _sdl_minor_re AND _sdl_micro_re)
     set(PACKAGE_VERSION "${_sdl_major}.${_sdl_minor}.${_sdl_micro}")
 else()
     message(AUTHOR_WARNING "Could not extract version from SDL_ttf.h.")
+    set(PACKAGE_VERSION_UNSUITABLE TRUE)
     return()
 endif()
 
@@ -45,6 +47,7 @@ unset(_sdl_minor_re)
 unset(_sdl_minor)
 unset(_sdl_micro_re)
 unset(_sdl_micro)
+unset(_sdl_version_h)
 
 if(PACKAGE_FIND_VERSION_RANGE)
     # Package version must be in the requested version range
diff --git a/build-scripts/build-release.py b/build-scripts/build-release.py
index e25bda8c..408624bb 100755
--- a/build-scripts/build-release.py
+++ b/build-scripts/build-release.py
@@ -1028,6 +1028,7 @@ def create_android_archives(self, android_api: int, android_home: Path, android_
                     # NDK 21e does not support -ffile-prefix-map
                     # f'''-DCMAKE_C_FLAGS="-ffile-prefix-map={self.root}=/src/{self.project}"''',
                     # f'''-DCMAKE_CXX_FLAGS="-ffile-prefix-map={self.root}=/src/{self.project}"''',
+                    f"-DANDROID_USE_LEGACY_TOOLCHAIN=0",
                     f"-DCMAKE_EXE_LINKER_FLAGS={extra_link_options}",
                     f"-DCMAKE_SHARED_LINKER_FLAGS={extra_link_options}",
                     f"-DCMAKE_TOOLCHAIN_FILE={cmake_toolchain_file}",
@@ -1126,8 +1127,7 @@ def download_dependencies(self):
         for dep, depinfo in self.release_info.get("dependencies", {}).items():
             startswith = depinfo["startswith"]
             dep_repo = depinfo["repo"]
-            # FIXME: dropped "--exclude-pre-releases"
-            dep_string_data = self.executer.check_output(["gh", "-R", dep_repo, "release", "list", "--exclude-drafts", "--json", "name,createdAt,tagName", "--jq", f'[.[]|select(.name|startswith("{startswith}"))]|max_by(.createdAt)']).strip()
+            dep_string_data = self.executer.check_output(["gh", "-R", dep_repo, "release", "list", "--exclude-drafts", "--exclude-pre-releases", "--json", "name,createdAt,tagName", "--jq", f'[.[]|select(.name|startswith("{startswith}"))]|max_by(.createdAt)']).strip()
             dep_data = json.loads(dep_string_data)
             dep_tag = dep_data["tagName"]
             dep_version = dep_data["name"]
@@ -1517,7 +1517,7 @@ def main(argv=None) -> int:
         if args.android_home is None or not Path(args.android_home).is_dir():
             parser.error("Invalid $ANDROID_HOME or --android-home: must be a directory containing the Android SDK")
         if args.android_ndk_home is None or not Path(args.android_ndk_home).is_dir():
-            parser.error("Invalid $ANDROID_NDK_HOME or --android_ndk_home: must be a directory containing the Android NDK")
+            parser.error("Invalid $ANDROID_NDK_HOME or --android-ndk-home: must be a directory containing the Android NDK")
         if args.android_api is None:
             with section_printer.group("Detect Android APIS"):
                 args.android_api = releaser._detect_android_api(android_home=args.android_home)
diff --git a/build-scripts/check_elf_alignment.sh b/build-scripts/check_elf_alignment.sh
new file mode 100755
index 00000000..d3846bca
--- /dev/null
+++ b/build-scripts/check_elf_alignment.sh
@@ -0,0 +1,127 @@
+#!/bin/bash
+progname="${0##*/}"
+progname="${progname%.sh}"
+
+# usage: check_elf_alignment.sh [path to *.so files|path to *.apk]
+
+cleanup_trap() {
+  if [ -n "${tmp}" -a -d "${tmp}" ]; then
+    rm -rf ${tmp}
+  fi
+  exit $1
+}
+
+usage() {
+  echo "Host side script to check the ELF alignment of shared libraries."
+  echo "Shared libraries are reported ALIGNED when their ELF regions are"
+  echo "16 KB or 64 KB aligned. Otherwise they are reported as UNALIGNED."
+  echo
+  echo "Usage: ${progname} [input-path|input-APK|input-APEX]"
+}
+
+if [ ${#} -ne 1 ]; then
+  usage
+  exit
+fi
+
+case ${1} in
+  --help | -h | -\?)
+    usage
+    exit
+    ;;
+
+  *)
+    dir="${1}"
+    ;;
+esac
+
+if ! [ -f "${dir}" -o -d "${dir}" ]; then
+  echo "Invalid file: ${dir}" >&2
+  exit 1
+fi
+
+if [[ "${dir}" == *.apk ]]; then
+  trap 'cleanup_trap' EXIT
+
+  echo
+  echo "Recursively analyzing $dir"
+  echo
+
+  if { zipalign --help 2>&1 | grep -q "\-P <pagesize_kb>"; }; then
+    echo "=== APK zip-alignment ==="
+    zipalign -v -c -P 16 4 "${dir}" | egrep 'lib/arm64-v8a|lib/x86_64|Verification'
+    echo "========================="
+  else
+    echo "NOTICE: Zip alignment check requires build-tools version 35.0.0-rc3 or higher."
+    echo "  You can install the latest build-tools by running the below command"
+    echo "  and updating your \$PATH:"
+    echo
+    echo "    sdkmanager \"build-tools;35.0.0-rc3\""
+  fi
+
+  dir_filename=$(basename "${dir}")
+  tmp=$(mktemp -d -t "${dir_filename%.apk}_out_XXXXX")
+  unzip "${dir}" lib/* -d "${tmp}" >/dev/null 2>&1
+  dir="${tmp}"
+fi
+
+if [[ "${dir}" == *.apex ]]; then
+  trap 'cleanup_trap' EXIT
+
+  echo
+  echo "Recursively analyzing $dir"
+  echo
+
+  dir_filename=$(basename "${dir}")
+  tmp=$(mktemp -d -t "${dir_filename%.apex}_out_XXXXX")
+  deapexer extract "${dir}" "${tmp}" || { echo "Failed to deapex." && exit 1; }
+  dir="${tmp}"
+fi
+
+RED="\e[31m"
+GREEN="\e[32m"
+ENDCOLOR="\e[0m"
+
+unaligned_libs=()
+unaligned_critical_libs=()
+
+echo
+echo "=== ELF alignment ==="
+
+matches="$(find "${dir}" -type f)"
+IFS=$'\n'
+for match in $matches; do
+  # We could recursively call this script or rewrite it to though.
+  [[ "${match}" == *".apk" ]] && echo "WARNING: doesn't recursively inspect .apk file: ${match}"
+  [[ "${match}" == *".apex" ]] && echo "WARNING: doesn't recursively inspect .apex file: ${match}"
+
+  [[ $(file "${match}") == *"ELF"* ]] || continue
+
+  res="$(objdump -p "${match}" | grep LOAD | awk '{ print $NF }' | head -1)"
+  if [[ $res =~ 2\*\*(1[4-9]|[2-9][0-9]|[1-9][0-9]{2,}) ]]; then
+    echo -e "${match}: ${GREEN}ALIGNED${ENDCOLOR} ($res)"
+  else
+    unaligned_libs+=("${match}")
+    # Check if this is a critical architecture (arm64-v8a or x86_64)
+    if [[ "${match}" == *"arm64-v8a"* ]] || [[ "${match}" == *"x86_64"* ]]; then
+      unaligned_critical_libs+=("${match}")
+      echo -e "${match}: ${RED}UNALIGNED${ENDCOLOR} ($res)"
+    else
+      echo -e "${match}: UNALIGNED ($res)"
+    fi
+  fi
+done
+
+if [ ${#unaligned_libs[@]} -gt 0 ]; then
+  echo -e "Found ${#unaligned_libs[@]} unaligned libs (only arm64-v8a/x86_64 libs need to be aligned).${ENDCOLOR}"
+fi
+echo "====================="
+
+# Exit with appropriate code: 1 if critical unaligned libs found, 0 otherwise
+if [ ${#unaligned_critical_libs[@]} -gt 0 ]; then
+  echo -e "${RED}Found ${#unaligned_critical_libs[@]} critical unaligned libs.${ENDCOLOR}"
+  exit 1
+else
+  echo -e "${GREEN}ELF Verification Successful${ENDCOLOR}"
+  exit 0
+fi