Exclude some inaccessible code
[platform/core/system/dlog.git] / src / libdlog / log.c
1 /*  MIT License
2  *
3  * Copyright (c) 2012-2020 Samsung Electronics Co., Ltd
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy
6  * of this software and associated documentation files (the "Software"), to deal
7  * in the Software without restriction, including without limitation the rights
8  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9  * copies of the Software, and to permit persons to whom the Software is furnished
10  * to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21  * THE SOFTWARE. */
22
23 // C
24 #include <assert.h>
25 #include <stdbool.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28
29 // POSIX
30 #include <pthread.h>
31 #include <sys/wait.h>
32 #include <unistd.h>
33
34 // Tizen
35 #include <tizen.h>
36
37 // DLog
38 #include <buffer_traits.h>
39 #include "deduplicate.h"
40 #include <dynamic_config.h>
41 #include "extra_sinks.h"
42 #include <libdlog.h>
43 #include "logconfig.h"
44 #include "loglimiter.h"
45
46 #define DEFAULT_CONFIG_LIMITER false
47 #define DEFAULT_CONFIG_PLOG true
48 #define DEFAULT_CONFIG_DEBUGMODE 0
49 #define DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS 0
50
51
52 /* A pseudo-backend that does nothing. Useful for removing the overhead of dlog
53  * for debugging and measurement purposes, also it simplifies some checking as
54  * the `write_to_log` pointer below never needs to be NULL. Note that features
55  * independent of the backend (such as limiter or dynamic config) are controlled
56  * separately if dlog is to be disabled completely and that minimal overhead is
57  * always present (e.g. building the message via vprintf). */
58 static int write_to_log_null (log_id_t log_id, log_priority prio, const char *tag, const char *msg, struct timespec *tp_mono, int32_t pid, int32_t tid)
59 {
60         return DLOG_ERROR_NONE;
61 }
62
63 /**
64  * @brief Points to a function which writes a log message
65  * @details The function pointed to depends on the backend used
66  * @param[in] log_id ID of the buffer to log to. Belongs to (LOG_ID_INVALID, LOG_ID_MAX) non-inclusive
67  * @param[in] prio Priority of the message.
68  * @param[in] tag The message tag, identifies the sender.
69  * @param[in] msg The contents of the message.
70  * @return Returns the number of bytes written on success and a negative error value on error.
71  * @see __dlog_init_backend
72  */
73 int (*write_to_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg, struct timespec *tp_mono, int32_t pid, int32_t tid) = write_to_log_null;
74 void (*destroy_backend)(void);
75
76 int (*stash_failed_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg) = NULL;
77 #ifndef UNIT_TEST
78 static int stash_critical(log_id_t log_id, log_priority prio, const char *tag, const char *msg);
79 #endif
80
81 pthread_rwlock_t log_limiter_lock = PTHREAD_RWLOCK_INITIALIZER;
82 static pthread_mutex_t log_construction_lock = PTHREAD_MUTEX_INITIALIZER;
83 static bool is_initialized = false;
84
85 extern void __dlog_init_pipe(const struct log_config *conf);
86 extern void __dlog_init_android(const struct log_config *conf);
87 extern void __dlog_init_zero_copy();
88
89 extern void prepend_container_tag_if_in_container(size_t buf_size, char buf[static buf_size], int *len);
90
91 bool limiter;
92 struct limiter_data *limiter_data;
93 static bool dynamic_config;
94 static bool plog[SINKS_MAX];
95 static bool plog_default_values[SINKS_MAX];
96 static bool enable_secure_logs = true;
97 static bool enable_critical = true;
98
99 static bool should_disable_cancels;
100
101 static int debugmode;
102 static int fatal_assert;
103 static int limiter_apply_to_all_buffers;
104 static _Atomic log_priority priority_filter_level = DLOG_VERBOSE;
105
106 /* Cache pid and tid to avoid up to two syscalls per log. The update function
107  * is registered to happen when new threads are made (including a full fork). */
108 static int32_t cached_pid = 0;
109 _Thread_local int32_t cached_tid = 0;
110
111 static inline int32_t get_cached_pid()
112 {
113         return (cached_pid = cached_pid ?: getpid());
114 }
115
116 static inline int32_t get_cached_tid()
117 {
118         return (cached_tid = cached_tid ?: gettid());
119 }
120
121 static void update_thread_local_ids(void)
122 {
123         cached_pid = 0;
124         cached_tid = 0;
125 }
126
127 /* Here, static_config is the original config from /etc/dlog.conf{,.d} which can be overriden,
128  * but comes back if the override is removed. both_config additionally contains dynamic rules
129  * (by default from /run/dlog/filters.d) which can be changed in the runtime.
130  * The static_config has to be kept separately, so that we can go back to it when dynamic rules change.
131  * Note that most functions only use static_config, since the parameters can't be changed in runtime. */
132 static void __configure_limiter(struct log_config *static_config, struct log_config *both_config)
133 {
134         assert(static_config);
135         if (dynamic_config)
136                 assert(both_config);
137
138         if (!limiter)
139                 return;
140
141         limiter_data = __log_limiter_create(static_config);
142         if (limiter_data && dynamic_config)
143                 __log_limiter_update(limiter_data, both_config);
144         limiter = (bool)limiter_data;
145
146         should_disable_cancels |= limiter; // due to locks
147 }
148
149 static int __configure_backend(struct log_config *config)
150 {
151         assert(config);
152
153         const char *const backend = log_config_claim_backend(config);
154         if (!backend)
155                 return 0;
156
157         if (!strcmp(backend, "pipe")) {
158                 __dlog_init_pipe(config);
159                 should_disable_cancels = true;
160         } else if (!strcmp(backend, "logger"))
161                 __dlog_init_android(config);
162         else if (!strcmp(backend, "zero-copy"))
163                 __dlog_init_zero_copy(config);
164         else if (!strcmp(backend, "null"))
165                 ; // already the default
166         else
167                 return 0;
168
169         return 1;
170 }
171
172 static void __set_plog_default_values(void)
173 {
174         for (size_t i = 0; i < NELEMS(plog); ++i)
175                 plog_default_values[i] = plog[i];
176 }
177
178 static void __initialize_plog(const struct log_config *config)
179 {
180         assert(config);
181
182         /* plog stands for "platform logging", which is why
183          * non-platform (i.e. application) buffers ignore it */
184         const bool plog_default = log_config_get_boolean(config, "plog", DEFAULT_CONFIG_PLOG);
185         for (size_t i = 0; i < NELEMS(plog); ++i)
186                 plog[i] = is_platform_buffer(i) ? plog_default : true;
187
188         __set_plog_default_values();
189 }
190
191 static void __configure_parameters(struct log_config *static_config, struct log_config *both_config)
192 {
193         assert(static_config);
194         assert(both_config);
195
196         __initialize_plog(static_config);
197         __update_plog(static_config);
198         /* Like in __configure_limiter, we also check the dynamic rules. However, we make sure to
199      * set the default values to the ones generated by the static rules first. */
200         __set_plog_default_values();
201         __update_plog(both_config);
202
203         enable_secure_logs = log_config_get_boolean(both_config, "enable_secure_logs", enable_secure_logs);
204         enable_critical = log_config_get_boolean(both_config, "enable_critical", enable_critical);
205         debugmode = log_config_get_int(both_config, "debugmode", DEFAULT_CONFIG_DEBUGMODE);
206         fatal_assert = access(DEBUGMODE_FILE, F_OK) != -1;
207         limiter = log_config_get_boolean(both_config, "limiter", DEFAULT_CONFIG_LIMITER);
208         limiter_apply_to_all_buffers = log_config_get_int(both_config,
209                                                                         "limiter_apply_to_all_buffers",
210                                                                         DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS);
211
212         stash_failed_log = NULL;
213         const char *stash_failed_log_method = log_config_get(both_config, "stash_failed_log_method");
214         if (stash_failed_log_method) {
215 #ifndef UNIT_TEST
216                 if (strcmp(stash_failed_log_method, "critical") == 0)
217                         stash_failed_log = stash_critical;
218 #endif
219         }
220 }
221
222 void __update_plog(const struct log_config *conf)
223 {
224         assert(conf);
225
226         for (size_t i = 0; i < NELEMS(plog); ++i) {
227                 char key[MAX_CONF_KEY_LEN];
228                 const int r = snprintf(key, sizeof key, "enable_%s", log_name_by_id((log_id_t)i));
229                 if (r < 0)
230                         continue;
231                 plog[i] = log_config_get_boolean(conf, key, plog_default_values[i]);
232         }
233 }
234
235 /**
236  * @brief Configure the library
237  * @details Reads relevant config values
238  * @remarks This is more or less a constructor, but there are some obstacles
239  *          to using it as such (i.e. with attribute constructor):
240  *
241  *  - some important pieces of the system link to dlog, they start very early
242  *    such that dlog can't properly initialize (which lasts for program lifetime)
243  *    but don't actually log anything until later on and would be fine under lazy
244  *    initialisation. The way to do it "properly" would be to expose this function
245  *    into the API so that people can manually call it when they're ready, but
246  *    one of the design goals of the current API is that it requires absolutely no
247  *    other calls than `dlog_print`. Changing it would require somebody with a
248  *    bird's eye view of the system to produce a design so I wouldn't count on it.
249  *
250  *  - the constructor would need to have as high of a priority as possible (so as
251  *    to minimize the risk of another library's constructor using uninitialized data)
252  *    but at the same time others might want some room to wrap functions before
253  *    dlog uses them (think mprobe/mcheck). This would also require a design pass.
254  */
255 #ifndef UNIT_TEST
256 static
257 #endif
258 bool __configure(void)
259 {
260         __attribute__((cleanup(log_config_free))) struct log_config static_config = {};
261         __attribute__((cleanup(log_config_free))) struct log_config both_config = {};
262
263         if (log_config_read(&static_config) < 0)
264                 return false;
265         log_config_copy(&both_config, &static_config);
266
267         dynamic_config = __dynamic_config_create(&both_config);
268
269         __configure_parameters(&static_config, &both_config);
270
271         if (!__configure_backend(&both_config)) {
272                 __dynamic_config_destroy();
273                 dynamic_config = false;
274                 return false;
275         }
276
277         __configure_deduplicate(&both_config);
278         __configure_limiter(&static_config, &both_config);
279
280         /* The fork handler also runs when a new thread is made (not just
281          * when the whole process forks), so we can cache both pid and tid. */
282         pthread_atfork(NULL, NULL, update_thread_local_ids);
283
284         return true;
285 }
286
287 static void __attribute__((constructor(101))) __install_pipe_handler(void)
288 {
289         /* We mask SIGPIPE signal because most applications do not install their
290          * own SIGPIPE handler. Default behaviour in SIGPIPE case is to abort the
291          * process. SIGPIPE occurs when e.g. dlog daemon closes read pipe endpoint.
292          *
293          * We do this in the library constructor (at maximum priority) and not
294          * during regular (lazy) initialisation so as to prevent overwriting the
295          * program's actual signal handler, if it has one.
296          *
297          * In theory this is not required for the Android logger backend; however,
298          * this early we don't yet know the backend and also it is good to behave
299          * consistently in this regard anyway.
300          *
301          * We don't revert this in a destructor because Unix signals are bonkers
302          * and we have no way to do this cleanly. Most libdlog users don't use
303          * runtime linking so this would mostly done at program exit either way. */
304         signal(SIGPIPE, SIG_IGN);
305 }
306
307 static void __attribute__((constructor(102))) __set_output_buffering(void)
308 {
309         /* If stdout and/or stderr is redirected to dlog (service, driver)
310          * it is best if we buffer lines, otherwise the following can happen:
311          *  - no buffering: service/driver recives every single byte (precisely
312          *    every single write*(2) call), causing it to either buffer the data
313          *    anyway (service), or print logs at random places (driver)
314          *  - full buffering: service/driver receives several hundred lines,
315          *    which results in one giant entry being added (driver) or long delays
316          *    before logs appear (service) */
317         if (getenv(DLOG_ENV_STDOUT_LINE_BUFFERED))
318                 setlinebuf(stdout);
319
320         if (getenv(DLOG_ENV_STDERR_LINE_BUFFERED))
321                 setlinebuf(stderr);
322 }
323
324 static bool first = true;
325 static bool initialize(void)
326 {
327         if (is_initialized)
328                 return true;
329
330         /* The mutex acts as a barrier, but otherwise the C language's
331          * machine abstraction is single-threaded. This means that the
332          * compiler is free to rearrange calls inside the mutex according
333          * to the as-if rule because it doesn't care if another thread can
334          * access it in parallel. In particular, `is_initialized = true`
335          * directly after `__configure()` could be rearranged to go in
336          * front of it because it is not touched inside that function
337          * if the compiler thinks it helps somehow (not unlikely: since
338          * it is checked before the mutex, it is very probable for it to
339          * still be in the CPU register or something like that). On top
340          * of that, some architectures (in particular, armv7l) don't have
341          * strict memory guarantees and can reorder actual memory stores
342          * on their own, even if the compiler didn't do anything fancy
343          * when creating machine code. For more info about the issue,
344          * see https://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
345          *
346          * Ultimately this means that there needs to be some sort of
347          * barrier between `__configure` and `is_initialized = true`,
348          * and the simplest way to achieve that is to just wait until
349          * the second entry into the mutex. */
350
351         bool ret;
352         pthread_mutex_lock(&log_construction_lock);
353                 if (first)
354                         first = !__configure();
355                 else
356                         is_initialized = true;
357                 ret = !first;
358         pthread_mutex_unlock(&log_construction_lock);
359         return ret;
360 }
361
362 /**
363  * @brief Fatal assertion
364  * @details Conditionally crash the sucka who sent the log
365  * @param[in] prio Priority of the log
366  */
367 static void __dlog_fatal_assert(int prio)
368 {
369         assert(!fatal_assert || (prio != DLOG_FATAL));
370 }
371
372 /**
373  * @brief Check log validity
374  * @details Checks whether the log is valid and eligible for printing
375  * @param[in] log_id The target buffer ID
376  * @param[in] prio The log's priority
377  * @param[in] tag The log's tag
378  * @param[in] only_core Whether non-core buffers are rejected
379  * @return DLOG_ERROR_NONE on success, else an error code.
380  * @retval DLOG_ERROR_INVALID_PARAMETER Invalid parameter
381  */
382 static int dlog_check_validity(log_id_t log_id, int prio, const char *tag, bool only_core)
383 {
384         (void) prio;
385         if (!tag)
386                 return DLOG_ERROR_INVALID_PARAMETER;
387
388         if (!is_buffer_valid(log_id))
389                 return DLOG_ERROR_INVALID_PARAMETER;
390
391         /* The interface here is a bit confused. `__dlog_print` is nominally
392          * for platform logging and is not necessarily supposed to use the
393          * APPS buffer (which is a core buffer, but not a platform buffer),
394          * yet the internal interface (dlog-internal.h) exposes macros for
395          * platform programs to log into APPS. The design is probably too
396          * ossified to change at this point though. */
397         if (only_core && !is_core_buffer(log_id))
398                 return DLOG_ERROR_INVALID_PARAMETER;
399
400         return DLOG_ERROR_NONE;
401 }
402
403 /**
404  * @brief Check log against limiter rules
405  * @details Checks whether the log passes current limiter rules
406  * @param[in] log_id The target buffer ID
407  * @param[in] prio The log's priority
408  * @param[in] tag The log's tag
409  * @return DLOG_ERROR_NONE on success, else an error code.
410  * @retval DLOG_ERROR_NOT_PERMITTED Not permitted
411  */
412 static int dlog_check_limiter(log_id_t log_id, int prio, const char *tag)
413 {
414         if (!debugmode && prio <= DLOG_DEBUG)
415                 return DLOG_ERROR_NOT_PERMITTED;
416
417         if (dynamic_config)
418                 __dynamic_config_update(limiter_data);
419
420         if (limiter) {
421                 struct pass_log_result should_log = { .decision = DECISION_DENIED };
422
423                 /* Since the only `wrlock` is done by the dynamic config, we can avoid
424                  * the `rdlock` entirely if the config is static. This sounds unsafe
425                  * but lets us save an entire syscall, which is a lot (both comparatively
426                  * and because it compounds). */
427                 if (!dynamic_config || !pthread_rwlock_rdlock(&log_limiter_lock)) {
428                         should_log = __log_limiter_pass_log_pid(limiter_data, tag, prio, get_cached_pid());
429                         if (dynamic_config)
430                                 pthread_rwlock_unlock(&log_limiter_lock);
431                 }
432
433                 switch (should_log.decision) {
434                         case DECISION_DENIED:
435                                 return DLOG_ERROR_NOT_PERMITTED;
436
437                         case DECISION_TAG_LIMIT_EXCEEDED_MESSAGE:
438                         case DECISION_PID_LIMIT_EXCEEDED_MESSAGE: {
439                                 struct timespec tp;
440                                 int result = clock_gettime(CLOCK_MONOTONIC, &tp);
441                                 if (result < 0)
442                                         return DLOG_ERROR_NOT_PERMITTED;
443                                 char buf[100] = {};
444                                 snprintf(buf, sizeof(buf),
445                                                 "Your log has been blocked due to per-%s limit of %d logs per %d seconds.",
446                                                 should_log.decision == DECISION_TAG_LIMIT_EXCEEDED_MESSAGE ? "tag" : "PID",
447                                                 should_log.logs_per_period, should_log.period_s);
448                                 write_to_log(log_id, prio, tag, buf, &tp, get_cached_pid(), get_cached_tid());
449                                 return DLOG_ERROR_NOT_PERMITTED;
450                         }
451
452                         case DECISION_ALLOWED:
453                                 break;
454                 }
455         }
456
457         /* This can change due to __dynamic_config_update(), but is atomic and its
458          * value implies nothing else so does not need to be under a lock. */
459         if (!plog[log_id])
460                 return DLOG_ERROR_NOT_PERMITTED;
461
462         return DLOG_ERROR_NONE;
463 }
464
465 static int __write_to_log_critical_section(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap, bool check_should_log)
466 {
467         if ((check_should_log || limiter_apply_to_all_buffers) && (dlog_check_limiter(log_id, prio, tag) < 0))
468                 return DLOG_ERROR_NONE;
469
470         log_id = get_log_id_from_sink(log_id);
471
472         char buf[LOG_MAX_PAYLOAD_SIZE];
473         int len = vsnprintf(buf, sizeof buf, fmt, ap);
474         if (len < 0)
475                 return DLOG_ERROR_NONE;
476         else if (len >= sizeof buf)
477                 len = sizeof buf - 1;
478
479         // Temporary workaround, see temporary.c
480         prepend_container_tag_if_in_container(sizeof buf, buf, &len);
481
482         struct timespec tp;
483         int r;
484         if (deduplicate_func && !clock_gettime(CLOCK_MONOTONIC, &tp)) {
485                 dlog_deduplicate_e ret = deduplicate_func(buf, len, &tp);
486                 if (ret == DLOG_DEDUPLICATE)
487                         return DLOG_ERROR_NONE;
488                 else if (ret == DLOG_DO_NOT_DEDUPLICATE_BUT_WARN)
489                         deduplicate_warn(buf, sizeof buf, len);
490                 r = write_to_log(log_id, prio, tag, buf, &tp, get_cached_pid(), get_cached_tid());
491         } else
492                 r = write_to_log(log_id, prio, tag, buf, NULL, get_cached_pid(), get_cached_tid());
493
494         if (r < 0 && stash_failed_log)
495                 r = stash_failed_log(log_id, prio, tag, buf);
496
497         return r;
498 }
499
500 static int __write_to_log(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap, bool check_should_log, bool secure_log)
501 {
502         int ret = dlog_check_validity(log_id, prio, tag, check_should_log);
503         if (ret < 0)
504                 return ret;
505
506         if (check_should_log && prio < priority_filter_level)
507                 return DLOG_ERROR_NONE;
508
509         /* Threads can be cancelled before they give up a lock.
510          * Therefore cancellation is temporarily disabled as
511          * long as the current set of features uses a lock.
512          *
513          * This solution is comparatively simple and cheap.
514          * The other solutions (cleanup handlers, robust mutexes)
515          * would be much more complicated and also inflict larger
516          * runtime costs. The downside of disabling cancellation
517          * is not a problem in our case because it is temporary
518          * and very brief so we don't keep an obsolete thread
519          * for much longer than we otherwise would. */
520         int old_cancel_state;
521         if (should_disable_cancels)
522                 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancel_state);
523
524         if (!initialize())
525                 // TODO: We could consider stashing the failed log here
526                 ret = DLOG_ERROR_NOT_PERMITTED;
527         else if (secure_log && !enable_secure_logs)
528                 ret = 0;
529         else
530                 ret = __write_to_log_critical_section(log_id, prio, tag, fmt, ap, check_should_log);
531
532         if (should_disable_cancels)
533                 pthread_setcancelstate(old_cancel_state, NULL);
534
535         return ret;
536 }
537
538 int __critical_log_append_timestamp(char *buf, size_t buflen)
539 {
540         /* NB: the timestamp may slightly differ from the one that gets
541          * added onto the copy that goes into the regular buffer, and
542          * timestamp acquisition is duplicated. This would ideally be
543          * solved, but timestamps are currently added fairly deep in
544          * backend-specific functions so for now this will have to do.
545          * Also, since we're the sender, there is just this one set of
546          * timestamps, i.e. the send timestamp! The usual alternative
547          * set of receive timestamps will never have the opportunity
548          * to get added to the entry since this log is supposed to end
549          * up straight in the file (there's potentially the trusted
550          * writer binary but we're trying to keep the set of actions
551          * it needs to do to the minimum and those timestamps would
552          * in practice be the same anyway). */
553
554         struct timespec ts;
555         clock_gettime(CLOCK_REALTIME, &ts);
556         const time_t tt = ts.tv_sec;
557         const long int real_millisec = ts.tv_nsec / 1000000;
558         clock_gettime(CLOCK_MONOTONIC, &ts);
559         struct tm tmBuf;
560         struct tm *const ptm = localtime_r(&tt, &tmBuf);
561         assert(ptm); // we're in a short lived fork so asserts are fine and make things simple
562
563         int len = strftime(buf, buflen, "%m-%d %H:%M:%S", ptm);
564         assert(len != 0);
565
566         int tmp_len = snprintf(buf + len, buflen - len, ".%03ld", real_millisec);
567         assert(tmp_len > 0);
568         assert(tmp_len < buflen - len);
569         len += tmp_len;
570
571         tmp_len = strftime(buf + len, buflen - len, "%z ", ptm);
572         assert(tmp_len != 0);
573         len += tmp_len;
574
575         tmp_len = snprintf(buf + len, buflen - len, "%5lu.%03ld", ts.tv_sec, ts.tv_nsec / 1000000);
576         assert(tmp_len > 0);
577         assert(tmp_len < buflen - len);
578         len += tmp_len;
579
580         return len;
581 }
582
583 int __critical_log_build_msg(char *buf, size_t buflen, pid_t main_pid, pid_t main_tid, log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
584 {
585         int len = __critical_log_append_timestamp(buf, buflen);
586         const int metadata_len = snprintf(buf + len, buflen - len, " P%5d T%5d B%-6s %c/%-8s: ",
587                 main_pid,
588                 main_tid,
589                 log_name_by_id(log_id),
590                 filter_pri_to_char(prio),
591                 tag ?: "CRITICAL_NO_TAG");
592         assert(metadata_len > 0);
593         if (metadata_len >= buflen - len)
594                 return buflen - 1; // can genuinely happen with an exceedingly large tag
595         len += metadata_len;
596
597         const int content_len = vsnprintf(buf + len, buflen - len, fmt, ap);
598         assert(content_len >= 0); // 0 is legit with format == ""
599         if (content_len >= buflen - len)
600                 return buflen - 1;
601         len += content_len;
602
603         return len;
604 }
605
606 #ifndef UNIT_TEST
607 __attribute__ ((noreturn))
608 #endif
609 void __critical_log_child(pid_t main_pid, pid_t main_tid, log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
610 {
611         char buf[LOG_MAX_PAYLOAD_SIZE + 128]; // extra space for some metadata
612         const int len = __critical_log_build_msg(buf, sizeof buf - 1, main_pid, main_tid, log_id, prio, tag, fmt, ap);
613         buf[len] = '\n';
614         buf[len + 1] = '\0';
615
616         static const char *const path = "/usr/libexec/dlog-log-critical";
617         execl(path, path /* argv[0] convention */, buf, (char *) NULL);
618
619 #ifndef UNIT_TEST
620         /* Compilers are sometimes smart enough to recognize _exit's
621          * noreturn attribute, even if we wrap it with something that
622          * returns. This causes it to behave in unexpected ways, for
623          * example it can blow up the program regardless or it can
624          * optimize some conditionals out (and incorrectly enter them
625          * after the exit call fails to actually exit). This makes it
626          * unsuitable for tests. */
627
628         _exit(1); // not the regular `exit` so as not to trigger any `atexit` handlers prematurely
629 #endif
630 }
631
632 #ifndef UNIT_TEST // contains forks and exits, these don't work well with wrapping (see above)
633 void __critical_log(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
634 {
635         /* Critical log functionality is mostly done in a separate binary
636          * to handle security correctly (else every process would have to
637          * possess the necessary privilege to write onto that file, which
638          * would be opening a fairly nasty can of worms from the security
639          * point of view). Our use of exec() is why a simple thread would
640          * not suffice and we're resorting to a fork.
641          *
642          * The double fork, much like a double barreled 12 gauge shotgun,
643          * is an elegant solution designed to stop a zombie army. We'd be
644          * creating zombie processes if we didn't wait() for the children
645          * we spawn, but we don't really want to do that since it results
646          * in a needless delay. Instead, the writer process is actually a
647          * grandchild, with our direct child exiting immediately just for
648          * us to have something to wait on that is guaranteed not to take
649          * too long. The orphaned grandchild is adopted by init, who will
650          * take care to reap it when it dies. In addition to avoiding the
651          * delay, the client will not have any unexpected children (which
652          * could ruin logic in its own waits).
653          *
654          * Right after forks:
655          * ┌───────┐   ┌─────────┐   ┌─────────────┐   ┌────────┐
656          * │ pid 1 ├──>│ libdlog ├──>│ immediately ├──>│ execs  │
657          * │ init  │   │ client  │   │    exits    │   │ writer │
658          * └───────┘   └─────────┘   └─────────────┘   └────────┘
659          *
660          * Afterwards, libdlog has no children:
661          * ┌───────┐   ┌─────────┐                     ┌────────┐
662          * │ pid 1 ├──>│ libdlog │          ┌─────────>│ writer │
663          * │ init  ├─┐ │ client  │          │          │ binary │
664          * └───────┘ │ └─────────┘          │          └────────┘
665          *           └──────────────────────┘
666          */
667
668         initialize();
669
670         if (!enable_critical)
671                 return;
672
673         const pid_t main_pid = getpid();
674         const pid_t main_tid = gettid();
675
676         const int temporary_exiter_pid = fork();
677         if (temporary_exiter_pid < 0)
678                 return;
679         if (temporary_exiter_pid != 0) {
680                 waitpid(temporary_exiter_pid, NULL, 0);
681                 return;
682         }
683
684         const int child_pid = fork();
685         if (child_pid < 0)
686                 _exit(1);
687         if (child_pid != 0)
688                 _exit(0);
689
690         __critical_log_child(main_pid, main_tid, log_id, prio, tag, fmt, ap);
691 }
692
693 static void stash_critical_inner(log_id_t log_id, log_priority prio, const char *tag, const char *fmt, ...)
694 {
695         va_list ap;
696
697         va_start(ap, fmt);
698         __critical_log(log_id, prio, tag, fmt, ap);
699         va_end(ap);
700 }
701
702 static int stash_critical(log_id_t log_id, log_priority prio, const char *tag, const char *msg)
703 {
704         stash_critical_inner(log_id, prio, tag, "FAILED TO LOG: %s", msg);
705         return 0;
706 }
707
708 EXPORT_API int __dlog_critical_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
709 {
710         va_list ap;
711
712         va_start(ap, fmt);
713         __critical_log(log_id, prio, tag, fmt, ap);
714         va_end(ap);
715
716         va_start(ap, fmt);
717         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
718         va_end(ap);
719
720         return ret;
721 }
722 #endif
723
724 EXPORT_API int dlog_set_minimum_priority(int priority)
725 {
726         if (priority < DLOG_DEFAULT || priority > DLOG_PRIO_MAX)
727                 return DLOG_ERROR_INVALID_PARAMETER;
728
729         priority_filter_level = priority;
730         return DLOG_ERROR_NONE;
731 }
732
733 /**
734  * @brief Print log
735  * @details Print a log line
736  * @param[in] log_id The target buffer ID
737  * @param[in] prio Priority
738  * @param[in] tag tag
739  * @param[in] fmt Format (same as printf)
740  * @param[in] ap Argument list
741  * @return Bytes written, or negative error
742  */
743 EXPORT_API int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
744 {
745         int ret = __write_to_log(log_id, prio, tag, fmt, ap, true, false);
746         __dlog_fatal_assert(prio);
747
748         return ret;
749 }
750
751 /**
752  * @brief Print log
753  * @details Print a log line
754  * @param[in] log_id The target buffer ID
755  * @param[in] prio Priority
756  * @param[in] tag tag
757  * @param[in] fmt Format (same as printf)
758  * @return Bytes written, or negative error
759  */
760 EXPORT_API int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
761 {
762         va_list ap;
763
764         va_start(ap, fmt);
765         int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
766         va_end(ap);
767
768         return ret;
769 }
770
771 /**
772  * @brief Print log
773  * @details Print a log line
774  * @param[in] log_id The target buffer ID
775  * @param[in] prio Priority
776  * @param[in] tag tag
777  * @param[in] fmt Format (same as printf)
778  * @return Bytes written, or negative error
779  */
780 EXPORT_API int __dlog_sec_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
781 {
782         if (!enable_secure_logs)
783                 return 0;
784
785         va_list ap;
786
787         va_start(ap, fmt);
788         int ret = __write_to_log(log_id, prio, tag, fmt, ap, true, true);
789         __dlog_fatal_assert(prio);
790         va_end(ap);
791
792         return ret;
793 }
794
795 EXPORT_API int dlog_vprint(log_priority prio, const char *tag, const char *fmt, va_list ap)
796 {
797         return __write_to_log(LOG_ID_APPS, prio, tag, fmt, ap, false, false);
798 }
799
800 EXPORT_API int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
801 {
802         va_list ap;
803
804         va_start(ap, fmt);
805         int ret = dlog_vprint(prio, tag, fmt, ap);
806         va_end(ap);
807
808         return ret;
809 }
810
811 EXPORT_API int dlog_vprint_dotnet(log_priority prio, const char *tag, const char *fmt, va_list ap)
812 {
813         return __write_to_log(SINK_DOTNET, prio, tag, fmt, ap, false, false);
814 }
815
816 EXPORT_API int dlog_print_dotnet(log_priority prio, const char *tag, const char *fmt, ...)
817 {
818         va_list ap;
819
820         va_start(ap, fmt);
821         int ret = dlog_vprint_dotnet(prio, tag, fmt, ap);
822         va_end(ap);
823
824         return ret;
825 }
826
827 EXPORT_API int dlog_vprint_native(log_priority prio, const char *tag, const char *fmt, va_list ap)
828 {
829         return __write_to_log(SINK_NATIVE, prio, tag, fmt, ap, false, false);
830 }
831
832 EXPORT_API int dlog_print_native(log_priority prio, const char *tag, const char *fmt, ...)
833 {
834         va_list ap;
835
836         va_start(ap, fmt);
837         int ret = dlog_vprint_native(prio, tag, fmt, ap);
838         va_end(ap);
839
840         return ret;
841 }
842
843 // LCOV_EXCL_START : for internal use only, not accessible via public API
844
845 /**
846  * @brief Finalize DLog
847  * @details Finalizes and deallocates the library
848  * @notes Used directly in tests; brings back the pre-init state
849  */
850 void __dlog_fini(void)
851 {
852         if (destroy_backend) {
853                 destroy_backend();
854                 destroy_backend = NULL;
855         }
856         write_to_log = write_to_log_null;
857         stash_failed_log = NULL;
858         is_initialized = false;
859         first = true;
860
861         enable_secure_logs = true;
862         enable_critical = false;
863         __deduplicate_destroy();
864         __log_limiter_destroy(limiter_data);
865         limiter = false;
866         __dynamic_config_destroy();
867         should_disable_cancels = false;
868 }
869
870 // LCOV_EXCL_STOP