Modern Apps git

← Modern-Apps.git

kart: fix GLES SIGSEGV on Mali (backend order, link probe)

Commit
3bbb68f6af362431ffdb35eae76ed18e2de5902c
Author
vayun-mathur <[email protected]>
When
2026-10-18 20:21 UTC (1 month ago)
Parents
a0ea392

Diff

games/kart/src/main/rust/shaders/kart_gles.frag
diff --git a/games/kart/src/main/rust/shaders/kart_gles.frag b/games/kart/src/main/rust/shaders/kart_gles.fragindex 7068e92907..a33a6628b8 100644--- a/games/kart/src/main/rust/shaders/kart_gles.frag+++ b/games/kart/src/main/rust/shaders/kart_gles.frag@@ -5,13 +5,13 @@ // line never shows. Same `ndl` lighting + `exp` fog 0.0045 to // SKY(0.45, 0.68, 0.94) as the Vulkan twin. precision mediump float;+precision mediump sampler2D;  in vec3 vColor; in vec3 vWorld;  out vec4 outColor; -uniform mat4 uViewProj; uniform vec3 uSunDir; uniform vec3 uCamPos; 
games/kart/src/main/rust/shaders/kart_gles.vert
diff --git a/games/kart/src/main/rust/shaders/kart_gles.vert b/games/kart/src/main/rust/shaders/kart_gles.vertindex 9a5f7ba3a9..10986a15a3 100644--- a/games/kart/src/main/rust/shaders/kart_gles.vert+++ b/games/kart/src/main/rust/shaders/kart_gles.vert@@ -10,8 +10,6 @@ out vec3 vColor; out vec3 vWorld;  uniform mat4 uViewProj;-uniform vec3 uSunDir;-uniform vec3 uCamPos;  void main() {     vColor = inColor;
games/kart/src/main/rust/src/engine.rs
diff --git a/games/kart/src/main/rust/src/engine.rs b/games/kart/src/main/rust/src/engine.rsindex 89e7c4b69d..8ac60d26d7 100644--- a/games/kart/src/main/rust/src/engine.rs+++ b/games/kart/src/main/rust/src/engine.rs@@ -6,7 +6,6 @@ //! chase camera, draw. Everything fallible returns `Option`/`Result` — the //! JNI boundary logs and keeps the placeholder running rather than crashing. -use crate::gles::renderer::GlesRenderer; use crate::mesh::{self, KartVertex}; use crate::physics::DriveInput; use crate::race::Race;@@ -160,6 +159,14 @@ fn escape(s: &str) -> String { /// returns false. The winning backend is logged to logcat (`kart_engine` tag) /// so device triage can see which path engaged. ///+/// Backend order is by pointer width: 64-bit tries Vulkan first (drivers are+/// universal there); 32-bit tries GLES first. Rationale: 32-bit Google TV+/// boxes ship a `libvulkan.so` loader stub in `/system/lib` with no driver+/// behind it (`/vendor/lib/vulkan*` absent), and `Entry::load` + a stubbed+/// `create_instance` SIGSEGVs inside the stub instead of returning an error+/// — which no `Result` can catch. GLES-first on 32-bit never touches the+/// stub unless GLES itself fails.+/// /// # Safety /// `window` must be a live `ANativeWindow` adopted from the JNI surface (the /// caller acquired it via `ANativeWindow_acquire`); ownership moves here.@@ -168,25 +175,14 @@ pub unsafe fn create_renderer(window: *mut ANativeWindow, width: i32, height: i3         state.window_ptr = Some(window);         state.width = width.max(1) as u32;         state.height = height.max(1) as u32;-        let mut renderer = match try_vulkan(window, width, height, state.width, state.height) {-            Ok(r) => {-                log_backend("Vulkan");-                r+        let mut renderer = match unsafe {+            Renderer::select(window, width, height, state.width, state.height)+        } {+            Ok(r) => r,+            Err(e) => {+                log_backend(&e);+                return false;             }-            Err(vulkan_err) => match unsafe {-                GlesRenderer::new(window, state.width, state.height)-            } {-                Ok(r) => {-                    log_backend(&format!("GLES (Vulkan init failed: {vulkan_err})"));-                    Renderer::Gles(r)-                }-                Err(gles_err) => {-                    log_backend(&format!(-                        "no renderer (Vulkan: {vulkan_err}; GLES: {gles_err})"-                    ));-                    return false;-                }-            },         };         // A race may already be live (surface recreated on rotation): upload.         if state.race.is_some() {@@ -207,7 +203,7 @@ pub unsafe fn create_renderer(window: *mut ANativeWindow, width: i32, height: i3 /// /// # Safety /// Same contract as [`create_renderer`].-unsafe fn try_vulkan(+pub(crate) unsafe fn try_vulkan(     window: *mut ANativeWindow,     width: i32,     height: i32,@@ -227,7 +223,7 @@ unsafe fn try_vulkan( /// One logcat line naming the winning backend (the `kart_engine` tag the /// plan's triage filters on). `__android_log_print` on device; `eprintln` on /// host builds and tests so the selection stays visible off-device.-fn log_backend(msg: &str) {+pub(crate) fn log_backend(msg: &str) {     #[cfg(target_os = "android")]     unsafe {         use std::ffi::CString;
games/kart/src/main/rust/src/gles/egl.rs
diff --git a/games/kart/src/main/rust/src/gles/egl.rs b/games/kart/src/main/rust/src/gles/egl.rsindex 379f2d73b3..ccb75a3ada 100644--- a/games/kart/src/main/rust/src/gles/egl.rs+++ b/games/kart/src/main/rust/src/gles/egl.rs@@ -110,27 +110,37 @@ impl Egl {     ) -> Result<Self, String> {         let api =             unsafe { Api::load_required() }.map_err(|e| format!("load libEGL: {e:?}"))?;+        step_log("libEGL loaded");         let display = unsafe { api.get_display(egl::DEFAULT_DISPLAY) }             .ok_or_else(|| "eglGetDisplay failed".to_string())?;+        step_log("eglGetDisplay ok");         api.initialize(display)             .map_err(|e| format!("eglInitialize: {e:?}"))?;+        step_log("eglInitialize ok");         // Try configs richest-first: a single hard-coded config dies inside         // some Mali drivers when the window system cannot back it (SIGSEGV in         // libGLES_mali, not an EGL error). First config that yields BOTH a         // config AND a live window surface wins.         let mut configs = Vec::with_capacity(1);         let mut config = None;-        for attribs in [CONFIG_ATTRIBS_D24, CONFIG_ATTRIBS_D16, CONFIG_ATTRIBS_565] {+        let mut config_name = "none";+        for (label, attribs) in [+            ("D24", CONFIG_ATTRIBS_D24),+            ("D16", CONFIG_ATTRIBS_D16),+            ("565", CONFIG_ATTRIBS_565),+        ] {             configs.clear();             if api.choose_config(display, attribs, &mut configs).is_err() {                 continue;             }             if let Some(&c) = configs.first() {                 config = Some(c);+                config_name = label;                 break;             }         }         let config = config.ok_or_else(|| "no ES3 window EGL config".to_string())?;+        step_log(&format!("eglChooseConfig ok ({config_name})"));         let mut egl = Self {             api,             display,@@ -140,15 +150,23 @@ impl Egl {             terminated: false,         };         unsafe { egl.create_surface(window)? };+        step_log("eglCreateWindowSurface ok");         let context = egl             .api             .create_context(display, config, None, CONTEXT_ATTRIBS)             .map_err(|e| format!("eglCreateContext (ES3): {e:?}"))?;         egl.context = Some(context);         egl.make_current()?;+        step_log("eglMakeCurrent ok");         egl.api             .swap_interval(display, 1)             .map_err(|e| format!("eglSwapInterval: {e:?}"))?;+        // Prove the context is really usable BEFORE glow touches it: query+        // the surface size and the GL version string through directly+        // resolved pointers. If glGetString crashes here, the context (not+        // the loader) is bad — e.g. a zero-size or format-less window the+        // driver accepted but cannot back.+        unsafe { egl.probe_context()? };         Ok(egl)     } @@ -205,6 +223,45 @@ impl Egl {         Ok(())     } +    /// Prove the fresh context answers a direct `glGetString(GL_VERSION)`+    /// call before glow loads. Bypasses the loader entirely so a crash here+    /// indicts the context/surface (zero-size or unbackable window the+    /// driver accepted), not function resolution. Logs surface size ++    /// version on success.+    unsafe fn probe_context(&self) -> Result<(), String> {+        let surface = self.surface.ok_or_else(|| "probe: no surface".to_string())?;+        let w = self+            .api+            .query_surface(self.display, surface, egl::WIDTH)+            .map_err(|e| format!("eglQuerySurface WIDTH: {e:?}"))?;+        let h = self+            .api+            .query_surface(self.display, surface, egl::HEIGHT)+            .map_err(|e| format!("eglQuerySurface HEIGHT: {e:?}"))?;+        step_log(&format!("surface {w}x{h}"));+        if w <= 0 || h <= 0 {+            return Err(format!("surface has zero size ({w}x{h}) — not yet laid out"));+        }+        // glGetString(GL_VERSION=0x1F02) through a directly resolved pointer.+        const GL_VERSION: u32 = 0x1F02;+        let f = self+            .api+            .get_proc_address("glGetString")+            .ok_or_else(|| "eglGetProcAddress(glGetString) returned null".to_string())?;+        let version_ptr = unsafe {+            let callable: unsafe extern "C" fn(u32) -> *const std::os::raw::c_uchar = std::mem::transmute(f);+            callable(GL_VERSION)+        };+        if version_ptr.is_null() {+            return Err("glGetString(GL_VERSION) returned null".to_string());+        }+        let version = unsafe { std::ffi::CStr::from_ptr(version_ptr as *const std::os::raw::c_char) }+            .to_string_lossy()+            .into_owned();+        step_log(&format!("GL_VERSION: {version}"));+        Ok(())+    }+     /// Unbind, destroy surface/context, terminate the display. Idempotent.     pub fn teardown(&mut self) {         if self.terminated {@@ -261,3 +318,29 @@ impl Drop for Egl {         self.teardown();     } }++/// One logcat line per bring-up step (`kart_egl` tag), so a driver SIGSEGV+/// can be attributed to the exact EGL call: the last line present is the+/// call that died inside the driver. `__android_log_print` on device.+pub(crate) fn step_log(step: &str) {+    #[cfg(target_os = "android")]+    unsafe {+        use std::ffi::CString;+        use std::os::raw::{c_char, c_int};+        extern "C" {+            fn __android_log_print(prio: c_int, tag: *const c_char, fmt: *const c_char, ...) -> c_int;+        }+        // ANDROID_LOG_INFO = 4.+        if let (Ok(tag), Ok(line), Ok(fmt)) = (+            CString::new("kart_egl"),+            CString::new(format!("egl bring-up: {step}")),+            CString::new("%s"),+        ) {+            __android_log_print(4, tag.as_ptr(), fmt.as_ptr(), line.as_ptr());+        }+    }+    #[cfg(not(target_os = "android"))]+    {+        eprintln!("kart_egl: {step}");+    }+}
games/kart/src/main/rust/src/gles/renderer.rs
diff --git a/games/kart/src/main/rust/src/gles/renderer.rs b/games/kart/src/main/rust/src/gles/renderer.rsindex d9d33de305..5d4f65105e 100644--- a/games/kart/src/main/rust/src/gles/renderer.rs+++ b/games/kart/src/main/rust/src/gles/renderer.rs@@ -91,6 +91,7 @@ impl GlesRenderer {             glow::Context::from_loader_function(|name| egl.proc_address(name) as *const _)         };         let program = unsafe { shaders::compile_program(&gl)? };+        crate::gles::egl::step_log("program compiled+linked");         let (u_view_proj, u_sun_dir, u_cam_pos) = unsafe {             let view = gl                 .get_uniform_location(program, U_VIEW_PROJ)@@ -103,8 +104,11 @@ impl GlesRenderer {                 .ok_or_else(|| format!("missing uniform {U_CAM_POS}"))?;             (view, sun, cam)         };+        crate::gles::egl::step_log("uniforms located");         let track = unsafe { MeshBuffer::new(&gl)? };+        crate::gles::egl::step_log("track MeshBuffer created");         let dynamic = unsafe { MeshBuffer::new(&gl)? };+        crate::gles::egl::step_log("dynamic MeshBuffer created");         let renderer = Self {             egl,             gl,
games/kart/src/main/rust/src/gles/shaders.rs
diff --git a/games/kart/src/main/rust/src/gles/shaders.rs b/games/kart/src/main/rust/src/gles/shaders.rsindex d232083300..66c4f749d0 100644--- a/games/kart/src/main/rust/src/gles/shaders.rs+++ b/games/kart/src/main/rust/src/gles/shaders.rs@@ -23,6 +23,11 @@ pub const U_CAM_POS: &str = "uCamPos"; /// Compile `VERT_SRC` + `FRAG_SRC`, link, return the program. On any failure /// the returned string carries the shader/program info log from the driver. pub unsafe fn compile_program(gl: &glow::Context) -> Result<glow::Program, String> {+    // Prove the linker itself survives on this driver before feeding it the+    // real shaders: some Mali revisions SIGSEGV inside glLinkProgram on+    // specific source constructs (unused cross-stage uniforms, precision+    // mismatches). A crash here indicts the driver, not our source.+    unsafe { link_probe(gl)? };     let vert = unsafe { compile_stage(gl, glow::VERTEX_SHADER, "kart_gles.vert", VERT_SRC)? };     let frag = unsafe { compile_stage(gl, glow::FRAGMENT_SHADER, "kart_gles.frag", FRAG_SRC)? };     let program = unsafe { gl.create_program() }.map_err(|e| format!("glCreateProgram: {e}"))?;@@ -38,9 +43,37 @@ pub unsafe fn compile_program(gl: &glow::Context) -> Result<glow::Program, Strin         unsafe { gl.delete_program(program) };         return Err(format!("glLinkProgram kart_gles: {log}"));     }+    crate::gles::egl::step_log("linked kart_gles program");     Ok(program) } +/// Link a trivial passthrough program first: if the driver's linker cannot+/// survive this, it is broken for all programs (fail cleanly) rather than+/// our source being at fault.+unsafe fn link_probe(gl: &glow::Context) -> Result<(), String> {+    const PROBE_VERT: &str = "#version 300 es\nlayout(location=0) in vec3 p;void main(){gl_Position=vec4(p,1.0);}\n";+    const PROBE_FRAG: &str =+        "#version 300 es\nprecision mediump float;\nout vec4 o;\nvoid main(){o=vec4(1.0);}\n";+    let vert = unsafe { compile_stage(gl, glow::VERTEX_SHADER, "probe.vert", PROBE_VERT)? };+    let frag = unsafe { compile_stage(gl, glow::FRAGMENT_SHADER, "probe.frag", PROBE_FRAG)? };+    let program = unsafe { gl.create_program() }.map_err(|e| format!("glCreateProgram (probe): {e}"))?;+    unsafe {+        gl.attach_shader(program, vert);+        gl.attach_shader(program, frag);+        gl.link_program(program);+        gl.delete_shader(vert);+        gl.delete_shader(frag);+    }+    if !unsafe { gl.get_program_link_status(program) } {+        let log = unsafe { gl.get_program_info_log(program) };+        unsafe { gl.delete_program(program) };+        return Err(format!("glLinkProgram (probe): {log}"));+    }+    unsafe { gl.delete_program(program) };+    crate::gles::egl::step_log("probe program linked");+    Ok(())+}+ /// Compile one shader stage; the error carries the driver's info log. unsafe fn compile_stage(     gl: &glow::Context,@@ -59,6 +92,7 @@ unsafe fn compile_stage(         unsafe { gl.delete_shader(shader) };         return Err(format!("glCompileShader {name}: {log}"));     }+    crate::gles::egl::step_log(&format!("compiled {name}"));     Ok(shader) } @@ -79,8 +113,17 @@ mod tests {             "Vulkan Y flip must not ship on GLES"         );         for uniform in [U_VIEW_PROJ, U_SUN_DIR, U_CAM_POS] {-            assert!(VERT_SRC.contains(uniform), "vert missing {uniform}");+            assert!(+                VERT_SRC.contains(uniform) || FRAG_SRC.contains(uniform),+                "neither stage declares {uniform}"+            );         }+        // Each stage declares only what it uses (Mali linkers dislike dead+        // cross-stage uniforms): uViewProj is vert-only, sun/cam are frag-only.+        assert!(VERT_SRC.contains(U_VIEW_PROJ), "vert missing {U_VIEW_PROJ}");+        assert!(!VERT_SRC.contains(U_SUN_DIR), "vert must not declare {U_SUN_DIR}");+        assert!(!VERT_SRC.contains(U_CAM_POS), "vert must not declare {U_CAM_POS}");+        assert!(!FRAG_SRC.contains(U_VIEW_PROJ), "frag must not declare {U_VIEW_PROJ}");         for uniform in [U_SUN_DIR, U_CAM_POS] {             assert!(FRAG_SRC.contains(uniform), "frag missing {uniform}");         }
games/kart/src/main/rust/src/renderer.rs
diff --git a/games/kart/src/main/rust/src/renderer.rs b/games/kart/src/main/rust/src/renderer.rsindex 4798a90fa8..c2f68d72de 100644--- a/games/kart/src/main/rust/src/renderer.rs+++ b/games/kart/src/main/rust/src/renderer.rs@@ -92,4 +92,67 @@ impl Renderer {             r.ctx.destroy();         }     }++    /// Build the winning backend for `window`: GLES-first on 32-bit (where a+    /// `libvulkan.so` loader stub with no driver behind it SIGSEGVs inside+    /// `create_instance` instead of returning an error — no `Result` can+    /// catch that, so never touch the stub unless GLES itself fails),+    /// Vulkan-first on 64-bit. `Err` only when both backends fail.+    ///+    /// # Safety+    /// `window` must be a live adopted `ANativeWindow`; ownership stays with+    /// the engine (released on destroy), as on the Vulkan path.+    pub unsafe fn select(+        window: *mut crate::vulkan::context::ANativeWindow,+        width: i32,+        height: i32,+        state_width: u32,+        state_height: u32,+    ) -> Result<Self, String> {+        #[cfg(target_pointer_width = "32")]+        {+            match unsafe { GlesRenderer::new(window, state_width, state_height) } {+                Ok(r) => {+                    crate::engine::log_backend("GLES");+                    Ok(Self::Gles(r))+                }+                Err(gles_err) => {+                    match crate::engine::try_vulkan(window, width, height, state_width, state_height)+                    {+                        Ok(r) => {+                            crate::engine::log_backend(&format!(+                                "Vulkan (GLES init failed: {gles_err})"+                            ));+                            Ok(r)+                        }+                        Err(vulkan_err) => {+                            Err(format!("no renderer (GLES: {gles_err}; Vulkan: {vulkan_err})"))+                        }+                    }+                }+            }+        }+        #[cfg(not(target_pointer_width = "32"))]+        {+            match crate::engine::try_vulkan(window, width, height, state_width, state_height) {+                Ok(r) => {+                    crate::engine::log_backend("Vulkan");+                    Ok(r)+                }+                Err(vulkan_err) => {+                    match unsafe { GlesRenderer::new(window, state_width, state_height) } {+                        Ok(r) => {+                            crate::engine::log_backend(&format!(+                                "GLES (Vulkan init failed: {vulkan_err})"+                            ));+                            Ok(Self::Gles(r))+                        }+                        Err(gles_err) => Err(format!(+                            "no renderer (Vulkan: {vulkan_err}; GLES: {gles_err})"+                        )),+                    }+                }+            }+        }+    } }