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