Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions docs/framebuffer-copy-bounds.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# Quantized GX display-copy bounds

The standard 480-line AA presets use a 242-line EFB. In the pinned libogc2
toolchain, `GX_GetYScaleFactor(242,480)` returns `1.98760330677` and
`GX_GetNumXfbLines` reports **483** copied rows. A normal
`SYS_AllocateFramebuffer` request for the VI mode reserves only 480 rows.
At a 640-pixel padded stride and two bytes per XFB pixel, that leaves a
**3,840-byte overrun** on each affected copy.

The shared allocation helper queries the actual library's quantized copy
height, then allocates `max(VI rows, copied rows)`. Only the temporary storage
mode changes. The VI mode, EFB dimensions, stride, sample pattern and presented
480-line output remain intact. Both initialization and display transitions use
the helper. Transitions retain the existing allocate-both-before-publication
behavior and preserve the current buffers if either replacement allocation fails.

## Verification

The complete native host suite passes in its strict debug and shipped O3/LTO
configurations. The display fixture covers older libogc's 483-row result, a
479-row result from another quantizer, padded strides, ordinary 240/480/576
modes, unchanged VI metadata and both transactional allocation failures.

The optional PowerPC fixture in `tests/framebuffer_canary_gamecube.c` includes
the production helper. Its wrapped allocator reserves a separate 20 KiB red
zone, allowing an unsafe control copy to be observed without corrupting the
heap. The source EFB is cleared to black, so every copied YUYV byte differs
from the red-zone sentinel.

Using the exact pinned toolchain image
`ghcr.io/extremscorner/libogc2@sha256:13bb658d3f18903816617223f5d7c6f776d3db3ea806aae67f8d35a7a69d4c85`,
the fixture ran in Dolphin 2503 / OpenGL with XFB-to-RAM copies, emulator AA
and postprocessing disabled. The measured legacy 480i-AA and 480p-AA controls
both wrote 618,240 bytes into a claimed 614,400-byte framebuffer, changing all
3,840 bytes of the adjacent red zone. The helper requested 618,240 bytes and
both copies left its red zone intact.

| Native copy | Storage rows | Claimed bytes | Written bytes | Red-zone changes |
| --- | ---: | ---: | ---: | ---: |
| 480i AA, legacy | 480 | 614400 | 618240 | 3840 |
| 480p AA, legacy | 480 | 614400 | 618240 | 3840 |
| 480i/p AA, helper | 483 | 618240 | 618240 | 0 |
| Return from 576p to 480p AA | 483 | 618240 | 618240 | 0 |

All twelve cases completed: 240p, non-AA 480i/p, unsafe and protected 480i/p AA,
576i/p, return to 480p AA, 240p AA and a safe 480i return. Every protected copy
stayed within its allocation. This establishes actual emulator GX-copy bounds;
it is not physical-console qualification or proof of visual AA quality.
The [complete result and provenance](framebuffer-copy-bounds/native-canary.json)
include all twelve cases and hashes of the fixture, production helper, binaries
and original row readback.

## Reproduction

Run the host regression suite, including debug and O3/LTO assertions:

```sh
python3 scripts/ci_test_suite.py native
```

Use devkitPPC and libogc2 with the SDK's generated EXI overlay. The overlay is
needed for this pinned environment's pre-main RTC read; it does not replace
the GX math or copy implementation. Set `DND_EXI_OVERLAY` to the generated
`build/exi-overlay` directory, then build a matching DOL/ELF pair:

```sh
powerpc-eabi-gcc -g -O2 -Wall -Wextra -Werror -DGEKKO -mogc -mcpu=750 \
-meabi -mhard-float -Iinclude -I"$DEVKITPRO/libogc2/gamecube/include" \
tests/framebuffer_canary_gamecube.c -L"$DND_EXI_OVERLAY" \
-L"$DEVKITPRO/libogc2/gamecube/lib" -Wl,--wrap=SYS_AllocateFramebuffer \
-logc -lm -o /tmp/framebuffer-canary.elf
elf2dol /tmp/framebuffer-canary.elf /tmp/framebuffer-canary.dol
```

With a working X11 display (or Xvfb), run:

```sh
python3 scripts/dolphin_framebuffer_canary.py \
--dol /tmp/framebuffer-canary.dol --elf /tmp/framebuffer-canary.elf \
--logs /tmp/fresh-framebuffer-canary
```

