Fix how %m behaves in the log format
[platform/core/system/dlog.git] / src / libdlog / log.c
index 4c4ff1c..7119d49 100644 (file)
@@ -1,20 +1,24 @@
-/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: t -*-
- * DLOG
- * Copyright (c) 2005-2008, The Android Open Source Project
- * Copyright (c) 2012-2013 Samsung Electronics Co., Ltd.
+/*  MIT License
  *
- * Licensed under the Apache License, Version 2.0 (the License);
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Copyright (c) 2012-2020 Samsung Electronics Co., Ltd
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is furnished
+ * to do so, subject to the following conditions:
  *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE. */
 
 // C
 #include <assert.h>
 
 // POSIX
 #include <pthread.h>
+#include <sys/wait.h>
 #include <unistd.h>
 
+// Tizen
+#include <tizen.h>
+
 // DLog
+#include <buffer_traits.h>
+#include "deduplicate.h"
 #include <dynamic_config.h>
+#include "extra_sinks.h"
 #include <libdlog.h>
-#include <logcommon.h>
 #include "logconfig.h"
 #include "loglimiter.h"
 
 #define DEFAULT_CONFIG_DEBUGMODE 0
 #define DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS 0
 
+
+/* A pseudo-backend that does nothing. Useful for removing the overhead of dlog
+ * for debugging and measurement purposes, also it simplifies some checking as
+ * the `write_to_log` pointer below never needs to be NULL. Note that features
+ * independent of the backend (such as limiter or dynamic config) are controlled
+ * separately if dlog is to be disabled completely and that minimal overhead is
+ * always present (e.g. building the message via vprintf). */
+static int write_to_log_null (log_id_t log_id, log_priority prio, const char *tag, const char *msg, struct timespec *tp_mono, int32_t pid, int32_t tid)
+{
+       return DLOG_ERROR_NONE;
+}
+
 /**
  * @brief Points to a function which writes a log message
  * @details The function pointed to depends on the backend used
  * @return Returns the number of bytes written on success and a negative error value on error.
  * @see __dlog_init_backend
  */
-int (*write_to_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg) = NULL;
-void (*destroy_backend)();
+int (*write_to_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg, struct timespec *tp_mono, int32_t pid, int32_t tid) = write_to_log_null;
+void (*destroy_backend)(void);
+
+int (*stash_failed_log)(log_id_t log_id, log_priority prio, const char *tag, const char *msg) = NULL;
+#ifndef UNIT_TEST
+static int stash_critical(log_id_t log_id, log_priority prio, const char *tag, const char *msg);
+#endif
 
 pthread_rwlock_t log_limiter_lock = PTHREAD_RWLOCK_INITIALIZER;
-static pthread_rwlock_t log_destruction_lock = PTHREAD_RWLOCK_INITIALIZER;
 static pthread_mutex_t log_construction_lock = PTHREAD_MUTEX_INITIALIZER;
 static bool is_initialized = false;
 
 extern void __dlog_init_pipe(const struct log_config *conf);
 extern void __dlog_init_android(const struct log_config *conf);
+extern void __dlog_init_zero_copy();
+
+extern void prepend_container_tag_if_in_container(size_t buf_size, char buf[static buf_size], int *len);
 
 bool limiter;
-bool dynamic_config;
-bool plog[LOG_ID_MAX];
-bool plog_default_values[LOG_ID_MAX];
+struct limiter_data *limiter_data;
+static bool dynamic_config;
+static bool plog[SINKS_MAX];
+static bool plog_default_values[SINKS_MAX];
+static bool enable_secure_logs = true;
+static bool enable_critical = true;
+
+static bool should_disable_cancels;
 
 static int debugmode;
 static int fatal_assert;
 static int limiter_apply_to_all_buffers;
+static _Atomic log_priority priority_filter_level = DLOG_VERBOSE;
+
+/* Cache pid and tid to avoid up to two syscalls per log.
+ * PID is reset at fork() via pthread_atfork().
+ * TID is reset by being a thread local var. */
+static int32_t cached_pid = 0;
+_Thread_local int32_t cached_tid = 0;
 
