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