Skip to content

Commit 7e86e69

Browse files
committed
fix bugs with strings being incorrectly converted to Rust strings
We cannot use Rust strings in most places due to the requirement of them being in UTF-8 format. Also, introduce a new `printf!` macro to ensure compliance with mixing output through different streams (cout vs stdout). This commit ensures correct sequencing.
1 parent 75d014f commit 7e86e69

92 files changed

Lines changed: 1464 additions & 868 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ pub fn main() {
8787
std::process::exit(main_0());
8888
}
8989
fn main_0() -> i32 {
90-
println!("hello world");
90+
printf!(b"hello world\n");
9191
return 0;
9292
}
9393
```

‎cpp2rust/converter/converter.cpp‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1794,6 +1794,11 @@ std::string Converter::ConvertPointeeCast(std::string str,
17941794
target);
17951795
}
17961796

1797+
static bool IsCharPointer(const clang::Expr *expr) {
1798+
auto *ptr = expr->getType()->getAs<clang::PointerType>();
1799+
return ptr && ptr->getPointeeType()->isCharType();
1800+
}
1801+
17971802
bool Converter::GetFmtArg(clang::Expr *arg, std::string &fmt,
17981803
std::string &fmt_args, const char *&fmt_trait,
17991804
std::string &fmt_width) {
@@ -1818,7 +1823,7 @@ bool Converter::GetFmtArg(clang::Expr *arg, std::string &fmt,
18181823
fmt_trait = "";
18191824
} else if (IsStdFunction(arg, "setw")) {
18201825
fmt_width = Trim(ToString(arg));
1821-
} else if (!arg->getType()->isCharType() &&
1826+
} else if (!arg->getType()->isCharType() && !IsCharPointer(arg) &&
18221827
Mapper::Map(*this, arg->getType()) !=
18231828
std::format("Vec<{}>", CharRustType())) {
18241829
fmt += ("{:" + fmt_width + fmt_trait + "}");
@@ -1849,6 +1854,10 @@ bool Converter::GetRawArg(clang::Expr *arg,
18491854
raw_args.push_back("b\"\\n\"");
18501855
} else if (clang::isa<clang::StringLiteral>(arg->IgnoreImplicit())) {
18511856
raw_args.push_back("b" + GetEscapedStringLiteral(arg));
1857+
} else if (IsCharPointer(arg)) {
1858+
// Not formatted, as the bytes need not be UTF-8.
1859+
PushExprKind push(*this, ExprKind::RValue);
1860+
raw_args.push_back(GetCStrBytes(ToString(arg)));
18521861
} else {
18531862
return false;
18541863
}
@@ -1859,6 +1868,11 @@ std::string Converter::ConvertStream(clang::Expr *expr) {
18591868
return ToString(expr);
18601869
}
18611870

1871+
std::string Converter::GetCStrBytes(std::string_view ptr) const {
1872+
return std::format(
1873+
"::std::ffi::CStr::from_ptr({} as *const libc::c_char).to_bytes()", ptr);
1874+
}
1875+
18621876
void Converter::ConvertCallToOstream(clang::CallExpr *expr) {
18631877
clang::Expr *stream = nullptr;
18641878
auto collect_args = [expr, &stream]() -> std::vector<clang::Expr *> {

‎cpp2rust/converter/converter.h‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,8 @@ class Converter : public clang::RecursiveASTVisitor<Converter> {
292292

293293
void ConvertCallToOstream(clang::CallExpr *expr);
294294
virtual std::string ConvertStream(clang::Expr *expr);
295+
// The bytes, without the NUL, of the C string that `ptr` points to.
296+
virtual std::string GetCStrBytes(std::string_view ptr) const;
295297

296298
struct TempMaterializationCtx {
297299
std::vector<std::optional<clang::QualType>> materialized_args;

‎cpp2rust/converter/converter_lib.cpp‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#include <clang/Lex/Lexer.h>
1515
#include <clang/Sema/Initialization.h>
1616
#include <clang/Sema/Sema.h>
17+
#include <llvm/Support/ConvertUTF.h>
1718
#include <llvm/Support/ErrorHandling.h>
1819
#include <llvm/Support/raw_ostream.h>
1920

@@ -164,13 +165,20 @@ std::string GetAssertMessageAsString(const clang::Expr *expr,
164165
auto text = clang::Lexer::getSourceText(
165166
clang::CharSourceRange::getTokenRange(expr->getSourceRange()),
166167
ctx.getSourceManager(), ctx.getLangOpts());
168+
auto start = reinterpret_cast<const llvm::UTF8 *>(text.data());
169+
bool utf8 = llvm::isLegalUTF8String(&start, start + text.size());
167170
std::string message = R"(, ")";
168171
for (char c : text) {
169172
// Doubled so that assert! does not read them as a format placeholder.
170173
if (c == '{' || c == '}') {
171174
message += c;
172175
}
173-
message += GetEscapedCharLiteral(c);
176+
// A str holds UTF-8, but the message need not be exact.
177+
if (static_cast<unsigned char>(c) >= 0x80) {
178+
message += utf8 ? std::string(1, c) : "\\u{fffd}";
179+
} else {
180+
message += GetEscapedCharLiteral(c);
181+
}
174182
}
175183
return message + '"';
176184
}

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 16 additions & 155 deletions
Original file line numberDiff line numberDiff line change
@@ -1106,160 +1106,6 @@ void ConverterRefCount::ConvertDeclRefValue(clang::Expr *expr,
11061106
SetValueFreshness(expr->getType());
11071107
}
11081108

1109-
static std::vector<const char *> printf2fmt(std::string &format) {
1110-
std::vector<const char *> types;
1111-
std::string escaped;
1112-
for (char c : format) {
1113-
escaped += c;
1114-
if (c == '{' || c == '}') {
1115-
escaped += c;
1116-
}
1117-
}
1118-
format = std::move(escaped);
1119-
size_t pos = 0;
1120-
while ((pos = format.find('%', pos)) != std::string::npos) {
1121-
if (pos + 1 >= format.size())
1122-
break;
1123-
1124-
switch (auto c = format[pos + 1]) {
1125-
case 'c':
1126-
types.emplace_back("u8 as char");
1127-
format.replace(pos, 2, "{}");
1128-
pos += 2;
1129-
continue;
1130-
case 'd':
1131-
case 'i':
1132-
case 's':
1133-
case 'u':
1134-
types.emplace_back();
1135-
format.replace(pos, 2, "{}");
1136-
pos += 2;
1137-
continue;
1138-
case 'p':
1139-
types.emplace_back();
1140-
format.replace(pos, 2, "{:?}");
1141-
pos += 2;
1142-
continue;
1143-
case '%':
1144-
format.replace(pos, 2, "%");
1145-
pos += 1;
1146-
continue;
1147-
case 'l':
1148-
if (pos + 2 < format.size() &&
1149-
(format[pos + 2] == 'd' || format[pos + 2] == 'u')) {
1150-
types.emplace_back();
1151-
format.replace(pos, 3, "{}");
1152-
pos += 2;
1153-
continue;
1154-
}
1155-
if (pos + 3 < format.size() && format[pos + 2] == 'l' &&
1156-
(format[pos + 3] == 'd' || format[pos + 3] == 'u')) {
1157-
types.emplace_back();
1158-
format.replace(pos, 4, "{}");
1159-
pos += 2;
1160-
continue;
1161-
}
1162-
break;
1163-
case 'j':
1164-
case 'z':
1165-
if (pos + 2 < format.size() &&
1166-
(format[pos + 2] == 'd' || format[pos + 2] == 'u')) {
1167-
types.emplace_back();
1168-
format.replace(pos, 3, "{}");
1169-
pos += 2;
1170-
continue;
1171-
}
1172-
break;
1173-
case '.':
1174-
if (pos + 3 < format.size() && format[pos + 2] == '0') {
1175-
auto end = format.find_first_not_of("0123456789", pos + 3);
1176-
if (end != std::string::npos && format[end] == 'f') {
1177-
auto repl = "{:." + format.substr(pos + 3, end - pos - 3) + '}';
1178-
format.replace(pos, end - pos + 1, repl);
1179-
pos += repl.size();
1180-
types.emplace_back();
1181-
continue;
1182-
}
1183-
}
1184-
break;
1185-
default:
1186-
if (c >= '0' && c <= '9') {
1187-
auto end = format.find_first_not_of("0123456789", pos + 2);
1188-
if (end != std::string::npos) {
1189-
auto repl = "{:" + format.substr(pos + 1, end - pos - 1);
1190-
bool ok = true;
1191-
switch (c = format[end]) {
1192-
case 'd':
1193-
break;
1194-
case 'x':
1195-
repl += c;
1196-
break;
1197-
case 'z':
1198-
if (end + 1 < format.size() && format[end + 1] == 'u') {
1199-
++end;
1200-
} else {
1201-
ok = false;
1202-
}
1203-
break;
1204-
default:
1205-
ok = false;
1206-
break;
1207-
}
1208-
if (ok) {
1209-
repl += '}';
1210-
format.replace(pos, end - pos + 1, repl);
1211-
pos += repl.size();
1212-
types.emplace_back();
1213-
continue;
1214-
}
1215-
}
1216-
}
1217-
}
1218-
llvm::errs() << "Unknown printf format: " << format << '\n';
1219-
assert(0);
1220-
}
1221-
return types;
1222-
}
1223-
1224-
void ConverterRefCount::ConvertPrintf(clang::CallExpr *expr) {
1225-
bool is_fprintf = IsCDecl(expr->getDirectCallee(), "fprintf");
1226-
auto format = GetEscapedStringLiteral(clang::cast<clang::StringLiteral>(
1227-
expr->getArg(is_fprintf)->IgnoreImplicit()));
1228-
bool ends_newline = format.ends_with("\\n\"");
1229-
1230-
llvm::StringRef stream = "stdout";
1231-
if (is_fprintf) {
1232-
auto loc = expr->getArg(0)->IgnoreParenImpCasts()->getBeginLoc();
1233-
stream = loc.isMacroID()
1234-
? clang::Lexer::getImmediateMacroName(
1235-
loc, ctx_.getSourceManager(), ctx_.getLangOpts())
1236-
: "";
1237-
}
1238-
if (stream == "stdout") {
1239-
StrCat(ends_newline ? "println!(" : "print!(");
1240-
} else if (stream == "stderr") {
1241-
StrCat(ends_newline ? "eprintln!(" : "eprint!(");
1242-
} else {
1243-
llvm::errs() << "Unknown fprintf fd:\n";
1244-
expr->getArg(0)->dump(llvm::errs(), ctx_);
1245-
exit(1);
1246-
}
1247-
if (ends_newline) {
1248-
format.replace(format.size() - 3, 2, "");
1249-
}
1250-
auto types = printf2fmt(format);
1251-
StrCat(format);
1252-
1253-
unsigned j = 0;
1254-
for (unsigned i = is_fprintf + 1, e = expr->getNumArgs(); i < e; ++i) {
1255-
StrCat(token::kComma);
1256-
Convert(expr->getArg(i));
1257-
if (auto *type = types[j++])
1258-
StrCat(keyword::kAs, type);
1259-
}
1260-
StrCat(')');
1261-
}
1262-
12631109
void ConverterRefCount::ConvertVAArgCall(clang::CallExpr *expr) {
12641110
if (IsBuiltinVaStart(expr)) {
12651111
StrCat(ToString(expr->getArg(0)->IgnoreImpCasts()), "= __args.decay()");
@@ -1271,11 +1117,22 @@ void ConverterRefCount::ConvertVAArgCall(clang::CallExpr *expr) {
12711117
std::optional<Converter::TempMaterializationCtx>
12721118
ConverterRefCount::ConvertCallExpr(clang::CallExpr *expr) {
12731119
PushConversionKind push(*this, ConversionKind::Unboxed);
1120+
// With a literal format, printf and fprintf become macros, which read like
1121+
// print!.
12741122
bool is_fprintf = IsCDecl(expr->getDirectCallee(), "fprintf");
12751123
if ((is_fprintf || IsCDecl(expr->getDirectCallee(), "printf")) &&
12761124
clang::isa<clang::StringLiteral>(
12771125
expr->getArg(is_fprintf)->IgnoreImplicit())) {
1278-
ConvertPrintf(expr);
1126+
StrCat(is_fprintf ? "fprintf!(" : "printf!(");
1127+
if (is_fprintf) {
1128+
StrCat(ConvertFreshPointer(expr->getArg(0)), token::kComma);
1129+
}
1130+
StrCat("b" + GetEscapedStringLiteral(expr->getArg(is_fprintf)));
1131+
for (unsigned i = is_fprintf + 1, e = expr->getNumArgs(); i < e; ++i) {
1132+
StrCat(token::kComma);
1133+
ConvertVariadicArg(expr->getArg(i));
1134+
}
1135+
StrCat(')');
12791136
return std::nullopt;
12801137
}
12811138
return Converter::ConvertCallExpr(expr);
@@ -2153,6 +2010,10 @@ std::string ConverterRefCount::ConvertStream(clang::Expr *expr) {
21532010
return ConvertPointer(expr);
21542011
}
21552012

2013+
std::string ConverterRefCount::GetCStrBytes(std::string_view ptr) const {
2014+
return std::format("&({}).to_c_u8_bytes()", ptr);
2015+
}
2016+
21562017
bool ConverterRefCount::VisitCXXConstructExpr(clang::CXXConstructExpr *expr) {
21572018
if (expr->isElidable()) {
21582019
Convert(expr->getArg(0));

‎cpp2rust/converter/models/converter_refcount.h‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,8 +123,6 @@ class ConverterRefCount final : public Converter {
123123
void ConvertConditionalBranch(clang::Expr *expr,
124124
clang::QualType type) override;
125125

126-
void ConvertPrintf(clang::CallExpr *expr);
127-
128126
void ConvertVAArgCall(clang::CallExpr *expr) override;
129127

130128
std::optional<TempMaterializationCtx>
@@ -243,6 +241,7 @@ class ConverterRefCount final : public Converter {
243241
bool VisitCXXDeleteExpr(clang::CXXDeleteExpr *expr) override;
244242

245243
std::string ConvertStream(clang::Expr *expr) override;
244+
std::string GetCStrBytes(std::string_view ptr) const override;
246245

247246
bool VisitCXXConstructExpr(clang::CXXConstructExpr *expr) override;
248247

‎docs/src/project/usage.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ pub fn main() {
3030
std::process::exit(main_0());
3131
}
3232
fn main_0() -> i32 {
33-
println!("hello world");
33+
printf!(b"hello world\n");
3434
return 0;
3535
}
3636
```

