cmake_minimum_required(VERSION 3.20)
project(androidrecomp C CXX)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

if(MSVC)
  add_compile_options(/W4)
  # windows.h defines min/max macros that collide with <algorithm>, and the
  # shim forwarders deliberately reimplement strcpy/strcat & friends.
  add_compile_definitions(NOMINMAX WIN32_LEAN_AND_MEAN _CRT_SECURE_NO_WARNINGS)
else()
  add_compile_options(-Wall -Wextra)
endif()

# The reusable half: loader, Bionic/Android shims, host window. A port links
# this and supplies only its own title-specific bridge.
add_library(androidrecomp STATIC
  runtime/elf_image.cpp
  runtime/shim.cpp
  runtime/shim_pthread.cpp
  runtime/shim_math.cpp
  runtime/shim_posix.cpp
  runtime/shim_gl.cpp
  runtime/shim_asset.cpp
  runtime/shim_file.cpp
  runtime/shim_sys.cpp
  runtime/shim_zlib.cpp
  runtime/shim_varargs.cpp
  runtime/window.cpp
  runtime/jni_env.cpp
  runtime/arm64_runtime.c
)
target_include_directories(androidrecomp PUBLIC runtime)
set(ARC_RUST_MATH_LIB "" CACHE FILEPATH "Rust object file with ARM64 helpers")
if(ARC_RUST_MATH_LIB)
  if(NOT EXISTS "${ARC_RUST_MATH_LIB}")
    message(FATAL_ERROR "Rust ARM64 helper object does not exist: ${ARC_RUST_MATH_LIB}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_MATH)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_MATH_LIB}")
endif()
set(ARC_RUST_ZLIB_OBJ "" CACHE FILEPATH "Rust object file with the Android zlib bridge")
if(ARC_RUST_ZLIB_OBJ)
  if(NOT EXISTS "${ARC_RUST_ZLIB_OBJ}")
    message(FATAL_ERROR "Rust zlib bridge object does not exist: ${ARC_RUST_ZLIB_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_ZLIB)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_ZLIB_OBJ}")
endif()
set(ARC_RUST_SHIM_MATH_OBJ "" CACHE FILEPATH "Rust object file with Android math call bridging")
if(ARC_RUST_SHIM_MATH_OBJ)
  if(NOT EXISTS "${ARC_RUST_SHIM_MATH_OBJ}")
    message(FATAL_ERROR "Rust math bridge object does not exist: ${ARC_RUST_SHIM_MATH_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_SHIM_MATH)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_SHIM_MATH_OBJ}" m)
endif()
set(ARC_RUST_ASSET_OBJ "" CACHE FILEPATH "Rust object file with the Android asset manager bridge")
if(ARC_RUST_ASSET_OBJ)
  if(NOT EXISTS "${ARC_RUST_ASSET_OBJ}")
    message(FATAL_ERROR "Rust asset bridge object does not exist: ${ARC_RUST_ASSET_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_ASSET)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_ASSET_OBJ}")
endif()

set(ARC_RUST_ELF_OBJ "" CACHE FILEPATH "Rust object file with the AArch64 ELF image loader")
if(ARC_RUST_ELF_OBJ)
  if(NOT EXISTS "${ARC_RUST_ELF_OBJ}")
    message(FATAL_ERROR "Rust ELF loader object does not exist: ${ARC_RUST_ELF_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_ELF)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_ELF_OBJ}")
endif()

# The va_list formatter and the variadic entry points. Build the object with
# `--cfg arc_ffi` when libffi was found, so guest sscanf keeps its bridge.
set(ARC_RUST_VARARGS_OBJ "" CACHE FILEPATH "Rust object file with the guest va_list formatter")
if(ARC_RUST_VARARGS_OBJ)
  if(NOT EXISTS "${ARC_RUST_VARARGS_OBJ}")
    message(FATAL_ERROR "Rust varargs object does not exist: ${ARC_RUST_VARARGS_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_VARARGS)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_VARARGS_OBJ}")
endif()

