1 /* GLIB - Library of useful routines for C programming
2 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
13 *
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, see <http://www.gnu.org/licenses/>.
16 */
17
18 /*
19 * Modified by the GLib Team and others 1997-2000. See the AUTHORS
20 * file for a list of people on the GLib Team. See the ChangeLog
21 * files for a list of changes. These files are distributed with
22 * GLib at ftp://ftp.gtk.org/pub/gtk/.
23 */
24
25 /*
26 * MT safe
27 */
28
29 /**
30 * SECTION:messages
31 * @Title: Message Output and Debugging Functions
32 * @Short_description: functions to output messages and help debug applications
33 *
34 * These functions provide support for outputting messages.
35 *
36 * The g_return family of macros (g_return_if_fail(),
37 * g_return_val_if_fail(), g_return_if_reached(),
38 * g_return_val_if_reached()) should only be used for programming
39 * errors, a typical use case is checking for invalid parameters at
40 * the beginning of a public function. They should not be used if
41 * you just mean "if (error) return", they should only be used if
42 * you mean "if (bug in program) return". The program behavior is
43 * generally considered undefined after one of these checks fails.
44 * They are not intended for normal control flow, only to give a
45 * perhaps-helpful warning before giving up.
46 *
47 * Structured logging output is supported using g_log_structured(). This differs
48 * from the traditional g_log() API in that log messages are handled as a
49 * collection of key–value pairs representing individual pieces of information,
50 * rather than as a single string containing all the information in an arbitrary
51 * format.
52 *
53 * The convenience macros g_info(), g_message(), g_debug(), g_warning() and g_error()
54 * will use the traditional g_log() API unless you define the symbol
55 * %G_LOG_USE_STRUCTURED before including `glib.h`. But note that even messages
56 * logged through the traditional g_log() API are ultimatively passed to
57 * g_log_structured(), so that all log messages end up in same destination.
58 * If %G_LOG_USE_STRUCTURED is defined, g_test_expect_message() will become
59 * ineffective for the wrapper macros g_warning() and friends (see
60 * [Testing for Messages][testing-for-messages]).
61 *
62 * The support for structured logging was motivated by the following needs (some
63 * of which were supported previously; others weren’t):
64 * * Support for multiple logging levels.
65 * * Structured log support with the ability to add `MESSAGE_ID`s (see
66 * g_log_structured()).
67 * * Moving the responsibility for filtering log messages from the program to
68 * the log viewer — instead of libraries and programs installing log handlers
69 * (with g_log_set_handler()) which filter messages before output, all log
70 * messages are outputted, and the log viewer program (such as `journalctl`)
71 * must filter them. This is based on the idea that bugs are sometimes hard
72 * to reproduce, so it is better to log everything possible and then use
73 * tools to analyse the logs than it is to not be able to reproduce a bug to
74 * get additional log data. Code which uses logging in performance-critical
75 * sections should compile out the g_log_structured() calls in
76 * release builds, and compile them in in debugging builds.
77 * * A single writer function which handles all log messages in a process, from
78 * all libraries and program code; rather than multiple log handlers with
79 * poorly defined interactions between them. This allows a program to easily
80 * change its logging policy by changing the writer function, for example to
81 * log to an additional location or to change what logging output fallbacks
82 * are used. The log writer functions provided by GLib are exposed publicly
83 * so they can be used from programs’ log writers. This allows log writer
84 * policy and implementation to be kept separate.
85 * * If a library wants to add standard information to all of its log messages
86 * (such as library state) or to redact private data (such as passwords or
87 * network credentials), it should use a wrapper function around its
88 * g_log_structured() calls or implement that in the single log writer
89 * function.
90 * * If a program wants to pass context data from a g_log_structured() call to
91 * its log writer function so that, for example, it can use the correct
92 * server connection to submit logs to, that user data can be passed as a
93 * zero-length #GLogField to g_log_structured_array().
94 * * Color output needed to be supported on the terminal, to make reading
95 * through logs easier.
96 *
97 * ## Using Structured Logging ## {#using-structured-logging}
98 *
99 * To use structured logging (rather than the old-style logging), either use
100 * the g_log_structured() and g_log_structured_array() functions; or define
101 * `G_LOG_USE_STRUCTURED` before including any GLib header, and use the
102 * g_message(), g_debug(), g_error() (etc.) macros.
103 *
104 * You do not need to define `G_LOG_USE_STRUCTURED` to use g_log_structured(),
105 * but it is a good idea to avoid confusion.
106 *
107 * ## Log Domains ## {#log-domains}
108 *
109 * Log domains may be used to broadly split up the origins of log messages.
110 * Typically, there are one or a few log domains per application or library.
111 * %G_LOG_DOMAIN should be used to define the default log domain for the current
112 * compilation unit — it is typically defined at the top of a source file, or in
113 * the preprocessor flags for a group of source files.
114 *
115 * Log domains must be unique, and it is recommended that they are the
116 * application or library name, optionally followed by a hyphen and a sub-domain
117 * name. For example, `bloatpad` or `bloatpad-io`.
118 *
119 * ## Debug Message Output ## {#debug-message-output}
120 *
121 * The default log functions (g_log_default_handler() for the old-style API and
122 * g_log_writer_default() for the structured API) both drop debug and
123 * informational messages by default, unless the log domains of those messages
124 * are listed in the `G_MESSAGES_DEBUG` environment variable (or it is set to
125 * `all`).
126 *
127 * It is recommended that custom log writer functions re-use the
128 * `G_MESSAGES_DEBUG` environment variable, rather than inventing a custom one,
129 * so that developers can re-use the same debugging techniques and tools across
130 * projects.
131 *
132 * ## Testing for Messages ## {#testing-for-messages}
133 *
134 * With the old g_log() API, g_test_expect_message() and
135 * g_test_assert_expected_messages() could be used in simple cases to check
136 * whether some code under test had emitted a given log message. These
137 * functions have been deprecated with the structured logging API, for several
138 * reasons:
139 * * They relied on an internal queue which was too inflexible for many use
140 * cases, where messages might be emitted in several orders, some
141 * messages might not be emitted deterministically, or messages might be
142 * emitted by unrelated log domains.
143 * * They do not support structured log fields.
144 * * Examining the log output of code is a bad approach to testing it, and
145 * while it might be necessary for legacy code which uses g_log(), it should
146 * be avoided for new code using g_log_structured().
147 *
148 * They will continue to work as before if g_log() is in use (and
149 * %G_LOG_USE_STRUCTURED is not defined). They will do nothing if used with the
150 * structured logging API.
151 *
152 * Examining the log output of code is discouraged: libraries should not emit to
153 * `stderr` during defined behaviour, and hence this should not be tested. If
154 * the log emissions of a library during undefined behaviour need to be tested,
155 * they should be limited to asserting that the library aborts and prints a
156 * suitable error message before aborting. This should be done with
157 * g_test_trap_assert_stderr().
158 *
159 * If it is really necessary to test the structured log messages emitted by a
160 * particular piece of code – and the code cannot be restructured to be more
161 * suitable to more conventional unit testing – you should write a custom log
162 * writer function (see g_log_set_writer_func()) which appends all log messages
163 * to a queue. When you want to check the log messages, examine and clear the
164 * queue, ignoring irrelevant log messages (for example, from log domains other
165 * than the one under test).
166 */
167
168 #include "config.h"
169
170 #include <stdlib.h>
171 #include <stdarg.h>
172 #include <stdio.h>
173 #include <string.h>
174 #include <signal.h>
175 #include <locale.h>
176 #include <errno.h>
177
178 #if defined(__linux__) && !defined(__BIONIC__)
179 #include <sys/types.h>
180 #include <sys/socket.h>
181 #include <sys/un.h>
182 #include <fcntl.h>
183 #include <sys/uio.h>
184 #endif
185
186 #include "glib-init.h"
187 #include "galloca.h"
188 #include "gbacktrace.h"
189 #include "gcharset.h"
190 #include "gconvert.h"
191 #include "genviron.h"
192 #include "gmain.h"
193 #include "gmem.h"
194 #include "gprintfint.h"
195 #include "gtestutils.h"
196 #include "gthread.h"
197 #include "gstrfuncs.h"
198 #include "gstring.h"
199 #include "gpattern.h"
200
201 #ifdef G_OS_UNIX
202 #include <unistd.h>
203 #endif
204
205 #ifdef G_OS_WIN32
206 #include <process.h> /* For getpid() */
207 #include <io.h>
208 # include <windows.h>
209
210 #ifndef ENABLE_VIRTUAL_TERMINAL_PROCESSING
211 #define ENABLE_VIRTUAL_TERMINAL_PROCESSING 0x0004
212 #endif
213
214 #if defined (_MSC_VER) && (_MSC_VER >=1400)
215 /* This is ugly, but we need it for isatty() in case we have bad fd's,
216 * otherwise Windows will abort() the program on msvcrt80.dll and later
217 */
218 #include <crtdbg.h>
219
220 _GLIB_EXTERN void
myInvalidParameterHandler(const wchar_t * expression,const wchar_t * function,const wchar_t * file,unsigned int line,uintptr_t pReserved)221 myInvalidParameterHandler(const wchar_t *expression,
222 const wchar_t *function,
223 const wchar_t *file,
224 unsigned int line,
225 uintptr_t pReserved)
226 {
227 }
228 #endif
229
230 #include "gwin32.h"
231 #endif
232
233 /**
234 * G_LOG_DOMAIN:
235 *
236 * Defines the log domain. See [Log Domains](#log-domains).
237 *
238 * Libraries should define this so that any messages
239 * which they log can be differentiated from messages from other
240 * libraries and application code. But be careful not to define
241 * it in any public header files.
242 *
243 * Log domains must be unique, and it is recommended that they are the
244 * application or library name, optionally followed by a hyphen and a sub-domain
245 * name. For example, `bloatpad` or `bloatpad-io`.
246 *
247 * If undefined, it defaults to the default %NULL (or `""`) log domain; this is
248 * not advisable, as it cannot be filtered against using the `G_MESSAGES_DEBUG`
249 * environment variable.
250 *
251 * For example, GTK+ uses this in its `Makefile.am`:
252 * |[
253 * AM_CPPFLAGS = -DG_LOG_DOMAIN=\"Gtk\"
254 * ]|
255 *
256 * Applications can choose to leave it as the default %NULL (or `""`)
257 * domain. However, defining the domain offers the same advantages as
258 * above.
259 *
260
261 */
262
263 /**
264 * G_LOG_FATAL_MASK:
265 *
266 * GLib log levels that are considered fatal by default.
267 *
268 * This is not used if structured logging is enabled; see
269 * [Using Structured Logging][using-structured-logging].
270 */
271
272 /**
273 * GLogFunc:
274 * @log_domain: the log domain of the message
275 * @log_level: the log level of the message (including the
276 * fatal and recursion flags)
277 * @message: the message to process
278 * @user_data: user data, set in g_log_set_handler()
279 *
280 * Specifies the prototype of log handler functions.
281 *
282 * The default log handler, g_log_default_handler(), automatically appends a
283 * new-line character to @message when printing it. It is advised that any
284 * custom log handler functions behave similarly, so that logging calls in user
285 * code do not need modifying to add a new-line character to the message if the
286 * log handler is changed.
287 *
288 * This is not used if structured logging is enabled; see
289 * [Using Structured Logging][using-structured-logging].
290 */
291
292 /**
293 * GLogLevelFlags:
294 * @G_LOG_FLAG_RECURSION: internal flag
295 * @G_LOG_FLAG_FATAL: internal flag
296 * @G_LOG_LEVEL_ERROR: log level for errors, see g_error().
297 * This level is also used for messages produced by g_assert().
298 * @G_LOG_LEVEL_CRITICAL: log level for critical warning messages, see
299 * g_critical().
300 * This level is also used for messages produced by g_return_if_fail()
301 * and g_return_val_if_fail().
302 * @G_LOG_LEVEL_WARNING: log level for warnings, see g_warning()
303 * @G_LOG_LEVEL_MESSAGE: log level for messages, see g_message()
304 * @G_LOG_LEVEL_INFO: log level for informational messages, see g_info()
305 * @G_LOG_LEVEL_DEBUG: log level for debug messages, see g_debug()
306 * @G_LOG_LEVEL_MASK: a mask including all log levels
307 *
308 * Flags specifying the level of log messages.
309 *
310 * It is possible to change how GLib treats messages of the various
311 * levels using g_log_set_handler() and g_log_set_fatal_mask().
312 */
313
314 /**
315 * G_LOG_LEVEL_USER_SHIFT:
316 *
317 * Log levels below 1<<G_LOG_LEVEL_USER_SHIFT are used by GLib.
318 * Higher bits can be used for user-defined log levels.
319 */
320
321 /**
322 * g_message:
323 * @...: format string, followed by parameters to insert
324 * into the format string (as with printf())
325 *
326 * A convenience function/macro to log a normal message.
327 *
328 * If g_log_default_handler() is used as the log handler function, a new-line
329 * character will automatically be appended to @..., and need not be entered
330 * manually.
331 *
332 * If structured logging is enabled, this will use g_log_structured();
333 * otherwise it will use g_log(). See
334 * [Using Structured Logging][using-structured-logging].
335 */
336
337 /**
338 * g_warning:
339 * @...: format string, followed by parameters to insert
340 * into the format string (as with printf())
341 *
342 * A convenience function/macro to log a warning message. The message should
343 * typically *not* be translated to the user's language.
344 *
345 * This is not intended for end user error reporting. Use of #GError is
346 * preferred for that instead, as it allows calling functions to perform actions
347 * conditional on the type of error.
348 *
349 * Warning messages are intended to be used in the event of unexpected
350 * external conditions (system misconfiguration, missing files,
351 * other trusted programs violating protocol, invalid contents in
352 * trusted files, etc.)
353 *
354 * If attempting to deal with programmer errors (for example, incorrect function
355 * parameters) then you should use %G_LOG_LEVEL_CRITICAL instead.
356 *
357 * g_warn_if_reached() and g_warn_if_fail() log at %G_LOG_LEVEL_WARNING.
358 *
359 * You can make warnings fatal at runtime by setting the `G_DEBUG`
360 * environment variable (see
361 * [Running GLib Applications](glib-running.html)):
362 *
363 * |[
364 * G_DEBUG=fatal-warnings gdb ./my-program
365 * ]|
366 *
367 * Any unrelated failures can be skipped over in
368 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
369 *
370 * If g_log_default_handler() is used as the log handler function,
371 * a newline character will automatically be appended to @..., and
372 * need not be entered manually.
373 *
374 * If structured logging is enabled, this will use g_log_structured();
375 * otherwise it will use g_log(). See
376 * [Using Structured Logging][using-structured-logging].
377 */
378
379 /**
380 * g_critical:
381 * @...: format string, followed by parameters to insert
382 * into the format string (as with printf())
383 *
384 * Logs a "critical warning" (#G_LOG_LEVEL_CRITICAL).
385 *
386 * Critical warnings are intended to be used in the event of an error
387 * that originated in the current process (a programmer error).
388 * Logging of a critical error is by definition an indication of a bug
389 * somewhere in the current program (or its libraries).
390 *
391 * g_return_if_fail(), g_return_val_if_fail(), g_return_if_reached() and
392 * g_return_val_if_reached() log at %G_LOG_LEVEL_CRITICAL.
393 *
394 * You can make critical warnings fatal at runtime by
395 * setting the `G_DEBUG` environment variable (see
396 * [Running GLib Applications](glib-running.html)):
397 *
398 * |[
399 * G_DEBUG=fatal-warnings gdb ./my-program
400 * ]|
401 *
402 * You can also use g_log_set_always_fatal().
403 *
404 * Any unrelated failures can be skipped over in
405 * [gdb](https://www.gnu.org/software/gdb/) using the `continue` command.
406 *
407 * The message should typically *not* be translated to the
408 * user's language.
409 *
410 * If g_log_default_handler() is used as the log handler function, a new-line
411 * character will automatically be appended to @..., and need not be entered
412 * manually.
413 *
414 * If structured logging is enabled, this will use g_log_structured();
415 * otherwise it will use g_log(). See
416 * [Using Structured Logging][using-structured-logging].
417 */
418
419 /**
420 * g_error:
421 * @...: format string, followed by parameters to insert
422 * into the format string (as with printf())
423 *
424 * A convenience function/macro to log an error message. The message should
425 * typically *not* be translated to the user's language.
426 *
427 * This is not intended for end user error reporting. Use of #GError is
428 * preferred for that instead, as it allows calling functions to perform actions
429 * conditional on the type of error.
430 *
431 * Error messages are always fatal, resulting in a call to G_BREAKPOINT()
432 * to terminate the application. This function will
433 * result in a core dump; don't use it for errors you expect.
434 * Using this function indicates a bug in your program, i.e.
435 * an assertion failure.
436 *
437 * If g_log_default_handler() is used as the log handler function, a new-line
438 * character will automatically be appended to @..., and need not be entered
439 * manually.
440 *
441 * If structured logging is enabled, this will use g_log_structured();
442 * otherwise it will use g_log(). See
443 * [Using Structured Logging][using-structured-logging].
444 */
445
446 /**
447 * g_info:
448 * @...: format string, followed by parameters to insert
449 * into the format string (as with printf())
450 *
451 * A convenience function/macro to log an informational message. Seldom used.
452 *
453 * If g_log_default_handler() is used as the log handler function, a new-line
454 * character will automatically be appended to @..., and need not be entered
455 * manually.
456 *
457 * Such messages are suppressed by the g_log_default_handler() and
458 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
459 * set appropriately.
460 *
461 * If structured logging is enabled, this will use g_log_structured();
462 * otherwise it will use g_log(). See
463 * [Using Structured Logging][using-structured-logging].
464 *
465 * Since: 2.40
466 */
467
468 /**
469 * g_debug:
470 * @...: format string, followed by parameters to insert
471 * into the format string (as with printf())
472 *
473 * A convenience function/macro to log a debug message. The message should
474 * typically *not* be translated to the user's language.
475 *
476 * If g_log_default_handler() is used as the log handler function, a new-line
477 * character will automatically be appended to @..., and need not be entered
478 * manually.
479 *
480 * Such messages are suppressed by the g_log_default_handler() and
481 * g_log_writer_default() unless the `G_MESSAGES_DEBUG` environment variable is
482 * set appropriately.
483 *
484 * If structured logging is enabled, this will use g_log_structured();
485 * otherwise it will use g_log(). See
486 * [Using Structured Logging][using-structured-logging].
487 *
488 * Since: 2.6
489 */
490
491 /* --- structures --- */
492 typedef struct _GLogDomain GLogDomain;
493 typedef struct _GLogHandler GLogHandler;
494 struct _GLogDomain
495 {
496 gchar *log_domain;
497 GLogLevelFlags fatal_mask;
498 GLogHandler *handlers;
499 GLogDomain *next;
500 };
501 struct _GLogHandler
502 {
503 guint id;
504 GLogLevelFlags log_level;
505 GLogFunc log_func;
506 gpointer data;
507 GDestroyNotify destroy;
508 GLogHandler *next;
509 };
510
511
512 /* --- variables --- */
513 static GMutex g_messages_lock;
514 static GLogDomain *g_log_domains = NULL;
515 static GPrintFunc glib_print_func = NULL;
516 static GPrintFunc glib_printerr_func = NULL;
517 static GPrivate g_log_depth;
518 static GPrivate g_log_structured_depth;
519 static GLogFunc default_log_func = g_log_default_handler;
520 static gpointer default_log_data = NULL;
521 static GTestLogFatalFunc fatal_log_func = NULL;
522 static gpointer fatal_log_data;
523 static GLogWriterFunc log_writer_func = g_log_writer_default;
524 static gpointer log_writer_user_data = NULL;
525 static GDestroyNotify log_writer_user_data_free = NULL;
526
527 /* --- functions --- */
528
529 static void _g_log_abort (gboolean breakpoint);
530
531 static void
_g_log_abort(gboolean breakpoint)532 _g_log_abort (gboolean breakpoint)
533 {
534 gboolean debugger_present;
535
536 if (g_test_subprocess ())
537 {
538 /* If this is a test case subprocess then it probably caused
539 * this error message on purpose, so just exit() rather than
540 * abort()ing, to avoid triggering any system crash-reporting
541 * daemon.
542 */
543 _exit (1);
544 }
545
546 #ifdef G_OS_WIN32
547 debugger_present = IsDebuggerPresent ();
548 #else
549 /* Assume GDB is attached. */
550 debugger_present = TRUE;
551 #endif /* !G_OS_WIN32 */
552
553 if (debugger_present && breakpoint)
554 G_BREAKPOINT ();
555 else
556 g_abort ();
557 }
558
559 #ifdef G_OS_WIN32
560 static gboolean win32_keep_fatal_message = FALSE;
561
562 /* This default message will usually be overwritten. */
563 /* Yes, a fixed size buffer is bad. So sue me. But g_error() is never
564 * called with huge strings, is it?
565 */
566 static gchar fatal_msg_buf[1000] = "Unspecified fatal error encountered, aborting.";
567 static gchar *fatal_msg_ptr = fatal_msg_buf;
568
569 #undef write
570 static inline int
dowrite(int fd,const void * buf,unsigned int len)571 dowrite (int fd,
572 const void *buf,
573 unsigned int len)
574 {
575 if (win32_keep_fatal_message)
576 {
577 memcpy (fatal_msg_ptr, buf, len);
578 fatal_msg_ptr += len;
579 *fatal_msg_ptr = 0;
580 return len;
581 }
582
583 write (fd, buf, len);
584
585 return len;
586 }
587 #define write(fd, buf, len) dowrite(fd, buf, len)
588
589 #endif
590
591 static void
write_string(FILE * stream,const gchar * string)592 write_string (FILE *stream,
593 const gchar *string)
594 {
595 fputs (string, stream);
596 }
597
598 static void
write_string_sized(FILE * stream,const gchar * string,gssize length)599 write_string_sized (FILE *stream,
600 const gchar *string,
601 gssize length)
602 {
603 /* Is it nul-terminated? */
604 if (length < 0)
605 write_string (stream, string);
606 else
607 fwrite (string, 1, length, stream);
608 }
609
610 static GLogDomain*
g_log_find_domain_L(const gchar * log_domain)611 g_log_find_domain_L (const gchar *log_domain)
612 {
613 GLogDomain *domain;
614
615 domain = g_log_domains;
616 while (domain)
617 {
618 if (strcmp (domain->log_domain, log_domain) == 0)
619 return domain;
620 domain = domain->next;
621 }
622 return NULL;
623 }
624
625 static GLogDomain*
g_log_domain_new_L(const gchar * log_domain)626 g_log_domain_new_L (const gchar *log_domain)
627 {
628 GLogDomain *domain;
629
630 domain = g_new (GLogDomain, 1);
631 domain->log_domain = g_strdup (log_domain);
632 domain->fatal_mask = G_LOG_FATAL_MASK;
633 domain->handlers = NULL;
634
635 domain->next = g_log_domains;
636 g_log_domains = domain;
637
638 return domain;
639 }
640
641 static void
g_log_domain_check_free_L(GLogDomain * domain)642 g_log_domain_check_free_L (GLogDomain *domain)
643 {
644 if (domain->fatal_mask == G_LOG_FATAL_MASK &&
645 domain->handlers == NULL)
646 {
647 GLogDomain *last, *work;
648
649 last = NULL;
650
651 work = g_log_domains;
652 while (work)
653 {
654 if (work == domain)
655 {
656 if (last)
657 last->next = domain->next;
658 else
659 g_log_domains = domain->next;
660 g_free (domain->log_domain);
661 g_free (domain);
662 break;
663 }
664 last = work;
665 work = last->next;
666 }
667 }
668 }
669
670 static GLogFunc
g_log_domain_get_handler_L(GLogDomain * domain,GLogLevelFlags log_level,gpointer * data)671 g_log_domain_get_handler_L (GLogDomain *domain,
672 GLogLevelFlags log_level,
673 gpointer *data)
674 {
675 if (domain && log_level)
676 {
677 GLogHandler *handler;
678
679 handler = domain->handlers;
680 while (handler)
681 {
682 if ((handler->log_level & log_level) == log_level)
683 {
684 *data = handler->data;
685 return handler->log_func;
686 }
687 handler = handler->next;
688 }
689 }
690
691 *data = default_log_data;
692 return default_log_func;
693 }
694
695 /**
696 * g_log_set_always_fatal:
697 * @fatal_mask: the mask containing bits set for each level
698 * of error which is to be fatal
699 *
700 * Sets the message levels which are always fatal, in any log domain.
701 * When a message with any of these levels is logged the program terminates.
702 * You can only set the levels defined by GLib to be fatal.
703 * %G_LOG_LEVEL_ERROR is always fatal.
704 *
705 * You can also make some message levels fatal at runtime by setting
706 * the `G_DEBUG` environment variable (see
707 * [Running GLib Applications](glib-running.html)).
708 *
709 * Libraries should not call this function, as it affects all messages logged
710 * by a process, including those from other libraries.
711 *
712 * Structured log messages (using g_log_structured() and
713 * g_log_structured_array()) are fatal only if the default log writer is used;
714 * otherwise it is up to the writer function to determine which log messages
715 * are fatal. See [Using Structured Logging][using-structured-logging].
716 *
717 * Returns: the old fatal mask
718 */
719 GLogLevelFlags
g_log_set_always_fatal(GLogLevelFlags fatal_mask)720 g_log_set_always_fatal (GLogLevelFlags fatal_mask)
721 {
722 GLogLevelFlags old_mask;
723
724 /* restrict the global mask to levels that are known to glib
725 * since this setting applies to all domains
726 */
727 fatal_mask &= (1 << G_LOG_LEVEL_USER_SHIFT) - 1;
728 /* force errors to be fatal */
729 fatal_mask |= G_LOG_LEVEL_ERROR;
730 /* remove bogus flag */
731 fatal_mask &= ~G_LOG_FLAG_FATAL;
732
733 g_mutex_lock (&g_messages_lock);
734 old_mask = g_log_always_fatal;
735 g_log_always_fatal = fatal_mask;
736 g_mutex_unlock (&g_messages_lock);
737
738 return old_mask;
739 }
740
741 /**
742 * g_log_set_fatal_mask:
743 * @log_domain: the log domain
744 * @fatal_mask: the new fatal mask
745 *
746 * Sets the log levels which are fatal in the given domain.
747 * %G_LOG_LEVEL_ERROR is always fatal.
748 *
749 * This has no effect on structured log messages (using g_log_structured() or
750 * g_log_structured_array()). To change the fatal behaviour for specific log
751 * messages, programs must install a custom log writer function using
752 * g_log_set_writer_func(). See
753 * [Using Structured Logging][using-structured-logging].
754 *
755 * This function is mostly intended to be used with
756 * %G_LOG_LEVEL_CRITICAL. You should typically not set
757 * %G_LOG_LEVEL_WARNING, %G_LOG_LEVEL_MESSAGE, %G_LOG_LEVEL_INFO or
758 * %G_LOG_LEVEL_DEBUG as fatal except inside of test programs.
759 *
760 * Returns: the old fatal mask for the log domain
761 */
762 GLogLevelFlags
g_log_set_fatal_mask(const gchar * log_domain,GLogLevelFlags fatal_mask)763 g_log_set_fatal_mask (const gchar *log_domain,
764 GLogLevelFlags fatal_mask)
765 {
766 GLogLevelFlags old_flags;
767 GLogDomain *domain;
768
769 if (!log_domain)
770 log_domain = "";
771
772 /* force errors to be fatal */
773 fatal_mask |= G_LOG_LEVEL_ERROR;
774 /* remove bogus flag */
775 fatal_mask &= ~G_LOG_FLAG_FATAL;
776
777 g_mutex_lock (&g_messages_lock);
778
779 domain = g_log_find_domain_L (log_domain);
780 if (!domain)
781 domain = g_log_domain_new_L (log_domain);
782 old_flags = domain->fatal_mask;
783
784 domain->fatal_mask = fatal_mask;
785 g_log_domain_check_free_L (domain);
786
787 g_mutex_unlock (&g_messages_lock);
788
789 return old_flags;
790 }
791
792 /**
793 * g_log_set_handler:
794 * @log_domain: (nullable): the log domain, or %NULL for the default ""
795 * application domain
796 * @log_levels: the log levels to apply the log handler for.
797 * To handle fatal and recursive messages as well, combine
798 * the log levels with the #G_LOG_FLAG_FATAL and
799 * #G_LOG_FLAG_RECURSION bit flags.
800 * @log_func: the log handler function
801 * @user_data: data passed to the log handler
802 *
803 * Sets the log handler for a domain and a set of log levels.
804 * To handle fatal and recursive messages the @log_levels parameter
805 * must be combined with the #G_LOG_FLAG_FATAL and #G_LOG_FLAG_RECURSION
806 * bit flags.
807 *
808 * Note that since the #G_LOG_LEVEL_ERROR log level is always fatal, if
809 * you want to set a handler for this log level you must combine it with
810 * #G_LOG_FLAG_FATAL.
811 *
812 * This has no effect if structured logging is enabled; see
813 * [Using Structured Logging][using-structured-logging].
814 *
815 * Here is an example for adding a log handler for all warning messages
816 * in the default domain:
817 * |[<!-- language="C" -->
818 * g_log_set_handler (NULL, G_LOG_LEVEL_WARNING | G_LOG_FLAG_FATAL
819 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
820 * ]|
821 *
822 * This example adds a log handler for all critical messages from GTK+:
823 * |[<!-- language="C" -->
824 * g_log_set_handler ("Gtk", G_LOG_LEVEL_CRITICAL | G_LOG_FLAG_FATAL
825 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
826 * ]|
827 *
828 * This example adds a log handler for all messages from GLib:
829 * |[<!-- language="C" -->
830 * g_log_set_handler ("GLib", G_LOG_LEVEL_MASK | G_LOG_FLAG_FATAL
831 * | G_LOG_FLAG_RECURSION, my_log_handler, NULL);
832 * ]|
833 *
834 * Returns: the id of the new handler
835 */
836 guint
g_log_set_handler(const gchar * log_domain,GLogLevelFlags log_levels,GLogFunc log_func,gpointer user_data)837 g_log_set_handler (const gchar *log_domain,
838 GLogLevelFlags log_levels,
839 GLogFunc log_func,
840 gpointer user_data)
841 {
842 return g_log_set_handler_full (log_domain, log_levels, log_func, user_data, NULL);
843 }
844
845 /**
846 * g_log_set_handler_full: (rename-to g_log_set_handler)
847 * @log_domain: (nullable): the log domain, or %NULL for the default ""
848 * application domain
849 * @log_levels: the log levels to apply the log handler for.
850 * To handle fatal and recursive messages as well, combine
851 * the log levels with the #G_LOG_FLAG_FATAL and
852 * #G_LOG_FLAG_RECURSION bit flags.
853 * @log_func: the log handler function
854 * @user_data: data passed to the log handler
855 * @destroy: destroy notify for @user_data, or %NULL
856 *
857 * Like g_log_set_handler(), but takes a destroy notify for the @user_data.
858 *
859 * This has no effect if structured logging is enabled; see
860 * [Using Structured Logging][using-structured-logging].
861 *
862 * Returns: the id of the new handler
863 *
864 * Since: 2.46
865 */
866 guint
g_log_set_handler_full(const gchar * log_domain,GLogLevelFlags log_levels,GLogFunc log_func,gpointer user_data,GDestroyNotify destroy)867 g_log_set_handler_full (const gchar *log_domain,
868 GLogLevelFlags log_levels,
869 GLogFunc log_func,
870 gpointer user_data,
871 GDestroyNotify destroy)
872 {
873 static guint handler_id = 0;
874 GLogDomain *domain;
875 GLogHandler *handler;
876
877 g_return_val_if_fail ((log_levels & G_LOG_LEVEL_MASK) != 0, 0);
878 g_return_val_if_fail (log_func != NULL, 0);
879
880 if (!log_domain)
881 log_domain = "";
882
883 handler = g_new (GLogHandler, 1);
884
885 g_mutex_lock (&g_messages_lock);
886
887 domain = g_log_find_domain_L (log_domain);
888 if (!domain)
889 domain = g_log_domain_new_L (log_domain);
890
891 handler->id = ++handler_id;
892 handler->log_level = log_levels;
893 handler->log_func = log_func;
894 handler->data = user_data;
895 handler->destroy = destroy;
896 handler->next = domain->handlers;
897 domain->handlers = handler;
898
899 g_mutex_unlock (&g_messages_lock);
900
901 return handler_id;
902 }
903
904 /**
905 * g_log_set_default_handler:
906 * @log_func: the log handler function
907 * @user_data: data passed to the log handler
908 *
909 * Installs a default log handler which is used if no
910 * log handler has been set for the particular log domain
911 * and log level combination. By default, GLib uses
912 * g_log_default_handler() as default log handler.
913 *
914 * This has no effect if structured logging is enabled; see
915 * [Using Structured Logging][using-structured-logging].
916 *
917 * Returns: the previous default log handler
918 *
919 * Since: 2.6
920 */
921 GLogFunc
g_log_set_default_handler(GLogFunc log_func,gpointer user_data)922 g_log_set_default_handler (GLogFunc log_func,
923 gpointer user_data)
924 {
925 GLogFunc old_log_func;
926
927 g_mutex_lock (&g_messages_lock);
928 old_log_func = default_log_func;
929 default_log_func = log_func;
930 default_log_data = user_data;
931 g_mutex_unlock (&g_messages_lock);
932
933 return old_log_func;
934 }
935
936 /**
937 * g_test_log_set_fatal_handler:
938 * @log_func: the log handler function.
939 * @user_data: data passed to the log handler.
940 *
941 * Installs a non-error fatal log handler which can be
942 * used to decide whether log messages which are counted
943 * as fatal abort the program.
944 *
945 * The use case here is that you are running a test case
946 * that depends on particular libraries or circumstances
947 * and cannot prevent certain known critical or warning
948 * messages. So you install a handler that compares the
949 * domain and message to precisely not abort in such a case.
950 *
951 * Note that the handler is reset at the beginning of
952 * any test case, so you have to set it inside each test
953 * function which needs the special behavior.
954 *
955 * This handler has no effect on g_error messages.
956 *
957 * This handler also has no effect on structured log messages (using
958 * g_log_structured() or g_log_structured_array()). To change the fatal
959 * behaviour for specific log messages, programs must install a custom log
960 * writer function using g_log_set_writer_func().See
961 * [Using Structured Logging][using-structured-logging].
962 *
963 * Since: 2.22
964 **/
965 void
g_test_log_set_fatal_handler(GTestLogFatalFunc log_func,gpointer user_data)966 g_test_log_set_fatal_handler (GTestLogFatalFunc log_func,
967 gpointer user_data)
968 {
969 g_mutex_lock (&g_messages_lock);
970 fatal_log_func = log_func;
971 fatal_log_data = user_data;
972 g_mutex_unlock (&g_messages_lock);
973 }
974
975 /**
976 * g_log_remove_handler:
977 * @log_domain: the log domain
978 * @handler_id: the id of the handler, which was returned
979 * in g_log_set_handler()
980 *
981 * Removes the log handler.
982 *
983 * This has no effect if structured logging is enabled; see
984 * [Using Structured Logging][using-structured-logging].
985 */
986 void
g_log_remove_handler(const gchar * log_domain,guint handler_id)987 g_log_remove_handler (const gchar *log_domain,
988 guint handler_id)
989 {
990 GLogDomain *domain;
991
992 g_return_if_fail (handler_id > 0);
993
994 if (!log_domain)
995 log_domain = "";
996
997 g_mutex_lock (&g_messages_lock);
998 domain = g_log_find_domain_L (log_domain);
999 if (domain)
1000 {
1001 GLogHandler *work, *last;
1002
1003 last = NULL;
1004 work = domain->handlers;
1005 while (work)
1006 {
1007 if (work->id == handler_id)
1008 {
1009 if (last)
1010 last->next = work->next;
1011 else
1012 domain->handlers = work->next;
1013 g_log_domain_check_free_L (domain);
1014 g_mutex_unlock (&g_messages_lock);
1015 if (work->destroy)
1016 work->destroy (work->data);
1017 g_free (work);
1018 return;
1019 }
1020 last = work;
1021 work = last->next;
1022 }
1023 }
1024 g_mutex_unlock (&g_messages_lock);
1025 g_warning ("%s: could not find handler with id '%d' for domain \"%s\"",
1026 G_STRLOC, handler_id, log_domain);
1027 }
1028
1029 #define CHAR_IS_SAFE(wc) (!((wc < 0x20 && wc != '\t' && wc != '\n' && wc != '\r') || \
1030 (wc == 0x7f) || \
1031 (wc >= 0x80 && wc < 0xa0)))
1032
1033 static gchar*
strdup_convert(const gchar * string,const gchar * charset)1034 strdup_convert (const gchar *string,
1035 const gchar *charset)
1036 {
1037 if (!g_utf8_validate (string, -1, NULL))
1038 {
1039 GString *gstring = g_string_new ("[Invalid UTF-8] ");
1040 guchar *p;
1041
1042 for (p = (guchar *)string; *p; p++)
1043 {
1044 if (CHAR_IS_SAFE(*p) &&
1045 !(*p == '\r' && *(p + 1) != '\n') &&
1046 *p < 0x80)
1047 g_string_append_c (gstring, *p);
1048 else
1049 g_string_append_printf (gstring, "\\x%02x", (guint)(guchar)*p);
1050 }
1051
1052 return g_string_free (gstring, FALSE);
1053 }
1054 else
1055 {
1056 GError *err = NULL;
1057
1058 gchar *result = g_convert_with_fallback (string, -1, charset, "UTF-8", "?", NULL, NULL, &err);
1059 if (result)
1060 return result;
1061 else
1062 {
1063 /* Not thread-safe, but doesn't matter if we print the warning twice
1064 */
1065 static gboolean warned = FALSE;
1066 if (!warned)
1067 {
1068 warned = TRUE;
1069 _g_fprintf (stderr, "GLib: Cannot convert message: %s\n", err->message);
1070 }
1071 g_error_free (err);
1072
1073 return g_strdup (string);
1074 }
1075 }
1076 }
1077
1078 /* For a radix of 8 we need at most 3 output bytes for 1 input
1079 * byte. Additionally we might need up to 2 output bytes for the
1080 * readix prefix and 1 byte for the trailing NULL.
1081 */
1082 #define FORMAT_UNSIGNED_BUFSIZE ((GLIB_SIZEOF_LONG * 3) + 3)
1083
1084 static void
format_unsigned(gchar * buf,gulong num,guint radix)1085 format_unsigned (gchar *buf,
1086 gulong num,
1087 guint radix)
1088 {
1089 gulong tmp;
1090 gchar c;
1091 gint i, n;
1092
1093 /* we may not call _any_ GLib functions here (or macros like g_return_if_fail()) */
1094
1095 if (radix != 8 && radix != 10 && radix != 16)
1096 {
1097 *buf = '\000';
1098 return;
1099 }
1100
1101 if (!num)
1102 {
1103 *buf++ = '0';
1104 *buf = '\000';
1105 return;
1106 }
1107
1108 if (radix == 16)
1109 {
1110 *buf++ = '0';
1111 *buf++ = 'x';
1112 }
1113 else if (radix == 8)
1114 {
1115 *buf++ = '0';
1116 }
1117
1118 n = 0;
1119 tmp = num;
1120 while (tmp)
1121 {
1122 tmp /= radix;
1123 n++;
1124 }
1125
1126 i = n;
1127
1128 /* Again we can't use g_assert; actually this check should _never_ fail. */
1129 if (n > FORMAT_UNSIGNED_BUFSIZE - 3)
1130 {
1131 *buf = '\000';
1132 return;
1133 }
1134
1135 while (num)
1136 {
1137 i--;
1138 c = (num % radix);
1139 if (c < 10)
1140 buf[i] = c + '0';
1141 else
1142 buf[i] = c + 'a' - 10;
1143 num /= radix;
1144 }
1145
1146 buf[n] = '\000';
1147 }
1148
1149 /* string size big enough to hold level prefix */
1150 #define STRING_BUFFER_SIZE (FORMAT_UNSIGNED_BUFSIZE + 32)
1151
1152 #define ALERT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING)
1153
1154 /* these are emitted by the default log handler */
1155 #define DEFAULT_LEVELS (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL | G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE)
1156 /* these are filtered by G_MESSAGES_DEBUG by the default log handler */
1157 #define INFO_LEVELS (G_LOG_LEVEL_INFO | G_LOG_LEVEL_DEBUG)
1158
1159 static const gchar *log_level_to_color (GLogLevelFlags log_level,
1160 gboolean use_color);
1161 static const gchar *color_reset (gboolean use_color);
1162
1163 static FILE *
mklevel_prefix(gchar level_prefix[STRING_BUFFER_SIZE],GLogLevelFlags log_level,gboolean use_color)1164 mklevel_prefix (gchar level_prefix[STRING_BUFFER_SIZE],
1165 GLogLevelFlags log_level,
1166 gboolean use_color)
1167 {
1168 gboolean to_stdout = TRUE;
1169
1170 /* we may not call _any_ GLib functions here */
1171
1172 strcpy (level_prefix, log_level_to_color (log_level, use_color));
1173
1174 switch (log_level & G_LOG_LEVEL_MASK)
1175 {
1176 case G_LOG_LEVEL_ERROR:
1177 strcat (level_prefix, "ERROR");
1178 to_stdout = FALSE;
1179 break;
1180 case G_LOG_LEVEL_CRITICAL:
1181 strcat (level_prefix, "CRITICAL");
1182 to_stdout = FALSE;
1183 break;
1184 case G_LOG_LEVEL_WARNING:
1185 strcat (level_prefix, "WARNING");
1186 to_stdout = FALSE;
1187 break;
1188 case G_LOG_LEVEL_MESSAGE:
1189 strcat (level_prefix, "Message");
1190 to_stdout = FALSE;
1191 break;
1192 case G_LOG_LEVEL_INFO:
1193 strcat (level_prefix, "INFO");
1194 break;
1195 case G_LOG_LEVEL_DEBUG:
1196 strcat (level_prefix, "DEBUG");
1197 break;
1198 default:
1199 if (log_level)
1200 {
1201 strcat (level_prefix, "LOG-");
1202 format_unsigned (level_prefix + 4, log_level & G_LOG_LEVEL_MASK, 16);
1203 }
1204 else
1205 strcat (level_prefix, "LOG");
1206 break;
1207 }
1208
1209 strcat (level_prefix, color_reset (use_color));
1210
1211 if (log_level & G_LOG_FLAG_RECURSION)
1212 strcat (level_prefix, " (recursed)");
1213 if (log_level & ALERT_LEVELS)
1214 strcat (level_prefix, " **");
1215
1216 #ifdef G_OS_WIN32
1217 if ((log_level & G_LOG_FLAG_FATAL) != 0 && !g_test_initialized ())
1218 win32_keep_fatal_message = TRUE;
1219 #endif
1220 return to_stdout ? stdout : stderr;
1221 }
1222
1223 typedef struct {
1224 gchar *log_domain;
1225 GLogLevelFlags log_level;
1226 gchar *pattern;
1227 } GTestExpectedMessage;
1228
1229 static GSList *expected_messages = NULL;
1230
1231 /**
1232 * g_logv:
1233 * @log_domain: (nullable): the log domain, or %NULL for the default ""
1234 * application domain
1235 * @log_level: the log level
1236 * @format: the message format. See the printf() documentation
1237 * @args: the parameters to insert into the format string
1238 *
1239 * Logs an error or debugging message.
1240 *
1241 * If the log level has been set as fatal, G_BREAKPOINT() is called
1242 * to terminate the program. See the documentation for G_BREAKPOINT() for
1243 * details of the debugging options this provides.
1244 *
1245 * If g_log_default_handler() is used as the log handler function, a new-line
1246 * character will automatically be appended to @..., and need not be entered
1247 * manually.
1248 *
1249 * If [structured logging is enabled][using-structured-logging] this will
1250 * output via the structured log writer function (see g_log_set_writer_func()).
1251 */
1252 void
g_logv(const gchar * log_domain,GLogLevelFlags log_level,const gchar * format,va_list args)1253 g_logv (const gchar *log_domain,
1254 GLogLevelFlags log_level,
1255 const gchar *format,
1256 va_list args)
1257 {
1258 gboolean was_fatal = (log_level & G_LOG_FLAG_FATAL) != 0;
1259 gboolean was_recursion = (log_level & G_LOG_FLAG_RECURSION) != 0;
1260 gchar buffer[1025], *msg, *msg_alloc = NULL;
1261 gint i;
1262
1263 log_level &= G_LOG_LEVEL_MASK;
1264 if (!log_level)
1265 return;
1266
1267 if (log_level & G_LOG_FLAG_RECURSION)
1268 {
1269 /* we use a stack buffer of fixed size, since we're likely
1270 * in an out-of-memory situation
1271 */
1272 gsize size G_GNUC_UNUSED;
1273
1274 size = _g_vsnprintf (buffer, 1024, format, args);
1275 msg = buffer;
1276 }
1277 else
1278 msg = msg_alloc = g_strdup_vprintf (format, args);
1279
1280 if (expected_messages)
1281 {
1282 GTestExpectedMessage *expected = expected_messages->data;
1283
1284 if (g_strcmp0 (expected->log_domain, log_domain) == 0 &&
1285 ((log_level & expected->log_level) == expected->log_level) &&
1286 g_pattern_match_simple (expected->pattern, msg))
1287 {
1288 expected_messages = g_slist_delete_link (expected_messages,
1289 expected_messages);
1290 g_free (expected->log_domain);
1291 g_free (expected->pattern);
1292 g_free (expected);
1293 g_free (msg_alloc);
1294 return;
1295 }
1296 else if ((log_level & G_LOG_LEVEL_DEBUG) != G_LOG_LEVEL_DEBUG)
1297 {
1298 gchar level_prefix[STRING_BUFFER_SIZE];
1299 gchar *expected_message;
1300
1301 mklevel_prefix (level_prefix, expected->log_level, FALSE);
1302 expected_message = g_strdup_printf ("Did not see expected message %s-%s: %s",
1303 expected->log_domain ? expected->log_domain : "**",
1304 level_prefix, expected->pattern);
1305 g_log_default_handler (G_LOG_DOMAIN, G_LOG_LEVEL_CRITICAL, expected_message, NULL);
1306 g_free (expected_message);
1307
1308 log_level |= G_LOG_FLAG_FATAL;
1309 }
1310 }
1311
1312 for (i = g_bit_nth_msf (log_level, -1); i >= 0; i = g_bit_nth_msf (log_level, i))
1313 {
1314 GLogLevelFlags test_level;
1315
1316 test_level = 1 << i;
1317 if (log_level & test_level)
1318 {
1319 GLogDomain *domain;
1320 GLogFunc log_func;
1321 GLogLevelFlags domain_fatal_mask;
1322 gpointer data = NULL;
1323 gboolean masquerade_fatal = FALSE;
1324 guint depth;
1325
1326 if (was_fatal)
1327 test_level |= G_LOG_FLAG_FATAL;
1328 if (was_recursion)
1329 test_level |= G_LOG_FLAG_RECURSION;
1330
1331 /* check recursion and lookup handler */
1332 g_mutex_lock (&g_messages_lock);
1333 depth = GPOINTER_TO_UINT (g_private_get (&g_log_depth));
1334 domain = g_log_find_domain_L (log_domain ? log_domain : "");
1335 if (depth)
1336 test_level |= G_LOG_FLAG_RECURSION;
1337 depth++;
1338 domain_fatal_mask = domain ? domain->fatal_mask : G_LOG_FATAL_MASK;
1339 if ((domain_fatal_mask | g_log_always_fatal) & test_level)
1340 test_level |= G_LOG_FLAG_FATAL;
1341 if (test_level & G_LOG_FLAG_RECURSION)
1342 log_func = _g_log_fallback_handler;
1343 else
1344 log_func = g_log_domain_get_handler_L (domain, test_level, &data);
1345 domain = NULL;
1346 g_mutex_unlock (&g_messages_lock);
1347
1348 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1349
1350 log_func (log_domain, test_level, msg, data);
1351
1352 if ((test_level & G_LOG_FLAG_FATAL)
1353 && !(test_level & G_LOG_LEVEL_ERROR))
1354 {
1355 masquerade_fatal = fatal_log_func
1356 && !fatal_log_func (log_domain, test_level, msg, fatal_log_data);
1357 }
1358
1359 if ((test_level & G_LOG_FLAG_FATAL) && !masquerade_fatal)
1360 {
1361 /* MessageBox is allowed on UWP apps only when building against
1362 * the debug CRT, which will set -D_DEBUG */
1363 #if defined(G_OS_WIN32) && (defined(_DEBUG) || !defined(G_WINAPI_ONLY_APP))
1364 if (win32_keep_fatal_message)
1365 {
1366 gchar *locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
1367
1368 MessageBox (NULL, locale_msg, NULL,
1369 MB_ICONERROR|MB_SETFOREGROUND);
1370 }
1371 #endif
1372
1373 _g_log_abort (!(test_level & G_LOG_FLAG_RECURSION));
1374 }
1375
1376 depth--;
1377 g_private_set (&g_log_depth, GUINT_TO_POINTER (depth));
1378 }
1379 }
1380
1381 g_free (msg_alloc);
1382 }
1383
1384 /**
1385 * g_log:
1386 * @log_domain: (nullable): the log domain, usually #G_LOG_DOMAIN, or %NULL
1387 * for the default
1388 * @log_level: the log level, either from #GLogLevelFlags
1389 * or a user-defined level
1390 * @format: the message format. See the printf() documentation
1391 * @...: the parameters to insert into the format string
1392 *
1393 * Logs an error or debugging message.
1394 *
1395 * If the log level has been set as fatal, G_BREAKPOINT() is called
1396 * to terminate the program. See the documentation for G_BREAKPOINT() for
1397 * details of the debugging options this provides.
1398 *
1399 * If g_log_default_handler() is used as the log handler function, a new-line
1400 * character will automatically be appended to @..., and need not be entered
1401 * manually.
1402 *
1403 * If [structured logging is enabled][using-structured-logging] this will
1404 * output via the structured log writer function (see g_log_set_writer_func()).
1405 */
1406 void
g_log(const gchar * log_domain,GLogLevelFlags log_level,const gchar * format,...)1407 g_log (const gchar *log_domain,
1408 GLogLevelFlags log_level,
1409 const gchar *format,
1410 ...)
1411 {
1412 va_list args;
1413
1414 va_start (args, format);
1415 g_logv (log_domain, log_level, format, args);
1416 va_end (args);
1417 }
1418
1419 /* Return value must be 1 byte long (plus nul byte).
1420 * Reference: http://man7.org/linux/man-pages/man3/syslog.3.html#DESCRIPTION
1421 */
1422 static const gchar *
log_level_to_priority(GLogLevelFlags log_level)1423 log_level_to_priority (GLogLevelFlags log_level)
1424 {
1425 if (log_level & G_LOG_LEVEL_ERROR)
1426 return "3";
1427 else if (log_level & G_LOG_LEVEL_CRITICAL)
1428 return "4";
1429 else if (log_level & G_LOG_LEVEL_WARNING)
1430 return "4";
1431 else if (log_level & G_LOG_LEVEL_MESSAGE)
1432 return "5";
1433 else if (log_level & G_LOG_LEVEL_INFO)
1434 return "6";
1435 else if (log_level & G_LOG_LEVEL_DEBUG)
1436 return "7";
1437
1438 /* Default to LOG_NOTICE for custom log levels. */
1439 return "5";
1440 }
1441
1442 static FILE *
log_level_to_file(GLogLevelFlags log_level)1443 log_level_to_file (GLogLevelFlags log_level)
1444 {
1445 if (log_level & (G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL |
1446 G_LOG_LEVEL_WARNING | G_LOG_LEVEL_MESSAGE))
1447 return stderr;
1448 else
1449 return stdout;
1450 }
1451
1452 static const gchar *
log_level_to_color(GLogLevelFlags log_level,gboolean use_color)1453 log_level_to_color (GLogLevelFlags log_level,
1454 gboolean use_color)
1455 {
1456 /* we may not call _any_ GLib functions here */
1457
1458 if (!use_color)
1459 return "";
1460
1461 if (log_level & G_LOG_LEVEL_ERROR)
1462 return "\033[1;31m"; /* red */
1463 else if (log_level & G_LOG_LEVEL_CRITICAL)
1464 return "\033[1;35m"; /* magenta */
1465 else if (log_level & G_LOG_LEVEL_WARNING)
1466 return "\033[1;33m"; /* yellow */
1467 else if (log_level & G_LOG_LEVEL_MESSAGE)
1468 return "\033[1;32m"; /* green */
1469 else if (log_level & G_LOG_LEVEL_INFO)
1470 return "\033[1;32m"; /* green */
1471 else if (log_level & G_LOG_LEVEL_DEBUG)
1472 return "\033[1;32m"; /* green */
1473
1474 /* No color for custom log levels. */
1475 return "";
1476 }
1477
1478 static const gchar *
color_reset(gboolean use_color)1479 color_reset (gboolean use_color)
1480 {
1481 /* we may not call _any_ GLib functions here */
1482
1483 if (!use_color)
1484 return "";
1485
1486 return "\033[0m";
1487 }
1488
1489 #ifdef G_OS_WIN32
1490
1491 /* We might be using tty emulators such as mintty, so try to detect it, if we passed in a valid FD
1492 * so we need to check the name of the pipe if _isatty (fd) == 0
1493 */
1494
1495 static gboolean
win32_is_pipe_tty(int fd)1496 win32_is_pipe_tty (int fd)
1497 {
1498 gboolean result = FALSE;
1499 HANDLE h_fd;
1500 FILE_NAME_INFO *info = NULL;
1501 gint info_size = sizeof (FILE_NAME_INFO) + sizeof (WCHAR) * MAX_PATH;
1502 wchar_t *name = NULL;
1503 gint length;
1504
1505 h_fd = (HANDLE) _get_osfhandle (fd);
1506
1507 if (h_fd == INVALID_HANDLE_VALUE || GetFileType (h_fd) != FILE_TYPE_PIPE)
1508 goto done_query;
1509
1510 /* mintty uses a pipe, in the form of \{cygwin|msys}-xxxxxxxxxxxxxxxx-ptyN-{from|to}-master */
1511
1512 info = g_try_malloc (info_size);
1513
1514 if (info == NULL ||
1515 !GetFileInformationByHandleEx (h_fd, FileNameInfo, info, info_size))
1516 goto done_query;
1517
1518 info->FileName[info->FileNameLength / sizeof (WCHAR)] = L'\0';
1519 name = info->FileName;
1520
1521 length = wcslen (L"\\cygwin-");
1522 if (wcsncmp (name, L"\\cygwin-", length))
1523 {
1524 length = wcslen (L"\\msys-");
1525 if (wcsncmp (name, L"\\msys-", length))
1526 goto done_query;
1527 }
1528
1529 name += length;
1530 length = wcsspn (name, L"0123456789abcdefABCDEF");
1531 if (length != 16)
1532 goto done_query;
1533
1534 name += length;
1535 length = wcslen (L"-pty");
1536 if (wcsncmp (name, L"-pty", length))
1537 goto done_query;
1538
1539 name += length;
1540 length = wcsspn (name, L"0123456789");
1541 if (length != 1)
1542 goto done_query;
1543
1544 name += length;
1545 length = wcslen (L"-to-master");
1546 if (wcsncmp (name, L"-to-master", length))
1547 {
1548 length = wcslen (L"-from-master");
1549 if (wcsncmp (name, L"-from-master", length))
1550 goto done_query;
1551 }
1552
1553 result = TRUE;
1554
1555 done_query:
1556 if (info != NULL)
1557 g_free (info);
1558
1559 return result;
1560 }
1561 #endif
1562
1563 #pragma GCC diagnostic push
1564 #pragma GCC diagnostic ignored "-Wformat-nonliteral"
1565
1566 /**
1567 * g_log_structured:
1568 * @log_domain: log domain, usually %G_LOG_DOMAIN
1569 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1570 * level
1571 * @...: key-value pairs of structured data to add to the log entry, followed
1572 * by the key "MESSAGE", followed by a printf()-style message format,
1573 * followed by parameters to insert in the format string
1574 *
1575 * Log a message with structured data. The message will be passed through to
1576 * the log writer set by the application using g_log_set_writer_func(). If the
1577 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1578 * be aborted by calling G_BREAKPOINT() at the end of this function. If the log writer returns
1579 * %G_LOG_WRITER_UNHANDLED (failure), no other fallback writers will be tried.
1580 * See the documentation for #GLogWriterFunc for information on chaining
1581 * writers.
1582 *
1583 * The structured data is provided as key–value pairs, where keys are UTF-8
1584 * strings, and values are arbitrary pointers — typically pointing to UTF-8
1585 * strings, but that is not a requirement. To pass binary (non-nul-terminated)
1586 * structured data, use g_log_structured_array(). The keys for structured data
1587 * should follow the [systemd journal
1588 * fields](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html)
1589 * specification. It is suggested that custom keys are namespaced according to
1590 * the code which sets them. For example, custom keys from GLib all have a
1591 * `GLIB_` prefix.
1592 *
1593 * The @log_domain will be converted into a `GLIB_DOMAIN` field. @log_level will
1594 * be converted into a
1595 * [`PRIORITY`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#PRIORITY=)
1596 * field. The format string will have its placeholders substituted for the provided
1597 * values and be converted into a
1598 * [`MESSAGE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE=)
1599 * field.
1600 *
1601 * Other fields you may commonly want to pass into this function:
1602 *
1603 * * [`MESSAGE_ID`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=)
1604 * * [`CODE_FILE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FILE=)
1605 * * [`CODE_LINE`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_LINE=)
1606 * * [`CODE_FUNC`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#CODE_FUNC=)
1607 * * [`ERRNO`](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#ERRNO=)
1608 *
1609 * Note that `CODE_FILE`, `CODE_LINE` and `CODE_FUNC` are automatically set by
1610 * the logging macros, G_DEBUG_HERE(), g_message(), g_warning(), g_critical(),
1611 * g_error(), etc, if the symbols `G_LOG_USE_STRUCTURED` is defined before including
1612 * glib.h.
1613 *
1614 * For example:
1615 * |[<!-- language="C" -->
1616 * g_log_structured (G_LOG_DOMAIN, G_LOG_LEVEL_DEBUG,
1617 * "MESSAGE_ID", "06d4df59e6c24647bfe69d2c27ef0b4e",
1618 * "MY_APPLICATION_CUSTOM_FIELD", "some debug string",
1619 * "MESSAGE", "This is a debug message about pointer %p and integer %u.",
1620 * some_pointer, some_integer);
1621 * ]|
1622 *
1623 * Note that each `MESSAGE_ID` must be [uniquely and randomly
1624 * generated](https://www.freedesktop.org/software/systemd/man/systemd.journal-fields.html#MESSAGE_ID=).
1625 * If adding a `MESSAGE_ID`, consider shipping a [message
1626 * catalog](https://www.freedesktop.org/wiki/Software/systemd/catalog/) with
1627 * your software.
1628 *
1629 * To pass a user data pointer to the log writer function which is specific to
1630 * this logging call, you must use g_log_structured_array() and pass the pointer
1631 * as a field with #GLogField.length set to zero, otherwise it will be
1632 * interpreted as a string.
1633 *
1634 * For example:
1635 * |[<!-- language="C" -->
1636 * const GLogField fields[] = {
1637 * { "MESSAGE", "This is a debug message.", -1 },
1638 * { "MESSAGE_ID", "fcfb2e1e65c3494386b74878f1abf893", -1 },
1639 * { "MY_APPLICATION_CUSTOM_FIELD", "some debug string", -1 },
1640 * { "MY_APPLICATION_STATE", state_object, 0 },
1641 * };
1642 * g_log_structured_array (G_LOG_LEVEL_DEBUG, fields, G_N_ELEMENTS (fields));
1643 * ]|
1644 *
1645 * Note also that, even if no other structured fields are specified, there
1646 * must always be a `MESSAGE` key before the format string. The `MESSAGE`-format
1647 * pair has to be the last of the key-value pairs, and `MESSAGE` is the only
1648 * field for which printf()-style formatting is supported.
1649 *
1650 * The default writer function for `stdout` and `stderr` will automatically
1651 * append a new-line character after the message, so you should not add one
1652 * manually to the format string.
1653 *
1654 * Since: 2.50
1655 */
1656 void
g_log_structured(const gchar * log_domain,GLogLevelFlags log_level,...)1657 g_log_structured (const gchar *log_domain,
1658 GLogLevelFlags log_level,
1659 ...)
1660 {
1661 va_list args;
1662 gchar buffer[1025], *message_allocated = NULL;
1663 const char *format;
1664 const gchar *message;
1665 gpointer p;
1666 gsize n_fields, i;
1667 GLogField stack_fields[16];
1668 GLogField *fields = stack_fields;
1669 GLogField *fields_allocated = NULL;
1670 GArray *array = NULL;
1671
1672 va_start (args, log_level);
1673
1674 /* MESSAGE and PRIORITY are a given */
1675 n_fields = 2;
1676
1677 if (log_domain)
1678 n_fields++;
1679
1680 for (p = va_arg (args, gchar *), i = n_fields;
1681 strcmp (p, "MESSAGE") != 0;
1682 p = va_arg (args, gchar *), i++)
1683 {
1684 GLogField field;
1685 const gchar *key = p;
1686 gconstpointer value = va_arg (args, gpointer);
1687
1688 field.key = key;
1689 field.value = value;
1690 field.length = -1;
1691
1692 if (i < 16)
1693 stack_fields[i] = field;
1694 else
1695 {
1696 /* Don't allow dynamic allocation, since we're likely
1697 * in an out-of-memory situation. For lack of a better solution,
1698 * just ignore further key-value pairs.
1699 */
1700 if (log_level & G_LOG_FLAG_RECURSION)
1701 continue;
1702
1703 if (i == 16)
1704 {
1705 array = g_array_sized_new (FALSE, FALSE, sizeof (GLogField), 32);
1706 g_array_append_vals (array, stack_fields, 16);
1707 }
1708
1709 g_array_append_val (array, field);
1710 }
1711 }
1712
1713 n_fields = i;
1714
1715 if (array)
1716 fields = fields_allocated = (GLogField *) g_array_free (array, FALSE);
1717
1718 format = va_arg (args, gchar *);
1719
1720 if (log_level & G_LOG_FLAG_RECURSION)
1721 {
1722 /* we use a stack buffer of fixed size, since we're likely
1723 * in an out-of-memory situation
1724 */
1725 gsize size G_GNUC_UNUSED;
1726
1727 size = _g_vsnprintf (buffer, sizeof (buffer), format, args);
1728 message = buffer;
1729 }
1730 else
1731 {
1732 message = message_allocated = g_strdup_vprintf (format, args);
1733 }
1734
1735 /* Add MESSAGE, PRIORITY and GLIB_DOMAIN. */
1736 fields[0].key = "MESSAGE";
1737 fields[0].value = message;
1738 fields[0].length = -1;
1739
1740 fields[1].key = "PRIORITY";
1741 fields[1].value = log_level_to_priority (log_level);
1742 fields[1].length = -1;
1743
1744 if (log_domain)
1745 {
1746 fields[2].key = "GLIB_DOMAIN";
1747 fields[2].value = log_domain;
1748 fields[2].length = -1;
1749 }
1750
1751 /* Log it. */
1752 g_log_structured_array (log_level, fields, n_fields);
1753
1754 g_free (fields_allocated);
1755 g_free (message_allocated);
1756
1757 va_end (args);
1758 }
1759
1760 /**
1761 * g_log_variant:
1762 * @log_domain: (nullable): log domain, usually %G_LOG_DOMAIN
1763 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1764 * level
1765 * @fields: a dictionary (#GVariant of the type %G_VARIANT_TYPE_VARDICT)
1766 * containing the key-value pairs of message data.
1767 *
1768 * Log a message with structured data, accepting the data within a #GVariant. This
1769 * version is especially useful for use in other languages, via introspection.
1770 *
1771 * The only mandatory item in the @fields dictionary is the "MESSAGE" which must
1772 * contain the text shown to the user.
1773 *
1774 * The values in the @fields dictionary are likely to be of type String
1775 * (#G_VARIANT_TYPE_STRING). Array of bytes (#G_VARIANT_TYPE_BYTESTRING) is also
1776 * supported. In this case the message is handled as binary and will be forwarded
1777 * to the log writer as such. The size of the array should not be higher than
1778 * %G_MAXSSIZE. Otherwise it will be truncated to this size. For other types
1779 * g_variant_print() will be used to convert the value into a string.
1780 *
1781 * For more details on its usage and about the parameters, see g_log_structured().
1782 *
1783 * Since: 2.50
1784 */
1785
1786 void
g_log_variant(const gchar * log_domain,GLogLevelFlags log_level,GVariant * fields)1787 g_log_variant (const gchar *log_domain,
1788 GLogLevelFlags log_level,
1789 GVariant *fields)
1790 {
1791 GVariantIter iter;
1792 GVariant *value;
1793 gchar *key;
1794 GArray *fields_array;
1795 GLogField field;
1796 GSList *values_list, *print_list;
1797
1798 g_return_if_fail (g_variant_is_of_type (fields, G_VARIANT_TYPE_VARDICT));
1799
1800 values_list = print_list = NULL;
1801 fields_array = g_array_new (FALSE, FALSE, sizeof (GLogField));
1802
1803 field.key = "PRIORITY";
1804 field.value = log_level_to_priority (log_level);
1805 field.length = -1;
1806 g_array_append_val (fields_array, field);
1807
1808 if (log_domain)
1809 {
1810 field.key = "GLIB_DOMAIN";
1811 field.value = log_domain;
1812 field.length = -1;
1813 g_array_append_val (fields_array, field);
1814 }
1815
1816 g_variant_iter_init (&iter, fields);
1817 while (g_variant_iter_next (&iter, "{&sv}", &key, &value))
1818 {
1819 gboolean defer_unref = TRUE;
1820
1821 field.key = key;
1822 field.length = -1;
1823
1824 if (g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
1825 {
1826 field.value = g_variant_get_string (value, NULL);
1827 }
1828 else if (g_variant_is_of_type (value, G_VARIANT_TYPE_BYTESTRING))
1829 {
1830 gsize s;
1831 field.value = g_variant_get_fixed_array (value, &s, sizeof (guchar));
1832 if (G_LIKELY (s <= G_MAXSSIZE))
1833 {
1834 field.length = s;
1835 }
1836 else
1837 {
1838 _g_fprintf (stderr,
1839 "Byte array too large (%" G_GSIZE_FORMAT " bytes)"
1840 " passed to g_log_variant(). Truncating to " G_STRINGIFY (G_MAXSSIZE)
1841 " bytes.", s);
1842 field.length = G_MAXSSIZE;
1843 }
1844 }
1845 else
1846 {
1847 char *s = g_variant_print (value, FALSE);
1848 field.value = s;
1849 print_list = g_slist_prepend (print_list, s);
1850 defer_unref = FALSE;
1851 }
1852
1853 g_array_append_val (fields_array, field);
1854
1855 if (G_LIKELY (defer_unref))
1856 values_list = g_slist_prepend (values_list, value);
1857 else
1858 g_variant_unref (value);
1859 }
1860
1861 /* Log it. */
1862 g_log_structured_array (log_level, (GLogField *) fields_array->data, fields_array->len);
1863
1864 g_array_free (fields_array, TRUE);
1865 g_slist_free_full (values_list, (GDestroyNotify) g_variant_unref);
1866 g_slist_free_full (print_list, g_free);
1867 }
1868
1869
1870 #pragma GCC diagnostic pop
1871
1872 static GLogWriterOutput _g_log_writer_fallback (GLogLevelFlags log_level,
1873 const GLogField *fields,
1874 gsize n_fields,
1875 gpointer user_data);
1876
1877 /**
1878 * g_log_structured_array:
1879 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
1880 * level
1881 * @fields: (array length=n_fields): key–value pairs of structured data to add
1882 * to the log message
1883 * @n_fields: number of elements in the @fields array
1884 *
1885 * Log a message with structured data. The message will be passed through to the
1886 * log writer set by the application using g_log_set_writer_func(). If the
1887 * message is fatal (i.e. its log level is %G_LOG_LEVEL_ERROR), the program will
1888 * be aborted at the end of this function.
1889 *
1890 * See g_log_structured() for more documentation.
1891 *
1892 * This assumes that @log_level is already present in @fields (typically as the
1893 * `PRIORITY` field).
1894 *
1895 * Since: 2.50
1896 */
1897 void
g_log_structured_array(GLogLevelFlags log_level,const GLogField * fields,gsize n_fields)1898 g_log_structured_array (GLogLevelFlags log_level,
1899 const GLogField *fields,
1900 gsize n_fields)
1901 {
1902 GLogWriterFunc writer_func;
1903 gpointer writer_user_data;
1904 gboolean recursion;
1905 guint depth;
1906
1907 if (n_fields == 0)
1908 return;
1909
1910 /* Check for recursion and look up the writer function. */
1911 depth = GPOINTER_TO_UINT (g_private_get (&g_log_structured_depth));
1912 recursion = (depth > 0);
1913
1914 g_mutex_lock (&g_messages_lock);
1915
1916 writer_func = recursion ? _g_log_writer_fallback : log_writer_func;
1917 writer_user_data = log_writer_user_data;
1918
1919 g_mutex_unlock (&g_messages_lock);
1920
1921 /* Write the log entry. */
1922 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (++depth));
1923
1924 g_assert (writer_func != NULL);
1925 writer_func (log_level, fields, n_fields, writer_user_data);
1926
1927 g_private_set (&g_log_structured_depth, GUINT_TO_POINTER (--depth));
1928
1929 /* Abort if the message was fatal. */
1930 if (log_level & G_LOG_FATAL_MASK)
1931 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
1932 }
1933
1934 /* Semi-private helper function to implement the g_message() (etc.) macros
1935 * with support for G_GNUC_PRINTF so that @message_format can be checked
1936 * with -Wformat. */
1937 void
g_log_structured_standard(const gchar * log_domain,GLogLevelFlags log_level,const gchar * file,const gchar * line,const gchar * func,const gchar * message_format,...)1938 g_log_structured_standard (const gchar *log_domain,
1939 GLogLevelFlags log_level,
1940 const gchar *file,
1941 const gchar *line,
1942 const gchar *func,
1943 const gchar *message_format,
1944 ...)
1945 {
1946 GLogField fields[] =
1947 {
1948 { "PRIORITY", log_level_to_priority (log_level), -1 },
1949 { "CODE_FILE", file, -1 },
1950 { "CODE_LINE", line, -1 },
1951 { "CODE_FUNC", func, -1 },
1952 /* Filled in later: */
1953 { "MESSAGE", NULL, -1 },
1954 /* If @log_domain is %NULL, we will not pass this field: */
1955 { "GLIB_DOMAIN", log_domain, -1 },
1956 };
1957 gsize n_fields;
1958 gchar *message_allocated = NULL;
1959 gchar buffer[1025];
1960 va_list args;
1961
1962 va_start (args, message_format);
1963
1964 if (log_level & G_LOG_FLAG_RECURSION)
1965 {
1966 /* we use a stack buffer of fixed size, since we're likely
1967 * in an out-of-memory situation
1968 */
1969 gsize size G_GNUC_UNUSED;
1970
1971 size = _g_vsnprintf (buffer, sizeof (buffer), message_format, args);
1972 fields[4].value = buffer;
1973 }
1974 else
1975 {
1976 fields[4].value = message_allocated = g_strdup_vprintf (message_format, args);
1977 }
1978
1979 va_end (args);
1980
1981 n_fields = G_N_ELEMENTS (fields) - ((log_domain == NULL) ? 1 : 0);
1982 g_log_structured_array (log_level, fields, n_fields);
1983
1984 g_free (message_allocated);
1985 }
1986
1987 /**
1988 * g_log_set_writer_func:
1989 * @func: log writer function, which must not be %NULL
1990 * @user_data: (closure func): user data to pass to @func
1991 * @user_data_free: (destroy func): function to free @user_data once it’s
1992 * finished with, if non-%NULL
1993 *
1994 * Set a writer function which will be called to format and write out each log
1995 * message. Each program should set a writer function, or the default writer
1996 * (g_log_writer_default()) will be used.
1997 *
1998 * Libraries **must not** call this function — only programs are allowed to
1999 * install a writer function, as there must be a single, central point where
2000 * log messages are formatted and outputted.
2001 *
2002 * There can only be one writer function. It is an error to set more than one.
2003 *
2004 * Since: 2.50
2005 */
2006 void
g_log_set_writer_func(GLogWriterFunc func,gpointer user_data,GDestroyNotify user_data_free)2007 g_log_set_writer_func (GLogWriterFunc func,
2008 gpointer user_data,
2009 GDestroyNotify user_data_free)
2010 {
2011 g_return_if_fail (func != NULL);
2012
2013 g_mutex_lock (&g_messages_lock);
2014 log_writer_func = func;
2015 log_writer_user_data = user_data;
2016 log_writer_user_data_free = user_data_free;
2017 g_mutex_unlock (&g_messages_lock);
2018 }
2019
2020 /**
2021 * g_log_writer_supports_color:
2022 * @output_fd: output file descriptor to check
2023 *
2024 * Check whether the given @output_fd file descriptor supports ANSI color
2025 * escape sequences. If so, they can safely be used when formatting log
2026 * messages.
2027 *
2028 * Returns: %TRUE if ANSI color escapes are supported, %FALSE otherwise
2029 * Since: 2.50
2030 */
2031 gboolean
g_log_writer_supports_color(gint output_fd)2032 g_log_writer_supports_color (gint output_fd)
2033 {
2034 #ifdef G_OS_WIN32
2035 gboolean result = FALSE;
2036
2037 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2038 _invalid_parameter_handler oldHandler, newHandler;
2039 int prev_report_mode = 0;
2040 #endif
2041
2042 #endif
2043
2044 g_return_val_if_fail (output_fd >= 0, FALSE);
2045
2046 /* FIXME: This check could easily be expanded in future to be more robust
2047 * against different types of terminal, which still vary in their color
2048 * support. cmd.exe on Windows, for example, supports ANSI colors only
2049 * from Windows 10 onwards; bash on Windows has always supported ANSI colors.
2050 * The Windows 10 color support is supported on:
2051 * -Output in the cmd.exe, MSYS/Cygwin standard consoles.
2052 * -Output in the cmd.exe, MSYS/Cygwin piped to the less program.
2053 * but not:
2054 * -Output in Cygwin via mintty (https://github.com/mintty/mintty/issues/482)
2055 * -Color code output when output redirected to file (i.e. program 2> some.txt)
2056 *
2057 * On UNIX systems, we probably want to use the functions from terminfo to
2058 * work out whether colors are supported.
2059 *
2060 * Some examples:
2061 * - https://github.com/chalk/supports-color/blob/9434c93918301a6b47faa01999482adfbf1b715c/index.js#L61
2062 * - http://stackoverflow.com/questions/16755142/how-to-make-win32-console-recognize-ansi-vt100-escape-sequences
2063 * - http://blog.mmediasys.com/2010/11/24/we-all-love-colors/
2064 * - http://unix.stackexchange.com/questions/198794/where-does-the-term-environment-variable-default-get-set
2065 */
2066 #ifdef G_OS_WIN32
2067
2068 #if (defined (_MSC_VER) && _MSC_VER >= 1400)
2069 /* Set up our empty invalid parameter handler, for isatty(),
2070 * in case of bad fd's passed in for isatty(), so that
2071 * msvcrt80.dll+ won't abort the program
2072 */
2073 newHandler = myInvalidParameterHandler;
2074 oldHandler = _set_invalid_parameter_handler (newHandler);
2075
2076 /* Disable the message box for assertions. */
2077 prev_report_mode = _CrtSetReportMode(_CRT_ASSERT, 0);
2078 #endif
2079
2080 if (g_win32_check_windows_version (10, 0, 0, G_WIN32_OS_ANY))
2081 {
2082 HANDLE h_output;
2083 DWORD dw_mode;
2084
2085 if (_isatty (output_fd))
2086 {
2087 h_output = (HANDLE) _get_osfhandle (output_fd);
2088
2089 if (!GetConsoleMode (h_output, &dw_mode))
2090 goto reset_invalid_param_handler;
2091
2092 if (dw_mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)
2093 result = TRUE;
2094
2095 if (!SetConsoleMode (h_output, dw_mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING))
2096 goto reset_invalid_param_handler;
2097
2098 result = TRUE;
2099 }
2100 }
2101
2102 /* FIXME: Support colored outputs for structured logs for pre-Windows 10,
2103 * perhaps using WriteConsoleOutput or SetConsoleTextAttribute
2104 * (bug 775468), on standard Windows consoles, such as cmd.exe
2105 */
2106 if (!result)
2107 result = win32_is_pipe_tty (output_fd);
2108
2109 reset_invalid_param_handler:
2110 #if defined (_MSC_VER) && (_MSC_VER >= 1400)
2111 _CrtSetReportMode(_CRT_ASSERT, prev_report_mode);
2112 _set_invalid_parameter_handler (oldHandler);
2113 #endif
2114
2115 return result;
2116 #else
2117 return isatty (output_fd);
2118 #endif
2119 }
2120
2121 #if defined(__linux__) && !defined(__BIONIC__)
2122 static int journal_fd = -1;
2123
2124 #ifndef SOCK_CLOEXEC
2125 #define SOCK_CLOEXEC 0
2126 #else
2127 #define HAVE_SOCK_CLOEXEC 1
2128 #endif
2129
2130 static void
open_journal(void)2131 open_journal (void)
2132 {
2133 if ((journal_fd = socket (AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
2134 return;
2135
2136 #ifndef HAVE_SOCK_CLOEXEC
2137 if (fcntl (journal_fd, F_SETFD, FD_CLOEXEC) < 0)
2138 {
2139 close (journal_fd);
2140 journal_fd = -1;
2141 }
2142 #endif
2143 }
2144 #endif
2145
2146 /**
2147 * g_log_writer_is_journald:
2148 * @output_fd: output file descriptor to check
2149 *
2150 * Check whether the given @output_fd file descriptor is a connection to the
2151 * systemd journal, or something else (like a log file or `stdout` or
2152 * `stderr`).
2153 *
2154 * Invalid file descriptors are accepted and return %FALSE, which allows for
2155 * the following construct without needing any additional error handling:
2156 * |[<!-- language="C" -->
2157 * is_journald = g_log_writer_is_journald (fileno (stderr));
2158 * ]|
2159 *
2160 * Returns: %TRUE if @output_fd points to the journal, %FALSE otherwise
2161 * Since: 2.50
2162 */
2163 gboolean
g_log_writer_is_journald(gint output_fd)2164 g_log_writer_is_journald (gint output_fd)
2165 {
2166 #if defined(__linux__) && !defined(__BIONIC__)
2167 /* FIXME: Use the new journal API for detecting whether we’re writing to the
2168 * journal. See: https://github.com/systemd/systemd/issues/2473
2169 */
2170 union {
2171 struct sockaddr_storage storage;
2172 struct sockaddr sa;
2173 struct sockaddr_un un;
2174 } addr;
2175 socklen_t addr_len;
2176 int err;
2177
2178 if (output_fd < 0)
2179 return FALSE;
2180
2181 addr_len = sizeof(addr);
2182 err = getpeername (output_fd, &addr.sa, &addr_len);
2183 if (err == 0 && addr.storage.ss_family == AF_UNIX)
2184 return g_str_has_prefix (addr.un.sun_path, "/run/systemd/journal/");
2185 #endif
2186
2187 return FALSE;
2188 }
2189
2190 static void escape_string (GString *string);
2191
2192 /**
2193 * g_log_writer_format_fields:
2194 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2195 * level
2196 * @fields: (array length=n_fields): key–value pairs of structured data forming
2197 * the log message
2198 * @n_fields: number of elements in the @fields array
2199 * @use_color: %TRUE to use ANSI color escape sequences when formatting the
2200 * message, %FALSE to not
2201 *
2202 * Format a structured log message as a string suitable for outputting to the
2203 * terminal (or elsewhere). This will include the values of all fields it knows
2204 * how to interpret, which includes `MESSAGE` and `GLIB_DOMAIN` (see the
2205 * documentation for g_log_structured()). It does not include values from
2206 * unknown fields.
2207 *
2208 * The returned string does **not** have a trailing new-line character. It is
2209 * encoded in the character set of the current locale, which is not necessarily
2210 * UTF-8.
2211 *
2212 * Returns: (transfer full): string containing the formatted log message, in
2213 * the character set of the current locale
2214 * Since: 2.50
2215 */
2216 gchar *
g_log_writer_format_fields(GLogLevelFlags log_level,const GLogField * fields,gsize n_fields,gboolean use_color)2217 g_log_writer_format_fields (GLogLevelFlags log_level,
2218 const GLogField *fields,
2219 gsize n_fields,
2220 gboolean use_color)
2221 {
2222 gsize i;
2223 const gchar *message = NULL;
2224 const gchar *log_domain = NULL;
2225 gchar level_prefix[STRING_BUFFER_SIZE];
2226 GString *gstring;
2227 gint64 now;
2228 time_t now_secs;
2229 struct tm *now_tm;
2230 gchar time_buf[128];
2231
2232 /* Extract some common fields. */
2233 for (i = 0; (message == NULL || log_domain == NULL) && i < n_fields; i++)
2234 {
2235 const GLogField *field = &fields[i];
2236
2237 if (g_strcmp0 (field->key, "MESSAGE") == 0)
2238 message = field->value;
2239 else if (g_strcmp0 (field->key, "GLIB_DOMAIN") == 0)
2240 log_domain = field->value;
2241 }
2242
2243 /* Format things. */
2244 mklevel_prefix (level_prefix, log_level, use_color);
2245
2246 gstring = g_string_new (NULL);
2247 if (log_level & ALERT_LEVELS)
2248 g_string_append (gstring, "\n");
2249 if (!log_domain)
2250 g_string_append (gstring, "** ");
2251
2252 if ((g_log_msg_prefix & (log_level & G_LOG_LEVEL_MASK)) ==
2253 (log_level & G_LOG_LEVEL_MASK))
2254 {
2255 const gchar *prg_name = g_get_prgname ();
2256 gulong pid = getpid ();
2257
2258 if (prg_name == NULL)
2259 g_string_append_printf (gstring, "(process:%lu): ", pid);
2260 else
2261 g_string_append_printf (gstring, "(%s:%lu): ", prg_name, pid);
2262 }
2263
2264 if (log_domain != NULL)
2265 {
2266 g_string_append (gstring, log_domain);
2267 g_string_append_c (gstring, '-');
2268 }
2269 g_string_append (gstring, level_prefix);
2270
2271 g_string_append (gstring, ": ");
2272
2273 /* Timestamp */
2274 now = g_get_real_time ();
2275 now_secs = (time_t) (now / 1000000);
2276 now_tm = localtime (&now_secs);
2277 strftime (time_buf, sizeof (time_buf), "%H:%M:%S", now_tm);
2278
2279 g_string_append_printf (gstring, "%s%s.%03d%s: ",
2280 use_color ? "\033[34m" : "",
2281 time_buf, (gint) ((now / 1000) % 1000),
2282 color_reset (use_color));
2283
2284 if (message == NULL)
2285 {
2286 g_string_append (gstring, "(NULL) message");
2287 }
2288 else
2289 {
2290 GString *msg;
2291 const gchar *charset;
2292
2293 msg = g_string_new (message);
2294 escape_string (msg);
2295
2296 if (g_get_console_charset (&charset))
2297 {
2298 /* charset is UTF-8 already */
2299 g_string_append (gstring, msg->str);
2300 }
2301 else
2302 {
2303 gchar *lstring = strdup_convert (msg->str, charset);
2304 g_string_append (gstring, lstring);
2305 g_free (lstring);
2306 }
2307
2308 g_string_free (msg, TRUE);
2309 }
2310
2311 return g_string_free (gstring, FALSE);
2312 }
2313
2314 /* Enable support for the journal if we're on a recent enough Linux */
2315 #if defined(__linux__) && !defined(__BIONIC__) && defined(HAVE_MKOSTEMP) && defined(O_CLOEXEC)
2316 #define ENABLE_JOURNAL_SENDV
2317 #endif
2318
2319 #ifdef ENABLE_JOURNAL_SENDV
2320 static int
journal_sendv(struct iovec * iov,gsize iovlen)2321 journal_sendv (struct iovec *iov,
2322 gsize iovlen)
2323 {
2324 int buf_fd = -1;
2325 struct msghdr mh;
2326 struct sockaddr_un sa;
2327 union {
2328 struct cmsghdr cmsghdr;
2329 guint8 buf[CMSG_SPACE(sizeof(int))];
2330 } control;
2331 struct cmsghdr *cmsg;
2332 char path[] = "/dev/shm/journal.XXXXXX";
2333
2334 if (journal_fd < 0)
2335 open_journal ();
2336
2337 if (journal_fd < 0)
2338 return -1;
2339
2340 memset (&sa, 0, sizeof (sa));
2341 sa.sun_family = AF_UNIX;
2342 if (g_strlcpy (sa.sun_path, "/run/systemd/journal/socket", sizeof (sa.sun_path)) >= sizeof (sa.sun_path))
2343 return -1;
2344
2345 memset (&mh, 0, sizeof (mh));
2346 mh.msg_name = &sa;
2347 mh.msg_namelen = offsetof (struct sockaddr_un, sun_path) + strlen (sa.sun_path);
2348 mh.msg_iov = iov;
2349 mh.msg_iovlen = iovlen;
2350
2351 retry:
2352 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2353 return 0;
2354
2355 if (errno == EINTR)
2356 goto retry;
2357
2358 if (errno != EMSGSIZE && errno != ENOBUFS)
2359 return -1;
2360
2361 /* Message was too large, so dump to temporary file
2362 * and pass an FD to the journal
2363 */
2364 if ((buf_fd = mkostemp (path, O_CLOEXEC|O_RDWR)) < 0)
2365 return -1;
2366
2367 if (unlink (path) < 0)
2368 {
2369 close (buf_fd);
2370 return -1;
2371 }
2372
2373 if (writev (buf_fd, iov, iovlen) < 0)
2374 {
2375 close (buf_fd);
2376 return -1;
2377 }
2378
2379 mh.msg_iov = NULL;
2380 mh.msg_iovlen = 0;
2381
2382 memset (&control, 0, sizeof (control));
2383 mh.msg_control = &control;
2384 mh.msg_controllen = sizeof (control);
2385
2386 cmsg = CMSG_FIRSTHDR (&mh);
2387 cmsg->cmsg_level = SOL_SOCKET;
2388 cmsg->cmsg_type = SCM_RIGHTS;
2389 cmsg->cmsg_len = CMSG_LEN (sizeof (int));
2390 memcpy (CMSG_DATA (cmsg), &buf_fd, sizeof (int));
2391
2392 mh.msg_controllen = cmsg->cmsg_len;
2393
2394 retry2:
2395 if (sendmsg (journal_fd, &mh, MSG_NOSIGNAL) >= 0)
2396 return 0;
2397
2398 if (errno == EINTR)
2399 goto retry2;
2400
2401 return -1;
2402 }
2403 #endif /* ENABLE_JOURNAL_SENDV */
2404
2405 /**
2406 * g_log_writer_journald:
2407 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2408 * level
2409 * @fields: (array length=n_fields): key–value pairs of structured data forming
2410 * the log message
2411 * @n_fields: number of elements in the @fields array
2412 * @user_data: user data passed to g_log_set_writer_func()
2413 *
2414 * Format a structured log message and send it to the systemd journal as a set
2415 * of key–value pairs. All fields are sent to the journal, but if a field has
2416 * length zero (indicating program-specific data) then only its key will be
2417 * sent.
2418 *
2419 * This is suitable for use as a #GLogWriterFunc.
2420 *
2421 * If GLib has been compiled without systemd support, this function is still
2422 * defined, but will always return %G_LOG_WRITER_UNHANDLED.
2423 *
2424 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2425 * Since: 2.50
2426 */
2427 GLogWriterOutput
g_log_writer_journald(GLogLevelFlags log_level,const GLogField * fields,gsize n_fields,gpointer user_data)2428 g_log_writer_journald (GLogLevelFlags log_level,
2429 const GLogField *fields,
2430 gsize n_fields,
2431 gpointer user_data)
2432 {
2433 #ifdef ENABLE_JOURNAL_SENDV
2434 const char equals = '=';
2435 const char newline = '\n';
2436 gsize i, k;
2437 struct iovec *iov, *v;
2438 char *buf;
2439 gint retval;
2440
2441 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2442 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2443
2444 /* According to systemd.journal-fields(7), the journal allows fields in any
2445 * format (including arbitrary binary), but expects text fields to be UTF-8.
2446 * This is great, because we require input strings to be in UTF-8, so no
2447 * conversion is necessary and we don’t need to care about the current
2448 * locale’s character set.
2449 */
2450
2451 iov = g_alloca (sizeof (struct iovec) * 5 * n_fields);
2452 buf = g_alloca (32 * n_fields);
2453
2454 k = 0;
2455 v = iov;
2456 for (i = 0; i < n_fields; i++)
2457 {
2458 guint64 length;
2459 gboolean binary;
2460
2461 if (fields[i].length < 0)
2462 {
2463 length = strlen (fields[i].value);
2464 binary = strchr (fields[i].value, '\n') != NULL;
2465 }
2466 else
2467 {
2468 length = fields[i].length;
2469 binary = TRUE;
2470 }
2471
2472 if (binary)
2473 {
2474 guint64 nstr;
2475
2476 v[0].iov_base = (gpointer)fields[i].key;
2477 v[0].iov_len = strlen (fields[i].key);
2478
2479 v[1].iov_base = (gpointer)&newline;
2480 v[1].iov_len = 1;
2481
2482 nstr = GUINT64_TO_LE(length);
2483 memcpy (&buf[k], &nstr, sizeof (nstr));
2484
2485 v[2].iov_base = &buf[k];
2486 v[2].iov_len = sizeof (nstr);
2487 v += 3;
2488 k += sizeof (nstr);
2489 }
2490 else
2491 {
2492 v[0].iov_base = (gpointer)fields[i].key;
2493 v[0].iov_len = strlen (fields[i].key);
2494
2495 v[1].iov_base = (gpointer)=
2496 v[1].iov_len = 1;
2497 v += 2;
2498 }
2499
2500 v[0].iov_base = (gpointer)fields[i].value;
2501 v[0].iov_len = length;
2502
2503 v[1].iov_base = (gpointer)&newline;
2504 v[1].iov_len = 1;
2505 v += 2;
2506 }
2507
2508 retval = journal_sendv (iov, v - iov);
2509
2510 return retval == 0 ? G_LOG_WRITER_HANDLED : G_LOG_WRITER_UNHANDLED;
2511 #else
2512 return G_LOG_WRITER_UNHANDLED;
2513 #endif /* ENABLE_JOURNAL_SENDV */
2514 }
2515
2516 /**
2517 * g_log_writer_standard_streams:
2518 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2519 * level
2520 * @fields: (array length=n_fields): key–value pairs of structured data forming
2521 * the log message
2522 * @n_fields: number of elements in the @fields array
2523 * @user_data: user data passed to g_log_set_writer_func()
2524 *
2525 * Format a structured log message and print it to either `stdout` or `stderr`,
2526 * depending on its log level. %G_LOG_LEVEL_INFO and %G_LOG_LEVEL_DEBUG messages
2527 * are sent to `stdout`; all other log levels are sent to `stderr`. Only fields
2528 * which are understood by this function are included in the formatted string
2529 * which is printed.
2530 *
2531 * If the output stream supports ANSI color escape sequences, they will be used
2532 * in the output.
2533 *
2534 * A trailing new-line character is added to the log message when it is printed.
2535 *
2536 * This is suitable for use as a #GLogWriterFunc.
2537 *
2538 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2539 * Since: 2.50
2540 */
2541 GLogWriterOutput
g_log_writer_standard_streams(GLogLevelFlags log_level,const GLogField * fields,gsize n_fields,gpointer user_data)2542 g_log_writer_standard_streams (GLogLevelFlags log_level,
2543 const GLogField *fields,
2544 gsize n_fields,
2545 gpointer user_data)
2546 {
2547 FILE *stream;
2548 gchar *out = NULL; /* in the current locale’s character set */
2549
2550 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2551 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2552
2553 stream = log_level_to_file (log_level);
2554 if (!stream || fileno (stream) < 0)
2555 return G_LOG_WRITER_UNHANDLED;
2556
2557 out = g_log_writer_format_fields (log_level, fields, n_fields,
2558 g_log_writer_supports_color (fileno (stream)));
2559 _g_fprintf (stream, "%s\n", out);
2560 fflush (stream);
2561 g_free (out);
2562
2563 return G_LOG_WRITER_HANDLED;
2564 }
2565
2566 /* The old g_log() API is implemented in terms of the new structured log API.
2567 * However, some of the checks do not line up between the two APIs: the
2568 * structured API only handles fatalness of messages for log levels; the old API
2569 * handles it per-domain as well. Consequently, we need to disable fatalness
2570 * handling in the structured log API when called from the old g_log() API.
2571 *
2572 * We can guarantee that g_log_default_handler() will pass GLIB_OLD_LOG_API as
2573 * the first field to g_log_structured_array(), if that is the case.
2574 */
2575 static gboolean
log_is_old_api(const GLogField * fields,gsize n_fields)2576 log_is_old_api (const GLogField *fields,
2577 gsize n_fields)
2578 {
2579 return (n_fields >= 1 &&
2580 g_strcmp0 (fields[0].key, "GLIB_OLD_LOG_API") == 0 &&
2581 g_strcmp0 (fields[0].value, "1") == 0);
2582 }
2583
2584 /**
2585 * g_log_writer_default:
2586 * @log_level: log level, either from #GLogLevelFlags, or a user-defined
2587 * level
2588 * @fields: (array length=n_fields): key–value pairs of structured data forming
2589 * the log message
2590 * @n_fields: number of elements in the @fields array
2591 * @user_data: user data passed to g_log_set_writer_func()
2592 *
2593 * Format a structured log message and output it to the default log destination
2594 * for the platform. On Linux, this is typically the systemd journal, falling
2595 * back to `stdout` or `stderr` if running from the terminal or if output is
2596 * being redirected to a file.
2597 *
2598 * Support for other platform-specific logging mechanisms may be added in
2599 * future. Distributors of GLib may modify this function to impose their own
2600 * (documented) platform-specific log writing policies.
2601 *
2602 * This is suitable for use as a #GLogWriterFunc, and is the default writer used
2603 * if no other is set using g_log_set_writer_func().
2604 *
2605 * As with g_log_default_handler(), this function drops debug and informational
2606 * messages unless their log domain (or `all`) is listed in the space-separated
2607 * `G_MESSAGES_DEBUG` environment variable.
2608 *
2609 * Returns: %G_LOG_WRITER_HANDLED on success, %G_LOG_WRITER_UNHANDLED otherwise
2610 * Since: 2.50
2611 */
2612 GLogWriterOutput
g_log_writer_default(GLogLevelFlags log_level,const GLogField * fields,gsize n_fields,gpointer user_data)2613 g_log_writer_default (GLogLevelFlags log_level,
2614 const GLogField *fields,
2615 gsize n_fields,
2616 gpointer user_data)
2617 {
2618 static gsize initialized = 0;
2619 static gboolean stderr_is_journal = FALSE;
2620
2621 g_return_val_if_fail (fields != NULL, G_LOG_WRITER_UNHANDLED);
2622 g_return_val_if_fail (n_fields > 0, G_LOG_WRITER_UNHANDLED);
2623
2624 /* Disable debug message output unless specified in G_MESSAGES_DEBUG. */
2625 if (!(log_level & DEFAULT_LEVELS) && !(log_level >> G_LOG_LEVEL_USER_SHIFT))
2626 {
2627 const gchar *domains, *log_domain = NULL;
2628 gsize i;
2629
2630 domains = g_getenv ("G_MESSAGES_DEBUG");
2631
2632 if ((log_level & INFO_LEVELS) == 0 ||
2633 domains == NULL)
2634 return G_LOG_WRITER_HANDLED;
2635
2636 for (i = 0; i < n_fields; i++)
2637 {
2638 if (g_strcmp0 (fields[i].key, "GLIB_DOMAIN") == 0)
2639 {
2640 log_domain = fields[i].value;
2641 break;
2642 }
2643 }
2644
2645 if (strcmp (domains, "all") != 0 &&
2646 (log_domain == NULL || !strstr (domains, log_domain)))
2647 return G_LOG_WRITER_HANDLED;
2648 }
2649
2650 /* Mark messages as fatal if they have a level set in
2651 * g_log_set_always_fatal().
2652 */
2653 if ((log_level & g_log_always_fatal) && !log_is_old_api (fields, n_fields))
2654 log_level |= G_LOG_FLAG_FATAL;
2655
2656 /* Try logging to the systemd journal as first choice. */
2657 if (g_once_init_enter (&initialized))
2658 {
2659 stderr_is_journal = g_log_writer_is_journald (fileno (stderr));
2660 g_once_init_leave (&initialized, TRUE);
2661 }
2662
2663 if (stderr_is_journal &&
2664 g_log_writer_journald (log_level, fields, n_fields, user_data) ==
2665 G_LOG_WRITER_HANDLED)
2666 goto handled;
2667
2668 /* FIXME: Add support for the Windows log. */
2669
2670 if (g_log_writer_standard_streams (log_level, fields, n_fields, user_data) ==
2671 G_LOG_WRITER_HANDLED)
2672 goto handled;
2673
2674 return G_LOG_WRITER_UNHANDLED;
2675
2676 handled:
2677 /* Abort if the message was fatal. */
2678 if (log_level & G_LOG_FLAG_FATAL)
2679 {
2680 /* MessageBox is allowed on UWP apps only when building against
2681 * the debug CRT, which will set -D_DEBUG */
2682 #if defined(G_OS_WIN32) && (defined(_DEBUG) || !defined(G_WINAPI_ONLY_APP))
2683 if (!g_test_initialized ())
2684 {
2685 gchar *locale_msg = NULL;
2686
2687 locale_msg = g_locale_from_utf8 (fatal_msg_buf, -1, NULL, NULL, NULL);
2688 MessageBox (NULL, locale_msg, NULL,
2689 MB_ICONERROR | MB_SETFOREGROUND);
2690 g_free (locale_msg);
2691 }
2692 #endif /* !G_OS_WIN32 */
2693
2694 _g_log_abort (!(log_level & G_LOG_FLAG_RECURSION));
2695 }
2696
2697 return G_LOG_WRITER_HANDLED;
2698 }
2699
2700 static GLogWriterOutput
_g_log_writer_fallback(GLogLevelFlags log_level,const GLogField * fields,gsize n_fields,gpointer user_data)2701 _g_log_writer_fallback (GLogLevelFlags log_level,
2702 const GLogField *fields,
2703 gsize n_fields,
2704 gpointer user_data)
2705 {
2706 FILE *stream;
2707 gsize i;
2708
2709 /* we cannot call _any_ GLib functions in this fallback handler,
2710 * which is why we skip UTF-8 conversion, etc.
2711 * since we either recursed or ran out of memory, we're in a pretty
2712 * pathologic situation anyways, what we can do is giving the
2713 * the process ID unconditionally however.
2714 */
2715
2716 stream = log_level_to_file (log_level);
2717
2718 for (i = 0; i < n_fields; i++)
2719 {
2720 const GLogField *field = &fields[i];
2721
2722 /* Only print fields we definitely recognise, otherwise we could end up
2723 * printing a random non-string pointer provided by the user to be
2724 * interpreted by their writer function.
2725 */
2726 if (strcmp (field->key, "MESSAGE") != 0 &&
2727 strcmp (field->key, "MESSAGE_ID") != 0 &&
2728 strcmp (field->key, "PRIORITY") != 0 &&
2729 strcmp (field->key, "CODE_FILE") != 0 &&
2730 strcmp (field->key, "CODE_LINE") != 0 &&
2731 strcmp (field->key, "CODE_FUNC") != 0 &&
2732 strcmp (field->key, "ERRNO") != 0 &&
2733 strcmp (field->key, "SYSLOG_FACILITY") != 0 &&
2734 strcmp (field->key, "SYSLOG_IDENTIFIER") != 0 &&
2735 strcmp (field->key, "SYSLOG_PID") != 0 &&
2736 strcmp (field->key, "GLIB_DOMAIN") != 0)
2737 continue;
2738
2739 write_string (stream, field->key);
2740 write_string (stream, "=");
2741 write_string_sized (stream, field->value, field->length);
2742 }
2743
2744 #ifndef G_OS_WIN32
2745 {
2746 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2747
2748 format_unsigned (pid_string, getpid (), 10);
2749 write_string (stream, "_PID=");
2750 write_string (stream, pid_string);
2751 }
2752 #endif
2753
2754 return G_LOG_WRITER_HANDLED;
2755 }
2756
2757 /**
2758 * g_return_if_fail_warning: (skip)
2759 * @log_domain: (nullable): log domain
2760 * @pretty_function: function containing the assertion
2761 * @expression: (nullable): expression which failed
2762 *
2763 * Internal function used to print messages from the public g_return_if_fail()
2764 * and g_return_val_if_fail() macros.
2765 */
2766 void
g_return_if_fail_warning(const char * log_domain,const char * pretty_function,const char * expression)2767 g_return_if_fail_warning (const char *log_domain,
2768 const char *pretty_function,
2769 const char *expression)
2770 {
2771 g_log (log_domain,
2772 G_LOG_LEVEL_CRITICAL,
2773 "%s: assertion '%s' failed",
2774 pretty_function,
2775 expression);
2776 }
2777
2778 /**
2779 * g_warn_message: (skip)
2780 * @domain: (nullable): log domain
2781 * @file: file containing the warning
2782 * @line: line number of the warning
2783 * @func: function containing the warning
2784 * @warnexpr: (nullable): expression which failed
2785 *
2786 * Internal function used to print messages from the public g_warn_if_reached()
2787 * and g_warn_if_fail() macros.
2788 */
2789 void
g_warn_message(const char * domain,const char * file,int line,const char * func,const char * warnexpr)2790 g_warn_message (const char *domain,
2791 const char *file,
2792 int line,
2793 const char *func,
2794 const char *warnexpr)
2795 {
2796 char *s, lstr[32];
2797 g_snprintf (lstr, 32, "%d", line);
2798 if (warnexpr)
2799 s = g_strconcat ("(", file, ":", lstr, "):",
2800 func, func[0] ? ":" : "",
2801 " runtime check failed: (", warnexpr, ")", NULL);
2802 else
2803 s = g_strconcat ("(", file, ":", lstr, "):",
2804 func, func[0] ? ":" : "",
2805 " ", "code should not be reached", NULL);
2806 g_log (domain, G_LOG_LEVEL_WARNING, "%s", s);
2807 g_free (s);
2808 }
2809
2810 void
g_assert_warning(const char * log_domain,const char * file,const int line,const char * pretty_function,const char * expression)2811 g_assert_warning (const char *log_domain,
2812 const char *file,
2813 const int line,
2814 const char *pretty_function,
2815 const char *expression)
2816 {
2817 if (expression)
2818 g_log (log_domain,
2819 G_LOG_LEVEL_ERROR,
2820 "file %s: line %d (%s): assertion failed: (%s)",
2821 file,
2822 line,
2823 pretty_function,
2824 expression);
2825 else
2826 g_log (log_domain,
2827 G_LOG_LEVEL_ERROR,
2828 "file %s: line %d (%s): should not be reached",
2829 file,
2830 line,
2831 pretty_function);
2832 _g_log_abort (FALSE);
2833 g_abort ();
2834 }
2835
2836 /**
2837 * g_test_expect_message:
2838 * @log_domain: (nullable): the log domain of the message
2839 * @log_level: the log level of the message
2840 * @pattern: a glob-style [pattern][glib-Glob-style-pattern-matching]
2841 *
2842 * Indicates that a message with the given @log_domain and @log_level,
2843 * with text matching @pattern, is expected to be logged. When this
2844 * message is logged, it will not be printed, and the test case will
2845 * not abort.
2846 *
2847 * This API may only be used with the old logging API (g_log() without
2848 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2849 * API. See [Testing for Messages][testing-for-messages].
2850 *
2851 * Use g_test_assert_expected_messages() to assert that all
2852 * previously-expected messages have been seen and suppressed.
2853 *
2854 * You can call this multiple times in a row, if multiple messages are
2855 * expected as a result of a single call. (The messages must appear in
2856 * the same order as the calls to g_test_expect_message().)
2857 *
2858 * For example:
2859 *
2860 * |[<!-- language="C" -->
2861 * // g_main_context_push_thread_default() should fail if the
2862 * // context is already owned by another thread.
2863 * g_test_expect_message (G_LOG_DOMAIN,
2864 * G_LOG_LEVEL_CRITICAL,
2865 * "assertion*acquired_context*failed");
2866 * g_main_context_push_thread_default (bad_context);
2867 * g_test_assert_expected_messages ();
2868 * ]|
2869 *
2870 * Note that you cannot use this to test g_error() messages, since
2871 * g_error() intentionally never returns even if the program doesn't
2872 * abort; use g_test_trap_subprocess() in this case.
2873 *
2874 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2875 * expected via g_test_expect_message() then they will be ignored.
2876 *
2877 * Since: 2.34
2878 */
2879 void
g_test_expect_message(const gchar * log_domain,GLogLevelFlags log_level,const gchar * pattern)2880 g_test_expect_message (const gchar *log_domain,
2881 GLogLevelFlags log_level,
2882 const gchar *pattern)
2883 {
2884 GTestExpectedMessage *expected;
2885
2886 g_return_if_fail (log_level != 0);
2887 g_return_if_fail (pattern != NULL);
2888 g_return_if_fail (~log_level & G_LOG_LEVEL_ERROR);
2889
2890 expected = g_new (GTestExpectedMessage, 1);
2891 expected->log_domain = g_strdup (log_domain);
2892 expected->log_level = log_level;
2893 expected->pattern = g_strdup (pattern);
2894
2895 expected_messages = g_slist_append (expected_messages, expected);
2896 }
2897
2898 void
g_test_assert_expected_messages_internal(const char * domain,const char * file,int line,const char * func)2899 g_test_assert_expected_messages_internal (const char *domain,
2900 const char *file,
2901 int line,
2902 const char *func)
2903 {
2904 if (expected_messages)
2905 {
2906 GTestExpectedMessage *expected;
2907 gchar level_prefix[STRING_BUFFER_SIZE];
2908 gchar *message;
2909
2910 expected = expected_messages->data;
2911
2912 mklevel_prefix (level_prefix, expected->log_level, FALSE);
2913 message = g_strdup_printf ("Did not see expected message %s-%s: %s",
2914 expected->log_domain ? expected->log_domain : "**",
2915 level_prefix, expected->pattern);
2916 g_assertion_message (G_LOG_DOMAIN, file, line, func, message);
2917 g_free (message);
2918 }
2919 }
2920
2921 /**
2922 * g_test_assert_expected_messages:
2923 *
2924 * Asserts that all messages previously indicated via
2925 * g_test_expect_message() have been seen and suppressed.
2926 *
2927 * This API may only be used with the old logging API (g_log() without
2928 * %G_LOG_USE_STRUCTURED defined). It will not work with the structured logging
2929 * API. See [Testing for Messages][testing-for-messages].
2930 *
2931 * If messages at %G_LOG_LEVEL_DEBUG are emitted, but not explicitly
2932 * expected via g_test_expect_message() then they will be ignored.
2933 *
2934 * Since: 2.34
2935 */
2936
2937 void
_g_log_fallback_handler(const gchar * log_domain,GLogLevelFlags log_level,const gchar * message,gpointer unused_data)2938 _g_log_fallback_handler (const gchar *log_domain,
2939 GLogLevelFlags log_level,
2940 const gchar *message,
2941 gpointer unused_data)
2942 {
2943 gchar level_prefix[STRING_BUFFER_SIZE];
2944 #ifndef G_OS_WIN32
2945 gchar pid_string[FORMAT_UNSIGNED_BUFSIZE];
2946 #endif
2947 FILE *stream;
2948
2949 /* we cannot call _any_ GLib functions in this fallback handler,
2950 * which is why we skip UTF-8 conversion, etc.
2951 * since we either recursed or ran out of memory, we're in a pretty
2952 * pathologic situation anyways, what we can do is giving the
2953 * the process ID unconditionally however.
2954 */
2955
2956 stream = mklevel_prefix (level_prefix, log_level, FALSE);
2957 if (!message)
2958 message = "(NULL) message";
2959
2960 #ifndef G_OS_WIN32
2961 format_unsigned (pid_string, getpid (), 10);
2962 #endif
2963
2964 if (log_domain)
2965 write_string (stream, "\n");
2966 else
2967 write_string (stream, "\n** ");
2968
2969 #ifndef G_OS_WIN32
2970 write_string (stream, "(process:");
2971 write_string (stream, pid_string);
2972 write_string (stream, "): ");
2973 #endif
2974
2975 if (log_domain)
2976 {
2977 write_string (stream, log_domain);
2978 write_string (stream, "-");
2979 }
2980 write_string (stream, level_prefix);
2981 write_string (stream, ": ");
2982 write_string (stream, message);
2983 }
2984
2985 static void
escape_string(GString * string)2986 escape_string (GString *string)
2987 {
2988 const char *p = string->str;
2989 gunichar wc;
2990
2991 while (p < string->str + string->len)
2992 {
2993 gboolean safe;
2994
2995 wc = g_utf8_get_char_validated (p, -1);
2996 if (wc == (gunichar)-1 || wc == (gunichar)-2)
2997 {
2998 gchar *tmp;
2999 guint pos;
3000
3001 pos = p - string->str;
3002
3003 /* Emit invalid UTF-8 as hex escapes
3004 */
3005 tmp = g_strdup_printf ("\\x%02x", (guint)(guchar)*p);
3006 g_string_erase (string, pos, 1);
3007 g_string_insert (string, pos, tmp);
3008
3009 p = string->str + (pos + 4); /* Skip over escape sequence */
3010
3011 g_free (tmp);
3012 continue;
3013 }
3014 if (wc == '\r')
3015 {
3016 safe = *(p + 1) == '\n';
3017 }
3018 else
3019 {
3020 safe = CHAR_IS_SAFE (wc);
3021 }
3022
3023 if (!safe)
3024 {
3025 gchar *tmp;
3026 guint pos;
3027
3028 pos = p - string->str;
3029
3030 /* Largest char we escape is 0x0a, so we don't have to worry
3031 * about 8-digit \Uxxxxyyyy
3032 */
3033 tmp = g_strdup_printf ("\\u%04x", wc);
3034 g_string_erase (string, pos, g_utf8_next_char (p) - p);
3035 g_string_insert (string, pos, tmp);
3036 g_free (tmp);
3037
3038 p = string->str + (pos + 6); /* Skip over escape sequence */
3039 }
3040 else
3041 p = g_utf8_next_char (p);
3042 }
3043 }
3044
3045 /**
3046 * g_log_default_handler:
3047 * @log_domain: (nullable): the log domain of the message, or %NULL for the
3048 * default "" application domain
3049 * @log_level: the level of the message
3050 * @message: (nullable): the message
3051 * @unused_data: (nullable): data passed from g_log() which is unused
3052 *
3053 * The default log handler set up by GLib; g_log_set_default_handler()
3054 * allows to install an alternate default log handler.
3055 * This is used if no log handler has been set for the particular log
3056 * domain and log level combination. It outputs the message to stderr
3057 * or stdout and if the log level is fatal it calls G_BREAKPOINT(). It automatically
3058 * prints a new-line character after the message, so one does not need to be
3059 * manually included in @message.
3060 *
3061 * The behavior of this log handler can be influenced by a number of
3062 * environment variables:
3063 *
3064 * - `G_MESSAGES_PREFIXED`: A :-separated list of log levels for which
3065 * messages should be prefixed by the program name and PID of the
3066 * aplication.
3067 *
3068 * - `G_MESSAGES_DEBUG`: A space-separated list of log domains for
3069 * which debug and informational messages are printed. By default
3070 * these messages are not printed.
3071 *
3072 * stderr is used for levels %G_LOG_LEVEL_ERROR, %G_LOG_LEVEL_CRITICAL,
3073 * %G_LOG_LEVEL_WARNING and %G_LOG_LEVEL_MESSAGE. stdout is used for
3074 * the rest.
3075 *
3076 * This has no effect if structured logging is enabled; see
3077 * [Using Structured Logging][using-structured-logging].
3078 */
3079 void
g_log_default_handler(const gchar * log_domain,GLogLevelFlags log_level,const gchar * message,gpointer unused_data)3080 g_log_default_handler (const gchar *log_domain,
3081 GLogLevelFlags log_level,
3082 const gchar *message,
3083 gpointer unused_data)
3084 {
3085 GLogField fields[4];
3086 int n_fields = 0;
3087
3088 /* we can be called externally with recursion for whatever reason */
3089 if (log_level & G_LOG_FLAG_RECURSION)
3090 {
3091 _g_log_fallback_handler (log_domain, log_level, message, unused_data);
3092 return;
3093 }
3094
3095 fields[0].key = "GLIB_OLD_LOG_API";
3096 fields[0].value = "1";
3097 fields[0].length = -1;
3098 n_fields++;
3099
3100 fields[1].key = "MESSAGE";
3101 fields[1].value = message;
3102 fields[1].length = -1;
3103 n_fields++;
3104
3105 fields[2].key = "PRIORITY";
3106 fields[2].value = log_level_to_priority (log_level);
3107 fields[2].length = -1;
3108 n_fields++;
3109
3110 if (log_domain)
3111 {
3112 fields[3].key = "GLIB_DOMAIN";
3113 fields[3].value = log_domain;
3114 fields[3].length = -1;
3115 n_fields++;
3116 }
3117
3118 /* Print out via the structured log API, but drop any fatal flags since we
3119 * have already handled them. The fatal handling in the structured logging
3120 * API is more coarse-grained than in the old g_log() API, so we don't want
3121 * to use it here.
3122 */
3123 g_log_structured_array (log_level & ~G_LOG_FLAG_FATAL, fields, n_fields);
3124 }
3125
3126 /**
3127 * g_set_print_handler:
3128 * @func: the new print handler
3129 *
3130 * Sets the print handler.
3131 *
3132 * Any messages passed to g_print() will be output via
3133 * the new handler. The default handler simply outputs
3134 * the message to stdout. By providing your own handler
3135 * you can redirect the output, to a GTK+ widget or a
3136 * log file for example.
3137 *
3138 * Returns: the old print handler
3139 */
3140 GPrintFunc
g_set_print_handler(GPrintFunc func)3141 g_set_print_handler (GPrintFunc func)
3142 {
3143 GPrintFunc old_print_func;
3144
3145 g_mutex_lock (&g_messages_lock);
3146 old_print_func = glib_print_func;
3147 glib_print_func = func;
3148 g_mutex_unlock (&g_messages_lock);
3149
3150 return old_print_func;
3151 }
3152
3153 /**
3154 * g_print:
3155 * @format: the message format. See the printf() documentation
3156 * @...: the parameters to insert into the format string
3157 *
3158 * Outputs a formatted message via the print handler.
3159 * The default print handler simply outputs the message to stdout, without
3160 * appending a trailing new-line character. Typically, @format should end with
3161 * its own new-line character.
3162 *
3163 * g_print() should not be used from within libraries for debugging
3164 * messages, since it may be redirected by applications to special
3165 * purpose message windows or even files. Instead, libraries should
3166 * use g_log(), g_log_structured(), or the convenience macros g_message(),
3167 * g_warning() and g_error().
3168 */
3169 void
g_print(const gchar * format,...)3170 g_print (const gchar *format,
3171 ...)
3172 {
3173 va_list args;
3174 gchar *string;
3175 GPrintFunc local_glib_print_func;
3176
3177 g_return_if_fail (format != NULL);
3178
3179 va_start (args, format);
3180 string = g_strdup_vprintf (format, args);
3181 va_end (args);
3182
3183 g_mutex_lock (&g_messages_lock);
3184 local_glib_print_func = glib_print_func;
3185 g_mutex_unlock (&g_messages_lock);
3186
3187 if (local_glib_print_func)
3188 local_glib_print_func (string);
3189 else
3190 {
3191 const gchar *charset;
3192
3193 if (g_get_console_charset (&charset))
3194 fputs (string, stdout); /* charset is UTF-8 already */
3195 else
3196 {
3197 gchar *lstring = strdup_convert (string, charset);
3198
3199 fputs (lstring, stdout);
3200 g_free (lstring);
3201 }
3202 fflush (stdout);
3203 }
3204 g_free (string);
3205 }
3206
3207 /**
3208 * g_set_printerr_handler:
3209 * @func: the new error message handler
3210 *
3211 * Sets the handler for printing error messages.
3212 *
3213 * Any messages passed to g_printerr() will be output via
3214 * the new handler. The default handler simply outputs the
3215 * message to stderr. By providing your own handler you can
3216 * redirect the output, to a GTK+ widget or a log file for
3217 * example.
3218 *
3219 * Returns: the old error message handler
3220 */
3221 GPrintFunc
g_set_printerr_handler(GPrintFunc func)3222 g_set_printerr_handler (GPrintFunc func)
3223 {
3224 GPrintFunc old_printerr_func;
3225
3226 g_mutex_lock (&g_messages_lock);
3227 old_printerr_func = glib_printerr_func;
3228 glib_printerr_func = func;
3229 g_mutex_unlock (&g_messages_lock);
3230
3231 return old_printerr_func;
3232 }
3233
3234 /**
3235 * g_printerr:
3236 * @format: the message format. See the printf() documentation
3237 * @...: the parameters to insert into the format string
3238 *
3239 * Outputs a formatted message via the error message handler.
3240 * The default handler simply outputs the message to stderr, without appending
3241 * a trailing new-line character. Typically, @format should end with its own
3242 * new-line character.
3243 *
3244 * g_printerr() should not be used from within libraries.
3245 * Instead g_log() or g_log_structured() should be used, or the convenience
3246 * macros g_message(), g_warning() and g_error().
3247 */
3248 void
g_printerr(const gchar * format,...)3249 g_printerr (const gchar *format,
3250 ...)
3251 {
3252 va_list args;
3253 gchar *string;
3254 GPrintFunc local_glib_printerr_func;
3255
3256 g_return_if_fail (format != NULL);
3257
3258 va_start (args, format);
3259 string = g_strdup_vprintf (format, args);
3260 va_end (args);
3261
3262 g_mutex_lock (&g_messages_lock);
3263 local_glib_printerr_func = glib_printerr_func;
3264 g_mutex_unlock (&g_messages_lock);
3265
3266 if (local_glib_printerr_func)
3267 local_glib_printerr_func (string);
3268 else
3269 {
3270 const gchar *charset;
3271
3272 if (g_get_console_charset (&charset))
3273 fputs (string, stderr); /* charset is UTF-8 already */
3274 else
3275 {
3276 gchar *lstring = strdup_convert (string, charset);
3277
3278 fputs (lstring, stderr);
3279 g_free (lstring);
3280 }
3281 fflush (stderr);
3282 }
3283 g_free (string);
3284 }
3285
3286 /**
3287 * g_printf_string_upper_bound:
3288 * @format: the format string. See the printf() documentation
3289 * @args: the parameters to be inserted into the format string
3290 *
3291 * Calculates the maximum space needed to store the output
3292 * of the sprintf() function.
3293 *
3294 * Returns: the maximum space needed to store the formatted string
3295 */
3296 gsize
g_printf_string_upper_bound(const gchar * format,va_list args)3297 g_printf_string_upper_bound (const gchar *format,
3298 va_list args)
3299 {
3300 gchar c;
3301 return _g_vsnprintf (&c, 1, format, args) + 1;
3302 }
3303