feat(libScePigletv2VSH): implement the EGL and GLES 2 calls of the piglet sample #6521

Open
Get-fix wants to merge 3 commits from upstream-pr/6521 into main
Get-fix commented 2026-10-15 18:36:50 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Get-fix on 2026-10-15T18:36:50Z.


What

The OpenOrbis piglet sample renders through the PS4 GLES library libScePigletv2VSH, which AnyPS5 does not have. It imports 47 functions from it: scePigletSetConfigurationVSH, 13 EGL 1.4 functions and 33 OpenGL ES 2.0 functions. It loads the library and libScePrecompiledShaders with sceKernelLoadStartModule and passes the shaders from #6520 to glShaderBinary.

This adds libScePigletv2VSH with those 47 functions on Vulkan. The first commit is #6520; this pull request adds the second one.

  • Shaders: glShaderBinary takes AnyPS5's GLSL ES source from #6520; glLinkProgram compiles it with glslang to SPIR-V, packs the loose uniforms into one uniform buffer and binds the samplers as combined image samplers. A PS4 shader binary throws.
  • Drawing: draws are recorded into one render pass per frame, with pipelines cached by their state. Client-side vertex arrays, blending, viewports, glPixelStorei unpack alignment and the GL_RGBA, GL_RGB, GL_LUMINANCE, GL_LUMINANCE_ALPHA and GL_ALPHA texel formats are handled. A texture whose minifying filter needs mipmaps it does not have samples as incomplete, as OpenGL ES requires. The Y axis is flipped with a negative viewport height, and OpenGL's clip-space depth is kept where the device has VK_EXT_depth_clip_control.
  • Presenting: eglCreateWindowSurface opens a VideoOut port and registers two linear R8G8B8A8 buffers. eglSwapBuffers copies the frame into the next buffer once no flip is pending and submits the flip, on vblank for swap interval 1 and on hsync for 0. The sample calls eglSwapInterval before it has a context, so that call succeeds and sets the interval of the next surface.
  • Errors: invalid arguments set the EGL or GL error, and glGetError and eglGetError report it. What the sample does not use throws, among it cube maps, mipmap levels other than 0, texel types other than GL_UNSIGNED_BYTE, shared contexts and GL_LINE_LOOP; eglChooseConfig finds no config with depth or stencil.
  • Linking on MinGW: libc's import library is linked before glslang, and libstdc++ before the import library's trailing copy. The C++ runtime (__cxa_throw, _Unwind_*) then binds to libc.prx, so exceptions thrown here reach the caller's handlers. glslang's std::string members bind to libstdc++, because the import library lists 12 of them that libc.prx does not export, which made the library fail to load with error 127.

The limits are in the new docs/dev/debt/libScePigletv2VSH.md. Part of the PS4 homebrew work tracked in #3093.

Tested