-static void __configure_limiter(struct log_config *config)
+static inline int32_t get_cached_pid()
 {
-       assert(config);
+       return cached_pid;
+}
+
+static inline int32_t get_cached_tid()
+{
+       return (cached_tid = cached_tid ?: gettid());
+}
+
+static void update_cached_pid()
+{
+       cached_pid = getpid();
+       // tid is reset passively (to 0) by virtue of being thread-local
+}
+
+/* Here, static_config is the original config from /etc/dlog.conf{,.d} which can be overriden,
+ * but comes back if the override is removed. both_config additionally contains dynamic rules
+ * (by default from /run/dlog/filters.d) which can be changed in the runtime.
+ * The static_config has to be kept separately, so that we can go back to it when dynamic rules change.
+ * Note that most functions only use static_config, since the parameters can't be changed in runtime. */
+static void __configure_limiter(struct log_config *static_config, struct log_config *both_config)
+{
+       assert(static_config);
+       if (dynamic_config)
+               assert(both_config);
 
        if (!limiter)
                return;
 
-       limiter = __log_limiter_create(config);
+       limiter_data = __log_limiter_create(static_config);
+       if (limiter_data && dynamic_config)
+               __log_limiter_update(limiter_data, both_config);
+       limiter = (bool)limiter_data;
+
+       should_disable_cancels |= limiter; // due to locks
 }
 
 static int __configure_backend(struct log_config *config)
 {
        assert(config);
 
-       const char *const backend = log_config_get(config, "backend");
+       const char *const backend = log_config_claim_backend(config);
        if (!backend)
                return 0;
 
-       if (!strcmp(backend, "pipe"))
+       if (!strcmp(backend, "pipe")) {
                __dlog_init_pipe(config);
-       else if (!strcmp(backend, "logger"))
+               should_disable_cancels = true;
+       } else if (!strcmp(backend, "logger"))
                __dlog_init_android(config);
+       else if (!strcmp(backend, "zero-copy"))
+               __dlog_init_zero_copy(config);
+       else if (!strcmp(backend, "null"))
+               ; // already the default
        else
                return 0;
 
        return 1;
 }
 
-static void __set_plog_default_values()
+static void __set_plog_default_values(void)
 {
-       for (int i = 0; i < NELEMS(plog); ++i)
+       for (size_t i = 0; i < NELEMS(plog); ++i)
                plog_default_values[i] = plog[i];
 }
 
@@ -106,34 +180,51 @@ static void __initialize_plog(const struct log_config *config)
 {
        assert(config);
 
+       /* plog stands for "platform logging", which is why
+        * non-platform (i.e. application) buffers ignore it */
        const bool plog_default = log_config_get_boolean(config, "plog", DEFAULT_CONFIG_PLOG);
-       for (int i = 0; i < NELEMS(plog); ++i)
-               plog[i] = plog_default;
-       plog[LOG_ID_APPS] = true; // the default does not apply here for backward compatibility reasons.
+       for (size_t i = 0; i < NELEMS(plog); ++i)
+               plog[i] = is_platform_buffer(i) ? plog_default : true;
+
        __set_plog_default_values();
 }
 
