Skip to content

Commit 5718fd5

Browse files
committed
test: cover ImageData ownership and the V8 bridge invariants, and run them in CI
Nothing in CI ran tests, and the four crates that already had #[test] modules could not be built on the host at all, so none of them had ever executed. With the canvas-core build fixed they do; `make test` and two new CI jobs run them. ImageData ownership (crates/canvas-c/src/c2d/image_data.rs) ImageData is a manually refcounted handle -- Clone copies the raw pixel pointer and bumps an Arc, and the storage is freed only when the last handle drops. canvas_native_image_data_get_data borrows and hands back a second handle to the same pixels, which is what makes the JS `data` view live and what #149 turned on. The tests pin all three parts: the buffer aliases the ImageData's pixels, releasing the buffer leaves the ImageData usable (the double free #149 fixed), and the buffer keeps the pixels alive when the ImageData handle is dropped first. V8 bridge invariants (tools/tests/check-v8-bridge-invariants.py) Static checks over the bridge sources for things the compiler accepts but that break at runtime or silently cost performance: internal-field and external-pointer accessors that are missing their V8 14 tag (an untagged read returns null rather than failing to build), V8 14-removed APIs coming back, dual-version shims re-entering a branch that ships one vendored V8, and the overload helper regressing to a bare pointer -- which is exactly how 23 of the 41 fast-call overloads went unregistered. Both of the regressions this merge introduced by auto-merge would have been caught here.
1 parent f9cf101 commit 5718fd5

4 files changed

Lines changed: 250 additions & 0 deletions

File tree

‎.github/workflows/pull-request.yml‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,41 @@ on:
1515
workflow_dispatch:
1616

1717
jobs:
18+
# Fast, dependency-free guards. These run first because they catch the class
19+
# of regression that merges introduce silently -- see
20+
# tools/tests/check-v8-bridge-invariants.py.
21+
static-checks:
22+
name: Static Checks
23+
runs-on: ubuntu-22.04
24+
steps:
25+
- uses: actions/checkout@v4
26+
- name: V8 bridge invariants
27+
run: python3 tools/tests/check-v8-bridge-invariants.py
28+
29+
unit-tests:
30+
name: Unit Tests
31+
runs-on: macos-15
32+
steps:
33+
- uses: actions/checkout@v4
34+
- uses: actions/cache@v4
35+
with:
36+
path: |
37+
~/.cargo/registry
38+
~/.cargo/git
39+
target
40+
key: ${{ runner.os }}-cargo-test-${{ hashFiles('Cargo.toml', 'crates/*/Cargo.toml') }}
41+
restore-keys: ${{ runner.os }}-cargo-test-
42+
# canvas-c needs 2d (skia) and webgl to compile; gl pulls the WebGL utils
43+
# the 2d and webgpu paths import.
44+
#
45+
# .cargo/config.toml adds `-C panic=abort` on the Apple host targets for
46+
# the macOS dylib build, and libtest cannot link against that, so the
47+
# rustflags are overridden for this run only.
48+
- name: Rust unit tests
49+
env:
50+
RUSTFLAGS: '-C link-arg=-undefined -C link-arg=dynamic_lookup'
51+
run: cargo test -p canvas-c --features 2d,webgl,gl
52+
1853
build-native:
1954
name: Build Native
2055
uses: ./.github/workflows/build-native.yml

‎Makefile‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ svg: GENERATE_IOS_SVG GENERATE_VISIONOS_SVG
2424

2525
android-svg: GENERATE_ANDROID_SVG
2626

27+
# Host-side tests. The workspace pins `-C panic=abort` for the Apple host
28+
# targets in .cargo/config.toml (needed by the macOS dylib build) and libtest
29+
# cannot link against that, so the rustflags are replaced for this run.
30+
.PHONY: test
31+
test:
32+
python3 ./tools/tests/check-v8-bridge-invariants.py
33+
RUSTFLAGS="-C link-arg=-undefined -C link-arg=dynamic_lookup" \
34+
cargo test -p canvas-c --features 2d,webgl,gl
35+
2736
.PHONY: GENERATE_HEADERS
2837
GENERATE_HEADERS:
2938
./tools/scripts/build-headers.sh