Windows 11 Pro 26200, WinLibs GCC 15.2.0 r7, Release, BUILD_TESTING=ON, on main 03c4cb5e7:

  • The new guest_piglet test creates a 64x64 offscreen surface, links the two shaders from the table and renders five frames, checking pixels in each: a 2x2 RGBA texture on the left half (the four texels in place and the clear colour elsewhere); the same with opacity 0.5 and GL_SRC_ALPHA blending; a mipmapping filter without mipmaps (black); a 32x32 viewport; an RGB texture with the default 4-byte row alignment. It also checks EGL initialization, config choice, eglSwapInterval without a context, the reflected attribute and uniforms, the GL errors of invalid calls, and that a PS4 shader binary throws an exception the test catches.
  • Each of these makes the test fail: no Y flip, blending never enabled, sampling a texture that needs missing mipmaps, ignoring unpack alignment, RGB expanded with alpha 0, ignoring glViewport, writing glUniform1f at offset 0, accepting a PS4 binary as source, eglSwapInterval failing without a context.
  • The patched libScePigletv2VSH.prx exports exactly the 47 functions the sample imports, and imports from libc.prx only functions the patched libc.prx exports.
  • The OpenOrbis piglet sample on main 03c4cb5e7 with this, #6519, #5990 to #5994, #6376, #5138 and a change that answers the Linux TIOCGWINSZ with ENOTTY, as #5569 did: it loads both modules, prints GL_RENDERER: AnyPS5 Piglet on Vulkan, finds both shaders and draws its rotating textured square at 59.96 FPS (window title OpenOrbis piglet sample | FPS: 59.96 (666)). With neither library, it stops at start-up with 48 FAIL: unresolved ELF import lines, one for each function and one for scePrecompiledShaderEntries. The 14 other samples that start with my open pull requests still start.
  • Full ctest of this branch on main 03c4cb5e7: 1296 of 1300 pass. agc_driver_gpu_indirect_arguments_misaligned_writer_ahead does not compile with MinGW on main (#6452 fixes it), and prx_thread_local_destructors fails as it did on main 92cdc7b62 on this machine without my changes; agc_shader_disk_cache (timeout) and agc_driver_multisample_fill_host_only failed under ctest -j8 and pass when run alone. Full ctest of the build with all my open pull requests: 1304 of 1306 pass; the two that do not are the first two above.
  • tools/check_conventions.py passes.

Not tested on Linux or macOS.

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: #6520 (its commit is the first one here); the piglet sample also needs #6519
  • Unblocks: OpenOrbis PS4 toolchain sample piglet, #3093
  • GPUs tested: NVIDIA GeForce RTX 5060 Ti, driver 32.0.16.1088, Windows 11 Pro 26200
  • AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:issue:4878094519 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521). Originally posted by [Get-fix](https://github.com/Get-fix) on 2026-10-15T18:36:50Z. --- ### What The OpenOrbis piglet sample renders through the PS4 GLES library `libScePigletv2VSH`, which AnyPS5 does not have. It imports 47 functions from it: `scePigletSetConfigurationVSH`, 13 EGL 1.4 functions and 33 OpenGL ES 2.0 functions. It loads the library and `libScePrecompiledShaders` with `sceKernelLoadStartModule` and passes the shaders from #6520 to `glShaderBinary`. This adds `libScePigletv2VSH` with those 47 functions on Vulkan. The first commit is #6520; this pull request adds the second one. - **Shaders:** `glShaderBinary` takes AnyPS5's GLSL ES source from #6520; `glLinkProgram` compiles it with glslang to SPIR-V, packs the loose uniforms into one uniform buffer and binds the samplers as combined image samplers. A PS4 shader binary throws. - **Drawing:** draws are recorded into one render pass per frame, with pipelines cached by their state. Client-side vertex arrays, blending, viewports, `glPixelStorei` unpack alignment and the `GL_RGBA`, `GL_RGB`, `GL_LUMINANCE`, `GL_LUMINANCE_ALPHA` and `GL_ALPHA` texel formats are handled. A texture whose minifying filter needs mipmaps it does not have samples as incomplete, as OpenGL ES requires. The Y axis is flipped with a negative viewport height, and OpenGL's clip-space depth is kept where the device has `VK_EXT_depth_clip_control`. - **Presenting:** `eglCreateWindowSurface` opens a VideoOut port and registers two linear R8G8B8A8 buffers. `eglSwapBuffers` copies the frame into the next buffer once no flip is pending and submits the flip, on vblank for swap interval 1 and on hsync for 0. The sample calls `eglSwapInterval` before it has a context, so that call succeeds and sets the interval of the next surface. - **Errors:** invalid arguments set the EGL or GL error, and `glGetError` and `eglGetError` report it. What the sample does not use throws, among it cube maps, mipmap levels other than 0, texel types other than `GL_UNSIGNED_BYTE`, shared contexts and `GL_LINE_LOOP`; `eglChooseConfig` finds no config with depth or stencil. - **Linking on MinGW:** libc's import library is linked before glslang, and libstdc++ before the import library's trailing copy. The C++ runtime (`__cxa_throw`, `_Unwind_*`) then binds to `libc.prx`, so exceptions thrown here reach the caller's handlers. glslang's `std::string` members bind to libstdc++, because the import library lists 12 of them that `libc.prx` does not export, which made the library fail to load with error 127. The limits are in the new `docs/dev/debt/libScePigletv2VSH.md`. Part of the PS4 homebrew work tracked in #3093. ### Tested Windows 11 Pro 26200, WinLibs GCC 15.2.0 r7, Release, `BUILD_TESTING=ON`, on `main` `03c4cb5e7`: - The new `guest_piglet` test creates a 64x64 offscreen surface, links the two shaders from the table and renders five frames, checking pixels in each: a 2x2 RGBA texture on the left half (the four texels in place and the clear colour elsewhere); the same with opacity 0.5 and `GL_SRC_ALPHA` blending; a mipmapping filter without mipmaps (black); a 32x32 viewport; an RGB texture with the default 4-byte row alignment. It also checks EGL initialization, config choice, `eglSwapInterval` without a context, the reflected attribute and uniforms, the GL errors of invalid calls, and that a PS4 shader binary throws an exception the test catches. - Each of these makes the test fail: no Y flip, blending never enabled, sampling a texture that needs missing mipmaps, ignoring unpack alignment, RGB expanded with alpha 0, ignoring `glViewport`, writing `glUniform1f` at offset 0, accepting a PS4 binary as source, `eglSwapInterval` failing without a context. - The patched `libScePigletv2VSH.prx` exports exactly the 47 functions the sample imports, and imports from `libc.prx` only functions the patched `libc.prx` exports. - The OpenOrbis piglet sample on `main` `03c4cb5e7` with this, #6519, #5990 to #5994, #6376, #5138 and a change that answers the Linux `TIOCGWINSZ` with `ENOTTY`, as #5569 did: it loads both modules, prints `GL_RENDERER: AnyPS5 Piglet on Vulkan`, finds both shaders and draws its rotating textured square at 59.96 FPS (window title `OpenOrbis piglet sample | FPS: 59.96 (666)`). With neither library, it stops at start-up with 48 `FAIL: unresolved ELF import` lines, one for each function and one for `scePrecompiledShaderEntries`. The 14 other samples that start with my open pull requests still start. - Full ctest of this branch on `main` `03c4cb5e7`: 1296 of 1300 pass. `agc_driver_gpu_indirect_arguments_misaligned_writer_ahead` does not compile with MinGW on `main` (#6452 fixes it), and `prx_thread_local_destructors` fails as it did on `main` `92cdc7b62` on this machine without my changes; `agc_shader_disk_cache` (timeout) and `agc_driver_multisample_fill_host_only` failed under `ctest -j8` and pass when run alone. Full ctest of the build with all my open pull requests: 1304 of 1306 pass; the two that do not are the first two above. - `tools/check_conventions.py` passes. Not tested on Linux or macOS. ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: #6520 (its commit is the first one here); the piglet sample also needs #6519 - [x] Unblocks: OpenOrbis PS4 toolchain sample piglet, #3093 - [x] GPUs tested: NVIDIA GeForce RTX 5060 Ti, driver 32.0.16.1088, Windows 11 Pro 26200 - [x] AI-assisted: yes (Claude Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
github-actions[bot] commented 2026-10-15 18:37:37 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by github-actions[bot] on 2026-10-15T18:37:37Z.


Progress report (cecb540 → 95b1f00)

📈 System libraries: 42.35% (+0.25%, +47 implemented functions)

✅ 47 implemented
Library Name
libScePigletv2VSH eglBindAPI
libScePigletv2VSH eglChooseConfig
libScePigletv2VSH eglCreateContext
libScePigletv2VSH eglCreateWindowSurface
libScePigletv2VSH eglDestroyContext
libScePigletv2VSH eglDestroySurface
libScePigletv2VSH eglGetDisplay
libScePigletv2VSH eglGetError
libScePigletv2VSH eglInitialize
libScePigletv2VSH eglMakeCurrent
libScePigletv2VSH eglSwapBuffers
libScePigletv2VSH eglSwapInterval
libScePigletv2VSH eglTerminate
libScePigletv2VSH glActiveTexture
libScePigletv2VSH glAttachShader
libScePigletv2VSH glBindTexture
libScePigletv2VSH glBlendFunc
libScePigletv2VSH glClear
libScePigletv2VSH glClearColor
libScePigletv2VSH glCreateProgram
libScePigletv2VSH glCreateShader
libScePigletv2VSH glDeleteProgram
libScePigletv2VSH glDeleteShader
libScePigletv2VSH glDeleteTextures
libScePigletv2VSH glDrawArrays
libScePigletv2VSH glEnable
libScePigletv2VSH glEnableVertexAttribArray
libScePigletv2VSH glGenTextures
libScePigletv2VSH glGetActiveAttrib
libScePigletv2VSH glGetActiveUniform
libScePigletv2VSH glGetAttribLocation
libScePigletv2VSH glGetError
libScePigletv2VSH glGetProgramiv
libScePigletv2VSH glGetString
libScePigletv2VSH glGetUniformLocation
libScePigletv2VSH glLinkProgram
libScePigletv2VSH glPixelStorei
libScePigletv2VSH glShaderBinary
libScePigletv2VSH glTexImage2D
libScePigletv2VSH glTexParameteri
libScePigletv2VSH glUniform1f
libScePigletv2VSH glUniform1i
libScePigletv2VSH glUniformMatrix4fv
libScePigletv2VSH glUseProgram
libScePigletv2VSH glVertexAttribPointer
libScePigletv2VSH glViewport
libScePigletv2VSH scePigletSetConfigurationVSH
<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6199520614 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#issuecomment-6199520614). Originally posted by [github-actions[bot]](https://github.com/apps/github-actions) on 2026-10-15T18:37:37Z. --- <!-- progress-report --> ### Progress report (cecb540 → 95b1f00) 📈 **System libraries**: 42.35% (+0.25%, +47 implemented functions) <details> <summary>✅ 47 implemented</summary> | Library | Name | | - | - | | libScePigletv2VSH | `eglBindAPI` | | libScePigletv2VSH | `eglChooseConfig` | | libScePigletv2VSH | `eglCreateContext` | | libScePigletv2VSH | `eglCreateWindowSurface` | | libScePigletv2VSH | `eglDestroyContext` | | libScePigletv2VSH | `eglDestroySurface` | | libScePigletv2VSH | `eglGetDisplay` | | libScePigletv2VSH | `eglGetError` | | libScePigletv2VSH | `eglInitialize` | | libScePigletv2VSH | `eglMakeCurrent` | | libScePigletv2VSH | `eglSwapBuffers` | | libScePigletv2VSH | `eglSwapInterval` | | libScePigletv2VSH | `eglTerminate` | | libScePigletv2VSH | `glActiveTexture` | | libScePigletv2VSH | `glAttachShader` | | libScePigletv2VSH | `glBindTexture` | | libScePigletv2VSH | `glBlendFunc` | | libScePigletv2VSH | `glClear` | | libScePigletv2VSH | `glClearColor` | | libScePigletv2VSH | `glCreateProgram` | | libScePigletv2VSH | `glCreateShader` | | libScePigletv2VSH | `glDeleteProgram` | | libScePigletv2VSH | `glDeleteShader` | | libScePigletv2VSH | `glDeleteTextures` | | libScePigletv2VSH | `glDrawArrays` | | libScePigletv2VSH | `glEnable` | | libScePigletv2VSH | `glEnableVertexAttribArray` | | libScePigletv2VSH | `glGenTextures` | | libScePigletv2VSH | `glGetActiveAttrib` | | libScePigletv2VSH | `glGetActiveUniform` | | libScePigletv2VSH | `glGetAttribLocation` | | libScePigletv2VSH | `glGetError` | | libScePigletv2VSH | `glGetProgramiv` | | libScePigletv2VSH | `glGetString` | | libScePigletv2VSH | `glGetUniformLocation` | | libScePigletv2VSH | `glLinkProgram` | | libScePigletv2VSH | `glPixelStorei` | | libScePigletv2VSH | `glShaderBinary` | | libScePigletv2VSH | `glTexImage2D` | | libScePigletv2VSH | `glTexParameteri` | | libScePigletv2VSH | `glUniform1f` | | libScePigletv2VSH | `glUniform1i` | | libScePigletv2VSH | `glUniformMatrix4fv` | | libScePigletv2VSH | `glUseProgram` | | libScePigletv2VSH | `glVertexAttribPointer` | | libScePigletv2VSH | `glViewport` | | libScePigletv2VSH | `scePigletSetConfigurationVSH` | </details>
jotitadev commented 2026-10-15 22:16:03 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by jotitadev on 2026-10-15T22:16:03Z.

Review: COMMENTED


A Linux run, since the description lists none.

Machine: NVIDIA GeForce RTX 3070, driver 595.99.02, Vulkan 1.4.329, Ubuntu 26.04 (kernel 7.0.0-38), i7-8700. GCC 15.2, Release, BUILD_TESTING=ON. Head e983d881f merged onto main 31cbb55d7, no conflicts. After reconfiguring for the new library, the build finishes with no warnings.

GPUs tested: NVIDIA GeForce RTX 3070 (595.99.02), Linux; llvmpipe (Mesa 26.0.3), Linux

  • guest_piglet and guest_precompiled_shaders pass 3/3 with ANYPS5_GPU="NVIDIA GeForce RTX 3070", 3/3 with ANYPS5_GPU=llvmpipe, and 3/3 with ANYPS5_GPU unset (both ICDs installed). With ANYPS5_GPU=NoSuchGPU, guest_piglet is skipped with no Vulkan 1.1 graphics device matches ANYPS5_GPU=NoSuchGPU, so the selector filters on Linux as well. The 3070 exposes VK_EXT_depth_clip_control, so that path is the one taken here.
  • Fault check on this driver: with the Y flip taken out of the draw viewport in Context.cpp (origin viewport[1], positive height), guest_piglet fails on the RTX 3070 at the first frame's texel check (Piglet check failed at line 204). With the flip restored, it passes.
  • ctest -R "^agc" -E "agc_display_buffer_dcc|agc_driver_flip|agc_driver_lds_atomics64" -j1 --timeout 60: 591/593 pass, the same result as unchanged main on this machine. agc_driver_stencil_ref_export is skipped (no VK_EXT_shader_stencil_export), and agc_driver_store_over_untracked fails as it does on main (#6385).

I did not run the OpenOrbis piglet sample itself.

Written with AI assistance (Claude Code). I ran the tests above on my machine.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5540588966 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#pullrequestreview-5540588966). Originally posted by [jotitadev](https://github.com/jotitadev) on 2026-10-15T22:16:03Z. **Review:** COMMENTED --- A Linux run, since the description lists none. **Machine:** NVIDIA GeForce RTX 3070, driver 595.99.02, Vulkan 1.4.329, Ubuntu 26.04 (kernel 7.0.0-38), i7-8700. GCC 15.2, Release, `BUILD_TESTING=ON`. Head `e983d881f` merged onto `main` `31cbb55d7`, no conflicts. After reconfiguring for the new library, the build finishes with no warnings. GPUs tested: NVIDIA GeForce RTX 3070 (595.99.02), Linux; llvmpipe (Mesa 26.0.3), Linux - `guest_piglet` and `guest_precompiled_shaders` pass 3/3 with `ANYPS5_GPU="NVIDIA GeForce RTX 3070"`, 3/3 with `ANYPS5_GPU=llvmpipe`, and 3/3 with `ANYPS5_GPU` unset (both ICDs installed). With `ANYPS5_GPU=NoSuchGPU`, `guest_piglet` is skipped with `no Vulkan 1.1 graphics device matches ANYPS5_GPU=NoSuchGPU`, so the selector filters on Linux as well. The 3070 exposes `VK_EXT_depth_clip_control`, so that path is the one taken here. - Fault check on this driver: with the Y flip taken out of the draw viewport in `Context.cpp` (origin `viewport[1]`, positive height), `guest_piglet` fails on the RTX 3070 at the first frame's texel check (`Piglet check failed at line 204`). With the flip restored, it passes. - `ctest -R "^agc" -E "agc_display_buffer_dcc|agc_driver_flip|agc_driver_lds_atomics64" -j1 --timeout 60`: 591/593 pass, the same result as unchanged `main` on this machine. `agc_driver_stencil_ref_export` is skipped (no `VK_EXT_shader_stencil_export`), and `agc_driver_store_over_untracked` fails as it does on `main` (#6385). I did not run the OpenOrbis piglet sample itself. Written with AI assistance (Claude Code). I ran the tests above on my machine.
Get-fix commented 2026-10-15 23:26:43 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Get-fix on 2026-10-15T23:26:43Z.


Thank you for the thorough Linux run, @jotitadev: two GPUs, the ANYPS5_GPU selector, and the fault check with the Y flip taken out. It's good to know the VK_EXT_depth_clip_control path works on the RTX 3070, and that llvmpipe passes too.

AI-assisted: yes (Claude Code).

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6204398098 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#issuecomment-6204398098). Originally posted by [Get-fix](https://github.com/Get-fix) on 2026-10-15T23:26:43Z. --- Thank you for the thorough Linux run, @jotitadev: two GPUs, the `ANYPS5_GPU` selector, and the fault check with the Y flip taken out. It's good to know the `VK_EXT_depth_clip_control` path works on the RTX 3070, and that llvmpipe passes too. AI-assisted: yes (Claude Code). 🤖 Generated with [Claude Code](https://claude.com/claude-code)
javierUDP commented 2026-10-19 18:30:03 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by javierUDP on 2026-10-19T18:30:03Z.

Review: COMMENTED


Static review on macOS, head of this branch. I could not build or run any of it: these libraries need the full build, which does not configure on macOS, so everything below comes from reading the code and from the OpenOrbis piglet sample, not from execution.

eglCreateWindowSurface leaks its Vulkan objects on every error path.

Image and Buffer (include/Vulkan.hpp) are plain structs with no destructor; they are released explicitly, as DestroySurfaceNow does with DestroyImage, DestroyBuffer and vkDestroyFramebuffer. EglCreateWindowSurface creates the colour image, the readback buffer and the framebuffer, and only then reaches three statements that throw:

  • Check(device.vkCreateFramebuffer(...), "vkCreateFramebuffer")
  • if (created->videoOut < 0) throw ... sceVideoOutOpen failed
  • if (sceVideoOutRegisterBuffers2(...) < 0) throw ... failed

When one of them throws, std::unique_ptr<WindowSurface> deletes the object without touching the handles, so a VkImage, its VkDeviceMemory and VkImageView, the VkFramebuffer, and the readback VkBuffer with its memory are all lost.

A title that creates a second window surface while the first is alive reaches this: the second sceVideoOutOpen fails, and each retry leaks that set again. EGL allows more than one window surface, so this is not only a malformed-input path.

Releasing what was created before rethrowing, or giving Surface the destructor that DestroySurfaceNow currently open-codes, would close all three at once.

What I checked and found correct, in case it saves someone repeating it:

  • The export surface matches the sample exactly: this PR exports 46 EGL and GLES symbols, and the piglet sample of OpenOrbis samples-elf-llvm-18.zip imports exactly those 46, with nothing missing and nothing unused. I took the import list from relinker --registry on the sample.
  • Describe() bounds its copy with min(item.name.size(), bufferSize - 1) and writes the terminator inside the buffer, so glGetActiveAttrib and glGetActiveUniform do not overrun a caller buffer.
  • lastError is thread_local, as EGL requires, and objectsMutex is held across the surfaces and contexts updates in eglMakeCurrent.

I did not review Context.cpp's GLES state machine beyond the queries above, the glslang path in Program.cpp, or the two companion PRs.

Written with AI assistance. The import cross-check above was run on my own machine; nothing here was executed.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:5575950963 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#pullrequestreview-5575950963). Originally posted by [javierUDP](https://github.com/javierUDP) on 2026-10-19T18:30:03Z. **Review:** COMMENTED --- Static review on macOS, head of this branch. I could not build or run any of it: these libraries need the full build, which does not configure on macOS, so everything below comes from reading the code and from the OpenOrbis `piglet` sample, not from execution. **`eglCreateWindowSurface` leaks its Vulkan objects on every error path.** `Image` and `Buffer` (`include/Vulkan.hpp`) are plain structs with no destructor; they are released explicitly, as `DestroySurfaceNow` does with `DestroyImage`, `DestroyBuffer` and `vkDestroyFramebuffer`. `EglCreateWindowSurface` creates the colour image, the readback buffer and the framebuffer, and only then reaches three statements that throw: - `Check(device.vkCreateFramebuffer(...), "vkCreateFramebuffer")` - `if (created->videoOut < 0) throw ... sceVideoOutOpen failed` - `if (sceVideoOutRegisterBuffers2(...) < 0) throw ... failed` When one of them throws, `std::unique_ptr<WindowSurface>` deletes the object without touching the handles, so a `VkImage`, its `VkDeviceMemory` and `VkImageView`, the `VkFramebuffer`, and the readback `VkBuffer` with its memory are all lost. A title that creates a second window surface while the first is alive reaches this: the second `sceVideoOutOpen` fails, and each retry leaks that set again. EGL allows more than one window surface, so this is not only a malformed-input path. Releasing what was created before rethrowing, or giving `Surface` the destructor that `DestroySurfaceNow` currently open-codes, would close all three at once. **What I checked and found correct**, in case it saves someone repeating it: - The export surface matches the sample exactly: this PR exports 46 EGL and GLES symbols, and the `piglet` sample of OpenOrbis `samples-elf-llvm-18.zip` imports exactly those 46, with nothing missing and nothing unused. I took the import list from `relinker --registry` on the sample. - `Describe()` bounds its copy with `min(item.name.size(), bufferSize - 1)` and writes the terminator inside the buffer, so `glGetActiveAttrib` and `glGetActiveUniform` do not overrun a caller buffer. - `lastError` is `thread_local`, as EGL requires, and `objectsMutex` is held across the `surfaces` and `contexts` updates in `eglMakeCurrent`. I did not review `Context.cpp`'s GLES state machine beyond the queries above, the glslang path in `Program.cpp`, or the two companion PRs. Written with AI assistance. The import cross-check above was run on my own machine; nothing here was executed.
javierUDP commented 2026-10-19 18:30:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by javierUDP on 2026-10-19T18:30:04Z.

Code review location: core/libs/prx/libScePigletv2VSH/src/Egl.cpp; line 155

@@ -0,0 +1,286 @@
+#include "prx/libScePigletv2VSH/include/Egl.hpp"
+
+#include "SceTypes.hpp"
+#include "prx/libc/include/General.hpp"
+
+#include <algorithm>
+#include <chrono>
+#include <cstring>
+#include <mutex>
+#include <set>
+#include <stdexcept>
+#include <thread>
+
+extern "C" {
+int APS5_VABI sceVideoOutOpen(int userId, int busType, int index, const void* param);
+int APS5_VABI sceVideoOutClose(int handle);
+void APS5_VABI sceVideoOutSetBufferAttribute2(VideoOutBufferAttribute2* attribute, uint64_t pixelFormat, uint32_t tilingMode, uint32_t width, uint32_t height, uint64_t option, uint32_t dccControl, uint64_t dccCbRegisterClearColor);
+int APS5_VABI sceVideoOutRegisterBuffers2(int handle, int setIndex, int bufferIndexStart, const VideoOutBuffers* buffers, int bufferNum, const VideoOutBufferAttribute2* attribute, int category, void* option);
+int APS5_VABI sceVideoOutSubmitFlip(int handle, int index, int flipMode, int64_t flipArg);
+int APS5_VABI sceVideoOutGetFlipStatus(int handle, VideoOutFlipStatus* status);
+}
+
+namespace Piglet {
+
+namespace {
+
+constexpr std::uint64_t PixelFormatR8G8B8A8 = 0x8000000022000000ull;
+constexpr int UserServiceUserIdSystem = 255;
+constexpr int VideoOutBusTypeMain = 0;
+constexpr int VideoOutTilingLinear = 1;
+constexpr int VideoOutFlipModeVsync = 1;
+constexpr int VideoOutFlipModeHsync = 2;
+constexpr std::size_t DisplayAlignment = 65536;
+
+thread_local EGLint lastError = EGL_SUCCESS;
+std::mutex objectsMutex;
+bool initialized = false;
+int displayObject = 0;
+int configObject = 0;
+std::set<WindowSurface*> surfaces;
+std::set<ContextObject*> contexts;
+thread_local ContextObject* currentContext = nullptr;
+EGLint defaultInterval = 1;
+
+EGLBoolean Fail(EGLint code) {
+    lastError = code;
+    return 0;
+}
+
+void* FailHandle(EGLint code) {
+    lastError = code;
+    return nullptr;
+}
+
+EGLBoolean Succeed() {
+    lastError = EGL_SUCCESS;
+    return 1;
+}
+
+bool ValidDisplay(void* display) {
+    if (display != &displayObject) return Fail(EGL_BAD_DISPLAY), false;
+    if (!initialized) return Fail(EGL_NOT_INITIALIZED), false;
+    return true;
+}
+
+void DestroySurfaceNow(WindowSurface* window) {
+    auto& device = Device::Get();
+    if (window->surface.framebuffer) device.vkDestroyFramebuffer(device.device, window->surface.framebuffer, nullptr);
+    device.DestroyImage(window->surface.color);
+    device.DestroyBuffer(window->surface.readback);
+    if (window->videoOut >= 0) sceVideoOutClose(window->videoOut);
+    surfaces.erase(window);
+    delete window;
+}
+
+}
+
+void* EglGetDisplay(void* native) {
+    static_cast<void>(native);
+    lastError = EGL_SUCCESS;
+    return &displayObject;
+}
+
+EGLBoolean EglInitialize(void* display, EGLint* major, EGLint* minor) {
+    if (display != &displayObject) return Fail(EGL_BAD_DISPLAY);
+    initialized = true;
+    if (major) *major = 1;
+    if (minor) *minor = 4;
+    return Succeed();
+}
+
+EGLBoolean EglTerminate(void* display) {
+    if (display != &displayObject) return Fail(EGL_BAD_DISPLAY);
+    initialized = false;
+    return Succeed();
+}
+
+EGLBoolean EglBindAPI(EGLenum api) {
+    if (api != EGL_OPENGL_ES_API) return Fail(EGL_BAD_PARAMETER);
+    return Succeed();
+}
+
+EGLBoolean EglChooseConfig(void* display, const EGLint* attributes, void** configs, EGLint size, EGLint* count) {
+    if (!ValidDisplay(display)) return 0;
+    if (!count) return Fail(EGL_BAD_PARAMETER);
+    bool matches = true;
+    for (const EGLint* attribute = attributes; attribute && *attribute != EGL_NONE; attribute += 2) {
+        const EGLint value = attribute[1];
+        switch (attribute[0]) {
+            case EGL_RED_SIZE:
+            case EGL_GREEN_SIZE:
+            case EGL_BLUE_SIZE:
+            case EGL_ALPHA_SIZE: matches = matches && value <= 8; break;
+            case EGL_DEPTH_SIZE:
+            case EGL_STENCIL_SIZE:
+            case EGL_SAMPLE_BUFFERS:
+            case EGL_SAMPLES: matches = matches && value <= 0; break;
+            case EGL_RENDERABLE_TYPE: matches = matches && (value & ~EGL_OPENGL_ES2_BIT) == 0; break;
+            case EGL_SURFACE_TYPE: matches = matches && (value & ~EGL_WINDOW_BIT) == 0; break;
+            default: throw std::runtime_error("eglChooseConfig: attribute " + std::to_string(attribute[0]) + " is not implemented");
+        }
+    }
+    *count = matches ? 1 : 0;
+    if (configs && matches && size > 0) configs[0] = &configObject;
+    return Succeed();
+}
+
+void* EglCreateWindowSurface(void* display, void* config, const NativeWindow* window, const EGLint* attributes) {
+    if (!ValidDisplay(display)) return nullptr;
+    if (config != &configObject) return FailHandle(EGL_BAD_CONFIG);
+    if (!window || window->width == 0 || window->height == 0 || window->width > 16384 || window->height > 16384) return FailHandle(EGL_BAD_NATIVE_WINDOW);
+    for (const EGLint* attribute = attributes; attribute && *attribute != EGL_NONE; attribute += 2) {
+        if (attribute[0] != EGL_RENDER_BUFFER) throw std::runtime_error("eglCreateWindowSurface: attribute " + std::to_string(attribute[0]) + " is not implemented");
+        if (attribute[1] != EGL_BACK_BUFFER) throw std::runtime_error("eglCreateWindowSurface: single-buffered surfaces are not implemented");
+    }
+    auto& device = Device::Get();
+    auto created = std::make_unique<WindowSurface>();
+    created->interval = defaultInterval;
+    auto& surface = created->surface;
+    surface.width = window->width;
+    surface.height = window->height;
+    surface.color = device.CreateImage(surface.width, surface.height, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT);
+    const VkDeviceSize bytes = static_cast<VkDeviceSize>(surface.width) * surface.height * 4;
+    surface.readback = device.CreateBuffer(bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true);
+    VkFramebufferCreateInfo framebuffer{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};
+    framebuffer.renderPass = ColorRenderPass();
+    framebuffer.attachmentCount = 1;
+    framebuffer.pAttachments = &surface.color.view;
+    framebuffer.width = surface.width;
+    framebuffer.height = surface.height;
+    framebuffer.layers = 1;
+    Check(device.vkCreateFramebuffer(device.device, &framebuffer, nullptr, &surface.framebuffer), "vkCreateFramebuffer");
+
+    created->videoOut = sceVideoOutOpen(UserServiceUserIdSystem, VideoOutBusTypeMain, 0, nullptr);
+    if (created->videoOut < 0) throw std::runtime_error("eglCreateWindowSurface: sceVideoOutOpen failed");

This throw, the one below it and the Check on vkCreateFramebuffer all run after the colour image, the readback buffer and the framebuffer exist, and Image/Buffer have no destructor, so unwinding here drops those handles. A second window surface created while the first is open reaches it through sceVideoOutOpen.

<!-- greyfinch-sync:boykopovar/AnyPS5:review-comment:4317371221 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#discussion_r4317371221). Originally posted by [javierUDP](https://github.com/javierUDP) on 2026-10-19T18:30:04Z. **Code review location:** `core/libs/prx/libScePigletv2VSH/src/Egl.cpp`; line 155 ~~~~diff @@ -0,0 +1,286 @@ +#include "prx/libScePigletv2VSH/include/Egl.hpp" + +#include "SceTypes.hpp" +#include "prx/libc/include/General.hpp" + +#include <algorithm> +#include <chrono> +#include <cstring> +#include <mutex> +#include <set> +#include <stdexcept> +#include <thread> + +extern "C" { +int APS5_VABI sceVideoOutOpen(int userId, int busType, int index, const void* param); +int APS5_VABI sceVideoOutClose(int handle); +void APS5_VABI sceVideoOutSetBufferAttribute2(VideoOutBufferAttribute2* attribute, uint64_t pixelFormat, uint32_t tilingMode, uint32_t width, uint32_t height, uint64_t option, uint32_t dccControl, uint64_t dccCbRegisterClearColor); +int APS5_VABI sceVideoOutRegisterBuffers2(int handle, int setIndex, int bufferIndexStart, const VideoOutBuffers* buffers, int bufferNum, const VideoOutBufferAttribute2* attribute, int category, void* option); +int APS5_VABI sceVideoOutSubmitFlip(int handle, int index, int flipMode, int64_t flipArg); +int APS5_VABI sceVideoOutGetFlipStatus(int handle, VideoOutFlipStatus* status); +} + +namespace Piglet { + +namespace { + +constexpr std::uint64_t PixelFormatR8G8B8A8 = 0x8000000022000000ull; +constexpr int UserServiceUserIdSystem = 255; +constexpr int VideoOutBusTypeMain = 0; +constexpr int VideoOutTilingLinear = 1; +constexpr int VideoOutFlipModeVsync = 1; +constexpr int VideoOutFlipModeHsync = 2; +constexpr std::size_t DisplayAlignment = 65536; + +thread_local EGLint lastError = EGL_SUCCESS; +std::mutex objectsMutex; +bool initialized = false; +int displayObject = 0; +int configObject = 0; +std::set<WindowSurface*> surfaces; +std::set<ContextObject*> contexts; +thread_local ContextObject* currentContext = nullptr; +EGLint defaultInterval = 1; + +EGLBoolean Fail(EGLint code) { + lastError = code; + return 0; +} + +void* FailHandle(EGLint code) { + lastError = code; + return nullptr; +} + +EGLBoolean Succeed() { + lastError = EGL_SUCCESS; + return 1; +} + +bool ValidDisplay(void* display) { + if (display != &displayObject) return Fail(EGL_BAD_DISPLAY), false; + if (!initialized) return Fail(EGL_NOT_INITIALIZED), false; + return true; +} + +void DestroySurfaceNow(WindowSurface* window) { + auto& device = Device::Get(); + if (window->surface.framebuffer) device.vkDestroyFramebuffer(device.device, window->surface.framebuffer, nullptr); + device.DestroyImage(window->surface.color); + device.DestroyBuffer(window->surface.readback); + if (window->videoOut >= 0) sceVideoOutClose(window->videoOut); + surfaces.erase(window); + delete window; +} + +} + +void* EglGetDisplay(void* native) { + static_cast<void>(native); + lastError = EGL_SUCCESS; + return &displayObject; +} + +EGLBoolean EglInitialize(void* display, EGLint* major, EGLint* minor) { + if (display != &displayObject) return Fail(EGL_BAD_DISPLAY); + initialized = true; + if (major) *major = 1; + if (minor) *minor = 4; + return Succeed(); +} + +EGLBoolean EglTerminate(void* display) { + if (display != &displayObject) return Fail(EGL_BAD_DISPLAY); + initialized = false; + return Succeed(); +} + +EGLBoolean EglBindAPI(EGLenum api) { + if (api != EGL_OPENGL_ES_API) return Fail(EGL_BAD_PARAMETER); + return Succeed(); +} + +EGLBoolean EglChooseConfig(void* display, const EGLint* attributes, void** configs, EGLint size, EGLint* count) { + if (!ValidDisplay(display)) return 0; + if (!count) return Fail(EGL_BAD_PARAMETER); + bool matches = true; + for (const EGLint* attribute = attributes; attribute && *attribute != EGL_NONE; attribute += 2) { + const EGLint value = attribute[1]; + switch (attribute[0]) { + case EGL_RED_SIZE: + case EGL_GREEN_SIZE: + case EGL_BLUE_SIZE: + case EGL_ALPHA_SIZE: matches = matches && value <= 8; break; + case EGL_DEPTH_SIZE: + case EGL_STENCIL_SIZE: + case EGL_SAMPLE_BUFFERS: + case EGL_SAMPLES: matches = matches && value <= 0; break; + case EGL_RENDERABLE_TYPE: matches = matches && (value & ~EGL_OPENGL_ES2_BIT) == 0; break; + case EGL_SURFACE_TYPE: matches = matches && (value & ~EGL_WINDOW_BIT) == 0; break; + default: throw std::runtime_error("eglChooseConfig: attribute " + std::to_string(attribute[0]) + " is not implemented"); + } + } + *count = matches ? 1 : 0; + if (configs && matches && size > 0) configs[0] = &configObject; + return Succeed(); +} + +void* EglCreateWindowSurface(void* display, void* config, const NativeWindow* window, const EGLint* attributes) { + if (!ValidDisplay(display)) return nullptr; + if (config != &configObject) return FailHandle(EGL_BAD_CONFIG); + if (!window || window->width == 0 || window->height == 0 || window->width > 16384 || window->height > 16384) return FailHandle(EGL_BAD_NATIVE_WINDOW); + for (const EGLint* attribute = attributes; attribute && *attribute != EGL_NONE; attribute += 2) { + if (attribute[0] != EGL_RENDER_BUFFER) throw std::runtime_error("eglCreateWindowSurface: attribute " + std::to_string(attribute[0]) + " is not implemented"); + if (attribute[1] != EGL_BACK_BUFFER) throw std::runtime_error("eglCreateWindowSurface: single-buffered surfaces are not implemented"); + } + auto& device = Device::Get(); + auto created = std::make_unique<WindowSurface>(); + created->interval = defaultInterval; + auto& surface = created->surface; + surface.width = window->width; + surface.height = window->height; + surface.color = device.CreateImage(surface.width, surface.height, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT); + const VkDeviceSize bytes = static_cast<VkDeviceSize>(surface.width) * surface.height * 4; + surface.readback = device.CreateBuffer(bytes, VK_BUFFER_USAGE_TRANSFER_DST_BIT, true); + VkFramebufferCreateInfo framebuffer{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; + framebuffer.renderPass = ColorRenderPass(); + framebuffer.attachmentCount = 1; + framebuffer.pAttachments = &surface.color.view; + framebuffer.width = surface.width; + framebuffer.height = surface.height; + framebuffer.layers = 1; + Check(device.vkCreateFramebuffer(device.device, &framebuffer, nullptr, &surface.framebuffer), "vkCreateFramebuffer"); + + created->videoOut = sceVideoOutOpen(UserServiceUserIdSystem, VideoOutBusTypeMain, 0, nullptr); + if (created->videoOut < 0) throw std::runtime_error("eglCreateWindowSurface: sceVideoOutOpen failed"); ~~~~ --- This throw, the one below it and the `Check` on `vkCreateFramebuffer` all run after the colour image, the readback buffer and the framebuffer exist, and `Image`/`Buffer` have no destructor, so unwinding here drops those handles. A second window surface created while the first is open reaches it through `sceVideoOutOpen`.
oneandonlydean commented 2026-10-20 17:27:15 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by oneandonlydean on 2026-10-20T17:27:15Z.


Thanks, this builds and both guest tests pass for us on current main (NVIDIA, Linux).

One change before merge, the same point javierUDP raised: in EglCreateWindowSurface (Egl.cpp), the colour image, readback buffer and framebuffer are created before three calls that can throw (vkCreateFramebuffer at :152, sceVideoOutOpen at :155, sceVideoOutRegisterBuffers2 at :165). WindowSurface has no destructor, so when created goes out of scope on a throw those Vulkan objects leak, and after a sceVideoOutRegisterBuffers2 failure the VideoOut port stays open, so every later attempt fails at sceVideoOutOpen. Could you release them on those paths, for example by giving WindowSurface a destructor that does what DestroySurfaceNow does (and having DestroySurfaceNow rely on it)?

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6296967110 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#issuecomment-6296967110). Originally posted by [oneandonlydean](https://github.com/oneandonlydean) on 2026-10-20T17:27:15Z. --- Thanks, this builds and both guest tests pass for us on current main (NVIDIA, Linux). One change before merge, the same point javierUDP raised: in `EglCreateWindowSurface` (Egl.cpp), the colour image, readback buffer and framebuffer are created before three calls that can throw (`vkCreateFramebuffer` at :152, `sceVideoOutOpen` at :155, `sceVideoOutRegisterBuffers2` at :165). `WindowSurface` has no destructor, so when `created` goes out of scope on a throw those Vulkan objects leak, and after a `sceVideoOutRegisterBuffers2` failure the VideoOut port stays open, so every later attempt fails at `sceVideoOutOpen`. Could you release them on those paths, for example by giving `WindowSurface` a destructor that does what `DestroySurfaceNow` does (and having `DestroySurfaceNow` rely on it)?
nikowolf123 commented 2026-10-20 20:40:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by nikowolf123 on 2026-10-20T20:40:22Z.


There are four more problems besides the eglCreateWindowSurface error-path leak already raised.

1. eglDestroyContext frees none of the context's Vulkan objects. Context has no destructor (Context.hpp#L87). Image, Buffer and Program hold raw handles, so delete target (Egl.cpp#L272) and delete previous in eglMakeCurrent (Egl.cpp#L206) free only the containers. Each destroyed context leaks:

  • its command buffer and the 1x1 incomplete image
  • its 4 MiB vertex and uniform ring chunks
  • its descriptor pools, pipelines and samplers
  • every texture and program still alive

A title that repeats eglCreateContext, eglMakeCurrent, one texmap glDrawArrays, eglSwapBuffers, eglMakeCurrent(EGL_NO_CONTEXT) and eglDestroyContext loses at least 8 MiB of host-visible memory and three VkDeviceMemory allocations per round, until an allocation fails. Device::Submit waits on its fence, so a destructor can free everything directly. vkFreeCommandBuffers and vkDestroyDescriptorPool have to be added to PIGLET_DEVICE_FUNCTIONS first:

Context::~Context() {
    for (auto& [name, program] : programs) program->deletePending = true;
    currentProgram = 0;
    ReleasePrograms();
    for (auto& image : retired) device.DestroyImage(image);
    for (auto& [name, texture] : textures) device.DestroyImage(texture.image);
    device.DestroyImage(incomplete.image);
    for (auto& [key, sampler] : samplers) device.vkDestroySampler(device.device, sampler, nullptr);
    for (const auto pool : pools) device.vkDestroyDescriptorPool(device.device, pool, nullptr);
    for (auto* ring : {&vertexRing, &uniformRing})
        for (auto& chunk : ring->chunks) device.DestroyBuffer(chunk);
    device.vkFreeCommandBuffers(device.device, device.pool, 1, &commands);
}

2. eglDestroySurface frees the display buffers while the last flip may still read them. DestroySurfaceNow closes the port, then delete window frees storage, which holds the two buffers registered with sceVideoOutRegisterBuffers2 (Egl.cpp#L71). eglSwapBuffers waits for flipPendingNum == 0 only before its next copy (Egl.cpp#L243), so the last flip is normally still pending when the surface is destroyed.

On current main, processFlip releases the port's mutex after its vblank wait (VideoOutDriver.cpp#L551-L559). It then presents the buffer (L584), which reads a linear buffer through ReadDisplayBuffer (VulkanDevice.cpp#L3128). close() (L381) only sets closing and does not wait for a presentation that is already past that point. flipPendingNum drops only after the read (L615).

So suppose eglSwapBuffers is followed by eglMakeCurrent(EGL_NO_CONTEXT) and eglDestroySurface, and they land after that vblank but before the presenter has read the frame. The presenter then reads a freed block of about 8 MiB at 1920x1080. If the allocator has already given that block back to the system, CheckRange throws or the read faults, and the presentation thread ends the process. Waiting the way eglSwapBuffers does before closing avoids this, and the same order fits the WindowSurface destructor requested above:

if (window->videoOut >= 0) {
    VideoOutFlipStatus status{};
    while (sceVideoOutGetFlipStatus(window->videoOut, &status) >= 0 && status.flipPendingNum != 0)
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    sceVideoOutClose(window->videoOut);
}

3. A 1x1 texture with a mipmap minifying filter samples as incomplete, including with the default GL_NEAREST_MIPMAP_LINEAR. SampledTexture returns incomplete for any mipmap filter, whatever the texture size (Context.cpp#L293). The OpenGL ES 2.0 glTexParameter page says that a w x h texture has floor(log2(max(w, h))) + 1 mipmap levels, and that level floor(log2(max(w, h))) is the final 1x1 mipmap (es2.0/glTexParameter.xml#L161-L310). It returns (0, 0, 0, 1) only when "there are fewer texture images defined than are needed" (L548-L557). For a 1x1 texture, level 0 is the whole chain, so the texture is complete.

Example: create a white 1x1 GL_RGBA texture with glTexImage2D, call no glTexParameteri, and draw with texmap. OpenGL ES draws white; this draws black. The mipmap frame in guest_piglet uses the 2x2 texture, so it does not cover this case. Fix: change the condition to MipmapFilter(found->second.minFilter) && (found->second.width > 1 || found->second.height > 1).

4. maxLod = 0 makes every sampler use the magnifying filter (Context.cpp#L308). The Vulkan spec note "Mapping of OpenGL to Vulkan Filter Modes" (samplers.adoc#L145-L172) emulates the GL_NEAREST and GL_LINEAR minifying filters with VK_SAMPLER_MIPMAP_MODE_NEAREST, minLod = 0 and maxLod = 0.25. It also says that "using a maxLod of zero would cause magnification to always be performed, and the magFilter to always be used", which only works when the two filters are equal. So GL_TEXTURE_MIN_FILTER is ignored whenever it differs from the magnifying filter.

Example: set GL_TEXTURE_MIN_FILTER to GL_NEAREST, keep the default GL_TEXTURE_MAG_FILTER (GL_LINEAR), and draw a 64x64 checkerboard of single black and white texels into a 16x16 quad. OpenGL ES returns single texels (0 or 255); this blends neighbouring texels into grey. guest_piglet sets both filters to GL_NEAREST, so it cannot catch this. Fix: info.maxLod = 0.25f;.

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6300993559 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#issuecomment-6300993559). Originally posted by [nikowolf123](https://github.com/nikowolf123) on 2026-10-20T20:40:22Z. --- There are four more problems besides the `eglCreateWindowSurface` error-path leak already raised. **1. `eglDestroyContext` frees none of the context's Vulkan objects.** `Context` has no destructor ([Context.hpp#L87](https://github.com/boykopovar/AnyPS5/blob/e983d881f40551228f63c09353083daf2905dae6/core/libs/prx/libScePigletv2VSH/include/Context.hpp#L87)). `Image`, `Buffer` and `Program` hold raw handles, so `delete target` ([Egl.cpp#L272](https://github.com/boykopovar/AnyPS5/blob/e983d881f40551228f63c09353083daf2905dae6/core/libs/prx/libScePigletv2VSH/src/Egl.cpp#L272)) and `delete previous` in `eglMakeCurrent` ([Egl.cpp#L206](https://github.com/boykopovar/AnyPS5/blob/e983d881f40551228f63c09353083daf2905dae6/core/libs/prx/libScePigletv2VSH/src/Egl.cpp#L206)) free only the containers. Each destroyed context leaks: - its command buffer and the 1x1 `incomplete` image - its 4 MiB vertex and uniform ring chunks - its descriptor pools, pipelines and samplers - every texture and program still alive A title that repeats `eglCreateContext`, `eglMakeCurrent`, one texmap `glDrawArrays`, `eglSwapBuffers`, `eglMakeCurrent(EGL_NO_CONTEXT)` and `eglDestroyContext` loses at least 8 MiB of host-visible memory and three `VkDeviceMemory` allocations per round, until an allocation fails. `Device::Submit` waits on its fence, so a destructor can free everything directly. `vkFreeCommandBuffers` and `vkDestroyDescriptorPool` have to be added to `PIGLET_DEVICE_FUNCTIONS` first: ```cpp Context::~Context() { for (auto& [name, program] : programs) program->deletePending = true; currentProgram = 0; ReleasePrograms(); for (auto& image : retired) device.DestroyImage(image); for (auto& [name, texture] : textures) device.DestroyImage(texture.image); device.DestroyImage(incomplete.image); for (auto& [key, sampler] : samplers) device.vkDestroySampler(device.device, sampler, nullptr); for (const auto pool : pools) device.vkDestroyDescriptorPool(device.device, pool, nullptr); for (auto* ring : {&vertexRing, &uniformRing}) for (auto& chunk : ring->chunks) device.DestroyBuffer(chunk); device.vkFreeCommandBuffers(device.device, device.pool, 1, &commands); } ``` **2. `eglDestroySurface` frees the display buffers while the last flip may still read them.** `DestroySurfaceNow` closes the port, then `delete window` frees `storage`, which holds the two buffers registered with `sceVideoOutRegisterBuffers2` ([Egl.cpp#L71](https://github.com/boykopovar/AnyPS5/blob/e983d881f40551228f63c09353083daf2905dae6/core/libs/prx/libScePigletv2VSH/src/Egl.cpp#L71)). `eglSwapBuffers` waits for `flipPendingNum == 0` only before its next copy ([Egl.cpp#L243](https://github.com/boykopovar/AnyPS5/blob/e983d881f40551228f63c09353083daf2905dae6/core/libs/prx/libScePigletv2VSH/src/Egl.cpp#L243)), so the last flip is normally still pending when the surface is destroyed. On current main, `processFlip` releases the port's mutex after its vblank wait ([VideoOutDriver.cpp#L551-L559](https://github.com/boykopovar/AnyPS5/blob/9a97ac784da5d40cc7b7d968898ffbf5b8b5377a/core/libs/prx/libSceVideoOut/src/VideoOutDriver.cpp#L551-L559)). It then presents the buffer ([L584](https://github.com/boykopovar/AnyPS5/blob/9a97ac784da5d40cc7b7d968898ffbf5b8b5377a/core/libs/prx/libSceVideoOut/src/VideoOutDriver.cpp#L584)), which reads a linear buffer through `ReadDisplayBuffer` ([VulkanDevice.cpp#L3128](https://github.com/boykopovar/AnyPS5/blob/9a97ac784da5d40cc7b7d968898ffbf5b8b5377a/core/libs/prx/libSceAgcDriver/Execution/src/VulkanDevice.cpp#L3128)). `close()` ([L381](https://github.com/boykopovar/AnyPS5/blob/9a97ac784da5d40cc7b7d968898ffbf5b8b5377a/core/libs/prx/libSceVideoOut/src/VideoOutDriver.cpp#L381)) only sets `closing` and does not wait for a presentation that is already past that point. `flipPendingNum` drops only after the read ([L615](https://github.com/boykopovar/AnyPS5/blob/9a97ac784da5d40cc7b7d968898ffbf5b8b5377a/core/libs/prx/libSceVideoOut/src/VideoOutDriver.cpp#L615)). So suppose `eglSwapBuffers` is followed by `eglMakeCurrent(EGL_NO_CONTEXT)` and `eglDestroySurface`, and they land after that vblank but before the presenter has read the frame. The presenter then reads a freed block of about 8 MiB at 1920x1080. If the allocator has already given that block back to the system, `CheckRange` throws or the read faults, and the presentation thread ends the process. Waiting the way `eglSwapBuffers` does before closing avoids this, and the same order fits the `WindowSurface` destructor requested above: ```cpp if (window->videoOut >= 0) { VideoOutFlipStatus status{}; while (sceVideoOutGetFlipStatus(window->videoOut, &status) >= 0 && status.flipPendingNum != 0) std::this_thread::sleep_for(std::chrono::milliseconds(1)); sceVideoOutClose(window->videoOut); } ``` **3. A 1x1 texture with a mipmap minifying filter samples as incomplete, including with the default `GL_NEAREST_MIPMAP_LINEAR`.** `SampledTexture` returns `incomplete` for any mipmap filter, whatever the texture size ([Context.cpp#L293](https://github.com/boykopovar/AnyPS5/blob/e983d881f40551228f63c09353083daf2905dae6/core/libs/prx/libScePigletv2VSH/src/Context.cpp#L293)). The OpenGL ES 2.0 `glTexParameter` page says that a w x h texture has floor(log2(max(w, h))) + 1 mipmap levels, and that level floor(log2(max(w, h))) is the final 1x1 mipmap ([es2.0/glTexParameter.xml#L161-L310](https://github.com/KhronosGroup/OpenGL-Refpages/blob/a654c649a26064afadb94ff40c6292c86ad76d4b/es2.0/glTexParameter.xml?plain=1#L161-L310)). It returns (0, 0, 0, 1) only when "there are fewer texture images defined than are needed" ([L548-L557](https://github.com/KhronosGroup/OpenGL-Refpages/blob/a654c649a26064afadb94ff40c6292c86ad76d4b/es2.0/glTexParameter.xml?plain=1#L548-L557)). For a 1x1 texture, level 0 is the whole chain, so the texture is complete. Example: create a white 1x1 `GL_RGBA` texture with `glTexImage2D`, call no `glTexParameteri`, and draw with texmap. OpenGL ES draws white; this draws black. The mipmap frame in `guest_piglet` uses the 2x2 texture, so it does not cover this case. Fix: change the condition to `MipmapFilter(found->second.minFilter) && (found->second.width > 1 || found->second.height > 1)`. **4. `maxLod = 0` makes every sampler use the magnifying filter** ([Context.cpp#L308](https://github.com/boykopovar/AnyPS5/blob/e983d881f40551228f63c09353083daf2905dae6/core/libs/prx/libScePigletv2VSH/src/Context.cpp#L308)). The Vulkan spec note "Mapping of OpenGL to Vulkan Filter Modes" ([samplers.adoc#L145-L172](https://github.com/KhronosGroup/Vulkan-Docs/blob/8c9361ba8180c1f4164c0bf79de2f6e817770b0d/chapters/samplers.adoc?plain=1#L145-L172)) emulates the `GL_NEAREST` and `GL_LINEAR` minifying filters with `VK_SAMPLER_MIPMAP_MODE_NEAREST`, `minLod = 0` and `maxLod = 0.25`. It also says that "using a maxLod of zero would cause magnification to always be performed, and the magFilter to always be used", which only works when the two filters are equal. So `GL_TEXTURE_MIN_FILTER` is ignored whenever it differs from the magnifying filter. Example: set `GL_TEXTURE_MIN_FILTER` to `GL_NEAREST`, keep the default `GL_TEXTURE_MAG_FILTER` (`GL_LINEAR`), and draw a 64x64 checkerboard of single black and white texels into a 16x16 quad. OpenGL ES returns single texels (0 or 255); this blends neighbouring texels into grey. `guest_piglet` sets both filters to `GL_NEAREST`, so it cannot catch this. Fix: `info.maxLod = 0.25f;`.
Get-fix commented 2026-10-21 21:51:22 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by Get-fix on 2026-10-21T21:51:22Z.


Thanks @oneandonlydean, @nikowolf123 and @javierUDP. All five points are fixed in Get-fix/AnyPS5@95b1f0029, and the branch is rebased onto main cecb540a6 (#6520 with it, since this one stacks on it):

  1. eglCreateWindowSurface error paths. WindowSurface now has the destructor DestroySurfaceNow used to open-code: it releases the framebuffer, color image and readback buffer, and closes the VideoOut port. A throw from vkCreateFramebuffer, sceVideoOutOpen or sceVideoOutRegisterBuffers2 no longer leaks them, and the port no longer stays open after a failed registration. DestroySurfaceNow now just erases and deletes.
  2. eglDestroyContext. Context has a destructor that releases its programs and pipelines, retired and live textures, the incomplete texture, samplers, descriptor pools, ring chunks and its command buffer (vkDestroyDescriptorPool and vkFreeCommandBuffers added to PIGLET_DEVICE_FUNCTIONS).
  3. eglDestroySurface during the last flip. The surface destructor waits until flipPendingNum is 0 before sceVideoOutClose, so the display buffers are freed only after the presenter has read them.
  4. 1x1 textures with a mipmap filter are complete; only larger textures with a mipmap minifying filter sample as incomplete.
  5. maxLod is 0.25, so GL_TEXTURE_MIN_FILTER applies when it differs from the magnifying filter.

guest_piglet gains a 1x1 white texture drawn with the default GL_NEAREST_MIPMAP_LINEAR (white, not black), a 64x64 checkerboard minified 4:1 with GL_NEAREST and the default GL_LINEAR magnifying filter (only 0 or 255, no grey), and a second context created and destroyed while the first keeps drawing. Reverting fix 4 fails the test at the white texture, and reverting fix 5 at the checkerboard. On main cecb540a6 with this branch, guest_piglet and guest_precompiled_shaders pass on Windows 11 with an RTX 5060 Ti (610.88), and check_conventions.py passes for both branches. The long debt entry is split into three, each under 1000 characters.

AI-assisted: yes (Claude Code)

🤖 Generated with Claude Code

<!-- greyfinch-sync:boykopovar/AnyPS5:comment:6327346715 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#issuecomment-6327346715). Originally posted by [Get-fix](https://github.com/Get-fix) on 2026-10-21T21:51:22Z. --- Thanks @oneandonlydean, @nikowolf123 and @javierUDP. All five points are fixed in Get-fix/AnyPS5@95b1f0029, and the branch is rebased onto `main` cecb540a6 (#6520 with it, since this one stacks on it): 1. **`eglCreateWindowSurface` error paths.** `WindowSurface` now has the destructor `DestroySurfaceNow` used to open-code: it releases the framebuffer, color image and readback buffer, and closes the VideoOut port. A throw from `vkCreateFramebuffer`, `sceVideoOutOpen` or `sceVideoOutRegisterBuffers2` no longer leaks them, and the port no longer stays open after a failed registration. `DestroySurfaceNow` now just erases and deletes. 2. **`eglDestroyContext`.** `Context` has a destructor that releases its programs and pipelines, retired and live textures, the incomplete texture, samplers, descriptor pools, ring chunks and its command buffer (`vkDestroyDescriptorPool` and `vkFreeCommandBuffers` added to `PIGLET_DEVICE_FUNCTIONS`). 3. **`eglDestroySurface` during the last flip.** The surface destructor waits until `flipPendingNum` is 0 before `sceVideoOutClose`, so the display buffers are freed only after the presenter has read them. 4. **1x1 textures with a mipmap filter** are complete; only larger textures with a mipmap minifying filter sample as incomplete. 5. **`maxLod`** is 0.25, so `GL_TEXTURE_MIN_FILTER` applies when it differs from the magnifying filter. `guest_piglet` gains a 1x1 white texture drawn with the default `GL_NEAREST_MIPMAP_LINEAR` (white, not black), a 64x64 checkerboard minified 4:1 with `GL_NEAREST` and the default `GL_LINEAR` magnifying filter (only 0 or 255, no grey), and a second context created and destroyed while the first keeps drawing. Reverting fix 4 fails the test at the white texture, and reverting fix 5 at the checkerboard. On `main` cecb540a6 with this branch, `guest_piglet` and `guest_precompiled_shaders` pass on Windows 11 with an RTX 5060 Ti (610.88), and `check_conventions.py` passes for both branches. The long debt entry is split into three, each under 1000 characters. AI-assisted: yes (Claude Code) 🤖 Generated with [Claude Code](https://claude.com/claude-code)
MarcZX10 commented 2026-11-21 03:22:04 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-21T03:22:04Z.

Review: CHANGES_REQUESTED


Reviewed — changes requested

Changes are required before merge: ensure programs with no active uniforms do not attempt to allocate a zero-sized uniform buffer.

What I ran

Reviewed head 95b1f0029a4e0b75e73a87bfcb27d24976df5733 against the prepared diff and read changed source through repo_read.py. No build or tests were run; test results in the description are author-reported.

Results

Check Result Note
Changed code review failed One concrete crash path found
Build and tests not run No execution performed
Manifest coverage passed All listed changed files are included

Findings

Blocking

  • A valid linked program with no active uniforms has no default uniform block, so uniformBinding remains -1 and uniformData remains empty. DrawArrays still calls Allocate for a zero-sized uniform buffer when that binding is present; Allocate then creates a buffer of at least 4 MiB and copies zero bytes, but later writes a descriptor with range zero. Vulkan requires a nonzero uniform buffer descriptor range, so drawing with such a program reaches invalid descriptor state and can fail validation or rendering. Skip the uniform buffer allocation and descriptor write when the block size is zero, or otherwise ensure a valid nonzero range. See core/libs/prx/libScePigletv2VSH/src/Context.cpp:1559.

Non-blocking

None.

Not verified

No build, tests, or hardware execution were performed. The description reports Windows tests and sample execution, but those results were not independently verified. Linux and macOS behavior was not tested according to the description. I read the prepared description, commits, manifest and diff, plus the changed Piglet EGL, context, shader program, Vulkan, and guest test code; all 16 manifest-listed files are included, but the full text of every changed file was not read. The excluded-file list was unavailable in the prepared bundle.

To get this to a good state

Guard uniform buffer descriptor allocation when no uniform block exists, then rerun the relevant guest Piglet test and build checks on the updated head.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6002520363 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/6521#pullrequestreview-6002520363). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-21T03:22:04Z. **Review:** CHANGES_REQUESTED --- # Reviewed — changes requested Changes are required before merge: ensure programs with no active uniforms do not attempt to allocate a zero-sized uniform buffer. ## What I ran Reviewed head `95b1f0029a4e0b75e73a87bfcb27d24976df5733` against the prepared diff and read changed source through `repo_read.py`. No build or tests were run; test results in the description are author-reported. ## Results | Check | Result | Note | |---|---|---| | Changed code review | failed | One concrete crash path found | | Build and tests | not run | No execution performed | | Manifest coverage | passed | All listed changed files are included | ## Findings ### Blocking - A valid linked program with no active uniforms has no default uniform block, so `uniformBinding` remains `-1` and `uniformData` remains empty. `DrawArrays` still calls `Allocate` for a zero-sized uniform buffer when that binding is present; `Allocate` then creates a buffer of at least 4 MiB and copies zero bytes, but later writes a descriptor with range zero. Vulkan requires a nonzero uniform buffer descriptor range, so drawing with such a program reaches invalid descriptor state and can fail validation or rendering. Skip the uniform buffer allocation and descriptor write when the block size is zero, or otherwise ensure a valid nonzero range. See `core/libs/prx/libScePigletv2VSH/src/Context.cpp:1559`. ### Non-blocking None. ## Not verified No build, tests, or hardware execution were performed. The description reports Windows tests and sample execution, but those results were not independently verified. Linux and macOS behavior was not tested according to the description. I read the prepared description, commits, manifest and diff, plus the changed Piglet EGL, context, shader program, Vulkan, and guest test code; all 16 manifest-listed files are included, but the full text of every changed file was not read. The excluded-file list was unavailable in the prepared bundle. ## To get this to a good state Guard uniform buffer descriptor allocation when no uniform block exists, then rerun the relevant guest Piglet test and build checks on the updated head.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/6521:upstream-pr/6521'
git switch 'upstream-pr/6521'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'main'
git merge --no-ff 'upstream-pr/6521'
git switch 'upstream-pr/6521'
git rebase 'main'
git switch 'main'
git merge --ff-only 'upstream-pr/6521'
git switch 'upstream-pr/6521'
git rebase 'main'
git switch 'main'
git merge --no-ff 'upstream-pr/6521'
git switch 'main'
git merge --squash 'upstream-pr/6521'
git switch 'main'
git merge --ff-only 'upstream-pr/6521'
git switch 'main'
git merge 'upstream-pr/6521'
git push origin 'main'
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!6521
No description provided.