1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 18:27:35 +00:00

LibJS: Ensure enlarged ArrayBuffers are filled with zeros

Otherwise, the newly allocated bytes are uninitialized, causing UB when
reading from the buffer immediately after an enlarging resize.
This commit is contained in:
Timothy Flynn 2023-12-27 08:41:22 -05:00 committed by Andreas Kling
parent cabd599c8b
commit 916cb256de
2 changed files with 35 additions and 1 deletions

View file

@ -54,4 +54,38 @@ describe("normal behavior", () => {
expect(buffer.byteLength).toBe(i);
}
});
test("enlarged buffers filled with zeros", () => {
let buffer = new ArrayBuffer(5, { maxByteLength: 10 });
const readBuffer = () => {
let array = new Uint8Array(buffer, 0, buffer.byteLength / Uint8Array.BYTES_PER_ELEMENT);
let values = [];
for (let value of array) {
values.push(Number(value));
}
return values;
};
const writeBuffer = values => {
let array = new Uint8Array(buffer, 0, buffer.byteLength / Uint8Array.BYTES_PER_ELEMENT);
array.set(values);
};
expect(readBuffer()).toEqual([0, 0, 0, 0, 0]);
writeBuffer([1, 2, 3, 4, 5]);
expect(readBuffer()).toEqual([1, 2, 3, 4, 5]);
buffer.resize(8);
expect(readBuffer()).toEqual([1, 2, 3, 4, 5, 0, 0, 0]);
writeBuffer([1, 2, 3, 4, 5, 6, 7, 8]);
expect(readBuffer()).toEqual([1, 2, 3, 4, 5, 6, 7, 8]);
buffer.resize(10);
expect(readBuffer()).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 0, 0]);
});
});