-static void __configure_parameters(struct log_config *config)
+static void __configure_parameters(struct log_config *static_config, struct log_config *both_config)
 {
-       assert(config);
+       assert(static_config);
+       assert(both_config);
 
-       __initialize_plog(config);
-       __update_plog(config);
+       __initialize_plog(static_config);
+       __update_plog(static_config);
+       /* Like in __configure_limiter, we also check the dynamic rules. However, we make sure to
+     * set the default values to the ones generated by the static rules first. */
        __set_plog_default_values();
+       __update_plog(both_config);
 
-       debugmode = log_config_get_int(config, "debugmode", DEFAULT_CONFIG_DEBUGMODE);
+       enable_secure_logs = log_config_get_boolean(both_config, "enable_secure_logs", enable_secure_logs);
+       enable_critical = log_config_get_boolean(both_config, "enable_critical", enable_critical);
+       debugmode = log_config_get_int(both_config, "debugmode", DEFAULT_CONFIG_DEBUGMODE);
        fatal_assert = access(DEBUGMODE_FILE, F_OK) != -1;
-       limiter = log_config_get_boolean(config, "limiter", DEFAULT_CONFIG_LIMITER);
-       limiter_apply_to_all_buffers = log_config_get_int(config,
+       limiter = log_config_get_boolean(both_config, "limiter", DEFAULT_CONFIG_LIMITER);
+       limiter_apply_to_all_buffers = log_config_get_int(both_config,
                                                                        "limiter_apply_to_all_buffers",
                                                                        DEFAULT_CONFIG_LIMITER_APPLY_TO_ALL_BUFFERS);
+
+       stash_failed_log = NULL;
+       const char *stash_failed_log_method = log_config_get(both_config, "stash_failed_log_method");
+       if (stash_failed_log_method) {
+#ifndef UNIT_TEST
+               if (strcmp(stash_failed_log_method, "critical") == 0)
+                       stash_failed_log = stash_critical;
+#endif
+       }
 }
 
 void __update_plog(const struct log_config *conf)
 {
        assert(conf);
 
-       for (int i = 0; i < NELEMS(plog); ++i) {
+       for (size_t i = 0; i < NELEMS(plog); ++i) {
                char key[MAX_CONF_KEY_LEN];
                const int r = snprintf(key, sizeof key, "enable_%s", log_name_by_id((log_id_t)i));
                if (r < 0)
@@ -167,27 +258,72 @@ static
 #endif
 bool __configure(void)
 {
-       __attribute__((cleanup(log_config_free))) struct log_config config;
+       __attribute__((cleanup(log_config_free))) struct log_config static_config = {};
+       __attribute__((cleanup(log_config_free))) struct log_config both_config = {};
 
-       if (log_config_read(&config) < 0)
+       cached_pid = getpid();
+
+       if (log_config_read(&static_config) < 0)
                return false;
+       log_config_copy(&both_config, &static_config);
 
-       dynamic_config = __dynamic_config_create(&config);
+       dynamic_config = __dynamic_config_create(&both_config);
 
-       __configure_parameters(&config);
+       __configure_parameters(&static_config, &both_config);
 
-       if (!__configure_backend(&config)) {
+       if (!__configure_backend(&both_config)) {
                __dynamic_config_destroy();
                dynamic_config = false;
                return false;
        }
 
-       __configure_limiter(&config);
+       __configure_deduplicate(&both_config);
+       __configure_limiter(&static_config, &both_config);
+
+       pthread_atfork(NULL, NULL, update_cached_pid);
+
        return true;
 }
 
+static void __attribute__((constructor(101))) __install_pipe_handler(void)
+{
+       /* We mask SIGPIPE signal because most applications do not install their
+        * own SIGPIPE handler. Default behaviour in SIGPIPE case is to abort the
+        * process. SIGPIPE occurs when e.g. dlog daemon closes read pipe endpoint.
+        *
+        * We do this in the library constructor (at maximum priority) and not
+        * during regular (lazy) initialisation so as to prevent overwriting the
+        * program's actual signal handler, if it has one.
+        *
+        * In theory this is not required for the Android logger backend; however,
+        * this early we don't yet know the backend and also it is good to behave
+        * consistently in this regard anyway.
+        *
+        * We don't revert this in a destructor because Unix signals are bonkers
+        * and we have no way to do this cleanly. Most libdlog users don't use
+        * runtime linking so this would mostly done at program exit either way. */
+       signal(SIGPIPE, SIG_IGN);
+}
+
+static void __attribute__((constructor(102))) __set_output_buffering(void)
+{
+       /* If stdout and/or stderr is redirected to dlog (service, driver)
+        * it is best if we buffer lines, otherwise the following can happen:
+        *  - no buffering: service/driver recives every single byte (precisely
+        *    every single write*(2) call), causing it to either buffer the data
+        *    anyway (service), or print logs at random places (driver)
+        *  - full buffering: service/driver receives several hundred lines,
+        *    which results in one giant entry being added (driver) or long delays
+        *    before logs appear (service) */
+       if (getenv(DLOG_ENV_STDOUT_LINE_BUFFERED))
+               setlinebuf(stdout);
+
+       if (getenv(DLOG_ENV_STDERR_LINE_BUFFERED))
+               setlinebuf(stderr);
+}
+
 static bool first = true;
-static bool initialize()
+static bool initialize(void)
 {
        if (is_initialized)
                return true;
@@ -240,15 +376,26 @@ static void __dlog_fatal_assert(int prio)
  * @param[in] log_id The target buffer ID
  * @param[in] prio The log's priority
  * @param[in] tag The log's tag
+ * @param[in] only_core Whether non-core buffers are rejected
  * @return DLOG_ERROR_NONE on success, else an error code.
  * @retval DLOG_ERROR_INVALID_PARAMETER Invalid parameter
  */
-static int dlog_check_validity(log_id_t log_id, int prio, const char *tag)
+static int dlog_check_validity(log_id_t log_id, int prio, const char *tag, bool only_core)
 {
+       (void) prio;
        if (!tag)
                return DLOG_ERROR_INVALID_PARAMETER;
 
-       if (log_id <= LOG_ID_INVALID || LOG_ID_MAX <= log_id)
+       if (!is_buffer_valid(log_id))
+               return DLOG_ERROR_INVALID_PARAMETER;
+
+       /* The interface here is a bit confused. `__dlog_print` is nominally
+        * for platform logging and is not necessarily supposed to use the
+        * APPS buffer (which is a core buffer, but not a platform buffer),
+        * yet the internal interface (dlog-internal.h) exposes macros for
+        * platform programs to log into APPS. The design is probably too
+        * ossified to change at this point though. */
+       if (only_core && !is_core_buffer(log_id))
                return DLOG_ERROR_INVALID_PARAMETER;
 
        return DLOG_ERROR_NONE;
@@ -269,21 +416,42 @@ static int dlog_check_limiter(log_id_t log_id, int prio, const char *tag)
                return DLOG_ERROR_NOT_PERMITTED;
 
        if (dynamic_config)
-               __dynamic_config_update();
+               __dynamic_config_update(limiter_data);
 
        if (limiter) {
-               int should_log = 0;
-               if (!pthread_rwlock_rdlock(&log_limiter_lock)) {
-                       should_log = __log_limiter_pass_log(tag, prio);
-                       pthread_rwlock_unlock(&log_limiter_lock);
+               struct pass_log_result should_log = { .decision = DECISION_DENIED };
+
+               /* Since the only `wrlock` is done by the dynamic config, we can avoid
+                * the `rdlock` entirely if the config is static. This sounds unsafe
+                * but lets us save an entire syscall, which is a lot (both comparatively
+                * and because it compounds). */
+               if (!dynamic_config || !pthread_rwlock_rdlock(&log_limiter_lock)) {
+                       should_log = __log_limiter_pass_log_pid(limiter_data, tag, prio, get_cached_pid());
+                       if (dynamic_config)
+                               pthread_rwlock_unlock(&log_limiter_lock);
                }
 
-               if (!should_log) {
-                       return DLOG_ERROR_NOT_PERMITTED;
-               } else if (should_log < 0) {
-                       write_to_log(log_id, prio, tag,
-                                       "Your log has been blocked due to limit of log lines per minute.");
-                       return DLOG_ERROR_NOT_PERMITTED;
+               switch (should_log.decision) {
+                       case DECISION_DENIED:
+                               return DLOG_ERROR_NOT_PERMITTED;
+
+                       case DECISION_TAG_LIMIT_EXCEEDED_MESSAGE:
+                       case DECISION_PID_LIMIT_EXCEEDED_MESSAGE: {
+                               struct timespec tp;
+                               int result = clock_gettime(CLOCK_MONOTONIC, &tp);
+                               if (result < 0)
+                                       return DLOG_ERROR_NOT_PERMITTED;
+                               char buf[100] = {};
+                               snprintf(buf, sizeof(buf),
+                                               "Your log has been blocked due to per-%s limit of %d logs per %d seconds.",
+                                               should_log.decision == DECISION_TAG_LIMIT_EXCEEDED_MESSAGE ? "tag" : "PID",
+                                               should_log.logs_per_period, should_log.period_s);
+                               write_to_log(log_id, prio, tag, buf, &tp, get_cached_pid(), get_cached_tid());
+                               return DLOG_ERROR_NOT_PERMITTED;
+                       }
+
+                       case DECISION_ALLOWED:
+                               break;
                }
        }
 
@@ -295,39 +463,282 @@ static int dlog_check_limiter(log_id_t log_id, int prio, const char *tag)
        return DLOG_ERROR_NONE;
 }
 
-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)
+static int __write_to_log_critical_section(log_id_t log_id, int prio, const char *tag, size_t buf_size, char buf[static buf_size], int buf_len, bool check_should_log)
 {
        if ((check_should_log || limiter_apply_to_all_buffers) && (dlog_check_limiter(log_id, prio, tag) < 0))
                return DLOG_ERROR_NONE;
 
-       char buf[LOG_MAX_PAYLOAD_SIZE];
-       vsnprintf(buf, sizeof buf, fmt, ap);
-       return write_to_log(log_id, prio, tag, buf);
+       log_id = get_log_id_from_sink(log_id);
+
+
+       // Temporary workaround, see temporary.c
+       prepend_container_tag_if_in_container(buf_size, buf, &buf_len);
+
+       struct timespec tp;
+       int r;
+       if (deduplicate_func && !clock_gettime(CLOCK_MONOTONIC, &tp)) {
+               dlog_deduplicate_e ret = deduplicate_func(buf, buf_len, &tp);
+               if (ret == DLOG_DEDUPLICATE)
+                       return DLOG_ERROR_NONE;
+               else if (ret == DLOG_DO_NOT_DEDUPLICATE_BUT_WARN)
+                       deduplicate_warn(buf, buf_size, buf_len);
+               r = write_to_log(log_id, prio, tag, buf, &tp, get_cached_pid(), get_cached_tid());
+       } else
+               r = write_to_log(log_id, prio, tag, buf, NULL, get_cached_pid(), get_cached_tid());
+
+       if (r < 0 && stash_failed_log)
+               r = stash_failed_log(log_id, prio, tag, buf);
+
+       return r;
 }
 
-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)
+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)
 {
-       int ret = dlog_check_validity(log_id, prio, tag);
+       /* Write down the log first, before all other checks. This
+        * is because validity checks may involve syscalls, which
+        * could overwrite `errno` and ruin the `%m` specifier if
+        * the client specifies it in format. */
+       char buf[LOG_MAX_PAYLOAD_SIZE];
+       int len = vsnprintf(buf, sizeof buf, fmt, ap);
+       if (len < 0)
+               return DLOG_ERROR_NONE; // not really, but no better choice and not too realistic
+       else if (len >= sizeof buf)
+               len = sizeof buf - 1;
+
+
+       int ret = dlog_check_validity(log_id, prio, tag, check_should_log);
        if (ret < 0)
                return ret;
 
-       /* The only thing that needs to be protected here is `write_to_log` since
-        * all other resources already have their own specific locks (and even the
-        * pointer could be made to point at a null handler instead of a true NULL)
-        * but giving this guarantee makes everything a lot simpler as it removes
-        * the risk of something suddenly becoming NULL during processing. */
-       if (!pthread_rwlock_rdlock(&log_destruction_lock)) {
-               ret = !initialize() || !write_to_log
-                       ? DLOG_ERROR_NOT_PERMITTED
-                       : __write_to_log_critical_section(log_id, prio, tag, fmt, ap, check_should_log)
-               ;
-               pthread_rwlock_unlock(&log_destruction_lock);
-       } else
-               return DLOG_ERROR_NOT_PERMITTED;
+       if (check_should_log && prio < priority_filter_level)
+               return DLOG_ERROR_NONE;
+
+       /* Threads can be cancelled before they give up a lock.
+        * Therefore cancellation is temporarily disabled as
+        * long as the current set of features uses a lock.
+        *
+        * This solution is comparatively simple and cheap.
+        * The other solutions (cleanup handlers, robust mutexes)
+        * would be much more complicated and also inflict larger
+        * runtime costs. The downside of disabling cancellation
+        * is not a problem in our case because it is temporary
+        * and very brief so we don't keep an obsolete thread
+        * for much longer than we otherwise would. */
+       int old_cancel_state;
+       if (should_disable_cancels)
+               pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &old_cancel_state);
+
+       if (!initialize())
+               // TODO: We could consider stashing the failed log here
+               ret = DLOG_ERROR_NOT_PERMITTED;
+       else if (secure_log && !enable_secure_logs)
+               ret = 0;
+       else
+               ret = __write_to_log_critical_section(log_id, prio, tag, sizeof buf, buf, len, check_should_log);
+
+       if (should_disable_cancels)
+               pthread_setcancelstate(old_cancel_state, NULL);
 
        return ret;
 }
 
+int __critical_log_append_timestamp(char *buf, size_t buflen)
+{
+       /* NB: the timestamp may slightly differ from the one that gets
+        * added onto the copy that goes into the regular buffer, and
+        * timestamp acquisition is duplicated. This would ideally be
+        * solved, but timestamps are currently added fairly deep in
+        * backend-specific functions so for now this will have to do.
+        * Also, since we're the sender, there is just this one set of
+        * timestamps, i.e. the send timestamp! The usual alternative
+        * set of receive timestamps will never have the opportunity
+        * to get added to the entry since this log is supposed to end
+        * up straight in the file (there's potentially the trusted
+        * writer binary but we're trying to keep the set of actions
+        * it needs to do to the minimum and those timestamps would
+        * in practice be the same anyway). */
+
+       struct timespec ts;
+       clock_gettime(CLOCK_REALTIME, &ts);
+       const time_t tt = ts.tv_sec;
+       const long int real_millisec = ts.tv_nsec / 1000000;
+       clock_gettime(CLOCK_MONOTONIC, &ts);
+       struct tm tmBuf;
+       struct tm *const ptm = localtime_r(&tt, &tmBuf);
+       assert(ptm); // we're in a short lived fork so asserts are fine and make things simple
+
+       int len = strftime(buf, buflen, "%m-%d %H:%M:%S", ptm);
+       assert(len != 0);
+
+       int tmp_len = snprintf(buf + len, buflen - len, ".%03ld", real_millisec);
+       assert(tmp_len > 0);
+       assert(tmp_len < buflen - len);
+       len += tmp_len;
+
+       tmp_len = strftime(buf + len, buflen - len, "%z ", ptm);
+       assert(tmp_len != 0);
+       len += tmp_len;
+
+       tmp_len = snprintf(buf + len, buflen - len, "%5lu.%03ld", ts.tv_sec, ts.tv_nsec / 1000000);
+       assert(tmp_len > 0);
+       assert(tmp_len < buflen - len);
+       len += tmp_len;
+
+       return len;
+}
+
+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)
+{
+       int len = __critical_log_append_timestamp(buf, buflen);
+       const int metadata_len = snprintf(buf + len, buflen - len, " P%5d T%5d B%-6s %c/%-8s: ",
+               main_pid,
+               main_tid,
+               log_name_by_id(log_id),
+               filter_pri_to_char(prio),
+               tag ?: "CRITICAL_NO_TAG");
+       assert(metadata_len > 0);
+       if (metadata_len >= buflen - len)
+               return buflen - 1; // can genuinely happen with an exceedingly large tag
+       len += metadata_len;
+
+       const int content_len = vsnprintf(buf + len, buflen - len, fmt, ap);
+       assert(content_len >= 0); // 0 is legit with format == ""
+       if (content_len >= buflen - len)
+               return buflen - 1;
+       len += content_len;
+
+       return len;
+}
+
+#ifndef UNIT_TEST
+__attribute__ ((noreturn))
+#endif
+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)
+{
+       char buf[LOG_MAX_PAYLOAD_SIZE + 128]; // extra space for some metadata
+       const int len = __critical_log_build_msg(buf, sizeof buf - 1, main_pid, main_tid, log_id, prio, tag, fmt, ap);
+       buf[len] = '\n';
+       buf[len + 1] = '\0';
+
+       static const char *const path = "/usr/libexec/dlog-log-critical";
+       execl(path, path /* argv[0] convention */, buf, (char *) NULL);
+
+#ifndef UNIT_TEST
+       /* Compilers are sometimes smart enough to recognize _exit's
+        * noreturn attribute, even if we wrap it with something that
+        * returns. This causes it to behave in unexpected ways, for
+        * example it can blow up the program regardless or it can
+        * optimize some conditionals out (and incorrectly enter them
+        * after the exit call fails to actually exit). This makes it
+        * unsuitable for tests. */
+
+       _exit(1); // not the regular `exit` so as not to trigger any `atexit` handlers prematurely
+#endif
+}
+
+#ifndef UNIT_TEST // contains forks and exits, these don't work well with wrapping (see above)
+void __critical_log(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
+{
+       /* Critical log functionality is mostly done in a separate binary
+        * to handle security correctly (else every process would have to
+        * possess the necessary privilege to write onto that file, which
+        * would be opening a fairly nasty can of worms from the security
+        * point of view). Our use of exec() is why a simple thread would
+        * not suffice and we're resorting to a fork.
+        *
+        * The double fork, much like a double barreled 12 gauge shotgun,
+        * is an elegant solution designed to stop a zombie army. We'd be
+        * creating zombie processes if we didn't wait() for the children
+        * we spawn, but we don't really want to do that since it results
+        * in a needless delay. Instead, the writer process is actually a
+        * grandchild, with our direct child exiting immediately just for
+        * us to have something to wait on that is guaranteed not to take
+        * too long. The orphaned grandchild is adopted by init, who will
+        * take care to reap it when it dies. In addition to avoiding the
+        * delay, the client will not have any unexpected children (which
+        * could ruin logic in its own waits).
+        *
+        * Right after forks:
+        * ┌───────┐   ┌─────────┐   ┌─────────────┐   ┌────────┐
+        * │ pid 1 ├──>│ libdlog ├──>│ immediately ├──>│ execs  │
+        * │ init  │   │ client  │   │    exits    │   │ writer │
+        * └───────┘   └─────────┘   └─────────────┘   └────────┘
+        *
+        * Afterwards, libdlog has no children:
+        * ┌───────┐   ┌─────────┐                     ┌────────┐
+        * │ pid 1 ├──>│ libdlog │          ┌─────────>│ writer │
+        * │ init  ├─┐ │ client  │          │          │ binary │
+        * └───────┘ │ └─────────┘          │          └────────┘
+        *           └──────────────────────┘
+        */
+
+       initialize();
+
+       if (!enable_critical)
+               return;
+
+       const pid_t main_pid = getpid();
+       const pid_t main_tid = gettid();
+
+       const int temporary_exiter_pid = fork();
+       if (temporary_exiter_pid < 0)
+               return;
+       if (temporary_exiter_pid != 0) {
+               waitpid(temporary_exiter_pid, NULL, 0);
+               return;
+       }
+
+       const int child_pid = fork();
+       if (child_pid < 0)
+               _exit(1);
+       if (child_pid != 0)
+               _exit(0);
+
+       __critical_log_child(main_pid, main_tid, log_id, prio, tag, fmt, ap);
+}
+
+// LCOV_EXCL_START : stashing is essentially error handling.
+static void stash_critical_inner(log_id_t log_id, log_priority prio, const char *tag, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       __critical_log(log_id, prio, tag, fmt, ap);
+       va_end(ap);
+}
+
+static int stash_critical(log_id_t log_id, log_priority prio, const char *tag, const char *msg)
+{
+       stash_critical_inner(log_id, prio, tag, "FAILED TO LOG: %s", msg);
+       return 0;
+}
+// LCOV_EXCL_STOP
+
+EXPORT_API int __dlog_critical_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       __critical_log(log_id, prio, tag, fmt, ap);
+       va_end(ap);
+
+       va_start(ap, fmt);
+       int ret = __dlog_vprint(log_id, prio, tag, fmt, ap);
+       va_end(ap);
+
+       return ret;
+}
+#endif
+
+EXPORT_API int dlog_set_minimum_priority(int priority)
+{
+       if (priority < DLOG_DEFAULT || priority > DLOG_PRIO_MAX)
+               return DLOG_ERROR_INVALID_PARAMETER;
+
+       priority_filter_level = priority;
+       return DLOG_ERROR_NONE;
+}
+
 /**
  * @brief Print log
  * @details Print a log line
@@ -338,9 +749,9 @@ static int __write_to_log(log_id_t log_id, int prio, const char *tag, const char
  * @param[in] ap Argument list
  * @return Bytes written, or negative error
  */
-int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
+EXPORT_API int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, va_list ap)
 {
-       int ret = __write_to_log(log_id, prio, tag, fmt, ap, true);
+       int ret = __write_to_log(log_id, prio, tag, fmt, ap, true, false);
        __dlog_fatal_assert(prio);
 
        return ret;
@@ -355,7 +766,7 @@ int __dlog_vprint(log_id_t log_id, int prio, const char *tag, const char *fmt, v
  * @param[in] fmt Format (same as printf)
  * @return Bytes written, or negative error
  */
-int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
+EXPORT_API int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
 {
        va_list ap;
 
@@ -366,12 +777,36 @@ int __dlog_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ..
        return ret;
 }
 
-int dlog_vprint(log_priority prio, const char *tag, const char *fmt, va_list ap)
+/**
+ * @brief Print log
+ * @details Print a log line
+ * @param[in] log_id The target buffer ID
+ * @param[in] prio Priority
+ * @param[in] tag tag
+ * @param[in] fmt Format (same as printf)
+ * @return Bytes written, or negative error
+ */
+EXPORT_API int __dlog_sec_print(log_id_t log_id, int prio, const char *tag, const char *fmt, ...)
+{
+       if (!enable_secure_logs)
+               return 0;
+
+       va_list ap;
+
+       va_start(ap, fmt);
+       int ret = __write_to_log(log_id, prio, tag, fmt, ap, true, true);
+       __dlog_fatal_assert(prio);
+       va_end(ap);
+
+       return ret;
+}
+
+EXPORT_API int dlog_vprint(log_priority prio, const char *tag, const char *fmt, va_list ap)
 {
-       return __write_to_log(LOG_ID_APPS, prio, tag, fmt, ap, false);
+       return __write_to_log(LOG_ID_APPS, prio, tag, fmt, ap, false, false);
 }
 
-int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
+EXPORT_API int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
 {
        va_list ap;
 
@@ -382,56 +817,63 @@ int dlog_print(log_priority prio, const char *tag, const char *fmt, ...)
        return ret;
 }
 
+EXPORT_API int dlog_vprint_dotnet(log_priority prio, const char *tag, const char *fmt, va_list ap)
+{
+       return __write_to_log(SINK_DOTNET, prio, tag, fmt, ap, false, false);
+}
+
+EXPORT_API int dlog_print_dotnet(log_priority prio, const char *tag, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       int ret = dlog_vprint_dotnet(prio, tag, fmt, ap);
+       va_end(ap);
+
+       return ret;
+}
+
+EXPORT_API int dlog_vprint_native(log_priority prio, const char *tag, const char *fmt, va_list ap)
+{
+       return __write_to_log(SINK_NATIVE, prio, tag, fmt, ap, false, false);
+}
+
+EXPORT_API int dlog_print_native(log_priority prio, const char *tag, const char *fmt, ...)
+{
+       va_list ap;
+
+       va_start(ap, fmt);
+       int ret = dlog_vprint_native(prio, tag, fmt, ap);
+       va_end(ap);
+
+       return ret;
+}
+
+// LCOV_EXCL_START : for internal use only, not accessible via public API
+
 /**
  * @brief Finalize DLog
  * @details Finalizes and deallocates the library
  * @notes Used directly in tests; brings back the pre-init state
  */
-#ifndef UNIT_TEST
-static
-#endif
 void __dlog_fini(void)
 {
        if (destroy_backend) {
                destroy_backend();
                destroy_backend = NULL;
        }
-       write_to_log = NULL;
+       write_to_log = write_to_log_null;
+       stash_failed_log = NULL;
        is_initialized = false;
        first = true;
 
-       __log_limiter_destroy();
+       enable_secure_logs = true;
+       enable_critical = false;
+       __deduplicate_destroy();
+       __log_limiter_destroy(limiter_data);
+       limiter = false;
        __dynamic_config_destroy();
+       should_disable_cancels = false;
 }
 
-#ifdef UNIT_TEST
-void
-#else
-static void __attribute__((destructor))
-#endif
-__dlog_destroy(void)
-{
-       if (!pthread_rwlock_wrlock(&log_destruction_lock))
-               __dlog_fini();
-
-       /* IMPORTANT! The lock is NEVER RELEASED. This is done ON PURPOSE.
-        * The critical section can still be reached in some ways, NONE LEGAL.
-        *
-        * The first is that the program links the library dynamically and keeps
-        * pointers to API functions past dlclose(). This is UNDEFINED BEHAVIOUR
-        * and the implementation is NOT REQUIRED to keep the functions in memory
-        * AT ALL and doing this COULD HAVE ALREADY CRASHED the program under a
-        * different implementation.
-        *
-        * The second is when linking statically and FAILING TO JOIN threads before
-        * exit(). These threads then typically keep running and can access the
-        * library interface. However, they WILL DIE ANY MOMENT NOW ANYWAY so
-        * getting deadlocked is of no consequence.
-        *
-        * In theory it would be possible to detect that destruction has already
-        * taken place and reinitialize the library to salvage a logging attempt.
-        * This is a HORRIBLE IDEA since without a destructor to rely on, either
-        * those RESOURCES WOULD LEAK or we would have to MASSIVELY CONVOLUTE our
-        * logic for manual destruction in such cases. */
-}
-
+// LCOV_EXCL_STOP