# The desktop window, its GL context and the SDL event translation. Only
# meaningful when SDL2 was found, but the object is harmless without it: the
# C++ side then keeps its "built without SDL2" stubs.
set(ARC_RUST_WINDOW_OBJ "" CACHE FILEPATH "Rust object file with the SDL window and input translation")
if(ARC_RUST_WINDOW_OBJ)
  if(NOT EXISTS "${ARC_RUST_WINDOW_OBJ}")
    message(FATAL_ERROR "Rust window object does not exist: ${ARC_RUST_WINDOW_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_WINDOW)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_WINDOW_OBJ}")
endif()

# The bionic file/descriptor layer behind every guest libc call. It keeps the
# guest's 128-byte struct stat and 280-byte struct dirent layouts, so it must
# stay the only implementation of those translations.
set(ARC_RUST_FILE_OBJ "" CACHE FILEPATH "Rust object file with the bionic file and descriptor shims")
if(ARC_RUST_FILE_OBJ)
  if(NOT EXISTS "${ARC_RUST_FILE_OBJ}")
    message(FATAL_ERROR "Rust file shim object does not exist: ${ARC_RUST_FILE_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_FILE)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_FILE_OBJ}")
endif()

set(ARC_RUST_SHIM_OBJ "" CACHE FILEPATH "Rust object file with the Android C library shims")
if(ARC_RUST_SHIM_OBJ)
  if(NOT EXISTS "${ARC_RUST_SHIM_OBJ}")
    message(FATAL_ERROR "Rust core shim object does not exist: ${ARC_RUST_SHIM_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_SHIM)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_SHIM_OBJ}")
endif()

set(ARC_RUST_RUNTIME_OBJ "" CACHE FILEPATH "Rust object file with the ARM64 runtime core")
if(ARC_RUST_RUNTIME_OBJ)
  if(NOT EXISTS "${ARC_RUST_RUNTIME_OBJ}")
    message(FATAL_ERROR "Rust runtime object does not exist: ${ARC_RUST_RUNTIME_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_RUNTIME)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_RUNTIME_OBJ}")
endif()

