mirror of
https://github.com/zeek/zeek.git
synced 2025-10-02 06:38:20 +00:00
Fix unsafe and inefficient uses of copy_string
Add a new overload to `copy_string` that takes the input characters plus size. The new overload avoids inefficient scanning of the input for the null terminator in cases where we know the size beforehand. Furthermore, this overload *must* be used when dealing with input character sequences that may have no null terminator, e.g., when the input is from a `std::string_view` object.
This commit is contained in:
parent
4eb1b71d1b
commit
cebb85b1e8
25 changed files with 85 additions and 56 deletions
|
@ -135,10 +135,10 @@ void String::Set(std::string_view str) {
|
|||
|
||||
void String::Set(const String& str) { *this = str; }
|
||||
|
||||
const char* String::CheckString() const {
|
||||
std::pair<const char*, size_t> String::CheckStringWithSize() const {
|
||||
void* nulTerm;
|
||||
if ( n == 0 )
|
||||
return "";
|
||||
return {"", 0};
|
||||
|
||||
nulTerm = memchr(b, '\0', n + final_NUL);
|
||||
if ( nulTerm != &b[n] ) {
|
||||
|
@ -151,12 +151,15 @@ const char* String::CheckString() const {
|
|||
reporter->Error("string without NUL terminator: \"%s\"", exp_s);
|
||||
|
||||
delete[] exp_s;
|
||||
return "<string-with-NUL>";
|
||||
static constexpr const char result[] = "<string-with-NUL>";
|
||||
return {result, std::size(result) - 1};
|
||||
}
|
||||
|
||||
return (const char*)b;
|
||||
return {(const char*)b, n};
|
||||
}
|
||||
|
||||
const char* String::CheckString() const { return CheckStringWithSize().first; }
|
||||
|
||||
char* String::Render(int format, int* len) const {
|
||||
// Maximum character expansion is as \xHH, so a factor of 4.
|
||||
char* s = new char[n * 4 + 1]; // +1 is for final '\0'
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue