Skip to content

Commit

Permalink
codegen: Generate CStr only if possible.
Browse files Browse the repository at this point in the history
And fix a crash when strings have interior nulls.

Fixes #2566
  • Loading branch information
emilio committed Jun 26, 2023
1 parent ee980e1 commit 441bc7b
Show file tree
Hide file tree
Showing 5 changed files with 14 additions and 5 deletions.
2 changes: 2 additions & 0 deletions bindgen-tests/tests/expectations/tests/issue-2566-cstr.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions bindgen-tests/tests/expectations/tests/issue-2566.rs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions bindgen-tests/tests/headers/issue-2566-cstr.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// bindgen-flags: --generate-cstr

/// We should _not_ generate a cstr for this because cstr shouldn't have interior nulls.
#define FOO "a\0b"
1 change: 1 addition & 0 deletions bindgen-tests/tests/headers/issue-2566.h
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#define FOO "a\0b"
10 changes: 5 additions & 5 deletions bindgen/codegen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,18 +714,18 @@ impl CodeGenerator for Var {
let len = proc_macro2::Literal::usize_unsuffixed(
cstr_bytes.len(),
);
let cstr = CStr::from_bytes_with_nul(&cstr_bytes).unwrap();

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

let bytes = proc_macro2::Literal::byte_string(
cstr.to_bytes_with_nul(),
);
let bytes = proc_macro2::Literal::byte_string(&cstr_bytes);

if rust_features.const_cstr && options.generate_cstr {
if options.generate_cstr &&
rust_features.const_cstr &&
CStr::from_bytes_with_nul(&cstr_bytes).is_ok()
{
result.push(quote! {
#(#attrs)*
#[allow(unsafe_code)]
Expand Down

0 comments on commit 441bc7b

Please sign in to comment.