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