Skip to content

Commit 5a0d164

Browse files
committed
log : fix UBs
ggml-ci
1 parent c37e61f commit 5a0d164

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

common/log.cpp

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
#include <cstdarg>
55
#include <cstdio>
66
#include <mutex>
7+
#include <sstream>
78
#include <thread>
89
#include <vector>
910

@@ -100,6 +101,9 @@ struct gpt_log {
100101
running = false;
101102
t_start = t_us();
102103
entries.resize(capacity);
104+
for (auto & entry : entries) {
105+
entry.msg.resize(256);
106+
}
103107
head = 0;
104108
tail = 0;
105109

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

146150
{
151+
// cannot use args twice, so make a copy in case we need to expand the buffer
152+
va_list args_copy;
153+
va_copy(args_copy, args);
154+
147155
#if 1
148156
const size_t n = vsnprintf(entry.msg.data(), entry.msg.size(), fmt, args);
149157
if (n >= entry.msg.size()) {
150158
entry.msg.resize(n + 1);
151-
vsnprintf(entry.msg.data(), entry.msg.size(), fmt, args);
159+
vsnprintf(entry.msg.data(), entry.msg.size(), fmt, args_copy);
152160
}
153161
#else
154162
// hack for bolding arguments
@@ -166,7 +174,7 @@ struct gpt_log {
166174
const size_t n = vsnprintf(entry.msg.data(), entry.msg.size(), ss.str().c_str(), args);
167175
if (n >= entry.msg.size()) {
168176
entry.msg.resize(n + 1);
169-
vsnprintf(entry.msg.data(), entry.msg.size(), ss.str().c_str(), args);
177+
vsnprintf(entry.msg.data(), entry.msg.size(), ss.str().c_str(), args_copy);
170178
}
171179
#endif
172180
}
@@ -195,6 +203,10 @@ struct gpt_log {
195203
head = 0;
196204
tail = new_tail;
197205

206+
for (size_t i = tail; i < new_entries.size(); i++) {
207+
new_entries[i].msg.resize(256);
208+
}
209+
198210
entries = std::move(new_entries);
199211
}
200212

@@ -280,7 +292,7 @@ struct gpt_log {
280292
};
281293

282294
struct gpt_log * gpt_log_init() {
283-
return new gpt_log{1024};
295+
return new gpt_log{256};
284296
}
285297

286298
struct gpt_log * gpt_log_main() {

0 commit comments

Comments
 (0)