‎docs/src/rules/format.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ unsafe fn f4(a0: *const libc::c_char) -> i32 {
4545
```rust
4646
// rules/unistd/tgt_refcount.rs
4747
fn f4(a0: Ptr<u8>) -> i32 {
48-
match nix::unistd::unlink(a0.to_rust_string().as_str()) {
48+
match a0.with_c_bytes(|__path| nix::unistd::unlink(__path)) {
4949
Ok(()) => 0,
5050
Err(__e) => {
5151
libcc2rs::cpp2rust_errno().write(__e as i32);

‎docs/src/rules/writing-rules.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ int f1(const char *pathname, struct stat *statbuf) {
1717
```rust
1818
// rules/stat/tgt_refcount.rs
1919
fn f1(a0: Ptr<u8>, a1: Ptr<Stat>) -> i32 {
20-
match nix::sys::stat::stat(a0.to_rust_string().as_str()) {
20+
match a0.with_c_bytes(nix::sys::stat::stat) {
2121
Ok(__s) => {
2222
a1.with_mut(|__st| *__st = Stat::from_libc(&__s));
2323
0

‎docs/src/runtime/cstr.md‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,21 +6,21 @@ rather than Rust `String` values. A string literal becomes a per-thread interned
66
buffer with a trailing zero byte, handed out as a `Ptr<u8>` by
77
`Ptr::from_string_literal`. `Ptr<u8>` also carries the memory functions C
88
strings rely on: `memcpy` (with `memmove` semantics for overlapping buffers
9-
instead of undefined behavior), `memset`, `memcmp`, and `to_rust_string` for
10-
crossing into Rust APIs.
9+
instead of undefined behavior), `memset`, and `memcmp`. A C string crosses into
10+
Rust APIs as bytes (`with_c_bytes`), or as an `OsStr` (`with_c_os_str`) for
11+
paths and other names: never as a `str`, which must be UTF-8. For the same
12+
reason, a C string is not formatted with `Display`, but written as bytes.
1113

1214
`CStringIterator`, returned by `to_c_string_iterator`, walks the bytes of a
13-
`Ptr<u8>` up to the null terminator; the `string.h` rules are built on it, and
14-
`Display` for `Ptr<u8>` prints it, so a C string can be formatted directly.
15+
`Ptr<u8>` up to the null terminator; the `string.h` rules are built on it.
1516

1617
Copying a string does not go through the iterator, which would grow its
1718
destination as it goes. `with_c_str` scans for the null terminator in the
1819
backing storage and lends the bytes to a closure, so measuring or borrowing a
1920
string allocates nothing (`c_str_len`, and `count` on a `CStringIterator`, are
20-
built on it). `to_c_bytes` and `to_rust_string`, and through them `strdup` and
21-
the `std::string` constructors, copy the string with a single allocation.
22-
`to_c_bytes` leaves room for one more byte, which callers usually spend on the
23-
terminator or a newline.
21+
built on it). `to_c_bytes`, and through it `strdup` and the `std::string`
22+
constructors, copy the string with a single allocation. `to_c_bytes` leaves room
23+
for one more byte, which callers usually spend on the terminator or a newline.
2424

2525
Iterating a `Ptr<T>` reports how many elements are left, so collecting a `Ptr`
2626
into a `Vec` also allocates once.

0 commit comments

Comments
 (0)