toCString function
toNativeUtf8 with the two checks a C string needs and a Dart String
does not enforce, applied to every string parameter that crosses the ABI
(model ids, api keys, base URLs, dir paths, base64 payloads, media types,
JSON text):
- Interior NUL.
toNativeUtf8writes it verbatim, and the C side'sCStr::from_ptrstops there — the argument is silently truncated at the NUL rather than rejected. - Unpaired surrogate.
toNativeUtf8substitutes U+FFFD (documented inpackage:ffi'sStringUtf8Pointer.toNativeUtf8), so the argument is silently corrupted rather than rejected.
Both are catchable FormatExceptions here instead of silence there.
Implementation
Pointer<Utf8> toCString(String s) {
final nul = s.codeUnits.indexOf(0);
if (nul >= 0) {
throw FormatException(
'argument contains a NUL at index $nul; a C string ends there', s, nul);
}
_checkSurrogates(s, 'argument');
return s.toNativeUtf8();
}