‎crates/canvas-c/src/c2d/image_data.rs‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,75 @@ pub extern "C" fn canvas_native_image_data_release(value: *mut ImageData) {
4747
}
4848
unsafe { drop(Box::from_raw(value)) };
4949
}
50+
51+
#[cfg(test)]
52+
mod tests {
53+
use super::*;
54+
use crate::buffers::{
55+
canvas_native_u8_buffer_get_bytes_mut, canvas_native_u8_buffer_get_length,
56+
canvas_native_u8_buffer_release,
57+
};
58+
59+
// `ImageData` is a manually refcounted handle: cloning it copies the raw
60+
// pixel pointer and bumps an Arc, and the storage is freed only when the
61+
// last handle drops. `canvas_native_image_data_get_data` therefore hands
62+
// back a *second handle to the same pixels*, not a copy of them -- which is
63+
// what makes `imageData.data` a live view on the JS side, and what the
64+
// Apple bridge's ImageDataBuffer relies on.
65+
66+
#[test]
67+
fn get_data_aliases_the_same_pixels() {
68+
let image = canvas_native_image_data_create(2, 2);
69+
let buffer = canvas_native_image_data_get_data(unsafe { &*image });
70+
71+
unsafe { *canvas_native_u8_buffer_get_bytes_mut(buffer) = 0xAB };
72+
73+
// The write through the buffer is visible on the ImageData, so the two
74+
// are the same storage. A deep copy here would silently break putImageData.
75+
assert_eq!(unsafe { (*image).0.data()[0] }, 0xAB);
76+
77+
canvas_native_u8_buffer_release(buffer);
78+
canvas_native_image_data_release(image);
79+
}
80+
81+
#[test]
82+
fn releasing_the_buffer_leaves_the_image_data_usable() {
83+
let image = canvas_native_image_data_create(2, 2);
84+
let buffer = canvas_native_image_data_get_data(unsafe { &*image });
85+
unsafe { *canvas_native_u8_buffer_get_bytes_mut(buffer) = 0xCD };
86+
87+
canvas_native_u8_buffer_release(buffer);
88+
89+
// get_data borrows its argument, so releasing the buffer must not have
90+
// released the ImageData with it. The Apple ImageDataBuffer destructor
91+
// used to call canvas_native_image_data_release here as well, which
92+
// double-freed the Box that ImageDataImpl still owns.
93+
assert_eq!(canvas_native_image_data_get_length(unsafe { &*image }), 16);
94+
assert_eq!(unsafe { (*image).0.data()[0] }, 0xCD);
95+
96+
canvas_native_image_data_release(image);
97+
}
98+
99+
#[test]
100+
fn buffer_outlives_the_image_data_handle() {
101+
let image = canvas_native_image_data_create(2, 2);
102+
let buffer = canvas_native_image_data_get_data(unsafe { &*image });
103+
unsafe { *canvas_native_u8_buffer_get_bytes_mut(buffer) = 0x11 };
104+
105+
// Drop the wrapper first: the pixels stay alive because the buffer still
106+
// holds a handle, so a retained JS pixel view survives collection of the
107+
// ImageData wrapper it came from.
108+
canvas_native_image_data_release(image);
109+
110+
assert_eq!(canvas_native_u8_buffer_get_length(buffer), 16);
111+
assert_eq!(unsafe { *canvas_native_u8_buffer_get_bytes_mut(buffer) }, 0x11);
112+
unsafe { *canvas_native_u8_buffer_get_bytes_mut(buffer) = 0x22 };
113+
114+
canvas_native_u8_buffer_release(buffer);
115+
}
116+
117+
#[test]
118+
fn release_is_null_safe() {
119+
canvas_native_image_data_release(std::ptr::null_mut());
120+
}
121+
}
Lines changed: 134 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,134 @@
1+
#!/usr/bin/env python3
2+
"""Static invariants for the Apple/Android V8 bridge sources.
3+
4+
This branch builds against a single vendored V8 (14.9, tools/scripts/download-v8.sh)
5+
rather than supporting 10.3 and 14 from one tree, and its fast-call registration
6+
depends on a few things the compiler will not catch:
7+
8+
* V8 14 requires an explicit tag on internal-field and external pointer
9+
accessors. A read tagged differently from its write returns null rather
10+
than failing to build, so an untagged accessor is a runtime bug.
11+
* Fast-call overload sets are registered through a helper that deduces the
12+
array extent. If that helper ever goes back to taking a bare pointer, the
13+
extent is silently lost and only the first overload of each set survives
14+
(see the NUM(&method_overloads) bug fixed alongside this file).
15+
* Dual-version shims re-entering the tree would compile fast calls out on
16+
V8 >= 14, which is the only V8 this branch targets.
17+
18+
Run: python3 tools/tests/check-v8-bridge-invariants.py
19+
"""
20+
import re
21+
import sys
22+
from pathlib import Path
23+
24+
ROOT = Path(__file__).resolve().parents[2]
25+
SRC = ROOT / 'packages/canvas/platforms/ios/src/cpp'
26+
HELPERS = SRC / 'Helpers.h'
27+
28+
failures = []
29+
30+
31+
def fail(message, hits):
32+
failures.append((message, hits))
33+
34+
35+
def sources():
36+
for path in sorted([*SRC.rglob('*.cpp'), *SRC.rglob('*.h')]):
37+
yield path, path.read_text(encoding='utf-8', errors='replace')
38+
39+
40+
def strip_comments(text):
41+
text = re.sub(r'/\*.*?\*/', '', text, flags=re.S)
42+
return re.sub(r'//[^\n]*', '', text)
43+
44+
45+
def scan(pattern, predicate=None):
46+
"""Yield (path, lineno, line) for lines matching pattern, skipping comments."""
47+
hits = []
48+
for path, text in sources():
49+
for number, line in enumerate(text.splitlines(), 1):
50+
if line.lstrip().startswith(('//', '*', '/*')):
51+
continue
52+
if re.search(pattern, line) and (predicate is None or predicate(line)):
53+
hits.append((path.relative_to(ROOT), number, line.strip()))
54+
return hits
55+
56+
57+
# 1. Internal-field pointer accessors must carry the shared wrapper tag.
58+
# ObjectWrapperImpl::kInternalFieldTag is the one tag every wrapper uses;
59+
# an untagged call reads back null under V8 14.
60+
untagged = scan(r'(Get|Set)Aligned\w*InternalField\s*\(',
61+
lambda line: 'kInternalFieldTag' not in line)
62+
if untagged:
63+
fail('internal-field accessor without ObjectWrapperImpl::kInternalFieldTag', untagged)
64+
65+
# 2. v8::External values must carry the external pointer tag on both sides.
66+
ext_new = scan(r'v8::External::New\s*\(',
67+
lambda line: 'kExternalPointerTypeTagDefault' not in line)
68+
if ext_new:
69+
fail('v8::External::New without v8::kExternalPointerTypeTagDefault', ext_new)
70+
71+
# 3. APIs V8 14 removed or replaced must not come back.
72+
removed = {
73+
r'->Utf8Length\s*\(': 'Utf8Length was replaced by Utf8LengthV2',
74+
r'->WriteUtf8\s*\(': 'WriteUtf8 was replaced by WriteUtf8V2',
75+
r'\bSetAccessor\s*\(': 'SetAccessor was replaced by SetNativeDataProperty',
76+
}
77+
for pattern, why in removed.items():
78+
hits = scan(pattern)
79+
if hits:
80+
fail(why, hits)
81+
82+
# 4. No dual-version shims: this branch has a single vendored V8 14.9, so a
83+
# `#if V8_MAJOR_VERSION` fork means one of the two arms is dead, and the
84+
# upstream shims disable fast calls on exactly the version we ship.
85+
for pattern, why in {
86+
r'V8_MAJOR_VERSION': 'V8 version fork in a single-V8 branch (see Common.h notes)',
87+
r'CANVAS_FAST_FUNCTION': 'CANVAS_FAST_FUNCTION compiles fast calls out on V8 >= 14',
88+
r'canvas::(GetAlignedPointer|SetAlignedPointer|Receiver|NewExternal|ExternalValue|Utf8Length|WriteUtf8|SetAccessor)\b':
89+
'dual-version canvas:: shim; call the V8 14 API directly',
90+
}.items():
91+
hits = scan(pattern)
92+
if hits:
93+
fail(why, hits)
94+
95+
# 5. The overload helper must take the array by reference so its extent is
96+
# deduced. A bare `const v8::CFunction *` parameter loses the length.
97+
helpers = strip_comments(HELPERS.read_text(encoding='utf-8'))
98+
signature = re.search(
99+
r'SetFastMethodWithOverLoads\s*\([^)]*?const\s+v8::CFunction\s*(?P<form>\(\s*&\s*\w+\s*\)\s*\[\s*\w+\s*\]|\*\s*\w+)',
100+
helpers, re.S)
101+
if signature is None:
102+
fail('could not find SetFastMethodWithOverLoads signature in Helpers.h', [])
103+
elif signature.group('form').lstrip().startswith('*'):
104+
fail('SetFastMethodWithOverLoads takes a bare pointer, so the overload count '
105+
'is lost and only the first overload of each set is registered',
106+
[(HELPERS.relative_to(ROOT), helpers[:signature.start()].count('\n') + 1,
107+
signature.group(0).split('\n')[-1].strip())])
108+
109+
# 6. Every declared overload set must actually be registered, and every
110+
# registration must name a set declared as an array in the same file.
111+
for path, text in sources():
112+
body = strip_comments(text)
113+
declared = set(re.findall(r'const\s+v8::CFunction\s+(\w+_overloads_)\s*\[\s*\]', body))
114+
used = set(re.findall(r'SetFastMethodWithOverLoads\s*\([^;]*?\b(\w+_overloads_)\b', body, re.S))
115+
rel = path.relative_to(ROOT)
116+
for name in sorted(declared - used):
117+
fail(f'overload set declared but never registered: {name}', [(rel, 0, name)])
118+
for name in sorted(used - declared):
119+
# registered here but declared elsewhere -> the extent would not deduce
120+
fail(f'overload set registered but not declared as an array in this file: {name}',
121+
[(rel, 0, name)])
122+
123+
if failures:
124+
for message, hits in failures:
125+
print(f'FAIL: {message}', file=sys.stderr)
126+
for rel, number, line in hits[:20]:
127+
where = f'{rel}:{number}' if number else str(rel)
128+
print(f' {where}: {line}', file=sys.stderr)
129+
if len(hits) > 20:
130+
print(f' ... and {len(hits) - 20} more', file=sys.stderr)
131+
print(f'\n{len(failures)} invariant(s) violated', file=sys.stderr)
132+
sys.exit(1)
133+
134+
print(f'v8 bridge invariants hold across {len(list(sources()))} sources')

0 commit comments

Comments
 (0)