Skip to content

Add safe snprintf rule#275

Open
lucic71 wants to merge 7 commits into
Cpp2Rust:masterfrom
lucic71:printf
Open

Add safe snprintf rule#275
lucic71 wants to merge 7 commits into
Cpp2Rust:masterfrom
lucic71:printf

Conversation

@lucic71

@lucic71 lucic71 commented Jul 20, 2026

Copy link
Copy Markdown
Contributor

The snprintf safe rule uses the new libcc2rs::format_c function. The rule is:

1. let s = libcc2rs::format_c(&a2.to_rust_string(), va);
2. let b = s.as_bytes();
3. if a1 > 0 {
4.   let n = min(b.len(), a1 - 1);
5.   a0.with_slice_mut(n + 1, ... copy n+1 + NUL byte in a0)
6. }
7. b.len()

Initially, I planned to use format! instead of libcc2rs::format_c at line 1 because that's definitely more idiomatic. However we need to support runtime format strings, for example:

char fmt[] = "%d",
snprintf(buf, n, fmt, 123);

The format! macro in rust does not support runtime format strings. It only works with compile time format strings. For this reason I created libcc2rs::format_c which internally uses the sprintf crate. The role of format_c is to validate the format string, convert each libcc2rs::VaArg to sprintf::Printf then do the actual formatting.

@lucic71
lucic71 marked this pull request as draft July 20, 2026 13:19
@lucic71
lucic71 marked this pull request as ready for review July 20, 2026 14:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant