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
2 changes: 1 addition & 1 deletion .github/actions/graphics-sdk/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ runs:
name: Resolve graphics SDK cache identity
shell: bash
env:
SDK_INPUTS: ${{ hashFiles('eng/graphics/dependencies.lock.json', 'eng/graphics/windows-runtime.json', 'eng/graphics/build.py', 'eng/graphics/DawnSymbolBoundary.cmake', 'eng/graphics/dawn_exports.py', 'eng/graphics/install-windows-sdk.ps1', '.github/actions/graphics-sdk/action.yml') }}
SDK_INPUTS: ${{ hashFiles('eng/graphics/dependencies.lock.json', 'eng/graphics/windows-runtime.json', 'eng/graphics/build.py', 'eng/graphics/DawnSymbolBoundary.cmake', 'eng/graphics/dawn_exports.py', 'eng/graphics/dawn_native_device.cpp', 'eng/graphics/dawn_native_device_internal.h', 'experiments/WebScene.NativeEngine.Probe/native/graphics/webscene/dawn_native_device.h', 'eng/graphics/install-windows-sdk.ps1', '.github/actions/graphics-sdk/action.yml') }}
run: |
set -euo pipefail
{
Expand Down
43 changes: 43 additions & 0 deletions docs/validation/linux-exact-native-device-hook-646.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Exact Dawn Vulkan device hook

Issue: #646. The pinned Linux Dawn build exports
`websceneDawnQueryVulkanDeviceV1`, a product-neutral C ABI that accepts only a
live `WGPUDevice` created by that build. It returns borrowed opaque
`VkPhysicalDevice`, `VkDevice` and `VkQueue` identities, the graphics queue
family, exact public adapter/device tokens, and Vulkan device/driver UUIDs.

Dawn's existing instance device list is the lifecycle authority. A transient,
pin-specific build patch registers and unregisters devices at the same add/remove
methods. The query checks the registry before dereferencing a token, retains the
device during inspection, holds its guard, and rejects foreign, lost,
non-Vulkan or incomplete identities. SDK verification covers the installed
header, bridge sources, export allowlist and cache inputs. AppScene includes no
Dawn private header.

`bind_dawn_linux_external_device` is the factory consumption point. It copies
the `wgpu::Device` into the lifetime anchor and requires the same shared atomic
loss flag used by the host's Dawn device-lost callback. Allocation, begin,
end and export operations fail closed after loss. Native handles remain
Dawn-owned and borrowed; allocators may use them but never destroy them.

Per the directed checkpoint policy, the authored build and contract gates were
not run. Validation for this change is limited to `git diff --check`.

## Focused follow-up issue draft

**Title:** Implement exact-device Linux Vulkan external-memory allocator

Create the AppScene `dawn_linux_external_device_factory` around a Dawn Vulkan
device bound through `bind_dawn_linux_external_device`. Allocate exportable
opaque-FD and supported DMA-BUF images on the returned exact `VkDevice` and
queue family; retain `VkImage`, memory and create-info chains; export owned
memory and synchronization FDs; and adopt them through
`owned_dawn_linux_external_allocation`. Reject unsupported formats, modifiers,
handle types, queue ownership, UUID mismatches and device loss. Do not accept
ordinary Dawn textures and do not add CPU readback/upload fallback.

Acceptance requires real Linux Vulkan hardware evidence for both supported
handle routes, BeginAccess/EndAccess layout and synchronization rotation,
negative foreign-device and device-loss cases, X11 and Wayland presentation,
resize teardown, a 30-minute FD/residency plateau, and zero CPU transfer in
ordinary frames.
38 changes: 19 additions & 19 deletions docs/validation/linux-external-image-interop-28.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,23 +68,25 @@ provider seam around the pinned public Dawn ABI:
`linux_external_image_provider`. Failed or partial handoffs publish nothing
and RAII closes every already-exported FD.

The installed Dawn C ABI exposes only Vulkan `driverVersion` in
`AdapterPropertiesVk`. The pinned `dawn/native/VulkanBackend.h` adds only
`GetInstance` and `GetInstanceProcAddr`; it exposes no `VkDevice`,
`VkPhysicalDevice`, `VkQueue`, queue family or device/driver UUID, and Dawn's
adapter creates its own `VkDevice` rather than wrapping one supplied by a host.
The implementations that expose these objects live under Dawn's private
`src/dawn/native/vulkan` tree and are not an SDK contract. WebScene therefore
does not infer device identity from the Vulkan instance, adapter properties or
matching UUIDs.
The pinned public Dawn API still has no supported `VkDevice`,
`VkPhysicalDevice`, `VkQueue` or queue-family accessor. The WebScene-owned
Linux Dawn build now adds one narrow, versioned C ABI query at that private/public
boundary. Dawn registers devices on its authoritative `InstanceBase` add/remove
path. The query rejects tokens absent from that live registry before
dereferencing them, rejects lost and non-Vulkan devices, and returns the exact
public adapter/device tokens, borrowed native tuple, queue family and Vulkan
device/driver UUIDs. The SDK ships only `webscene/dawn_native_device.h`; no Dawn
private header crosses into AppScene.

The SDK now exposes `dawn_linux_external_device_factory`. An AppScene host with
an exact-device Dawn integration creates the WebGPU instance/adapter/device and
native allocator atomically, and returns one
`dawn_linux_external_device_lifetime` shared by the allocator and every
allocation. That lifetime carries the exact public `WGPUAdapter`/`WGPUDevice` tokens,
allocation. `bind_dawn_linux_external_device` populates it from the exact Dawn
device and retains a copied `wgpu::Device`. That lifetime carries the exact public `WGPUAdapter`/`WGPUDevice` tokens,
opaque identities for the native device/physical-device/queue, device/driver
UUIDs, Dawn queue family and a host-owned lifetime anchor for that tuple.
UUIDs, Dawn queue family, a host-owned lifetime anchor for that tuple and the
same atomic device-loss state installed in the factory callback.
Provider creation rejects a copied lifetime object, mismatched device token,
UUID or queue family.

Expand Down Expand Up @@ -125,14 +127,12 @@ FD/residency plateau, and proof of zero CPU readback/upload in ordinary frames.

## Remaining concrete blocker

Implement `dawn_linux_external_device_factory` in AppScene against a supported
exact-device Dawn integration. The current pinned public Dawn library cannot do
this by itself, so the host needs a narrowly supported Dawn SDK hook (or an
equivalent host-owned Dawn build) that returns the exact native device,
physical-device, queue and queue family for the created `WGPUDevice`. The host
then allocates/exports opaque-FD or DMA-BUF storage on those handles, adopts it
through `owned_dawn_linux_external_allocation`, and negotiates hardware support
per format, modifier, handle type and synchronization route. Real Linux Vulkan
Implement the AppScene factory's real Vulkan allocator against the exact native
tuple returned by `bind_dawn_linux_external_device`. It must allocate and export
opaque-FD or DMA-BUF storage on those handles, retain every `VkImage` and
`VkDeviceMemory`, adopt it through `owned_dawn_linux_external_allocation`, and
negotiate hardware support per format, modifier, handle type and synchronization
route. Real Linux Vulkan
hardware/driver execution is still required for pixels, negative identity and
layout cases, device loss, FD/residency plateau and zero-readback evidence.
Unsupported routes remain explicit and cannot fall back to CPU presentation
Expand Down
14 changes: 13 additions & 1 deletion eng/graphics/DawnSymbolBoundary.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,23 @@ function(webscene_isolate_dawn)
set_property(TARGET webgpu_dawn_objects PROPERTY ${property} "${definitions}")
endif()
endforeach()
if(UNIX AND NOT APPLE)
# This source is compiled inside Dawn so it can use the pinned private
# types. Consumers receive only its versioned C ABI header.
target_sources(dawn_native_objects PRIVATE
"${CMAKE_CURRENT_FUNCTION_LIST_DIR}/dawn_native_device.cpp")
target_include_directories(dawn_native_objects PRIVATE
"${CMAKE_CURRENT_FUNCTION_LIST_DIR}"
"${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../../experiments/WebScene.NativeEngine.Probe/native/graphics")
target_compile_definitions(dawn_native_objects PRIVATE
WEBSCENE_DAWN_NATIVE_DEVICE_BRIDGE=1)
endif()
if(APPLE)
file(WRITE "${CMAKE_BINARY_DIR}/webscene-dawn.exports" "_wgpu*\n")
target_link_options(webgpu_dawn PRIVATE "LINKER:-exported_symbols_list,${CMAKE_BINARY_DIR}/webscene-dawn.exports")
elseif(UNIX)
file(WRITE "${CMAKE_BINARY_DIR}/webscene-dawn.exports" "{ global: wgpu*; local: *; };\n")
file(WRITE "${CMAKE_BINARY_DIR}/webscene-dawn.exports"
"{ global: wgpu*; websceneDawnQueryVulkanDeviceV1; local: *; };\n")
target_link_options(webgpu_dawn PRIVATE "LINKER:--version-script=${CMAKE_BINARY_DIR}/webscene-dawn.exports")
endif()
# Windows exports only functions decorated by WGPU_SHARED_LIBRARY;
Expand Down
2 changes: 1 addition & 1 deletion eng/graphics/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ Implements part of [#23](https://github.com/wieslawsoltes/WebScene/issues/23), t

`dependencies.lock.json` pins Dawn (including Tint and generated WebGPU headers), ANGLE, depot_tools, WebGPU CTS, Khronos WebGL and WPT to exact commits. Dawn's own pinned `DEPS` supplies its transitive source revisions; ANGLE uses its pinned `DEPS` through gclient with depot_tools self-update disabled. The installed package records the transitive Git revision graph, exact CMake/GN settings, tool identities, source licenses/notices and hashes of every installed header/library. There is no ProGPU or renderer replacement dependency.

Dawn uses a shared `webgpu_dawn` monolith exporting only WebGPU C entry points. Static co-linkage with V8 exposed conflicting unversioned Abseil symbols and caused native runtime hangs; the shared boundary keeps those implementations private. `DawnSymbolBoundary.cmake` applies the export policy without patching upstream sources, and the builder checks actual binary exports before sealing the SDK. ANGLE uses shared EGL/GLESv2 with static internal dependencies and C ABI entry points. Windows release builds use static CRT for Dawn, matching the existing native engine/V8; ANGLE's non-component Chromium configuration controls its runtime. Windows build/link and runtime dependency validation (including D3D shader compiler packaging) remain hardware-runner gates. Never exchange CRT-owned allocations between these libraries.
Dawn uses a shared `webgpu_dawn` monolith exporting WebGPU C entry points. On Linux it also exports the single versioned `websceneDawnQueryVulkanDeviceV1` C entry point, which returns borrowed native identities only for a live device created by this exact Dawn build. Static co-linkage with V8 exposed conflicting unversioned Abseil symbols and caused native runtime hangs; the shared boundary keeps those implementations private. `DawnSymbolBoundary.cmake` applies the export policy, and the builder checks actual binary exports before sealing the SDK. The Linux builder temporarily connects Dawn's authoritative device add/remove path to the query registry and restores the pinned source before provenance sealing. No private Dawn header enters the installed SDK. ANGLE uses shared EGL/GLESv2 with static internal dependencies and C ABI entry points. Windows release builds use static CRT for Dawn, matching the existing native engine/V8; ANGLE's non-component Chromium configuration controls its runtime. Windows build/link and runtime dependency validation (including D3D shader compiler packaging) remain hardware-runner gates. Never exchange CRT-owned allocations between these libraries.

`GraphicsDependencies.cmake` verifies the SDK before importing it, including revision, RID, lock, settings, complete installed file inventory and content hashes. CMake cannot silently choose another `Dawn_DIR`. A dependency roll requires rebuilding headers and libraries together. Package manifests prove integrity and provenance, not API conformance or hardware execution.

Expand Down
60 changes: 59 additions & 1 deletion eng/graphics/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@
LOCK_PATH = Path(__file__).with_name("dependencies.lock.json")
LOCK = json.loads(LOCK_PATH.read_text())
WINDOWS_RUNTIME_PIN_PATH = Path(__file__).with_name("windows-runtime.json")
DAWN_NATIVE_DEVICE_HEADER = (ROOT / "experiments/WebScene.NativeEngine.Probe/native/graphics/"
"webscene/dawn_native_device.h")
DAWN_NATIVE_DEVICE_SOURCE = Path(__file__).with_name("dawn_native_device.cpp")
DAWN_NATIVE_DEVICE_INTERNAL = Path(__file__).with_name("dawn_native_device_internal.h")
WINDOWS_DEVELOPER_ENVIRONMENT_KEYS = {
"COMMANDPROMPTTYPE", "DEVENVDIR", "EXTENSIONSDKDIR", "EXTERNAL_INCLUDE",
"FRAMEWORK40VERSION", "FRAMEWORKDIR", "FRAMEWORKDIR64", "FRAMEWORKVERSION",
Expand Down Expand Up @@ -187,6 +191,49 @@ def seal(component, source, sdk, rid, settings, tools, env=None):
(sdk / "webscene-graphics-package.json").write_text(json.dumps(manifest, indent=2) + "\n")


@contextmanager
def patched_dawn_native_device_bridge(source):
"""Temporarily connect the pinned Dawn device registry to WebScene's bridge."""
instance = source / "src/dawn/native/Instance.cpp"
original = instance.read_bytes()
include = b'#include "src/dawn/native/Device.h"\n'
include_patch = (include + b'#if defined(WEBSCENE_DAWN_NATIVE_DEVICE_BRIDGE)\n'
b'#include "dawn_native_device_internal.h"\n'
b'#endif\n')
methods = b'''void InstanceBase::AddDevice(DeviceBase* device) {
mDevicesList.Use([&](auto deviceList) { deviceList->insert(device); });
}

void InstanceBase::RemoveDevice(DeviceBase* device) {
mDevicesList.Use([&](auto deviceList) { deviceList->erase(device); });
}
'''
methods_patch = b'''void InstanceBase::AddDevice(DeviceBase* device) {
mDevicesList.Use([&](auto deviceList) { deviceList->insert(device); });
#if defined(WEBSCENE_DAWN_NATIVE_DEVICE_BRIDGE)
webscene::dawn_bridge::register_device(device);
#endif
}

void InstanceBase::RemoveDevice(DeviceBase* device) {
#if defined(WEBSCENE_DAWN_NATIVE_DEVICE_BRIDGE)
webscene::dawn_bridge::unregister_device(device);
#endif
mDevicesList.Use([&](auto deviceList) { deviceList->erase(device); });
}
'''
if original.count(include) != 1 or original.count(methods) != 1:
raise ValueError(
"Pinned Dawn Instance device registry changed unexpectedly; "
"review the exact native-device bridge against the new source")
patched = original.replace(include, include_patch).replace(methods, methods_patch)
try:
instance.write_bytes(patched)
yield
finally:
instance.write_bytes(original)


def dawn(args):
source = args.sources / "dawn"
checkout("dawn", source)
Expand All @@ -204,13 +251,24 @@ def dawn(args):
f"-DCMAKE_INSTALL_PREFIX={sdk}", f"-DCMAKE_PROJECT_Dawn_INCLUDE={symbol_policy}",
"-DCMAKE_SHARED_LINKER_FLAGS="] + [f"-D{k}={v}" for k, v in settings.items()])
repair_dawn_dependencies(source)
run(["cmake", "--build", output, "--parallel", args.jobs])
bridge = (patched_dawn_native_device_bridge(source)
if args.rid.startswith("linux-") else nullcontext())
with bridge:
run(["cmake", "--build", output, "--parallel", args.jobs])
# Old installed headers/libraries must not survive a dependency roll.
if sdk.exists():
remove_sdk(sdk)
run(["cmake", "--install", output])
sdk.joinpath("build-info").mkdir()
shutil.copy2(symbol_policy, sdk / "build-info/DawnSymbolBoundary.cmake")
if args.rid.startswith("linux-"):
sdk.joinpath("include/webscene").mkdir()
shutil.copy2(DAWN_NATIVE_DEVICE_HEADER, sdk / "include/webscene/dawn_native_device.h")
bridge_info = sdk / "build-info/webscene-dawn-native-device"
bridge_info.mkdir()
for path in (DAWN_NATIVE_DEVICE_HEADER, DAWN_NATIVE_DEVICE_SOURCE,
DAWN_NATIVE_DEVICE_INTERNAL):
shutil.copy2(path, bridge_info / path.name)
binary = sdk / {"win-x64": "bin/webgpu_dawn.dll", "osx-arm64": "lib/libwebgpu_dawn.dylib",
"linux-x64": "lib/libwebgpu_dawn.so"}[args.rid]
(sdk / "build-info/exports.json").write_text(json.dumps(inspect_exports(binary, args.rid), indent=2) + "\n")
Expand Down
9 changes: 7 additions & 2 deletions eng/graphics/dawn_exports.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,12 @@ def inspect_exports(library, rid):
if match:
symbol = match.group(1)
symbols.append(symbol[1:] if rid.startswith("osx-") and symbol.startswith("_") else symbol)
unexpected = [name for name in symbols if not re.fullmatch(r"wgpu[A-Z][A-Za-z0-9]*", name)]
if unexpected or not {"wgpuCreateInstance", "wgpuGetProcAddress"} <= set(symbols):
allowed_bridge = ({"websceneDawnQueryVulkanDeviceV1"}
if rid.startswith("linux-") else set())
unexpected = [name for name in symbols
if not re.fullmatch(r"wgpu[A-Z][A-Za-z0-9]*", name)
and name not in allowed_bridge]
required = {"wgpuCreateInstance", "wgpuGetProcAddress"} | allowed_bridge
if unexpected or not required <= set(symbols):
raise ValueError(f"Dawn C export boundary failed: unexpected={unexpected[:20]}, exports={len(symbols)}")
return {"status": "passed", "command": command, "exports": sorted(symbols)}
Loading
Loading