Skip to content

iOS Backend Architecture

How Kanama runs Kotlin game scripts on iOS: generated Godot API wrappers over a C-shim generic ptrcall, the same wrapper generator as desktop/Android. For the hand-written/stub registry see ios-backend-handwritten.md.

This page describes the shipped architecture. The support tier and the device evidence behind it live in Platform Evidence → iOS; the user-facing export workflow is Export for iOS.

Runtime Shape

Kanama's iOS backend runs full Kanama project scripts through a C GDExtension shim plus a Kotlin/Native static .xcframework — no JVM, GraalVM, or TeaVM on device, and the same generated Godot API wrappers as desktop/Android.

Godot's iOS export loads the C shim, which bridges to the Kotlin/Native runtime; the generated wrappers call Godot through ObjectCalls over a generic ptrcall dispatch in the shim. Each instance-taking entry point that an ObjectCalls helper can reach with the static marker comes in two flavours — the guarded instance entry and a _static sibling for Godot's static methods, which ptrcall with a null object — and the iOS ObjectCalls picks between them per call. Entry points no helper reaches that way (kanama_ios_godot_ptrcall_string_arg and the object-handle entries, whose zero check guards a live engine handle rather than a static marker) keep their single guarded form; scripts/check_ios_static_dispatch.py derives that split from the shim and fails if it stops holding. The component diagram, the dispatch contract, and the generator rules are below; see Architecture: iOS for how this maps onto the desktop/Android runtime model.

Toolchain

Tool Version / Setting
Xcode 26.5 or newer enough to provide the installed iOS SDK (27.0 validated for the runtime build; it refuses any deployment target below 15.0)
iOS runtime Kotlin/Native static library inside an .xcframework
Device architecture arm64
Minimum iOS version 15.0 — Godot 4.7.2's exporter default (application/min_ios_version); Xcode 27 rejects a lower pin

Install the Godot iOS export templates for the same Godot version that opens or exports the project. If xcode-select points at Command Line Tools, set DEVELOPER_DIR for Gradle and Xcode commands so Kotlin/Native and Xcode use the full Xcode app.

Building the Device Libraries

From the Kanama checkout, build the device .xcframework artifacts:

DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer \
./gradlew assembleIosDeviceKanamaXcframework \
  -PkanamaXcodeDeveloperDir=/Applications/Xcode.app/Contents/Developer

The task writes:

build/ios/xcframework-device/debug/kanama_ios.debug.xcframework
build/ios/xcframework-device/release/kanama_ios.release.xcframework

installIosAddon also defaults to device-only xcframeworks. Pass -PkanamaIosXcframeworkMode=full only when intentionally building the optional device plus simulator xcframeworks.

installIosAddon installs these iOS descriptor entries into the project's addons/kanama/kanama.gdextension, keeping the desktop entries and, when the project has them, the Android AAR entries:

[configuration]
entry_symbol = "kanama_entry"
compatibility_minimum = "4.8"

[libraries]
ios.debug.arm64 = "res://addons/kanama/bin/ios/kanama_ios.debug.xcframework"
ios.release.arm64 = "res://addons/kanama/bin/ios/kanama_ios.release.xcframework"

The Kit Path

A project made from the macOS kit or the store addon has no checkout to build from. Its build.gradle.kts applies the Kanama Gradle plugin (net.multigesture.kanama, gradle-plugin/), and its addons/kanama/maven carries, beside the plugin and the processor, the runtime's iosArm64 klib (kanama-iosarm64, with the kanama_ios cinterop klib) and kanama-ios-shim, a zip of ios/bootstrap/*.c, ios/include/ and gdextension/gdextension_interface.h. Both are published by publishKanamaIosPackage from the same packaging run as everything else in that repository, so they share its version. The plugin's buildIosScripts is installIosAddon without the checkout:

  1. It depends on the project's buildScripts, so the desktop kanama-scripts.jar the editor needs during the export is current.
  2. It finds Xcode (-PkanamaXcodeDeveloperDir, DEVELOPER_DIR, xcode-select -p, then /Applications/Xcode.app; never the Command Line Tools) and writes a plugin-owned Gradle build to build/kanama/ios/ (the resources under gradle-plugin/src/main/resources/.../ios/, rewritten on every run): one iosArm64 target with kotlin-src as its source root (plus one empty file of its own, so a project without scripts still links), KSP from the kit's processor with the checkout's options, the klib as an api dependency, and a static library that export()s it. Kotlin/Native keeps a dependency klib's @CName functions, the kanama_ios_runtime_* entries the shim calls, only in a binary that exports that klib. Its settings allow addons/kanama/maven alone to serve net.multigesture artifacts, and no mavenLocal().
  3. It runs that build with the project's gradlew (linkDebugStaticIosArm64 and linkReleaseStaticIosArm64), compiles the shim and the source-line lookup with xcrun clang for each, generates the debug source-line table (IosSourceLines), and combines and wraps each library into a device xcframework with libtool and xcodebuild -create-xcframework, as the checkout's combineIos*Lib and createIosDevice*Xcframework tasks do.
  4. Before it installs anything, it checks with nm that each library defines every kanama_ios_* symbol the compiled shim references, and the generated register function when the project has scripts. A library without the exported runtime, or a shim and klib of different Kanama versions, stops there with one line instead of at Xcode's link.
  5. It installs the two xcframeworks under addons/kanama/bin/ios/ and the iOS descriptor lines (KanamaIosAddonFiles, gradle-plugin/src/shared, which the root buildSrc compiles too, so installIosAddon writes the same lines), and turns on rendering/textures/vram_compression/import_etc2_astc in project.godot, which Godot's iOS export requires as its Android export does.

