Skip to content

Commit e749ced

Browse files
tianhuasacrnsi
authored andcommitted
dm: remove unsafe apis in dm log
sprintf/vsnprintf are not safe, so use snprintf instead of sprintf, use vasprintf instead of vsnprintf. Tracked-On: #3394 Signed-off-by: Tianhua Sun <tianhuax.s.sun@intel.com> Reviewed-by: Yonghua Huang <yonghua.huang@intel.com> Reviewed-by: Minggui Cao <minggui.cao@intel.com>
1 parent d8b752c commit e749ced

File tree

2 files changed

+26
-9
lines changed

2 files changed

+26
-9
lines changed

devicemodel/log/disk_logger.c

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,8 @@ static void write_to_disk(const char *fmt, va_list args)
139139
{
140140
char buffer[DISK_LOG_MAX_LEN];
141141
char *file_name = buffer;
142-
int len1, len2;
142+
char *buf;
143+
int len;
143144
int write_cnt;
144145
struct timespec times = {0, 0};
145146

@@ -155,11 +156,23 @@ static void write_to_disk(const char *fmt, va_list args)
155156
}
156157
}
157158

159+
len = vasprintf(&buf, fmt, args);
160+
if (len < 0)
161+
return;
162+
158163
clock_gettime(CLOCK_MONOTONIC, &times);
159-
len1 = sprintf(buffer, "[%5lu.%06lu] ", times.tv_sec, times.tv_nsec / 1000);
160-
len2 = vsnprintf(buffer + len1, MAX_ONE_LOG_SIZE, fmt, args);
164+
len = snprintf(buffer, DISK_LOG_MAX_LEN, "[%5lu.%06lu] ", times.tv_sec, times.tv_nsec / 1000);
165+
if (len < 0 || len >= DISK_LOG_MAX_LEN) {
166+
free(buf);
167+
return;
168+
}
169+
len = strnlen(buffer, DISK_LOG_MAX_LEN);
170+
171+
strncpy(buffer + len, buf, DISK_LOG_MAX_LEN - len);
172+
buffer[DISK_LOG_MAX_LEN - 1] = '\0';
173+
free(buf);
161174

162-
write_cnt = write(disk_fd, buffer, len1 + len2);
175+
write_cnt = write(disk_fd, buffer, strnlen(buffer, DISK_LOG_MAX_LEN));
163176
if (write_cnt < 0) {
164177
perror(DISK_PREFIX"write disk failed");
165178
close(disk_fd);

devicemodel/log/kmsg_logger.c

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,17 +69,21 @@ static void deinit_kmsg(void)
6969

7070
static void write_to_kmsg(const char *fmt, va_list args)
7171
{
72+
char *buf;
7273
char kmsg_buf[KMSG_MAX_LEN] = KMSG_PREFIX;
73-
int len1, len2;
74-
int write_cnt;
74+
int len, write_cnt;
7575

7676
if (kmsg_fd < 0)
7777
return;
7878

79-
len1 = strlen(KMSG_PREFIX);
80-
len2 = vsnprintf(kmsg_buf + len1, MAX_ONE_LOG_SIZE, fmt, args);
79+
len = vasprintf(&buf, fmt, args);
80+
if (len < 0)
81+
return;
82+
strncpy(kmsg_buf + strlen(KMSG_PREFIX), buf, KMSG_MAX_LEN - strlen(KMSG_PREFIX));
83+
kmsg_buf[KMSG_MAX_LEN - 1] = '\0';
84+
free(buf);
8185

82-
write_cnt = write(kmsg_fd, kmsg_buf, len1 + len2);
86+
write_cnt = write(kmsg_fd, kmsg_buf, strnlen(kmsg_buf, KMSG_MAX_LEN));
8387
if (write_cnt < 0) {
8488
perror(KMSG_PREFIX"write kmsg failed");
8589
close(kmsg_fd);

0 commit comments

Comments
 (0)