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

codegen: Generate CStr only if possible. #2567

Merged
merged 1 commit into from
Jun 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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