The script records each mode's predicted and allocated rows, last written byte
and changed red-zone bytes in `result.json`, plus the original PowerPC readback
in `rows.bin`. It requires overwritten unsafe controls and intact protected
red zones before reporting success. No firmware or sample assets are required.
159 changes: 159 additions & 0 deletions docs/framebuffer-copy-bounds/native-canary.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
{
"success": true,
"scope": "Native PowerPC fixture; actual Dolphin OpenGL GX_CopyDisp writes, no emulator AA or postprocessing; not physical hardware",
"completion_pc": "0x800038e4",
"legacy_controls_overwrite_red_zone": true,
"production_helper_preserves_red_zone": true,
"rows": [
{
"mode": "240p/helper",
"width": 320,
"efb_rows": 240,
"vi_rows": 240,
"predicted_rows": 240,
"storage_rows": 240,
"claimed_bytes": 153600,
"last_written_byte": 153600,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "480i/helper",
"width": 640,
"efb_rows": 480,
"vi_rows": 480,
"predicted_rows": 480,
"storage_rows": 480,
"claimed_bytes": 614400,
"last_written_byte": 614400,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "480p/helper",
"width": 640,
"efb_rows": 480,
"vi_rows": 480,
"predicted_rows": 480,
"storage_rows": 480,
"claimed_bytes": 614400,
"last_written_byte": 614400,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "480i-AA/legacy",
"width": 640,
"efb_rows": 242,
"vi_rows": 480,
"predicted_rows": 483,
"storage_rows": 480,
"claimed_bytes": 614400,
"last_written_byte": 618240,
"red_zone_changed_bytes": 3840,
"legacy": 1
},
{
"mode": "480i-AA/helper",
"width": 640,
"efb_rows": 242,
"vi_rows": 480,
"predicted_rows": 483,
"storage_rows": 483,
"claimed_bytes": 618240,
"last_written_byte": 618240,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "480p-AA/legacy",
"width": 640,
"efb_rows": 242,
"vi_rows": 480,
"predicted_rows": 483,
"storage_rows": 480,
"claimed_bytes": 614400,
"last_written_byte": 618240,
"red_zone_changed_bytes": 3840,
"legacy": 1
},
{
"mode": "480p-AA/helper",
"width": 640,
"efb_rows": 242,
"vi_rows": 480,
"predicted_rows": 483,
"storage_rows": 483,
"claimed_bytes": 618240,
"last_written_byte": 618240,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "576i/helper",
"width": 640,
"efb_rows": 480,
"vi_rows": 576,
"predicted_rows": 576,
"storage_rows": 576,
"claimed_bytes": 737280,
"last_written_byte": 737280,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "576p/helper",
"width": 640,
"efb_rows": 480,
"vi_rows": 576,
"predicted_rows": 576,
"storage_rows": 576,
"claimed_bytes": 737280,
"last_written_byte": 737280,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "480p-AA/return",
"width": 640,
"efb_rows": 242,
"vi_rows": 480,
"predicted_rows": 483,
"storage_rows": 483,
"claimed_bytes": 618240,
"last_written_byte": 618240,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "240p-AA/helper",
"width": 320,
"efb_rows": 240,
"vi_rows": 240,
"predicted_rows": 240,
"storage_rows": 240,
"claimed_bytes": 153600,
"last_written_byte": 153600,
"red_zone_changed_bytes": 0,
"legacy": 0
},
{
"mode": "480i/safe-return",
"width": 640,
"efb_rows": 480,
"vi_rows": 480,
"predicted_rows": 480,
"storage_rows": 480,
"claimed_bytes": 614400,
"last_written_byte": 614400,
"red_zone_changed_bytes": 0,
"legacy": 0
}
],
"toolchain_image": "ghcr.io/extremscorner/libogc2@sha256:13bb658d3f18903816617223f5d7c6f776d3db3ea806aae67f8d35a7a69d4c85",
"fixture_sha256": "012ec4c1d9d7e4994a9b70f5c2abc79e0cc9c18229be19ffc105ce91eac7c6cf",
"production_helper_sha256": "55ef54883274b223869dab9eb1cc49d6385b46e35676eb3657f78fb8ee8e62fe",
"dol_sha256": "feb99d8670dd80e22b567e805ca28c63fcf34f557cd6dbcf1e8e10c2e47cd6f3",
"elf_sha256": "b2b9be70228896d4b88a6c2986df21d2c080faf559b08df4608843c9c8a5dc8b",
"raw_rows_sha256": "5b89743e4165d711a7e78b61c062264418853075c862b400471da553f47f0977"
}
3 changes: 2 additions & 1 deletion include/dnd_display_gx.inc
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* Included by the GX backend and the isolated display lifecycle fixture.
* mode/xfb/fb/first_frame are the backend's actual presentation state. */
#include "dnd_framebuffer_gx.inc"
static GXRModeObj configured_display_mode;
static int select_display_mode(int resolution,int scan,GXRModeObj *selected) {
if(resolution<0||resolution>3||scan<0||scan>2)return -1;
Expand Down Expand Up @@ -55,7 +56,7 @@ static int configure_display_mode(int resolution,int scan,int aa) {
if(!memcmp(mode,&next,sizeof next))return 0;
/* Allocate both replacements first. An allocation failure cannot destroy
* the current mode or scanout buffers. */
void *a=SYS_AllocateFramebuffer(&next),*b=SYS_AllocateFramebuffer(&next);
void *a=allocate_display_framebuffer(&next),*b=allocate_display_framebuffer(&next);
if(!a||!b){free(a);free(b);return -2;}
GX_DrawDone();
VIDEO_SetBlack(TRUE);VIDEO_Flush();VIDEO_WaitVSync();
Expand Down
13 changes: 13 additions & 0 deletions include/dnd_framebuffer_gx.inc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#ifndef DND_FRAMEBUFFER_GX_INCLUDED
#define DND_FRAMEBUFFER_GX_INCLUDED
/* GX quantizes the vertical copy scale. Some libogc versions copy 483
* rows for the 242-line EFB in a 480-line AA mode. Size storage for that
* extent without changing the VI mode, stride or allocation alignment. */
static void *allocate_display_framebuffer(const GXRModeObj *display) {
GXRModeObj storage=*display;
int copied=GX_GetNumXfbLines(display->efbHeight,
GX_GetYScaleFactor(display->efbHeight,display->xfbHeight));
if(copied>storage.xfbHeight)storage.xfbHeight=copied;
return SYS_AllocateFramebuffer(&storage);
}
#endif
76 changes: 76 additions & 0 deletions scripts/dolphin_framebuffer_canary.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#!/usr/bin/env python3
"""Qualify GX XFB copy bounds using the optional native red-zone fixture.

Build tests/framebuffer_canary_gamecube.c with the SDK EXI overlay and
-Wl,--wrap=SYS_AllocateFramebuffer, preserving a matching DOL/ELF pair.
Run under the repository's Linux Xvfb/Dolphin setup; no original IPL is needed.
This is emulator GPU evidence, not physical-console qualification.
"""
import argparse
import json
from pathlib import Path
import socket
import struct
import subprocess
import time

from dolphin_controller_test import request
from dolphin_gdb_probe import parse_stop_pc


def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--dol',type=Path,required=True)
parser.add_argument('--elf',type=Path,required=True)
parser.add_argument('--logs',type=Path,required=True)
parser.add_argument('--dolphin',default='/usr/games/dolphin-emu-nogui')
parser.add_argument('--port',type=int,default=7176)
args=parser.parse_args()
root=args.logs.resolve()
if root.exists() and any(root.iterdir()):parser.error('Use a fresh log directory')
root.mkdir(parents=True,exist_ok=True);config=root/'user/Config';config.mkdir(parents=True)
(config/'Dolphin.ini').write_text('[Core]\nGFXBackend = OGL\nCPUCore = 1\nCPUThread = False\n[General]\nGDBPort = '+str(args.port)+'\n[Interface]\nDebugModeEnabled = True\n[DSP]\nBackend = No Audio Output\n[Display]\nRenderWindowWidth = 640\nRenderWindowHeight = 480\n')
(config/'GFX.ini').write_text('[Settings]\nInternalResolution = 1\nMSAA = 1\nSSAA = False\n[Enhancements]\nPostProcessingShader = \n[Hacks]\nXFBToTextureEnable = False\nDeferEFBCopies = False\nForceProgressive = False\n')
wanted={'dnd_framebuffer_canary_done','dnd_framebuffer_canary_rows','dnd_framebuffer_canary_stage'};symbols={}
for line in subprocess.check_output(['nm','-a',str(args.elf.resolve())],text=True).splitlines():
parts=line.split()
if len(parts)==3 and parts[2] in wanted:symbols[parts[2]]=int(parts[0],16)
if symbols.keys()!=wanted:raise ValueError('Missing native canary symbols')
log=(root/'emulator.log').open('w')
process=subprocess.Popen([args.dolphin,'--platform','x11','-u',str(root/'user'),'-C','SYSCONF.IPL.PGS=True','-e',str(args.dol.resolve())],stdout=log,stderr=subprocess.STDOUT)
connection=None
try:
deadline=time.monotonic()+30
while time.monotonic()<deadline:
if process.poll() is not None:raise RuntimeError('Dolphin exited; inspect emulator.log')
try:connection=socket.create_connection(('127.0.0.1',args.port),timeout=.3);break
except OSError:time.sleep(.1)
if connection is None:raise TimeoutError('No native canary debugger')
connection.settimeout(60);address=symbols['dnd_framebuffer_canary_done']
if request(connection,f'Z0,{address:x},4')!='OK':raise RuntimeError('Cannot install completion breakpoint')
stop=request(connection,'c',60)
if parse_stop_pc(stop)!=address:raise RuntimeError('Unexpected native completion stop: '+stop)
stage=int(request(connection,f"m{symbols['dnd_framebuffer_canary_stage']:x},4"),16)
if stage!=12:raise RuntimeError('Native canary failed before completion, stage='+hex(stage))
raw=bytes.fromhex(request(connection,f"m{symbols['dnd_framebuffer_canary_rows']:x},{12*36:x}"))
if len(raw)!=12*36:raise ValueError('Incomplete native canary rows')
(root/'rows.bin').write_bytes(raw)
names=['240p/helper','480i/helper','480p/helper','480i-AA/legacy','480i-AA/helper','480p-AA/legacy','480p-AA/helper','576i/helper','576p/helper','480p-AA/return','240p-AA/helper','480i/safe-return']
fields=['width','efb_rows','vi_rows','predicted_rows','storage_rows','claimed_bytes','last_written_byte','red_zone_changed_bytes','legacy']
rows=[dict(mode=name,**dict(zip(fields,struct.unpack_from('>9I',raw,i*36)))) for i,name in enumerate(names)]
# The unsafe controls still have a separately allocated red zone. A
# changed control proves real DMA happened beyond the old claimed size.
controls=all(r['red_zone_changed_bytes']>0 and r['last_written_byte']>r['claimed_bytes'] for r in rows if r['legacy'])
protected=all(r['last_written_byte']>0 and r['last_written_byte']<=r['claimed_bytes'] and r['red_zone_changed_bytes']==0 for r in rows if not r['legacy'])
result={'success':controls and protected,'scope':'Native PowerPC fixture; actual Dolphin OpenGL GX_CopyDisp writes, no emulator AA or postprocessing; not physical hardware','completion_pc':hex(address),'legacy_controls_overwrite_red_zone':controls,'production_helper_preserves_red_zone':protected,'rows':rows}
(root/'result.json').write_text(json.dumps(result,indent=2)+'\n');print(json.dumps(result,indent=2),flush=True)
if not result['success']:raise RuntimeError('Native framebuffer canary failed; inspect result.json')
finally:
if connection is not None:connection.close()
process.terminate()
try:process.wait(timeout=10)
except subprocess.TimeoutExpired:process.kill();process.wait()
log.close()


if __name__=='__main__':main()
3 changes: 2 additions & 1 deletion source/graphics_gx.c
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,12 @@ static uint32_t tint(uint32_t a,uint32_t b) {
static uint32_t rgba(float r,float g,float b,float a) {
return (uint32_t)(r*255)<<24|(uint32_t)(g*255)<<16|(uint32_t)(b*255)<<8|(uint32_t)(a*255);
}
#include "dnd_framebuffer_gx.inc"
void dnd_graphics_init(void) {
if(mode)return;
VIDEO_Init();mode=VIDEO_GetPreferredMode(NULL);
if(!mode){dnd_exception_throw(DND_EXCEPTION_INVALID_OPERATION,"No video mode available.");return;}
void *first=SYS_AllocateFramebuffer(mode),*second=SYS_AllocateFramebuffer(mode);
void *first=allocate_display_framebuffer(mode),*second=allocate_display_framebuffer(mode);
fifo=memalign(32,256*1024);
/* A null allocation must be checked before the K0-to-K1 address alias. */
if(!first||!second||!fifo){free(first);free(second);free(fifo);fifo=NULL;mode=NULL;dnd_exception_throw(DND_EXCEPTION_OUT_OF_MEMORY,"Graphics initialization failed.");return;}
Expand Down
2 changes: 1 addition & 1 deletion tests/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ graphics_phase_two_test: graphics_phase_two_test.c ../source/draw_resources.c
graphics_resource_boundaries_test: graphics_resource_boundaries_test.c ../source/draw_resources.c
$(CC) $(CFLAGS) -ffunction-sections -fdata-sections $^ $(GC_LDFLAGS) -lm -o $@

display_mode_test: mesh_streams_test display_mode_test.c ../include/dnd_display_gx.inc
display_mode_test: mesh_streams_test display_mode_test.c ../include/dnd_display_gx.inc ../include/dnd_framebuffer_gx.inc
$(CC) $(CFLAGS) display_mode_test.c -o $@

.PHONY: system_firmware_native_test
Expand Down
Loading
Loading