Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(ext/ffi): Check CStr for UTF-8 validity on read #15318

Merged
merged 14 commits into from
Aug 5, 2022
Merged
Prev Previous commit
Next Next commit
Add test
  • Loading branch information
aapoalas committed Jul 27, 2022
commit a288b5be10db59666f590947b1b6b6c77977e80a
7 changes: 7 additions & 0 deletions test_ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,3 +404,10 @@ pub struct Structure {

#[no_mangle]
pub static mut static_ptr: Structure = Structure { _data: 42 };

/// Invalid UTF-8 characters, array of length 14
#[no_mangle]
pub static static_char: [u8; 14] = [
0xC0, 0xC1, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF,
0x00,
];
20 changes: 20 additions & 0 deletions test_ffi/tests/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

// Run using cargo test or `--v8-options=--allow-natives-syntax`

import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
import {
assertThrows,
} from "../../test_util/std/testing/asserts.ts";
Expand Down Expand Up @@ -186,6 +187,12 @@ const dylib = Deno.dlopen(libPath, {
"static_ptr": {
type: "pointer",
},
/**
* Invalid UTF-8 characters, buffer of length 14
*/
"static_char": {
type: "pointer",
},
});
const { symbols } = dylib;

Expand Down Expand Up @@ -465,6 +472,19 @@ uint32Array[0] = 55; // MUTATES!
console.log("uint32Array[0] after mutation:", uint32Array[0]);
console.log("Static ptr value after mutation:", view.getUint32());

// Test non-UTF-8 characters

const charView = new Deno.UnsafePointerView(dylib.symbols.static_char);

const charArrayBuffer = charView.getArrayBuffer(14);
const uint8Array = new Uint8Array(charArrayBuffer);
assertEquals([...uint8Array], [
0xC0, 0xC1, 0xF5, 0xF6, 0xF7, 0xF8, 0xF9, 0xFA, 0xFB, 0xFC, 0xFD, 0xFE, 0xFF,
0x00
]);

assertThrows(() => charView.getCString(), TypeError, "Invalid CString pointer, not valid UTF-8");

(function cleanup() {
dylib.close();
throwCallback.close();
Expand Down