Migrate unsafe sscanf call in str_format convert_test to safe buffers.
`MatchesPointerString` parsed formatted pointers back into addresses with
`sscanf("%p")`, which is an unsafe libc call under the Safe Buffers programming
model: Clang's `-Wunsafe-buffer-usage` (via
`-Wunsafe-buffer-usage-in-libc-call`) flags every `*scanf` call, because the
input must be NUL-terminated and the outputs are passed through type-erased
varargs.
Migrate the call to safe buffers by parsing the string with
`absl::SimpleHexAtoi` into a `uintptr_t`, which takes the input as a bounded
`absl::string_view`. absl formats a non-null `%p` as if by `%#x` (lowercase hex
with a `0x` prefix), padded with spaces, and `SimpleHexAtoi` trims surrounding
ASCII whitespace and accepts the optional `0x` prefix, so every width and
precision variant exercised by the test still parses. The matcher is also
slightly stricter: trailing characters after the hex digits now fail to parse
instead of being ignored.
PiperOrigin-RevId: 998910297
diff --git a/absl/strings/internal/str_format/convert_test.cc b/absl/strings/internal/str_format/convert_test.cc
index cd60ef3..9aa5671 100644
--- a/absl/strings/internal/str_format/convert_test.cc
+++ b/absl/strings/internal/str_format/convert_test.cc
@@ -47,6 +47,7 @@
#include "absl/strings/internal/str_format/arg.h"
#include "absl/strings/internal/str_format/bind.h"
#include "absl/strings/match.h"
+#include "absl/strings/numbers.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_format.h"
#include "absl/strings/string_view.h"
@@ -415,11 +416,11 @@
if (ptr == nullptr && arg == "(nil)") {
return true;
}
- void* parsed = nullptr;
- if (sscanf(arg.c_str(), "%p", &parsed) != 1) {
+ uintptr_t parsed = 0;
+ if (!absl::SimpleHexAtoi(arg, &parsed)) {
LOG(FATAL) << "Could not parse " << arg;
}
- return ptr == parsed;
+ return ptr == reinterpret_cast<void*>(parsed);
}
TEST_F(FormatConvertTest, Pointer) {