The seam that makes the separate compile possible: the generated registry is a @CName("kanama_ios_project_scripts_register") function (IosScriptCodeEmitter.registrySource), not an actual of a runtime expect, which cannot cross a module. The runtime calls it once, before its first script lookup, through the shim's kanama_ios_load_project_scripts. A build without scripts, such as the klib the kit carries, defines no register function, so the shim carries a weak default of it that only logs. The linker keeps the strong Kotlin definition because it sits in the same object as every kanama_ios_runtime_* entry the shim calls (buildIosScripts checks that); a weak_import reference instead would leave the symbol undefined at Xcode's link of a build without scripts. The runtime declarations that generated code names live in src/iosMain/.../ios/KanamaIosScriptSeam.kt, public behind the ERROR-level @InternalKanamaIosApi opt-in (the generated file opts in; the runtime's own iOS source sets opt in module-wide), and api-snapshots/ios-seam.txt records them. Publishing the klib from a build that compiles a project's scripts or the self-tests into it fails.

The inner build's daemon heap is 6 GB (BuildIosScripts.INNER_HEAP_GB, -PkanamaIosHeap for a larger project), passed as -Dorg.gradle.jvmargs on the inner gradlew command line so an org.gradle.jvmargs in the user's ~/.gradle/gradle.properties cannot shrink it. Once its links are up to date and the shim zip is unchanged, buildIosScripts reuses the xcframeworks it made, and copies them only when the installed ones came from other inputs. Measured on an M1 Max, the release link runs out of a 2 GB heap and links in 3 GB, and its process peaks at 9 to 11 GB with LLVM's native memory, which is why the user page asks for a 16 GB Mac. The checkout's own libraries measure roughly 172 MB debug / 113 MB release; a kit project's debug library is about 195 MB.

scripts/package_install_smoke.sh --ios runs the documented commands from an unzipped macOS kit or store addon with a fresh GRADLE_USER_HOME: then a headless Godot export of an Xcode project and xcodebuild -sdk iphoneos CODE_SIGNING_ALLOWED=NO, and it checks that the app defines the shim's entry, the runtime's and the register function. package.yml runs it on macOS.

Export-Time Script Binding

-PkanamaIosProjectScriptsDir registers the scripts for both targets: the iOS runtime gets its registrars, and the same sources are compiled into the desktop kanama-scripts.jar the export-time editor loads. The editor needs that jar to know the scripts' @Export names — Godot's export instantiates and re-packs every scene when it converts text resources to binary and keeps only the properties the script instance reports, so an unknown script would lose every scene-stored value without any error. Godot's iOS exporter ignores an export plugin's error, so on a command-line export (--export-debug iOS …) the Kanama Tools plugin ends the editor process before any file is written (verified on a macOS host); in the editor's Export dialog the error marks the export failed but leaves the files Godot wrote, and a one-click deploy has its temporary Xcode archive removed before the install step. -PkanamaProjectScriptsDir may still be passed explicitly (for example with a different desktop source set); it wins when both are given. Godot caches each converted scene in .godot/exported/, keyed by the source file's md5 and mtime, and reuses a stripped conversion until the .tscn itself changes, which is why the user page deletes that directory before exporting.

The demos' iOS runner and the starter smoke run scripts/check_exported_scene_properties.gd after every export.

iOS Type Checks

The KSP processor (the compiler plugin that generates Kanama's registration code) checks every export and registered method for iOS ahead of time, and fails the build instead of dropping a member on the device. An exported property whose value type has no iOS path (such as RID) fails like this:

e: [ksp] [kanama:ksp] [kanama-ios] Grid.cell (RID) — no iOS @Export
path for this value type, would keep its Kotlin default. On iOS the scene and inspector value of
this property would be dropped. ...

Every Godot value type (Vector2/2i, Vector3/3i, Vector4/4i, Rect2/2i, Plane, AABB, Quaternion, Basis, Transform2D/3D, Projection, Color), NodePath, the scalars, String, object references, List<String> and Map exports (Map<Int, String>, Map<Vector2i, Long>, Map<String, Texture2D>, keys kept as on desktop) reach iOS.

A registered function's parameters and return already use the types every platform supports (FunctionRegistration.SUPPORTED_FUNCTION_TYPES: no List, Map, ByteArray or Any?). The iOS check matters for engine virtuals and the iOS call path: a parameter type the iOS call path does not pass (a Map, a List, a Packed*Array), or an @OverrideVirtual whose return type iOS does not marshal, fails the same way:

e: [ksp] [kanama:ksp] [kanama-ios] Board.apply (godot: apply): argument table: Map<String, Any?>
has a type iOS does not pass to a script method. On iOS a call to this method from Godot would
not run. Use a supported parameter type (Long, Double, Boolean, String, ...), or accept the skip
with -PkanamaIosAllowSkips=true (KSP option kanamaIosAllowSkips).

The iOS call path passes the scalar types, String, NodePath, every value type, Color, RID, object wrappers, Godot enums and Any?. An Any? parameter that receives a Variant type iOS does not marshal (a Dictionary, an Array, a Packed*Array) fails that call with a script error naming the type, instead of seeing null. -PkanamaIosAllowSkips=true is the one opt-in for every iOS skip, exports and methods alike; each skipped member is then a warning.

FAULT Reasons

The word after the colon in a [kanama][ios][c] FAULT line is a fixed reason token. The user-facing advice is in Export for iOS → FAULT Lines in the Log; the sink that prints them is described under Contract: no silent paths.

Reason What went wrong
api-unresolved A Godot interface function was not found: the Godot version does not match, or the call came before the extension started.
bind-lookup-failed Godot has no method with that class, name and hash. Almost always a stale Kanama build after a Godot upgrade.
null-bind The call used a method that failed its lookup; an earlier bind-lookup-failed line names it.
null-instance An instance method was called on a null object.
null-handle An engine object, such as a node, a tween or a signal target, was null.
null-arg A required string argument, named in the line, was null.
pending-protocol A value was read before the call that produces it succeeded.
callable-build A bound Callable could not be built for the named method.
unknown-tag The call carried an argument type the iOS layer does not know.
encode-failed A container argument could not be converted for Godot.
short-payload A value inside a container was shorter than its type needs.
alloc-failed The call could not allocate memory for its arguments.
too-many-args A call or signal emission had more arguments than iOS carries.
progress-readback ResourceLoader.load_threaded_get_status returned no progress value.

Why iOS is different from desktop/Android

Kanama desktop uses the JVM + Panama (FFM) to call into Godot. iOS forbids JIT, so the JVM model does not apply. The iOS backend is Kotlin/Native (AOT-compiled) plus a C shim (ios/bootstrap/kanama_ios_shim.c) that implements the GDExtension entry points and bridges to the Kotlin/Native runtime via @CName exports.

What works today (verified on iPhone 12 + iPhone 15 Pro): script loading + lifecycle, @OnReady/@OnProcess/@OnPhysicsProcess/@OnInput, registered (public) functions, @OverrideVirtual for engine virtuals, @Export (including value types, object lists, user-script lists, and List<String>/PackedStringArray delivery), @Signal registration, named + lambda signal connections (custom Godot Callable), await, scene reload, and AudioStreamPlayer playback. Match3, 3D Platformer, Bunnymark, dodge, squash, Racing, character-controller, FPS, and third-person have all reached playable device runs; FPS still has an intermittent Audio autoload SIGSEGV follow-up.

Components

Godot (iOS, GDExtension)
        │
        ▼
ios/bootstrap/kanama_ios_shim.c  ── C shim ──────────────────────────────────┐
  • GDExtension entry, class/loader/language registration                    │
  • ScriptInstance lifecycle, property set, method/signal dispatch           │
  • Marshalling helpers: get_method_bind (cached), ptrcall_* helpers,        │
    Variant boxing, StringName helpers, custom-Callable trampoline           │
  • Guardrails: kanama_ios_check_call_error, kanama_ios_check_variant_arg     │
        │  @CName <-> extern bridge                                          │
        ▼                                                                    │
src/iosMain (Kotlin/Native)                                                  │
  • KanamaIosRuntime.kt — script registry, instance bridges, dispatch        │
  • IosCallableRegistry — lambda/bound signal callbacks                      │
  • binding/runtime/ObjectCalls.kt — the API call abstraction  <─────────────┘
  • api/*.kt — GENERATED Godot API wrappers (same generator as desktop/Android)
  • a bounded set of hand-written/sugar sites (see ios-backend-handwritten.md)
        ▲
        │  build.gradle.kts + KSP processor
Generated per-project script registry (methods/properties/signals of USER scripts)

Two distinct codegen concerns, do not confuse them: 1. Project-script registry (already generated): the user's @ScriptClass scripts' methods/properties/signals, emitted by the KSP processor + the root build.gradle.kts. 2. Godot API wrappers (also generated, see below): the Node3D/CharacterBody3D/… classes that user scripts call into.

Why generated wrappers (the hand-written stubs we left behind)

The first iOS slice hand-wrote the Godot API surface in one file, src/iosMain/.../api/IosGodotApi.kt (~1000 lines, ~30 classes), where most methods were no-op stubs that compiled and silently returned defaults. Adding one Godot method took ~6 manual edits across 3 files (extension_api.json hash lookup → C g_*_bind + binding function → kanama_ios.h decl → IosGodot wrapper → Kotlin API method). That did not scale, and it was the root of an entire bug class:

  • Silent no-op stubs: AudioStreamPlayer and CharacterBody3D were fully stubbed (moveAndSlide() → false, velocity a dead field) — they compiled and "ran" but did nothing. These are invisible until something downstream misbehaves.
  • Hand-marshalling bugs: the Match3 SIGSEGV (a raw Callable passed where a boxed Variant was required), a StringName over-dereference in script virtuals, and Variant type-tag mismatches all came from hand-written marshalling.

That approach could not reach the full API that real demos (3D platformer, FPS, racing, city-builder) need, so iOS adopted the desktop/Android generated-wrapper model described next.

Current architecture: generated wrappers + ObjectCalls

iOS reuses the desktop/Android solution. The Godot API wrappers are generated ("Generated from Godot docs") by scripts/generate_api_wrapper.py from extension_api.json, once, into the shared tree src/commonMain/kotlin/.../api/ — the module's KMP common fragment since task 117 P4′ — which iOS compiles as-is (task 103). Since task 30 iOS hosts the full desktop-equivalent class set: since task 129 D every class is generated once into the shared tree, FileAccess and DirAccess included, and PER_PLATFORM_WRAPPERS (with the IOS_UNSUPPORTED_CLASSES view of it) is empty. Methods whose ptrcall shape is not audited on iOS are desktop-only companions, listed in the generated iOS Shape Gap page. Each generated wrapper caches a MethodBind and calls a typed helper on a runtime abstraction ObjectCalls:

// generated CharacterBody3D.kt (desktop)
fun moveAndSlide(): Boolean = ObjectCalls.ptrcallNoArgsRetBool(moveAndSlideBind, handle)
fun setVelocity(velocity: Vector3) = ObjectCalls.ptrcallWithVector3Arg(setVelocityBind, segment, velocity)

ObjectCalls is the platform seam: desktop implements it with Panama/FFM; iOS implements it with the C shim (get_method_bind + the generic ptrcall dispatch). The generated wrappers depend only on ObjectCalls + types + GodotHandle, all of which iOS provides — GodotHandle is a per-platform @JvmInline value class over the backend's pointer type (iOS declares its own over the MemorySegment shim), so the same wrapper source runs on both backends. A wrapper BODY unwraps it once through the internal GodotObject.segment; the raw type never appears in a public signature.

The roots are shared too (task 117 P3′). GodotObject, RefCounted and GodotCallable are written once, by hand, in src/commonMain/kotlin/.../api/ — iOS no longer has its own copies (the old iOS GodotObject lived inside IosGodotApi.kt). Every member is the desktop ptrcall body over ObjectCalls, so iOS carries the full desktop GodotObject surface (setMeta/getMeta, setIndexed/getIndexed, callv, tr/trN, addUserSignal, isConnected, …). The four things a root cannot do through ObjectCalls go through the internal ObjectRuntime seam (src/commonMain/.../binding/runtime/ObjectRuntime.expect.kt); the iOS actual is src/iosMain/.../binding/runtime/ObjectRuntime.kt:

hook iOS actual
instanceIdOf IosGodot.objectGetInstanceId (kanama_ios_godot_object_get_instance_id)
emitSignal a single Int/Long/Vector2i argument takes the shim fast paths (kanama_ios_godot_object_emit_signal_int / _vector2i); everything else, including no-argument signals, goes through Object.call("emit_signal", …) on the Variant path
onPropertySet, onSetScript documented no-ops: desktop buffers a script property set on a Kanama-script owner before its Kotlin instance exists; iOS receives engine-driven sets directly through KanamaIosScriptBridge and does not buffer

The root Object helpers behind those members are generated into the iOS ObjectCalls GENERATED MEMBERS region where the renderer can emit the shape (collect_root_object_shapes in the generator); four are hand-written above the marker — connect delegates to IosGodot.objectConnect, the two bound-Callable shapes to the existing ObjectCalls.connectBound/disconnectBound, and add_user_signal (desktop's helper name) to the Variant path. GodotSignal/SignalConnection are the platform classes: expect classes in src/commonMain/.../api/GodotSignal.expect.kt whose iOS actuals (src/iosMain/.../api/GodotSignal.kt) dispatch through IosCallableRegistry + the shim's custom Callable; MainThread is an expect object whose iOS actual (src/iosMain/.../api/MainThread.kt) runs post/runOnMainThread inline and pumps its frame queues from KanamaIosRuntime.frame(). The compiler holds both to the desktop public surface (task 117 P4′).

Four rules of the bridge (three about ownership), each with its self-test rows:

  • A lambda's closure lives as long as any Callable of it (task 113). The shim creates a custom Callable per connect and per disconnect (the temp that Object.disconnect compares), and reports each creation (kanama_ios_runtime_callable_created) and each free_func (kanama_ios_runtime_callable_freed) to IosCallableLifetimes, which drops the IosCallableRegistry entry when the last one is freed. Releasing on the first free dropped the closure of a connection Godot still held (a refused second connect, a CONNECT_REFERENCE_COUNTED connect). SignalConnection.close() is a no-op once the entry is gone (a fired one-shot), so it never asks Godot to disconnect a connection it already dropped. The callable-lifetime row=1..7 rows cover every connect/disconnect/emit/free order.
  • The RefCounted elements of an Object.call container result are owned (task 122 item 3). kanama_ios_godot_object_call's own_elements (set by callWithVariantArgs and callWithVariantArgsOwned, not by the Variant getters routed through the same body) makes the blob encoder retain each RefCounted element while the return Variant still holds it, in its one encode pass. Whether an element is a RefCounted comes from its ObjectID (bit 63, variant_get_object_instance_id), never from the stored pointer, which is stale for a freed Node. Its record gains a ninth payload byte (1 = owned) and ContainerBlob.record() mints RefCounted.owned(...). The blob lists what it retained until Kotlin has the bytes: an OOM blob and a parked blob dropped undrained release them. No other container path sets the flag (the generated *RetArray wrappers and the measure-then-fill path stay borrowed). Desktop does the same in BuiltinTypes.readVariantScalar(..., ownElements = true). callv takes this path too (callWithVariantArgs with Godot's Object.callv bind). Rows (frame 1, RegEx.search_all): call-container-elements, callv-container-elements, and call-container-elements-parked (100 matches: the blob outgrows the 1024-byte inline buffer and takes the park -> take path with its retained list).
  • Inbound arguments decode like returns (task 122 item 4). kanama_ios_marshal_variant_args (a signal lambda's trampoline and a script method call) puts scalars, strings and value types in their cells and a container (Array, Dictionary, Packed*Array) in one blob record tagged PT_VARIANT_RECORD, which decodeIosCallArg reads with the container-return reader (ObjectCalls.decodeVariantRecord); its Object elements stay borrowed (the caller's Variant holds them for the call). A type with no cell (Callable, Signal) arrives tagged KANAMA_IOS_ARG_UNMARSHALLED_BASE + type and the decode throws naming it, never a silent null; a container whose blob cannot be allocated arrives tagged KANAMA_IOS_ARG_ENCODE_OOM_BASE + type and the decode reports the out-of-memory. The shared blob encoder (it also encodes container returns) has a case for every Godot 4.7 Variant type: RID as its id, the value types Vector3i ... Projection as their raw bytes (the scalar-return layout, decoded by decodeIosRawVariant), and Nil, Callable and Signal as an empty record that decodes to null, which is what desktop's variantToScalar answers for them. A Variant type a later engine adds reports a FAULT ... unknown-tag variant-type=<n> instead of encoding silently. The one remaining limit: a container nested more than KANAMA_IOS_BLOB_MAX_DEPTH (8) levels arrives as null. Rows: lambda-args(...) (scene init: String, Vector3, Color, Array, Dictionary, Vector3i).
  • Every Variant type round-trips the generic path like desktop, with one difference. A Callable or Signal reads back as null on both backends, but as an inbound signal or script-method argument iOS refuses it with an error naming the type (above), where desktop's variantToScalar passes null. A container element or script container return value with no Variant shape throws naming its type, as desktop's initVariantFromAny does; an element with fewer bytes than its type needs reports FAULT ... short-payload. The scalar return decode (kanama_ios_decode_variant_scalar) answers a RID (Object.get of a RID property) and a NodePath as a NodePath; the outbound encoders take a ByteArray (PT_PACKED_BYTE_ARRAY, boxed by kanama_ios_pt_arg_to_variant) and the value types inside a List/Map argument (IosReturnContainerScratch.taggedValue -> kanama_ios_pt_blob_value_to_variant). Rows: the API exercise's T rows (<Type> ret|elem|arg|in, one per Godot Variant type per path, each against a value the engine built or compared through an Expression; the same rows run on desktop, see "The exercise rows" in wrapper-maintenance.md), and its A rows CharFXTransform.font, NavigationPathQueryParameters2D.excluded_regions and GLTFSkin.inverse_binds for Object.get.
  • Map @Export properties cross as an any-key Dictionary. A set (kanama_ios_script_instance_set_property_of_type's Dictionary case) encodes the Dictionary with kanama_ios_blob_encode_dictionary_any ([count]([key record][value record])*), kanama_ios_runtime_script_instance_set_property_dictionary decodes it with ObjectCalls.decodeDictionaryAnyBlob, and the generated setPropertyDictionary converts keys and values with the desktop registrar's own transforms (mapKeyReadTransformSafe, mapValueReadTransformSafe), dropping what does not fit. A read returns KanamaIosTypedDictionary, shipped as KANAMA_IOS_PT_DICTIONARY_ANY (keys tagged like values) and rebuilt by kanama_ios_build_dictionary_any_from_blob. Map<String, Any?> keeps the generic String-keyed read. Object values are wrapped like desktop wraps them (fromHandle for a resource wrapper, the constructor for another, iosScriptInstanceForOwner for a script), and a Map of Resource values (dictionaryRetainedValues, the converted Map's values) records one reference per value in ScriptPropertyRetains after the set, as desktop's readVariantDictionaryObjectValuesRetained does. One difference: a script value whose owner has no live Kotlin instance is dropped on iOS (as in a List<UserScript>), where desktop builds a new script instance over the handle. Rows: map-export(...) (built-in probe DictionaryProbe.kt, whose bridge IosMapExportEmitTest holds to the emitter's output).
  • A script property's default is its initializer (task 138 item 8). The iOS registry carries KanamaIosScriptProperty.defaultValue, emitted by KSP from the literal desktop's registrar declares as default<Name> and converted like getProperty; Script._has/_get_property_default_value answer it through kanama_ios_runtime_script_resource_property_default. Host test: IosScriptPropertyParityTest.scalarDefaultsReachTheIosRegistry.
extension_api.json
   │  generate_api_wrapper.py (+ iOS emission target)
   ▼
Generated wrappers (Node3D, CharacterBody3D, …)
   │  ObjectCalls.ptrcall*/call*  (cached MethodBind + typed ptrcall)
   ▼
ObjectCalls  ──┬── desktop actual → Panama/FFM
               └── iOS actual → C shim (get_method_bind + ptrcall/method_bind_call)

The proven runtime stayed; the hand-written API was replaced with generated wrappers.

What is generated vs hand-written

  • iOS reuses the desktop generator's extension_api.json model, its CallShape signature taxonomy (the finite (argtypes→return) → helper-name map), its conservative skip logic (--skip-report), and its fixture-based check harness (scripts/check_wrapper_generator.py). See docs/contributing/wrapper-maintenance.md.
  • The iOS emission target decides the shared tree's method set, renders the iOS-only generated wrappers (src/iosMain/.../api) and the matching ObjectCalls helper bodies (generated from the CallShape set) inside the GENERATED MEMBERS region of the iOS actual object ObjectCalls; the generator also writes the common expect object ObjectCalls (every helper the tree calls), so the compiler proves iOS implements each one.
  • The hand-written layer is now only genuinely bespoke runtime pieces: the internal KanamaScope behind KanamaScript.scriptScope (the KanamaScript base itself is common code since task 133), Input/InputMap glue, the signal/Callable registry, lifecycle. Everything else is generated.

Contract: generic ptrcall dispatch (iOS ObjectCalls)

Informed by a survey of the desktop ObjectCalls.* helper shapes (regenerable with grep -rhoE "ObjectCalls\.[A-Za-z0-9_]+" src/commonMain/kotlin/net/multigesture/kanama/api/ | sort -u): the generated wrappers reference ~1500 distinct ObjectCalls.* helper shapes (1467 at the task-30 survey; 121 for the platformer's classes alone), of which only ~7% map to an existing iOS C primitive. Hand-writing a C function per shape is untenable, so:

  • One generic typed ptrcall dispatch in the C shim drives all ptrcall shapes: kanama_ios_godot_ptrcall(bind, instance, argTypes[], argValues[], argCount, retType, retOut). A small type tag enum selects each arg's cell layout (bool/int32/int64/uint32/ float/double/Object/Vector2/Vector2i/Vector3/Vector4/Color/Rect2/Transform2D/ Transform3D/Basis/Quaternion/AABB/Projection/RID/StringName/NodePath/String/ typed-list…) and the return read-back. New shapes need no new C function — only a Kotlin ObjectCalls helper body that packs the right arg/return tags.
  • ObjectCalls (iOS) exposes the typed helpers the generated wrappers call (ptrcallNoArgsRetBool, ptrcallWithVector3Arg, …); each is a thin wrapper over the generic dispatch and caches its MethodBind (via the existing kanama_ios_godot_get_method_bind, resolved once per wrapper method). These helper bodies are themselves generated from the survey's CallShape set so the surface stays in sync with the generator.
  • Marshalling lives in one place (the generic dispatch), guarded by kanama_ios_check_call_error / kanama_ios_check_variant_arg. This is the error-prone code; concentrating it there (vs scattered per-method functions) is how we avoid repeating the SIGSEGV / over-deref / boxing bug class.
  • Varargs / shapes ptrcall can't express fall back to the Variant object_method_bind_call path (already used by connect/emit/tween).
  • Sharing strategy: one shared source directory (src/commonMain/kotlin) compiled by each platform module, no module restructure (task 103); the KMP expect/actual ObjectCalls form remains the long-term target.

Generator approach

The desktop generator (scripts/generate_api_wrapper.py) renders each wrapper method as ObjectCalls.<shape.function>(bind, receiver, args) (see render_method) — this wrapper code is platform-agnostic. So the iOS target does NOT need different wrapper output:

  • Reuse the generated wrapper classes unchanged (they are the shared src/commonMain files since task 103). They depend only on ObjectCalls + types + GodotHandle, all present on iOS.
  • Generate the iOS ObjectCalls helper bodies for the set of shape.function names the wrappers use. As the generator picks each method's CallShape it knows the structured arg types + return type; collect a registry shape.function -> (arg godot-types, return godot-type) (deduped by name) and emit an iOS helper that marshals via the generic kanama_ios_godot_ptrcall. The hand-written iOS helpers in ObjectCalls.kt are the reference template + the override set.
  • Type → PT-tag mapping (the risky core) — apply exactly: scalar float/double → PT_FLOAT64 (8 bytes); int per meta (int32/int64); Vector/Color components → float32 (single-precision); Object → PT_OBJECT; StringName/String/NodePath → CONSTRUCT tags (built C-side from a C string); bool → PT_BOOL. Shapes ptrcall can't express (varargs) → the Variant callWithVariantArgs path.
  • Validation: generate one real class (e.g. CharacterBody3D), compile via installIosAddon, and round-trip its key methods on device (extend the ObjectCalls self-test) before generating the rest.

The type → PT-tag mapping is the single point where a marshalling mistake would propagate across the whole API, so it is guarded by the on-device ptrcall matrix and the ObjectCalls Kotlin probe (see Rules below).

Performance

This is the fast path, not generic reflection: a MethodBind is resolved once per method (cached in the wrapper, like desktop's *Bind fields) and calls go through typed ptrcall — the same mechanism as desktop and as the current hand-written iOS binding functions. Per-call cost is the C↔Kotlin/Native FFI crossing plus argument marshalling. Guidance (confirm by profiling per-frame _physics_process on the 3D platformer):

  • Cache MethodBind per generated method; never re-resolve per call.
  • Avoid per-call StringName allocation (intern/cache method + arg names).
  • Prefer ptrcall over the Variant call path; reserve call for varargs/signals.
  • Minimize boundary crossings in hot loops.

Contract: no silent paths (the fault sink)

ios/bootstrap/kanama_ios_shim.c is the entire iOS surface, and its default failure mode used to be silence. 132 exported entry points open with a stack of guards — the engine API did not resolve, the MethodBind is zero, the instance is zero, a C string is NULL, nothing is pending — and every one of them returned 0 / -1 / nothing without a word. That is how every Godot static method reached through the shared wrapper tree stayed a no-op on iOS for six days behind 205 green self-test checks and two green demo smokes (task 117 P2', 119 item 35), and how a self-test row passed for the wrong reason because a guard returned quietly (item 37).

Since task 124 the shim has one sink, near the top of the file:

static void kanama_ios_fault(const char *entry, const char *reason, const char *detail);
int32_t kanama_ios_fault_count(void);      /* never reset */
const char *kanama_ios_last_fault(void);   /* "<entry> <reason> <detail>", "" when none */
void kanama_ios_fault_set_probe(int32_t on); /* self-test only: tag lines FAULT-PROBE */

It increments a process-wide counter, stores "<entry> <reason> <detail>", and prints [kanama][ios][c] FAULT <entry>: <reason> <detail> to stderr for the first 64 faults (a tight loop must not flood the console; the count keeps counting past 64). There is deliberately no reset function: a fault in frame 1 is still in the count at the end of the run, which is what makes the self-test's end-of-run number an assertion rather than a snapshot.

The rule: every guarded early return reports. In an exported kanama_ios_* entry point or a static ..._dispatch body, an if (...) whose body returns must call kanama_ios_fault(...) first — on the same path and textually before the return, because a call after the return is dead code and a call nested inside a deeper block may never run. Return values and signatures never change — the bridge keeps behaving exactly as it did, it simply stops doing it quietly. scripts/check_ios_shim_faults.py (a local_ci.sh stage) re-derives the guard list from the source and fails on the first one that does not report, so the rule holds for the next guard somebody adds rather than for the ones instrumented that day.

Scope, precisely. The contract covers the shim's exported entry points, the _dispatch bodies behind them, and the static helpers those exported entries call directly — everything a Kotlin call passes through on its way to Godot. switch default: return ... arms in other static helpers (kanama_ios_packed_kind, kanama_ios_get_virtual_call_data, kanama_ios_construct_extension_object, kanama_ios_extension_create_instance) are outside it: each is a pure classifier or constructor whose "unknown" answer is checked by its caller, and that caller is in scope and reports (unknown-tag, api-unresolved, …) with the detail the helper could not name. They are not silent paths; they are the inside of a path whose exit reports.

The reason token is one of fourteen fixed spellings — api-unresolved, null-bind, bind-lookup-failed, null-instance, null-handle, null-arg, pending-protocol, callable-build, unknown-tag, encode-failed, short-payload, alloc-failed, too-many-args, progress-readback — and the detail names the specific thing: the missing interface pointer, the parameter, Class.method hash=<hash>, the tag number. They are documented for users in docs/exporting/ios.md.

Three guards deliberately do not report, each documented in its own function comment and listed in the gate's BENIGN table (which can only shrink — a stale entry fails the gate):

  • kanama_ios_godot_is_instance_id_valid(0) — a zero instance id is a legitimate question whose honest answer is "invalid", not a caller bug.
  • the target == NULL path in kanama_ios_godot_ptrcall_ret_callable_dispatch — an empty (object-less) Callable is a legitimate value; desktop's readCallable returns null too.
  • the label == NULL path in kanama_ios_godot_set_first_node_in_group_text — a lookup that legitimately finds nothing: NULL is the answer "no node is in the group", and the caller (KanamaIosRuntime.frame()) treats 0 as "not present". Only the iOS example project carries a kanama_ios_probe label. Task 124 first ruled this null-arg, and the first device run (Match3) printed it on every frame; the function's other guards (API, SceneTree, the two binds) still report. The caller also stops polling after 120 frames (probe label group absent after 120 frames; not retrying) — before that it ran a get_first_node_in_group ptrcall on every frame of every game without the label.

The gate prints the totals on PASS: 132 exported entry points and 24 _dispatch bodies; 219 guarded early returns across 83 functions, 216 reporting, 3 documented benign.

Bind lookups report at lookup time. kanama_ios_godot_get_method_bind and kanama_ios_godot_get_builtin_method call the sink with bind-lookup-failed and the detail Class.method hash=<hash> whenever the engine returns NULL — not only when the API itself did not resolve. The names and the hash exist there and nowhere else: by the time the zero bind reaches a ptrcall entry point all that is left to say is null-bind. Desktop mirrors the line ([kanama:kt] FAULT bind-lookup-failed Class.method hash=<hash> on System.err) but carries no counter — there is no shim on desktop, and a null bind crashes at the call, which is loud enough.

The self-test's seven expected probes. The level-2 (INITIALIZATION_LEVEL_SCENE) self-test in src/iosMain/kotlin/net/multigesture/kanama/binding/runtime/ObjectCalls.kt ends by calling runFaultProbes, which makes seven deliberate wrong calls and asserts that each one is reported:

# Probe Reason Asserted
1 getMethodBind("Node3D", "set_visible", 1L) — a wrong hash bind-lookup-failed +1, and Node3D.set_visible in lastFault()
2 ptrcallWithBoolArg through that null bind null-bind +1, reason in lastFault()
3 take_pending_utf8 on the drained UTF-8 slot pending-protocol -1, +1, buffer named in lastFault()
4 take_pending_utf8 on the drained UTF-8 slot, again pending-protocol -1, +1, buffer named
5 take_pending_packed on the drained packed slot pending-protocol -1, +1, buffer named
6 take_pending_container_blob on the drained container slot pending-protocol -1, +1, buffer named
7 take_pending_blob on the drained array-blob slot pending-protocol -1, +1, buffer named

Every other row in that file proves a call works; these seven prove that a call that does not work says so — a red run that re-executes itself on the device on every debug build, so it cannot be forgotten.

Rows 3–7 used to sit inline beside their producers as …(pending slot drained) rows asserting only take_pending_*(null, 0) == -1. That -1 is reachable only through the guard that reports pending-protocol, so they were always red runs of that guard in disguise: a healthy build printed five unexpected FAULT lines and faults=7 expected=2, which the device runner correctly failed. They are fault probes, so they now live with the probes and say so. Their producers, and the non-default assertions that proved those producers worked, stayed where they were.

The three ObjectCalls summary lines therefore end with faults=<count> expected=7 in <ms> ms:

[kanama][ios][kn] OBJECTCALLS SELFTEST: <N> passed, 0 failed faults=7 expected=7 in <ms> ms
[kanama][ios][kn] OBJECTCALLS SELFTEST (frame 1): <N> passed, 0 failed faults=7 expected=7 in <ms> ms
[kanama][ios][kn] OBJECTCALLS SELFTEST (api exercise): <N> passed, 0 failed, <W> weak, <K> known, <R> reach faults=7 expected=7 in <ms> ms

The third line is the generated API exercise (ApiExerciseSelfTest.kt, after the frame-1 rows): one row per ObjectCalls helper the shared tree calls (a static, a property pair, a const method, a singleton method, a RID factory, or a reach-only call), and one per Godot Variant type per generic Variant path, the same rows the desktop smoke runs (see "The exercise rows" in wrapper-maintenance.md). A call the shim refused shows as a FAULT line, fails the row it happened in, and shows as faults above expected; the demos' ios_device_run.sh fails on both, while ios_visual_smoke.sh fails on FAIL lines and failed rows but does not compare the fault counts. A row listed in KNOWN_FINDINGS (scripts/api_exercise_policy.py: an iOS gap already tracked, with the failure text it excuses) prints ... (api exercise) KNOWN: instead of FAIL: and counts as known when its Variant-path half fails with that text; any other failure prints FAIL:, and once it passes it prints a FAIL: line until the entry is removed.

(The counter is never reset, so the frame-1 phase and the API exercise, which raise no faults of their own, reprint the same total.) expected is the constant SELFTEST_EXPECTED_FAULTS, declared immediately above runFaultProbes with a comment listing the seven, so the number and the things it counts are one screen apart and cannot drift. Change it only when you change the probes. Only a debug build made with -PkanamaIosSelfTest=true runs the self-test (see below); every other build prints none of the summary lines.

The sink marks the probes, not the lines around them. runFaultProbes calls kanama_ios_fault_set_probe(1) before the first probe and kanama_ios_fault_set_probe(0) after the last, in a finally. While probe mode is on, the sink still counts each fault and still records it in g_last_fault, under the same print budget, but prints [kanama][ios][c] FAULT-PROBE <entry>: <reason> <detail> instead of [kanama][ios][c] FAULT …. kanama-demos/scripts/ios_device_run.sh then fails the device run on any line containing the literal [kanama][ios][c] FAULT (with the space, so FAULT-PROBE does not match), on any summary line where faults and expected disagree, and on a run where the self-test ran (the PTRCALL SELFTEST MATRIX line is in the console) but no summary line was printed. A real fault — null-bind, the most common one, included — therefore stays fatal: the probes are told apart by a mark the sink puts on the line at the moment it knows the fault is deliberate, never by the reason token. A real fault raised on another thread while probe mode is on would print as FAULT-PROBE, but it is still counted, so the summary reads faults=8 expected=7 and the run fails anyway.

Why line order across streams cannot be relied on. An earlier cut bracketed the probes with OBJECTCALLS SELFTEST fault-probes begin / ... end lines and trusted the FAULT lines between them. Those markers are Kotlin println (stdout); the sink is fprintf(stderr). devicectl --console merges the two streams without preserving their relative order, and on the first real device run (iPhone 12, Match3) all seven probe lines landed after the end marker, so the runner failed a healthy build. Any check that reads a stderr line's meaning from its position relative to a stdout line is wrong on a device. The begin/end lines are still printed, as human-readable markers only; nothing parses them. The runner's check can be re-run against any saved log with scripts/ios_device_run.sh --check-console-faults /path/to/console.log, which is how its own red runs are reproduced without a phone.

The sink under concurrency. Godot calls into the shim from more than the main thread, so g_fault_count is an _Atomic int32_t bumped with atomic_fetch_add and saturating at INT32_MAX — it never wraps, because a wrapped count reads as a small number and faults=<small> expected=7 would pass a run that faulted two billion times. g_last_fault is a plain buffer written with one snprintf, so kanama_ios_last_fault() is a best-effort snapshot that can tear when two threads fault at the same instant. Compare the count; read the text as a hint.

Script errors: the Kotlin line on a device

A contained Kotlin exception reaches Godot as a script error (IosScriptErrors, task 131) with the file and line of the game's top frame, parsed from Kotlin/Native's getStackTrace() lines by the shared ScriptErrorReport.parseNativeFrame. Kotlin/Native adds (File.kt:line:column) to a frame only when it can read DWARF. An iPhone app carries no DWARF (Apple's linker leaves it in the object files, or a dSYM next to the app), and Kotlin/Native does not offer CoreSymbolication for iosArm64; -Xbinary=sourceInfoType=libbacktrace would read DWARF from the app or a dSYM inside it, which a Godot iOS export does not ship. On the simulator, where CoreSymbolication is Kotlin/ Native's default, the frames carry no source either (measured in ios_visual_smoke.sh). So a frame is only kfun:<symbol> + <offset> (task 131 item 13; before it the self-test printed at selfTest (:0)).

The offset of a return address inside its function is fixed when the static library is built -- linking moves a function, never its body -- so the debug device build maps it ahead of time. generateIosDeviceDebugSourceLines (build.gradle.kts; the logic is gradle-plugin/src/shared/.../IosSourceLines.kt, which the kit's buildIosScripts runs too, and its tests are in buildSrc) reads the debug runtime library's own object (nm for the function starts, dwarfdump --debug-line for the rows, atos -i for rows inside inlined code) and writes a table of the functions with code from the project's script dirs and from the self-test probe KanamaIosScriptErrorProbe.kt: symbol and size, then rows of (offset from the function's start, file, line). The file is the res:// path when the script dir is inside a Godot project (res://kotlin-src/Player.kt, as desktop reports it), else the base name. ios/bootstrap/kanama_ios_source_lines.c compiles the table as static data into the addon library and answers kanama_ios_source_line(symbol, offset) by binary search; nothing runs until an error is reported. The simulator's debug library gets its own table; release builds compile the same file with an empty table. The Kanama runtime's own functions are left out on purpose: their table would be megabytes (1.9 million line rows), and a script error is reported at the game's frame.

Rules the generator keeps:

  • Never a wrong line. A row whose game line is not known for sure -- line 0 in DWARF, inlined code atos cannot place in a game file, a base name two files share -- is a line-0 row, and the lookup answers 0 there rather than the line before it; an offset past the function's size answers 0; an atos -i answer that does not line up with its addresses fails the build.
  • Paths may be another checkout's. Gradle's build cache can hand the build a Kotlin/Native library compiled elsewhere, whose DWARF names that checkout's paths (the device run of 412db412 shipped an empty table this way). A game file matches a DWARF path by its path from the source root's parent (kotlin-src/Player.kt), and a source root with no code in the library fails the build instead of shipping an empty table.
  • Offsets as Kotlin/Native prints them. A device frame's offset is the return address minus one (offsets are 3 mod 4), inside the call instruction, so it is looked up as is.

The app must keep its symbol table. The lookup is keyed by the frame's symbol, which dladdr reads from the app's symbol table. A build of Godot's exported Xcode project (Export Project Only, then Xcode's Run or xcodebuild build, the documented flow and the demos' device runner) keeps it. Godot's own .ipa export and its one-click deploy run xcodebuild archive, which strips the app (strip -D under DEPLOYMENT_POSTPROCESSING, even for the Debug configuration: measured on a 4.7.2 template project, 300,637 local symbols after build, none after archive). Godot gives an export plugin no hook for build settings ($linker_flags is quoted into OTHER_LDFLAGS), so Kanama cannot turn that off; such a build reports the containment site with line 0, never a wrong line. Shipping the runtime as a dynamic framework (copied unstripped in Debug) would lift this.

The self-test row script-error(report carries the Kotlin file:line) proves the device path: the report of the probe's exception names KanamaIosScriptErrorProbe.kt and a line above 0.

Rules

  • No silent stubs. Every API method must call through ObjectCalls. A method with an empty body or a bare return false/0.0/null is a bug — it hides missing functionality. Prefer generating the method (or omitting it) over stubbing it.
  • Marshalling goes through guardrails. Variant-based calls (object_method_bind_call) must use kanama_ios_check_call_error; argument Variants are checked with kanama_ios_check_variant_arg in debug builds. Both must log zero in a healthy run.
  • GDExtension virtual args[i] is already a pointer to the argument — do not double-dereference StringName args (a past bug in the connect/signal path).
  • Authoritative ptrcall scalar width table (from Godot core/variant/method_ptrcall.h). This is THE type→PT-tag mapping for the generator; getting it wrong corrupts that type across the whole API:
Godot scalar type ptrcall encoding bytes iOS handling
bool convert<bool,uint8_t> 1 PT_BOOL (uint8)
int8/16/32, uint8/16/32 convert<…,int64_t> 8 lay int64 (widen)
int64, uint64 direct 8 int64
float convert<float,double> 8 lay double (widen Float→Double)
double direct 8 double
Object/RID direct ptr 8 PT_OBJECT

Key gotcha — only SCALARS widen. scalar float AND all scalar ints are 8 bytes at ptrcall (converted from the smaller C++ type), regardless of meta. Struct/container types are PtrToArgDirect/PtrToArgByReference — passed as their native bytes, NOT widened:

Godot type group ptrcall layout notes
real_t structs: Vector2/3/4, Rect2, Plane, Quaternion, AABB, Basis, Transform2D/3D, Projection N× float32 (single-prec) components are real_t storage in Kotlin too (Double properties over GodotRealStorage fields): the cells take the stored rawX… values and reads build through the raw factories, unconverted (GodotRealVar)
int structs: Vector2i/3i/4i, Rect2i N× int32 (4B) NOT widened — unlike scalar ints
Color 4× float32 always float32 (not real_t), also in the Kotlin Color's storage: rawR… and Color.raw, unconverted
Object, RID 8B pointer/handle
String, StringName, NodePath constructed C-side from a string CONSTRUCT tag
Callable, Signal, Dictionary, Array, Packed* opaque handle defer / skip initially

So set_amount(int)/set_volume_db(float) take 8-byte cells, but Vector2i(x,y) lays two 4-byte int32s and Vector3(x,y,z) three 4-byte float32s. Source: core/variant/method_ptrcall.h. (The scalar-float case was the inaudible-audio bug; the scalar-int case was masked by int32 conversion + small self-test values.)

  • Guardrail: the generator emits ONLY audited types. Like the desktop generator's --skip-report, the iOS emission must refuse any method whose arg/return types aren't in the audited table above — skipped, never guessed. An un-audited type can therefore never silently produce a wrong-width helper. As each new type is added to the table it also gets a width-sensitive row in the debug-gated self-test matrix (use values where a wrong width fails — a small value can mask it, as the int bug showed). The matrix + ObjectCalls probe are the ptrcall path's only runtime check (check_call_error/check_variant_arg only cover the Variant path).
  • The self-test is a Kanama test hook, compiled only on request (task 138 item 24). It is not part of a user's game: build.gradle.kts compiles every *SelfTest.kt (the OBJECTCALLS rows live in ObjectCallsSelfTest.kt) and the script-error probe only into a build made with -PkanamaIosSelfTest=true, and defines KANAMA_IOS_SELFTEST=1 (the C ptrcall matrix and the calls into the Kotlin phases) only for that build's DEBUG shim; a release xcframework never carries the C side. Kanama's device runners pass the property (scripts/ios_visual_smoke.sh, the demos' scripts/ios_device_run.sh; scripts/ios_device_gate.sh refuses a demos checkout whose runner does not) and REQUIRE all four summary lines (the C matrix, the two ObjectCalls phases and the API exercise) with 0 failed, so a runner build that lost the flag fails rather than passing on silence. ios_visual_smoke.sh --check-selftest-log LOG and the demos' ios_device_run.sh --self-test-console-checks run that verdict without a device.
  • The on-device self-test runs in two phases, and a row must sit in the right one. The C ptrcall matrix and the Kotlin kanamaIosRuntimeObjectCallsSelfTest both run at SCENE-level extension init and print [kanama][ios][c] PTRCALL SELFTEST MATRIX: N passed, M failed and [kanama][ios][kn] OBJECTCALLS SELFTEST: N passed, M failed. A second Kotlin phase, kanamaIosRuntimeObjectCallsSelfTestFrame, runs once on the first frame — called from kanama_ios_frame when the frame counter first reaches 1, before kanama_ios_runtime_frame() — and prints [kanama][ios][kn] OBJECTCALLS SELFTEST (frame 1): N passed, M failed. Anything needing a singleton Godot registers after initialize_extensions(INITIALIZATION_LEVEL_SCENE) belongs in the frame-1 phase: the servers arrive only with register_server_singletons() (servers/register_server_types.cpp:400-401), so at scene init getSingleton("RenderingServer") — and getSingleton("NativeMenu"), registered by the same call — returns 0. Resolve every singleton through the phase's requireSingleton helper — it records singleton-present(<name>) as its own check and the row then skips its dependent calls — because a zero instance is the shared tree's static-method marker and now reaches Godot as a null this instead of no-opping. The same goes for constructing an object whose constructor uses a server Godot creates after scene init (PhysicsServer2D, PhysicsServer3D, CameraServer): its C++ singleton is still null, and the engine segfaults inside the constructor. Godot 4.8 added PhysicsServer2D/3D::get_singleton()->connect(...) to the constructors of TileMapLayer and the collision nodes, so the first 4.8 iPhone run died in TileMapLayer::TileMapLayer() (from the scene-init requireObject("TileMap") row). The TileMap, TileMapLayer and GridMap rows now sit in the frame-1 phase, and scripts/check_ios_selftest_phases.py (a local_ci stage) fails on the host when a scene-init row constructs such a class or a subclass of one. The class list, scripts/ios_scene_init_unsafe_classes.json, is generated from the constructors in the Godot source (scene/, modules/, servers/): upgrade_godot.sh reruns python3 scripts/check_ios_selftest_phases.py --regenerate --godot-src <godot checkout> --godot-bin <editor> at every bump, and the gate fails when the list's pin is not the current pin. With a checkout at the list's commit (GODOT_SRC, GODOT_DOCS) it also fails when the file is stale; without one it prints SKIP: ios-unsafe-classes-staleness. A row must finish in its own frame, so never assert that a threaded load is done by a deadline: the load is a low-priority worker task, an iPhone 12 has one low-priority thread, and on the first launch of a Mobile-renderer app that thread stays busy for seconds. The threaded-load row accepts a load still in progress at its bound, and proves LOADED with progress 1.0 through a request for a scene already in the resource cache, which Godot answers as loaded without queuing a task. Expected line shapes on a clean run:
[kanama][ios][c] PTRCALL SELFTEST MATRIX: 70 passed, 0 failed
[kanama][ios][kn] OBJECTCALLS SELFTEST: 274 passed, 0 failed faults=7 expected=7
[kanama][ios][kn] OBJECTCALLS SELFTEST (frame 1): 4 passed, 0 failed faults=7 expected=7
  • A probe must assert a value the no-op path cannot produce. This is the rule that decides whether a row is a probe at all. A static routed with a zero instance used to hit the C guard and return null / 0 / false / "" / an empty list / a zeroed struct, so a row whose expected value is any of those cannot tell the working call from the call that never happened — it keeps passing on the day the feature breaks. Three rows shipped that way and all three were found only once the singleton checks made the self-test honest: NativeMenu's empty Callable, and the two ShaderIncludeDB rows, whose "non-empty list / non-empty source" is the correct answer under the GL Compatibility renderer — Godot registers the built-in includes only from the RenderingDevice renderer (servers/rendering/renderer_rd/renderer_scene_render_rd.cpp:1796-1798). Prefer a named element over "non-empty", a valid RID over an invalid one, and a value with structure (a 64-character lowercase-hex SHA-256) over a truthy one. A default expectation is admissible only when something else in the row already rules the no-op out — a preceding non-default assertion through the same helper, or a requireSingleton / requireObject check proving the instance is non-zero, which means the static route is not taken. Every phase must contain at least one non-default assertion.
  • Validate on device. Every change ends with an on-device run (0 SIGSEGV baseline, guardrail logs clean).