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