set(ARC_RUST_GL_OBJ "" CACHE FILEPATH "Rust object file with the GL layer")
if(ARC_RUST_GL_OBJ)
  if(NOT EXISTS "${ARC_RUST_GL_OBJ}")
    message(FATAL_ERROR "Rust GL object does not exist: ${ARC_RUST_GL_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_GL)
  target_link_libraries(androidrecomp PUBLIC "${ARC_RUST_GL_OBJ}")
endif()

set(ARC_RUST_POSIX_OBJ "" CACHE FILEPATH "Rust object file with the POSIX/BSD/locale layer")
if(ARC_RUST_POSIX_OBJ)
  if(NOT EXISTS "${ARC_RUST_POSIX_OBJ}")
    message(FATAL_ERROR "Rust POSIX object does not exist: ${ARC_RUST_POSIX_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_POSIX)
  # The variadic definitions the Rust unit cannot express live in their own
  # archive, and the two reference each other in both directions: the Rust
  # object takes the adapter's address, the adapter calls back into Rust for
  # the `__sF` translation. One left-to-right scan of a static archive cannot
  # settle that, whatever the order, so the pair is rescanned as a group.
  add_library(arc_posix_adapter STATIC runtime/shim_posix_varargs.cpp)
  target_compile_definitions(arc_posix_adapter PRIVATE ARC_RUST_POSIX)
  target_link_libraries(androidrecomp PUBLIC
    "$<LINK_GROUP:RESCAN,arc_posix_adapter,${ARC_RUST_POSIX_OBJ}>")
endif()

set(ARC_RUST_SYS_OBJ "" CACHE FILEPATH "Rust object file with the socket/dlfcn/system layer")
if(ARC_RUST_SYS_OBJ)
  if(NOT EXISTS "${ARC_RUST_SYS_OBJ}")
    message(FATAL_ERROR "Rust SYS object does not exist: ${ARC_RUST_SYS_OBJ}")
  endif()
  # The port reaches the loader through the C ABI elf_image.rs exports, so it
  # cannot be linked against the C++ loader's private methods. Saying so here
  # beats a wall of undefined `arc_elf_*` at link time.
  if(NOT ARC_RUST_ELF_OBJ)
    message(FATAL_ERROR "ARC_RUST_SYS_OBJ needs ARC_RUST_ELF_OBJ: shim_sys.rs calls the Rust loader")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_SYS)
  # Archived rather than appended to the link line, and that is load-bearing.
  # `dlsym` in shim_sys.rs calls `arc::ShimResolve`, which lives in
  # shim.cpp.o inside this very archive; an object placed after an archive can
  # never reach back into it, so the executable failed to link with
  # "_ZN3arc10ShimResolveEPKc undefined". Inside one archive the symbol index
  # settles the order.
  set_source_files_properties("${ARC_RUST_SYS_OBJ}"
    PROPERTIES EXTERNAL_OBJECT TRUE GENERATED TRUE)
  target_sources(androidrecomp PRIVATE
    runtime/shim_sys_varargs.cpp "${ARC_RUST_SYS_OBJ}")
endif()

set(ARC_RUST_PTHREAD_OBJ "" CACHE FILEPATH "Rust object file with the pthread/semaphore layer")
if(ARC_RUST_PTHREAD_OBJ)
  if(NOT EXISTS "${ARC_RUST_PTHREAD_OBJ}")
    message(FATAL_ERROR "Rust pthread object does not exist: ${ARC_RUST_PTHREAD_OBJ}")
  endif()
  target_compile_definitions(androidrecomp PRIVATE ARC_RUST_PTHREAD)
  # Archived rather than appended to the link line, for the reason above: the
  # port starts guest threads through `arc_dispatch` and `arc_call_guest` in
  # the runtime core inside this very archive, and an object placed after an
  # archive can never reach back into it. There is no adapter TU this time --
  # the unit has no variadic definitions -- so the object goes in alone.
  set_source_files_properties("${ARC_RUST_PTHREAD_OBJ}"
    PROPERTIES EXTERNAL_OBJECT TRUE GENERATED TRUE)
  target_sources(androidrecomp PRIVATE "${ARC_RUST_PTHREAD_OBJ}")
endif()

if(UNIX AND NOT APPLE)
  target_link_libraries(androidrecomp PUBLIC dl)
endif()
# A cross build must not resolve libffi through the build host's pkg-config: it
# would hand over the host's headers and the guest's varargs bridge would be
# compiled against the wrong ABI.
if(NOT CMAKE_CROSSCOMPILING)
  find_package(PkgConfig QUIET)
  if(PkgConfig_FOUND)
    pkg_check_modules(ARC_FFI QUIET IMPORTED_TARGET libffi)
    if(ARC_FFI_FOUND)
      target_link_libraries(androidrecomp PRIVATE PkgConfig::ARC_FFI)
      target_compile_definitions(androidrecomp PRIVATE ARC_HAVE_FFI)
    endif()
  endif()
endif()

if(WIN32)
  # SDL loads GL through GetProcAddress at run time, so opengl32 is not on the
  # link line by itself; the host's eglMakeCurrent needs the real wgl entry
  # points to bind the guest's rendering thread.
  target_link_libraries(androidrecomp PUBLIC ws2_32 dbghelp opengl32)
endif()

# zlib satisfies a dozen imports directly -- Bionic ships stock zlib, so every
# signature matches. On Windows point CMake at vcpkg:
#   -DCMAKE_TOOLCHAIN_FILE=C:/vcpkg/scripts/buildsystems/vcpkg.cmake
find_package(ZLIB QUIET)
if(ARC_RUST_ZLIB_OBJ AND NOT ZLIB_FOUND)
  message(FATAL_ERROR "Rust zlib bridge requires the zlib development package")
endif()
if(ZLIB_FOUND)
  target_link_libraries(androidrecomp PUBLIC ZLIB::ZLIB)
  target_compile_definitions(androidrecomp PUBLIC ARC_HAVE_ZLIB)
  message(STATUS "androidrecomp: zlib found")
else()
  message(STATUS "androidrecomp: no zlib -- those imports stay on the work list")
endif()

# SDL2 supplies the window, the GL context and the event loop. Without it the
# library still loads and reports, it just cannot open a window -- and GL
# imports stay outstanding, since they bind through the live GL driver.
find_package(SDL2 CONFIG QUIET)
if(SDL2_FOUND)
  # SDL2main's whole job is to call into libSDL2, so it must come first on the
  # link line or its references stay unresolved.
  target_link_libraries(androidrecomp PUBLIC
    $<TARGET_NAME_IF_EXISTS:SDL2::SDL2main>
    $<TARGET_NAME_IF_EXISTS:SDL2::SDL2>)
  target_compile_definitions(androidrecomp PUBLIC ARC_HAVE_SDL2)
  message(STATUS "androidrecomp: SDL2 found -- window enabled")
else()
  message(STATUS "androidrecomp: no SDL2 -- headless, no window")
endif()

# Standalone triage tool. Ports usually build their own host instead, linking
# the library above and passing their own contract.
if(PROJECT_IS_TOP_LEVEL OR NOT DEFINED PROJECT_IS_TOP_LEVEL)
  add_executable(arc_host tools/arc_host.cpp)
  target_link_libraries(arc_host PRIVATE androidrecomp)
endif()

# The lifted program, when one has been generated. Building it here rather than
# from the verification driver means the dependency discovery above -- zlib,
# SDL2, the platform libraries -- is done once and reused, instead of being
# guessed at a second time.
#
#   python tools/lifter.py libengine.so --out generated
#   cmake -S . -B build-lifted -DARC_LIFTED_DIR=generated
#   cmake --build build-lifted
set(ARC_LIFTED_DIR "" CACHE PATH "directory of generated lifted C")
set(ARC_BOOT_PROFILE "debug" CACHE STRING "arc_boot profile: debug, baseline, sse42, avx or avx2")
set_property(CACHE ARC_BOOT_PROFILE PROPERTY STRINGS debug baseline sse42 avx avx2)
if(NOT ARC_BOOT_PROFILE MATCHES "^(debug|baseline|sse42|avx|avx2)$")
  message(FATAL_ERROR "Unknown ARC_BOOT_PROFILE: ${ARC_BOOT_PROFILE}")
endif()
if(ARC_BOOT_PROFILE MATCHES "^(avx|sse42)" AND NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
  message(FATAL_ERROR "ARC_BOOT_PROFILE=${ARC_BOOT_PROFILE} requires x86-64")
endif()
# One store per guest function call, in exchange for knowing which functions
# ran when something faults. Worth it while a port is being brought up.
option(ARC_FRAMES "record which lifted functions were entered" ON)
if(ARC_FRAMES)
  add_compile_definitions(ARC_FRAMES)
endif()
if(ARC_LIFTED_DIR)
  file(TO_CMAKE_PATH "${ARC_LIFTED_DIR}" ARC_LIFTED_DIR)
  file(GLOB ARC_LIFTED_SOURCES "${ARC_LIFTED_DIR}/*.c")
  list(LENGTH ARC_LIFTED_SOURCES ARC_LIFTED_COUNT)
  if(ARC_LIFTED_COUNT EQUAL 0)
    message(FATAL_ERROR "no generated C in ${ARC_LIFTED_DIR}")
  endif()
  message(STATUS "androidrecomp: lifted program, ${ARC_LIFTED_COUNT} units")
  # The lifter emits arc_dispatch; the runtime's fallback must stand down.
  target_compile_definitions(androidrecomp PUBLIC ARC_LIFTED)
  add_library(lifted SHARED ${ARC_LIFTED_SOURCES}
                            tools/lift_harness.cpp)
  target_include_directories(lifted PRIVATE runtime "${ARC_LIFTED_DIR}")
  target_link_libraries(lifted PRIVATE androidrecomp)
  set_target_properties(lifted PROPERTIES C_STANDARD 11)
  if(MSVC)
    # Optimising 430 MB of generated C buys nothing while it is being checked
    # for correctness, and costs a great deal of build time.
    target_compile_options(lifted PRIVATE /Od /MP)
  else()
    target_compile_options(lifted PRIVATE -O0)
  endif()

  # The boot attempt: runs the lifted program's static constructors, then an
  # entry point. Links the lifted code directly rather than through the shared
  # library, so a fault lands in this process with a usable stack.
  add_executable(arc_boot tools/arc_boot.cpp ${ARC_LIFTED_SOURCES})
  target_include_directories(arc_boot PRIVATE runtime "${ARC_LIFTED_DIR}")
  target_link_libraries(arc_boot PRIVATE androidrecomp)
  if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND SDL2_FOUND AND ARC_FFI_FOUND)
    find_path(ARC_EGL_INCLUDE EGL/egl.h)
    find_path(ARC_GLES_INCLUDE GLES3/gl3.h HINTS "${ARC_EGL_INCLUDE}")
    find_library(ARC_EGL_LIBRARY NAMES EGL libEGL.so.1)
    if(ARC_EGL_INCLUDE AND ARC_GLES_INCLUDE AND ARC_EGL_LIBRARY)
      target_sources(arc_boot PRIVATE tools/lcs_host.cpp tools/lcs_menu.cpp)
      set_source_files_properties(tools/arc_boot.cpp PROPERTIES COMPILE_DEFINITIONS ARC_HAVE_LCS)
      target_include_directories(arc_boot PRIVATE "${ARC_EGL_INCLUDE}" "${ARC_GLES_INCLUDE}")
      target_link_libraries(arc_boot PRIVATE "${ARC_EGL_LIBRARY}")
    endif()
  endif()
  # Windows: no EGL library exists, but tools/egl_win32.h answers the guest's
  # EGL calls from the SDL/WGL context the window already owns, so the same host
  # and menu sources build unchanged. libffi is not required -- shim_varargs.rs
  # has a bridge-free path when ARC_FFI is absent.
  if(CMAKE_SYSTEM_NAME STREQUAL "Windows" AND SDL2_FOUND AND ARC_GLES_INCLUDE)
    target_sources(arc_boot PRIVATE tools/lcs_host.cpp tools/lcs_menu.cpp)
    set_source_files_properties(tools/arc_boot.cpp PROPERTIES COMPILE_DEFINITIONS ARC_HAVE_LCS)
    target_include_directories(arc_boot PRIVATE "${ARC_GLES_INCLUDE}")
    message(STATUS "arc_boot: LCS host enabled for Windows")
  endif()

  if(MSVC)
    target_compile_options(arc_boot PRIVATE /MP)
    if(ARC_BOOT_PROFILE STREQUAL "debug")
      target_compile_options(arc_boot PRIVATE /Od)
    else()
      target_compile_options(arc_boot PRIVATE /O2 /fp:strict)
    endif()
    if(ARC_BOOT_PROFILE STREQUAL "avx2")
      target_compile_options(arc_boot PRIVATE /arch:AVX2)
    elseif(ARC_BOOT_PROFILE STREQUAL "avx")
      target_compile_options(arc_boot PRIVATE /arch:AVX)
    endif()
    # A map file, because a Release build has no PDB and the lifted functions
    # are not exported: without it a fault in this executable can only be
    # reported as an offset. /MAP costs a relink, not a rebuild.
    target_link_options(arc_boot PRIVATE /MAP)
  else()
    if(ARC_BOOT_PROFILE STREQUAL "debug")
      target_compile_options(arc_boot PRIVATE -O0)
    else()
      # Guest memory and vector lanes can alias. Keep guest FP rounding points.
      target_compile_options(arc_boot PRIVATE -O2 -fno-strict-aliasing -ffp-contract=off)
    endif()
    if(ARC_BOOT_PROFILE STREQUAL "avx2")
      target_compile_options(arc_boot PRIVATE -mavx2)
    elseif(ARC_BOOT_PROFILE STREQUAL "avx")
      target_compile_options(arc_boot PRIVATE -mavx)
    elseif(ARC_BOOT_PROFILE STREQUAL "sse42")
      target_compile_options(arc_boot PRIVATE -msse4.2)
    endif()
    # A portable MinGW toolchain ships libwinpthread-1.dll but often no
    # libgcc_s_seh-1.dll or libstdc++-6.dll, so a dynamic link produces an exe
    # nothing can start. Everything here has a static archive -- fold it in.
    if(MINGW)
      target_link_options(arc_boot PRIVATE -static -static-libgcc -static-libstdc++)
    endif()
  endif()
endif()
