1 /*
2 * This file is part of the flashrom project.
3 *
4 * Copyright (C) 2022 The Chromium OS Authors
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 */
16
17 #include <stdarg.h>
18 #include <stdlib.h>
19 #include <stdio.h>
20
21 #include "libflashrom.h"
22
23 void log_rust(enum flashrom_log_level level, const char *format);
24
25 // LOG_LEVEL = 0 (ERROR) means no messages are printed.
26 enum flashrom_log_level current_level = 0;
27
log_c(enum flashrom_log_level level,const char * format,va_list ap)28 static int log_c(enum flashrom_log_level level, const char *format, va_list ap)
29 {
30 static char *buf = NULL;
31 static int len = 0;
32 if (level >= current_level) {
33 return 0;
34 }
35
36 va_list ap2;
37 va_copy(ap2, ap);
38 // when buf is NULL, len is zero and this will not write to buf
39 int req_len = vsnprintf(buf, len, format, ap2);
40 va_end(ap2);
41
42 if (req_len > len) {
43 char *new_buf = realloc(buf, req_len + 1);
44 if (!new_buf) {
45 return 0;
46 }
47 buf = new_buf;
48 len = req_len + 1;
49 req_len = vsnprintf(buf, len, format, ap);
50 }
51
52 if (req_len > 0) {
53 log_rust(level, buf);
54 }
55 return req_len;
56 }
57
set_log_callback()58 void set_log_callback()
59 {
60 flashrom_set_log_callback(log_c);
61 }
62