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