#!/usr/bin/env bash # Builds the unmodified Stockfish 11 engine for Android as a standalone executable, one per ABI, # into app/src/main/jniLibs//libstockfish.so (it is an executable, named .so so the # installer extracts it to nativeLibraryDir). See BUILD_INFO.md for the recorded results. # # Usage: ANDROID_NDK_HOME= tools/stockfish/build_stockfish.sh # (defaults to the NDK below inside the Android SDK when ANDROID_NDK_HOME is unset) # Needs: bash, curl, tar, sha256sum. Works on Linux, macOS and Windows (Git Bash). # # The Stockfish source is never edited: SF11's Makefile has no Android/armv8 target, so the # sources are compiled directly with the NDK's clang, with the flags below. set -euo pipefail TAG=sf_11 URL="https://github.com/official-stockfish/Stockfish/archive/refs/tags/$TAG.tar.gz" SHA256=802261cc601b67bed00c0ef7d21e2125959630f0852a06db9fc9bd74f440b199 NDK_VERSION=28.2.13676358 API=26 HERE="$(cd "$(dirname "$0")" && pwd)" ROOT="$(cd "$HERE/../.." && pwd)" WORK="$HERE/work" OUT="$ROOT/app/src/main/jniLibs" if [ -z "${ANDROID_NDK_HOME:-}" ]; then for sdk in "${ANDROID_HOME:-}" "${ANDROID_SDK_ROOT:-}" "${LOCALAPPDATA:-}/Android/Sdk" "$HOME/Library/Android/sdk" "$HOME/Android/Sdk"; do if [ -n "$sdk" ] && [ -d "$sdk/ndk/$NDK_VERSION" ]; then ANDROID_NDK_HOME="$sdk/ndk/$NDK_VERSION"; break; fi done fi [ -d "${ANDROID_NDK_HOME:-}" ] || { echo "NDK $NDK_VERSION not found; set ANDROID_NDK_HOME" >&2; exit 1; } case "$(uname -s)" in Linux*) HOST=linux-x86_64 ;; Darwin*) HOST=darwin-x86_64 ;; MINGW* | MSYS* | CYGWIN*) HOST=windows-x86_64 ;; *) echo "unsupported host $(uname -s)" >&2; exit 1 ;; esac BIN="$ANDROID_NDK_HOME/toolchains/llvm/prebuilt/$HOST/bin" CXX="$BIN/clang++" READELF="$BIN/llvm-readelf" # Source: download once, verify, unpack. mkdir -p "$WORK" TARBALL="$WORK/$TAG.tar.gz" [ -f "$TARBALL" ] || curl -fsSL -o "$TARBALL" "$URL" echo "$SHA256 $TARBALL" | sha256sum -c - SRC_DIR="$WORK/Stockfish-$TAG" rm -rf "$SRC_DIR" tar xzf "$TARBALL" -C "$WORK" COMMON="-O3 -std=c++11 -DNDEBUG -fPIE -pie -static-libstdc++ -s -Wl,-z,max-page-size=16384 -Wl,-z,common-page-size=16384" build() { # local abi=$1 target=$2 shift 2 mkdir -p "$OUT/$abi" echo "== $abi" # Relative source paths keep the command line short (Windows) and the output path-independent. (cd "$SRC_DIR" && "$CXX" --target="$target$API" $COMMON "$@" src/*.cpp src/syzygy/tbprobe.cpp -o "$OUT/$abi/libstockfish.so") "$READELF" -l "$OUT/$abi/libstockfish.so" | grep LOAD } build arm64-v8a aarch64-linux-android -DIS_64BIT build armeabi-v7a armv7a-linux-androideabi -mthumb -march=armv7-a -mfpu=neon build x86_64 x86_64-linux-android -DIS_64BIT -DUSE_POPCNT -msse4.2 -mpopcnt # 16 KB page alignment is required on the 64-bit ABIs. for abi in arm64-v8a x86_64; do if "$READELF" -l "$OUT/$abi/libstockfish.so" | grep LOAD | grep -qv '0x4000$'; then echo "$abi: a LOAD segment is not 16 KB aligned" >&2 exit 1 fi done echo "== sha256" (cd "$OUT" && sha256sum */libstockfish.so)