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