Skip to content

Commit db60569

Browse files
authored
fix(canvas): avoid releasing borrowed ImageData from pixel buffer (#149)
1 parent 846e626 commit db60569

2 files changed

Lines changed: 29 additions & 5 deletions

File tree

‎packages/canvas/platforms/ios/src/cpp/canvas2d/ImageDataImpl.cpp‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,9 @@
88

99
struct ImageDataBuffer {
1010
public:
11-
explicit ImageDataBuffer(ImageData *imageData) : imageData_(imageData) {
12-
this->slice_ = canvas_native_image_data_get_data(imageData_);
11+
explicit ImageDataBuffer(ImageData *imageData) {
12+
// The buffer owns a clone of the pixel storage; ImageDataImpl owns imageData.
13+
this->slice_ = canvas_native_image_data_get_data(imageData);
1314
this->buf_ = canvas_native_u8_buffer_get_bytes_mut(slice_);
1415
this->size_ = canvas_native_u8_buffer_get_length(slice_);
1516
}
@@ -25,14 +26,11 @@ struct ImageDataBuffer {
2526
~ImageDataBuffer() {
2627
canvas_native_u8_buffer_release(slice_);
2728
slice_ = nullptr;
28-
canvas_native_image_data_release(imageData_);
29-
imageData_ = nullptr;
3029
}
3130

3231
private:
3332
uint8_t *buf_;
3433
size_t size_;
35-
ImageData *imageData_;
3634
U8Buffer *slice_;
3735
};
3836

‎tools/tests/imagedata-ownership.js‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// Run in a NativeScript Apple runtime. Rejects if explicit GC is unavailable.
2+
// Pixel views must survive collection of their ImageData wrapper, and collecting
3+
// both must release each native allocation only once (including V8 worker GC).
4+
export async function checkImageDataOwnership(ImageData) {
5+
if (typeof global.gc !== 'function') throw new Error('NativeScript global.gc is required');
6+
for (let round = 0; round < 8; round++) {
7+
const retained = [];
8+
for (let i = 0; i < 512; i++) {
9+
const image = new ImageData(4, 4);
10+
const bytes = image.data;
11+
bytes.set([i % 256, round, 127, 255]);
12+
if (i % 64 === 0) retained.push({ bytes, expected: i % 256 });
13+
}
14+
global.gc();
15+
await new Promise(resolve => setTimeout(resolve, 25));
16+
for (const { bytes, expected } of retained) {
17+
if (bytes[0] !== expected || bytes[1] !== round || bytes[2] !== 127 || bytes[3] !== 255)
18+
throw new Error('ImageData view changed after wrapper collection');
19+
bytes[0] = 255;
20+
if (bytes[0] !== 255) throw new Error('Retained ImageData view is not writable');
21+
}
22+
}
23+
global.gc();
24+
await new Promise(resolve => setTimeout(resolve, 100));
25+
return { allocations: 4096, retainedViews: 64 };
26+
}

0 commit comments

Comments
 (0)