[llvm] [NFC][CodeQL] Avoid incorrect-string-type-conversion in ConvertUTF8toWide (PR #217108)
David Justo via llvm-commits
llvm-commits at lists.llvm.org
Tue Aug 18 15:56:09 PDT 2026
https://github.com/davidmrdavid updated https://github.com/llvm/llvm-project/pull/217108
>From 037ca59f2f56d8f87d5da808b410a5805a8bedee Mon Sep 17 00:00:00 2001
From: David Justo <dajusto at microsoft.com>
Date: Tue, 18 Aug 2026 11:24:16 -0700
Subject: [PATCH] [NFC][CodeQL] Avoid incorrect-string-type-conversion in
ConvertUTF8toWide
CodeQL flags the use of reinterpret_cast<wchar_t *>(ResultPtr) as potentially
unsafe because casting from narrow and to wide string types can yield
incorrectly terminated strings.
ConvertUTF8toWideInternal converts UTF-8 input into a preallocated wide-string
buffer and then resizes the buffer to the number of elements written. For
resizing, the existing code casts the end of the converted output from char*
to wchar_t*, then subtracts the buffer's starting address to determine how many
wide characters were written.
Instead, we can calculate the number of bytes written by subtracting the char
pointers, then divide by sizeof(wchar_t) to obtain the number of wide
characters.
CodeQL warning docs:
https://codeql.github.com/codeql-query-help/cpp/cpp-incorrect-string-type-conversion/
---
llvm/lib/Support/ConvertUTFWrapper.cpp | 8 ++++++--
1 file changed, 6 insertions(+), 2 deletions(-)
diff --git a/llvm/lib/Support/ConvertUTFWrapper.cpp b/llvm/lib/Support/ConvertUTFWrapper.cpp
index 6bbd7d15e1808..dc41d76c4740f 100644
--- a/llvm/lib/Support/ConvertUTFWrapper.cpp
+++ b/llvm/lib/Support/ConvertUTFWrapper.cpp
@@ -246,13 +246,17 @@ static inline bool ConvertUTF8toWideInternal(llvm::StringRef Source,
// at least as large as the number of elements in the resulting wide
// string, because surrogate pairs take at least 4 bytes in UTF-8.
Result.resize(Source.size() + 1);
- char *ResultPtr = reinterpret_cast<char *>(&Result[0]);
+ char *ResultBegin = reinterpret_cast<char *>(&Result[0]);
+ char *ResultPtr = ResultBegin;
const UTF8 *ErrorPtr;
if (!ConvertUTF8toWide(sizeof(wchar_t), Source, ResultPtr, ErrorPtr)) {
Result.clear();
return false;
}
- Result.resize(reinterpret_cast<wchar_t *>(ResultPtr) - &Result[0]);
+ // ResultPtr points one position after the copied string, so the byte count
+ // (ResultPtr - ResultBegin) is nonnegative and safe to cast to size_t.
+ const size_t ResultBytes = static_cast<size_t>(ResultPtr - ResultBegin);
+ Result.resize(ResultBytes / sizeof(wchar_t));
return true;
}
More information about the llvm-commits
mailing list