Skip to content

Commit

Permalink
log : fix UBs
Browse files Browse the repository at this point in the history
ggml-ci
  • Loading branch information
ggerganov committed Sep 11, 2024
1 parent b89733e commit f029947
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions common/log.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#include <cstdarg>
#include <cstdio>
#include <mutex>
#include <sstream>
#include <thread>
#include <vector>

Expand Down Expand Up @@ -100,6 +101,9 @@ struct gpt_log {
running = false;
t_start = t_us();
entries.resize(capacity);
for (auto & entry : entries) {
entry.msg.resize(256);
}
head = 0;
tail = 0;

Expand Down Expand Up @@ -144,11 +148,15 @@ struct gpt_log {
auto & entry = entries[tail];

{
// cannot use args twice, so make a copy in case we need to expand the buffer
va_list args_copy;
va_copy(args_copy, args);

#if 1
const size_t n = vsnprintf(entry.msg.data(), entry.msg.size(), fmt, args);
if (n >= entry.msg.size()) {
entry.msg.resize(n + 1);
vsnprintf(entry.msg.data(), entry.msg.size(), fmt, args);
vsnprintf(entry.msg.data(), entry.msg.size(), fmt, args_copy);
}
#else
// hack for bolding arguments
Expand All @@ -166,7 +174,7 @@ struct gpt_log {
const size_t n = vsnprintf(entry.msg.data(), entry.msg.size(), ss.str().c_str(), args);
if (n >= entry.msg.size()) {
entry.msg.resize(n + 1);
vsnprintf(entry.msg.data(), entry.msg.size(), ss.str().c_str(), args);
vsnprintf(entry.msg.data(), entry.msg.size(), ss.str().c_str(), args_copy);
}
#endif
}
Expand Down Expand Up @@ -195,6 +203,10 @@ struct gpt_log {
head = 0;
tail = new_tail;

for (size_t i = tail; i < new_entries.size(); i++) {
new_entries[i].msg.resize(256);
}

entries = std::move(new_entries);
}

Expand Down Expand Up @@ -280,7 +292,7 @@ struct gpt_log {
};

struct gpt_log * gpt_log_init() {
return new gpt_log{1024};
return new gpt_log{256};
}

struct gpt_log * gpt_log_main() {
Expand Down

0 comments on commit f029947

Please sign in to comment.