Skip to content

Commit 441bc7b

Browse files
committed
codegen: Generate CStr only if possible.
And fix a crash when strings have interior nulls. Fixes #2566
1 parent ee980e1 commit 441bc7b

File tree

5 files changed

+14
-5
lines changed

5 files changed

+14
-5
lines changed

bindgen-tests/tests/expectations/tests/issue-2566-cstr.rs

+2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

bindgen-tests/tests/expectations/tests/issue-2566.rs

+2
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
// bindgen-flags: --generate-cstr
2+
3+
/// We should _not_ generate a cstr for this because cstr shouldn't have interior nulls.
4+
#define FOO "a\0b"
+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
#define FOO "a\0b"

bindgen/codegen/mod.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -714,18 +714,18 @@ impl CodeGenerator for Var {
714714
let len = proc_macro2::Literal::usize_unsuffixed(
715715
cstr_bytes.len(),
716716
);
717-
let cstr = CStr::from_bytes_with_nul(&cstr_bytes).unwrap();
718717

719718
// TODO: Here we ignore the type we just made up, probably
720719
// we should refactor how the variable type and ty ID work.
721720
let array_ty = quote! { [u8; #len] };
722721
let cstr_ty = quote! { ::#prefix::ffi::CStr };
723722

724-
let bytes = proc_macro2::Literal::byte_string(
725-
cstr.to_bytes_with_nul(),
726-
);
723+
let bytes = proc_macro2::Literal::byte_string(&cstr_bytes);
727724

728-
if rust_features.const_cstr && options.generate_cstr {
725+
if options.generate_cstr &&
726+
rust_features.const_cstr &&
727+
CStr::from_bytes_with_nul(&cstr_bytes).is_ok()
728+
{
729729
result.push(quote! {
730730
#(#attrs)*
731731
#[allow(unsafe_code)]

0 commit comments

Comments
 (0)