1 /*
2  * Logging support
3  *
4  *  Copyright (c) 2003 Fabrice Bellard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library 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 GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19 
20 #include "qemu/osdep.h"
21 #include "qemu/log.h"
22 #include "qemu/range.h"
23 #include "qemu/error-report.h"
24 #include "qapi/error.h"
25 #include "qemu/cutils.h"
26 #include "trace/control.h"
27 #include "qemu/thread.h"
28 
29 static char *logfilename;
30 static QemuMutex qemu_logfile_mutex;
31 QemuLogFile *qemu_logfile;
32 int qemu_loglevel;
33 static int log_append = 0;
34 static GArray *debug_regions;
35 
36 /* Return the number of characters emitted.  */
qemu_log(const char * fmt,...)37 int qemu_log(const char *fmt, ...)
38 {
39     int ret = 0;
40     QemuLogFile *logfile;
41 
42     rcu_read_lock();
43     logfile = atomic_rcu_read(&qemu_logfile);
44     if (logfile) {
45         va_list ap;
46         va_start(ap, fmt);
47         ret = vfprintf(logfile->fd, fmt, ap);
48         va_end(ap);
49 
50         /* Don't pass back error results.  */
51         if (ret < 0) {
52             ret = 0;
53         }
54     }
55     rcu_read_unlock();
56     return ret;
57 }
58 
qemu_logfile_init(void)59 static void __attribute__((__constructor__)) qemu_logfile_init(void)
60 {
61     qemu_mutex_init(&qemu_logfile_mutex);
62 }
63 
qemu_logfile_free(QemuLogFile * logfile)64 static void qemu_logfile_free(QemuLogFile *logfile)
65 {
66     g_assert(logfile);
67 
68     if (logfile->fd != stderr) {
69         fclose(logfile->fd);
70     }
71     g_free(logfile);
72 }
73 
74 static bool log_uses_own_buffers;
75 
76 __attribute__((weak)) void flush_tcg_on_log_instr_chage(void);
flush_tcg_on_log_instr_chage(void)77 __attribute__((weak)) void flush_tcg_on_log_instr_chage(void) {
78     // Real implementation in translate-all.c
79     warn_report("Calling no-op %s\r", __func__);
80 }
81 
82 /* enable or disable low levels log */
qemu_set_log(int log_flags)83 void qemu_set_log(int log_flags)
84 {
85     bool need_to_open_file = false;
86     QemuLogFile *logfile;
87 
88     const int need_to_flush_tcg_on_change =
89         CPU_LOG_INSTR | CPU_LOG_USER_ONLY | CPU_LOG_CVTRACE;
90     if ((qemu_loglevel & need_to_flush_tcg_on_change) !=
91         (log_flags & need_to_flush_tcg_on_change)) {
92         // When instruction tracing flags change, we have to re-translate all
93         // blocks that were translated with tracing on/off.
94         // This may flush too much state, but such changes should be rare.
95         flush_tcg_on_log_instr_chage();
96     }
97     qemu_loglevel = log_flags;
98 
99 #ifdef CONFIG_TRACE_LOG
100     qemu_loglevel |= LOG_TRACE;
101 #endif
102     /*
103      * In all cases we only log if qemu_loglevel is set.
104      * Also:
105      *   If not daemonized we will always log either to stderr
106      *     or to a file (if there is a logfilename).
107      *   If we are daemonized,
108      *     we will only log if there is a logfilename.
109      */
110     if (qemu_loglevel && (!is_daemonized() || logfilename)) {
111         need_to_open_file = true;
112     }
113 
114     qemu_mutex_lock(&qemu_logfile_mutex);
115     if (qemu_logfile && !need_to_open_file) {
116         logfile = qemu_logfile;
117         atomic_rcu_set(&qemu_logfile, NULL);
118         call_rcu(logfile, qemu_logfile_free, rcu);
119     } else if (!qemu_logfile && need_to_open_file) {
120         logfile = g_new0(QemuLogFile, 1);
121         if (logfilename) {
122             logfile->fd = fopen(logfilename, log_append ? "a" : "w");
123             if (!logfile->fd) {
124                 g_free(logfile);
125                 perror(logfilename);
126                 qemu_log_close();
127                 return;
128             }
129             /* In case we are a daemon redirect stderr to logfile */
130             if (is_daemonized()) {
131                 dup2(fileno(logfile->fd), STDERR_FILENO);
132                 fclose(logfile->fd);
133                 /* This will skip closing logfile in qemu_log_close() */
134                 logfile->fd = stderr;
135             }
136         } else {
137             /* Default to stderr if no log file specified */
138             assert(!is_daemonized());
139             logfile->fd = stderr;
140         }
141         /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
142         if (log_uses_own_buffers) {
143             static char logfile_buf[4096];
144 
145             setvbuf(logfile->fd, logfile_buf, _IOLBF, sizeof(logfile_buf));
146         } else {
147 #if defined(_WIN32)
148             /* Win32 doesn't support line-buffering, so use unbuffered output. */
149             setvbuf(logfile->fd, NULL, _IONBF, 0);
150 #else
151             setvbuf(logfile->fd, NULL, _IOLBF, 0);
152 #endif
153             log_append = 1;
154         }
155         atomic_rcu_set(&qemu_logfile, logfile);
156     }
157     qemu_mutex_unlock(&qemu_logfile_mutex);
158 }
159 
qemu_log_needs_buffers(void)160 void qemu_log_needs_buffers(void)
161 {
162     log_uses_own_buffers = true;
163 }
164 
165 /*
166  * Allow the user to include %d in their logfile which will be
167  * substituted with the current PID. This is useful for debugging many
168  * nested linux-user tasks but will result in lots of logs.
169  *
170  * filename may be NULL. In that case, log output is sent to stderr
171  */
qemu_set_log_filename(const char * filename,Error ** errp)172 void qemu_set_log_filename(const char *filename, Error **errp)
173 {
174     g_free(logfilename);
175     logfilename = NULL;
176 
177     if (filename) {
178             char *pidstr = strstr(filename, "%");
179             if (pidstr) {
180                 /* We only accept one %d, no other format strings */
181                 if (pidstr[1] != 'd' || strchr(pidstr + 2, '%')) {
182                     error_setg(errp, "Bad logfile format: %s", filename);
183                     return;
184                 } else {
185                     logfilename = g_strdup_printf(filename, getpid());
186                 }
187             } else {
188                 logfilename = g_strdup(filename);
189             }
190     }
191 
192     qemu_log_close();
193     qemu_set_log(qemu_loglevel);
194     if (!qemu_logfile) {
195         error_setg(errp, "Failed to open logfile: %s", filename);
196     }
197 }
198 
199 /* Returns true if addr is in our debug filter or no filter defined
200  */
qemu_log_in_addr_range(uint64_t addr)201 bool qemu_log_in_addr_range(uint64_t addr)
202 {
203     if (debug_regions) {
204         int i = 0;
205         for (i = 0; i < debug_regions->len; i++) {
206             Range *range = &g_array_index(debug_regions, Range, i);
207             if (range_contains(range, addr)) {
208                 return true;
209             }
210         }
211         return false;
212     } else {
213         return true;
214     }
215 }
216 
217 
qemu_set_dfilter_ranges(const char * filter_spec,Error ** errp)218 void qemu_set_dfilter_ranges(const char *filter_spec, Error **errp)
219 {
220     gchar **ranges = g_strsplit(filter_spec, ",", 0);
221     int i;
222 
223     if (debug_regions) {
224         g_array_unref(debug_regions);
225         debug_regions = NULL;
226     }
227 
228     debug_regions = g_array_sized_new(FALSE, FALSE,
229                                       sizeof(Range), g_strv_length(ranges));
230     for (i = 0; ranges[i]; i++) {
231         const char *r = ranges[i];
232         const char *range_op, *r2, *e;
233         uint64_t r1val, r2val, lob, upb;
234         struct Range range;
235 
236         range_op = strstr(r, "-");
237         r2 = range_op ? range_op + 1 : NULL;
238         if (!range_op) {
239             range_op = strstr(r, "+");
240             r2 = range_op ? range_op + 1 : NULL;
241         }
242         if (!range_op) {
243             range_op = strstr(r, "..");
244             r2 = range_op ? range_op + 2 : NULL;
245         }
246         if (!range_op) {
247             error_setg(errp, "Bad range specifier");
248             goto out;
249         }
250 
251         if (qemu_strtou64(r, &e, 0, &r1val)
252             || e != range_op) {
253             error_setg(errp, "Invalid number to the left of %.*s",
254                        (int)(r2 - range_op), range_op);
255             goto out;
256         }
257         if (qemu_strtou64(r2, NULL, 0, &r2val)) {
258             error_setg(errp, "Invalid number to the right of %.*s",
259                        (int)(r2 - range_op), range_op);
260             goto out;
261         }
262 
263         switch (*range_op) {
264         case '+':
265             lob = r1val;
266             upb = r1val + r2val - 1;
267             break;
268         case '-':
269             upb = r1val;
270             lob = r1val - (r2val - 1);
271             break;
272         case '.':
273             lob = r1val;
274             upb = r2val;
275             break;
276         default:
277             g_assert_not_reached();
278         }
279         if (lob > upb) {
280             error_setg(errp, "Invalid range");
281             goto out;
282         }
283         range_set_bounds(&range, lob, upb);
284         g_array_append_val(debug_regions, range);
285     }
286 out:
287     g_strfreev(ranges);
288 }
289 
290 /* fflush() the log file */
qemu_log_flush(void)291 void qemu_log_flush(void)
292 {
293     QemuLogFile *logfile;
294 
295     rcu_read_lock();
296     logfile = atomic_rcu_read(&qemu_logfile);
297     if (logfile) {
298         fflush(logfile->fd);
299     }
300     rcu_read_unlock();
301 }
302 
303 /* Close the log file */
qemu_log_close(void)304 void qemu_log_close(void)
305 {
306     QemuLogFile *logfile;
307 
308     qemu_mutex_lock(&qemu_logfile_mutex);
309     logfile = qemu_logfile;
310 
311     if (logfile) {
312         atomic_rcu_set(&qemu_logfile, NULL);
313         call_rcu(logfile, qemu_logfile_free, rcu);
314     }
315     qemu_mutex_unlock(&qemu_logfile_mutex);
316 }
317 
318 const QEMULogItem qemu_log_items[] = {
319     { CPU_LOG_TB_OUT_ASM, "out_asm",
320       "show generated host assembly code for each compiled TB" },
321     { CPU_LOG_TB_IN_ASM, "in_asm",
322       "show target assembly code for each compiled TB" },
323     { CPU_LOG_TB_OP, "op",
324       "show micro ops for each compiled TB" },
325     { CPU_LOG_TB_OP_OPT, "op_opt",
326       "show micro ops after optimization" },
327     { CPU_LOG_TB_OP_IND, "op_ind",
328       "show micro ops before indirect lowering" },
329     { CPU_LOG_INT, "int",
330       "show interrupts/exceptions in short format" },
331     { CPU_LOG_EXEC, "exec",
332       "show trace before each executed TB (lots of logs)" },
333     { CPU_LOG_USER_ONLY, "user-instr",
334       "CHERI only: like 'instr' but only for userspace instructions" },
335     { CPU_LOG_INSTR, "instr",
336       "CHERI only: show executed instructions and changed CPU state" },
337     { CPU_LOG_GUEST_DEBUG_MSG, "guest_debug",
338       "CHERI only: Print guest debug messages" },
339     { CPU_LOG_CHERI_BOUNDS, "bounds",
340       "CHERI only: Log out-of-bounds capability creation" },
341     { CPU_LOG_CVTRACE, "cvtrace",
342       "CHERI only: write CheriVis trace (can't be used with others)" },
343     { CPU_LOG_TB_CPU, "cpu",
344       "show CPU registers before entering a TB (lots of logs)" },
345     { CPU_LOG_TB_FPU, "fpu",
346       "include FPU registers in the 'cpu' logging" },
347     { CPU_LOG_MMU, "mmu",
348       "log MMU-related activities" },
349     { CPU_LOG_PCALL, "pcall",
350       "x86 only: show protected mode far calls/returns/exceptions" },
351     { CPU_LOG_RESET, "cpu_reset",
352       "show CPU state before CPU resets" },
353     { LOG_UNIMP, "unimp",
354       "log unimplemented functionality" },
355     { LOG_GUEST_ERROR, "guest_errors",
356       "log when the guest OS does something invalid (eg accessing a\n"
357       "non-existent register)" },
358     { CPU_LOG_PAGE, "page",
359       "dump pages at beginning of user mode emulation" },
360     { CPU_LOG_TB_NOCHAIN, "nochain",
361       "do not chain compiled TBs so that \"exec\" and \"cpu\" show\n"
362       "complete traces" },
363 #ifdef CONFIG_PLUGIN
364     { CPU_LOG_PLUGIN, "plugin", "output from TCG plugins\n"},
365 #endif
366     { LOG_STRACE, "strace",
367       "log every user-mode syscall, its input, and its result" },
368     { 0, NULL, NULL },
369 };
370 
371 /* takes a comma separated list of log masks. Return 0 if error. */
qemu_str_to_log_mask(const char * str)372 int qemu_str_to_log_mask(const char *str)
373 {
374     const QEMULogItem *item;
375     int mask = 0;
376     char **parts = g_strsplit(str, ",", 0);
377     char **tmp;
378 
379     for (tmp = parts; tmp && *tmp; tmp++) {
380         if (g_str_equal(*tmp, "all")) {
381             for (item = qemu_log_items; item->mask != 0; item++) {
382                 mask |= item->mask;
383             }
384 #ifdef CONFIG_TRACE_LOG
385         } else if (g_str_has_prefix(*tmp, "trace:") && (*tmp)[6] != '\0') {
386             trace_enable_events((*tmp) + 6);
387             mask |= LOG_TRACE;
388 #endif
389         } else {
390             for (item = qemu_log_items; item->mask != 0; item++) {
391                 if (g_str_equal(*tmp, item->name)) {
392                     goto found;
393                 }
394             }
395             goto error;
396         found:
397             mask |= item->mask;
398         }
399     }
400 
401     g_strfreev(parts);
402     return mask;
403 
404  error:
405     g_strfreev(parts);
406     return 0;
407 }
408 
qemu_print_log_usage(FILE * f)409 void qemu_print_log_usage(FILE *f)
410 {
411     const QEMULogItem *item;
412     fprintf(f, "Log items (comma separated):\n");
413     for (item = qemu_log_items; item->mask != 0; item++) {
414         fprintf(f, "%-15s %s\n", item->name, item->help);
415     }
416 #ifdef CONFIG_TRACE_LOG
417     fprintf(f, "trace:PATTERN   enable trace events\n");
418     fprintf(f, "\nUse \"-d trace:help\" to get a list of trace events.\n\n");
419 #endif
420 }
421