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