Dynamic backend loading for mw::log#

Goal#

  • mw/log as a single shared library (.so) with console backend/sink built-in.

  • backend .so files (libmwlog_file_backend.so, libmwlog_remote_backend.so, libmwlog_slog_backend.so) deployed to a well-known directory by the integrator. Each backend is an independent shared library.

  • At runtime, mw/log loads and registers all the *backend.so files specified by the integrator.

  • Libraries and binaries depend on a single mw/log target. No per-backend deps needed.

  • Customer-provided backends (libmwlog_custom_backend.so) use the same directory based discovery mechanism.

Targets#

  1. score_baselibs - libmwlog.so (cc_shared_library)

  • frontend

  • console backend (built-in)

  • backend_table (gBackendCreators)

  • backend_loader (via dl_open)

  1. score_logging - *backend.so (cc_shared_library)

  • libmwlog_file_backend.so

  • libmwlog_remote_backend.so

  • libmwlog_slog_backend.so (QNX)

  • libmwlog_custom_backend.so (custom)

Dynamic loading and Application Binary Interface (ABI)#

Dynamic loading introduces an ABI boundary between the main binary and the backend plugin .so. Unlike static linking where the compiler and linker can verify type compatibility at build time, dynamic linking defers binding to runtime making ABI stability an explicit design concern.

Design Decision for dlopen() based solution#

The rationale for choosing a dlopen-based solution is documented in the Design Decisions.

mw::log would use dlopen() based dynamic loading to compose recorders and respective backends at runtime. A libmwlog.so (frontend + console backend + dynamic backend loader) is the sole build dependency for all consumers. Per-backend .so files (libmwlog_file_backend.so, libmwlog_remote_backend.so, libmwlog_slog_backend.so) are deployed by the integrator and loaded at runtime from a configuration-specified list. The plugin boundary uses a C++ interface - backend .so files export a C++ recorder factory function discovered via a minimal extern “C” entry point.

mw::log is classified as ASIL B. The frontend preserves freedom from interference (FFI) - dlopen() occurs only during init, and the post-init Recorder interface boundary is identical to the static-link case.

Architectural decision: This approach preserves the existing C++ backend implementation unchanged, at the cost of requiring toolchain identity between libmwlog.so and all backend .so files. Security is enforced via OS-level compensating controls (pathtrust, secpol, procnto -mX, setuid bit, configuration-driven loading) rather than libc isolation.

Plugin API (mw_log_plugin_api.h)#

The plugin API uses minimal extern “C” entry points: one for version checking and one for backend registration. Both symbols use C linkage to avoid name-mangling dependencies across toolchain versions.

Rationale:

  • Both MwLogVersion() and MwLogRegisterBackends() use extern “C” to provide stable, mangling-independent symbols for dlsym() lookup.

  • Shared libc/libstdc++ (no RTLD_NOSHARE) enables standard C++ types, smart pointers, and allocators to cross the dlopen() boundary safely within the registration and recorder creation path.

    • Constraint: All backend .so files MUST be built with the identical toolchain (compiler version, -std= flag, libstdc++ version) as libmwlog.so. This is enforced via CI (REQ-DD-1).

  • The no-dlclose() policy (REQ-SAFE-1) guarantees that all code pages and vtable pointers remain valid for process lifetime.

1. Detailed Design#

Covers requirements for Detailed Design (DD) and Implementation.

The dynamic backend selection diagram shows the backend selection sequence.

Fig. 20 dynamic backend selection diagram#

The diagram uses swimlanes to clearly separate the two configuration layers:

Layer 1 (Integrator / backend_config.json): Shows the global backend creator slot population flow. Each backend .so becomes available but no recorder is created yet.

Layer 2 (User / logging.json): Shows CreateFromConfiguration reading the logMode set, then for each mode checking IsBackendAvailable() against the already-populated global backend creator and calls CreateRecorderForMode() to instantiate only what the user selected. If a requested mode has NO slot populated (integrator didn’t deploy that .so), it falls back to console.

Runtime init: Wraps both layers, enforcing the REQ-DD-7 ordering invariant, and shows the final CompositeRecorder / single recorder / EmptyRecorder outcome.

1.1 Detailed Design Requirements#

REQ-DD-1: C++ Plugin Boundary with Toolchain Identity#

The plugin .so files shall use the existing C++ Recorder interface. Each backend .so exports two extern “C” entry points: MwLogVersion() (ABI version gate) and MwLogRegisterBackends() (registration callback). The registration callback calls RegisterBackend() from backend_table.h, which stores a RecorderCreatorFn function pointer. The RecorderCreatorFn returns std::unique_ptr. C++ types (std::unique_ptr, Configuration&, std::pmr::memory_resource*) are permitted to cross the dlopen() boundary at recorder creation time. “RTLD_NOSHARE” shall not be used - all backend .so files share the process’s libc and libstdc++ instances.

Toolchain identity constraint: All backend .so files and libmwlog.so shall be built with the identical toolchain: same compiler version, same -std=c++XX flag, same optimization level (-O2), and same libstdc++/libc++ version. A CI gate shall enforce this by comparing compiler identification hashes (E.g.: gcc –version fingerprint) embedded in each .so at build time.

Reasoning: score_baselibs and score_logging reside in separate Bazel workspaces but share the same score_toolchain and reference integration platform. Since RTLD_NOSHARE is not used, libc/libstdc++ are shared, making C++ types safe to pass across the boundary “within the same toolchain”. The toolchain identity CI gate is the mechanism that prevents C++ ABI mismatches.

Limitation: Customer provided plugins built with a different toolchain are not supported.

References:

REQ-DD-2: ABI Version Guard#

Each plugin .so shall export an extern “C” function MwLogVersion() returning MW_LOG_ABI_VERSION. The dynamic backend loader shall call MwLogVersion() immediately after dlopen() and reject the plugin if the returned version does not match MW_LOG_ABI_VERSION compiled into libmwlog.so. MW_LOG_ABI_VERSION shall be incremented when the Recorder interface changes in a binary-incompatible way (virtual method addition, removal, reorder, or signature change).

Reasoning: The version check is a coarse-grained ABI gate. It catches obvious mismatches (E.g.: a backend built against an older Recorder interface). It does not catch subtle C++ ABI differences caused by toolchain mismatches - the toolchain identity CI gate (REQ-DD-1) is the primary defense for that class of errors.

References:

REQ-DD-3: Configuration-Driven Backend Loading#

The dynamic backend loader shall load only the backend .so files explicitly listed in the logging backend configuration file (E.g.: backend_config.json field “backends”: [“libmwlog_file_backend.so”, “libmwlog_remote_backend.so”, etc.]). It shall not blindly scan the backend directory for all matching files. Each listed filename is joined with the backend directory path, which is determined exclusively at compile time via Bazel feature flags (see below).

Reasoning: Glob-based directory scanning creates a wider attack surface - An incompatible backend version could potentially crash the application. An explicit compatible version is safe. Feature flags improve discoverability, and allow per-integration overrides without modifying source files. Security is preserved because feature flags are build-time constants, not runtime-configurable values.

Backend Directory and Config Path Resolution via Feature Flags#

The backend directory path and config file path should be compile-time constants controlled via Bazel string_flag feature flags defined in //score/mw/log/flags:BUILD.

Flag definitions in //score/mw/log/flags/BUILD:

load("@bazel_skylib//rules:common_settings.bzl", "string_flag")

string_flag(
    name = "backend_dir",
    build_setting_default = "/opt/libmwlog/backends/",
    visibility = [
        "@score_baselibs//score/mw/log:__subpackages__",
    ],
)

string_flag(
    name = "backend_config_path",
    build_setting_default = "/opt/libmwlog/backend_config.json",
    visibility = [
        "@score_baselibs//score/mw/log:__subpackages__",
    ],
)

Propagation to C++ is done via expand_template generating a header with the flag values, avoiding the select()/config_setting enumeration limitation inherent to arbitrary string paths:

expand_template(
    name = "backend_paths_header",
    out = "backend_paths_config.h",
    template = "backend_paths_config.h.tpl",
    substitutions = {
        "@BACKEND_DIR@": "$(//score/mw/log/flags:backend_dir)",
        "@BACKEND_CONFIG_PATH@": "$(//score/mw/log/flags:backend_config_path)",
    },
)

Per-integration override via command line:

bazel build //... \
  --//score/mw/log/flags:backend_dir="/xyz/platform/opt/mwlog/" \
  --//score/mw/log/flags:backend_config_path="/xyz/platform/opt/mwlog/backend_config.json"

Or via .bazelrc:

build:ipnext_isoc --//score/mw/log/flags:backend_dir="/xyz/platform/opt/mwlog/"
build:ipnext_isoc --//score/mw/log/flags:backend_config_path="/xyz/platform/opt/mwlog/backend_config.json"

The paths shall never be sourced from an environment variable or from the runtime configuration file. Feature flags are build-time settings, ensuring the paths are immutable after build and preventing runtime manipulation.

  • Default values match the most productive/stable configuration (/opt/libmwlog/backends/ and /opt/libmwlog/backend_config.json).

Constraints on the backend directory path:

  • Must be an absolute path (starts with /).

  • The dynamic backend loader shall static_assert that the backend directory path starts with / at compile time.

Constraints on the backend config path:

  • Must be an absolute path (starts with /).

  • Must reside on a qtsafefs-mounted filesystem that is RO to prevent tampering (AOU-7).

If a listed file is absent, it is treated as “not deployed”. If no configuration is provided, no backends are loaded and the system uses console-only logging.

NOTE: config file placed at the path specified by backend_config_path (default: /opt/libmwlog/backend_config.json) with content:

{ “backends”: [ “libmwlog_file_backend.so”, “libmwlog_remote_backend.so” ] }

References:

  • CWE-426: Untrusted Search Path

  • EP-23: Feature Flags in Bazel (docs/enhancement_proposals/proposals/23_feature_flags.md of the score_baselibs repository)

REQ-DD-4: Fallback Chain#

The dynamic backend loader shall implement the following fallback chain:

  1. For each configured backend: attempt dlopen(), ABI check via MwLogVersion(), then call MwLogRegisterBackends().

  2. If a configured backend fails to load (.so present but dlopen()/ABI check/registration fails): report an ERROR.

  3. If a configured backend .so is absent (file does not exist): report a warning.

  4. If no recorders are registered after loading, fallback to console-only logging (built-in).

  5. If console allocation also fails then EmptyRecorder (stub, no-op).

Fallback diagnostic messages shall use a non-mw::log channel to avoid circular dependency.

References:

REQ-DD-5: Frontend FFI Preservation#

The frontend’s steady-state behavior (after init) shall not be affected by which recorder backend is loaded. dlopen() shall occur only during the initialization window. Post-init, all logging calls go through the Recorder interface - identical to the static-link architecture. Backend failures shall not propagate into the frontend.

Reasoning: mw::log is ASIL B. ISO 26262: Part 6 requires freedom from interference (FFI). Confining dynamic loading to init preserves temporal, spatial, functional, and resource FFI. Take note of existing AoUs of mw::log that init is not time bounded.

REQ-DD-6: Shared libc/libstdc++ Contract#

RTLD_NOSHARE is explicitly not used. All backend .so files share the process’s single libc and libstdc++ instance. This means:

  • errno is shared (thread-local, single instance per thread).

  • malloc/free operate on a single heap - memory allocated by the backend can be freed by the frontend and vice versa.

  • File descriptors, atexit() handlers, and signal state are process-global and shared.

  • C++ standard library types (std::unique_ptr, std::string, std::mutex, etc.) have identical layouts and can safely cross the dlopen() boundary.

Constraints imposed by this decision:

  1. Toolchain identity is mandatory (REQ-DD-1). Different libstdc++ versions have different std::string layouts (pre/post-C++11 ABI), different allocator internals, etc.

  2. “RTLD_NOSHARE” cannot be enabled without first refactoring to a pure C ABI boundary. This is an explicit, documented trade-off.

  3. Security relies on OS-level compensating controls (pathtrust, secpol, procnto -mX, setuid bit) rather than libc isolation (see Security Requirements).

Reasoning: The existing backend implementation (RemoteDltRecorderFactory, DataRouterRecorder, DatarouterMessageClientImpl) uses C++ standard library types, spawns threads, opens file descriptors, and maps shared memory. These operations require a shared libc/libstdc++ instance to function correctly. Isolating libc via RTLD_NOSHARE would require a complete refactor to a pure C ABI boundary - a huge refactoring effort given that OS-level integrity controls (qtsafefs, pathtrust, secpol) already prevent loading untrusted code.

References:

REQ-DD-7: Backend Loading inside Runtime Constructor (Meyer’s Singleton)#

LoadConfiguredBackends() shall be called inside Runtime::Runtime(), before RegistryAwareRecorderFactory::CreateFromConfiguration(). The execution sequence within the Runtime constructor shall be:

  1. LoadConfiguredBackends() - writes to gBackendCreators[] via RegisterBackend().

  2. CreateRecorderFactory() calls CreateFromConfiguration() which invokes gBackendCreators[] via CreateRecorderForMode().

This ordering guarantees that all writes to gBackendCreators[] complete before any reads, within the same function call on the same thread. No synchronization primitive (mutex, atomic) is required on gBackendCreators[] itself.

Thread-safety is provided by the C++11 Meyer’s singleton guarantee: Runtime is constructed via singleton::MeyerSingleton::GetInstance(), which uses the C++11 “magic statics” guarantee ([stmt.dcl] p4) - if multiple threads call GetInstance() concurrently, exactly one thread executes the constructor while all others block until construction completes. After construction, gBackendCreators[] is effectively immutable for the remainder of the process lifetime.

Invariants:

  • LoadConfiguredBackends() is called exactly once, inside Runtime::Runtime(), on the thread that first triggers singleton construction.

  • All writes to gBackendCreators[] (both static-init registrants like console and dynamic-load registrants) complete before CreateFromConfiguration() reads the table.

  • After Runtime::Runtime() returns, gBackendCreators[] shall not be modified.

Implementation note: Runtime::Runtime() must read the backend configuration (directory path, filenames) before calling LoadConfiguredBackends(). The preferred approach is single-read + pass-through: read and parse the backend configuration file once, then pass the parsed backend list to LoadConfiguredBackends() and the full configuration to CreateFromConfiguration(). This avoids parsing the config file twice.

If the config file is read independently by LoadConfiguredBackends() and CreateFromConfiguration(), a TOCTOU race exists on the config file content between the two reads. On production QNX targets with RO qtsafefs (AOU-7) this is safe because the file is immutable. However, on development Linux environments where the config file is on a read-write filesystem, a concurrent modification between the two reads could cause LoadConfiguredBackends() and CreateFromConfiguration() to operate on inconsistent configuration state. The single-read + pass-through approach eliminates this race.

References:

1.2 Verification Requirements#

REQ-DD-V1: ABI Version Mismatch Rejection#

Verify that the dynamic backend loader rejects a plugin .so whose MwLogVersion() returns a value different from MW_LOG_ABI_VERSION. Verify the fallback chain activates and the mismatch is logged via slogf()/stderr.

Verification method: unit test

REQ-DD-V2: Configuration-Driven Loading#

Verify that the dynamic backend loader loads only the .so files listed in the configuration.

Verification method: component test/sctf.

REQ-DD-V3: Fallback Chain Activation#

Verify all fallback chain paths:

  1. All configured backends load successfully and all registered.

  2. One configured backend missing and remaining load

  3. One configured backend corrupt/failing and remaining load; error logged.

  4. All configured backends fail and console-only fallback activates.

  5. Console allocation fails and EmptyRecorder stub is returned.

Verification method: unit/component testing.

REQ-DD-V4: Backend Loading Order Inside Runtime Constructor#

Ensure that LoadConfiguredBackends() executes before CreateFromConfiguration() within Runtime::Runtime(), and that gBackendCreators[] is not modified after construction:

Verification method: unit test + Manual Analysis / clang (TODO)


2. Safety Requirements#

2.1 Detailed Design#

REQ-SAFE-1: No dlclose() Policy#

The loaded plugin handle shall not be closed during process lifetime. The handle is intentionally leaked: (void)handle;. This policy SHALL be enforced as follows:

  1. The dynamic backend loader SHALL NOT store the dlopen() handle in any data structure that could be passed to dlclose().

  2. The dynamic backend loader SHALL NOT expose any API that accepts or returns a dlopen() handle.

  3. No code path in libmwlog.so or any backend .so SHALL call dlclose().

Reasoning: The C++ virtual function table (vtable) and destructor code of Recorder objects returned by the backend factory reside in code pages mapped from the plugin .so. These code pages SHALL remain mapped for the entire process lifetime. This is the mechanism that prevents use-after-free (CWE-416) when the frontend destroys Recorder objects via std::unique_ptr. If dlclose() is called, those code pages are unmapped - but Recorder objects remain alive with dangling vtable pointers. Any subsequent virtual call (StartRecord(), StopRecord(), Log()) would jump to unmapped memory, causing a segfault or silent corruption. Since the plugin is loaded once at init and recorders live for the entire process, there is no legitimate reason to unload.

References:

REQ-SAFE-2: Plugin Constructor Restrictions#

The plugin .so shall not use mw::log in any attribute((constructor)) function or static initializer. The plugin .so shall not call setenv(), putenv(), signal(), or spawn threads in constructor functions.

Reasoning: Plugin constructors execute during dlopen() - before the version guard (MwLogVersion()) is checked. A constructor calling mw::log creates a circular dependency and potential deadlock (the logging runtime may not yet be initialized). Constructors that modify global process state (setenv, signal handlers) can interfere with the frontend’s FFI guarantees.

References:

REQ-SAFE-3: FMEA Coverage for dlopen() Path#

A formal FMEA entry shall be created covering dlopen, dlsym, MwLogVersion, MwLogRegisterBackends calls.

Reasoning: ISO 26262 Part 5 requires FMEA for all safety-relevant failure modes. The dlopen() path introduces new failure modes not present in the static-link architecture. In particular, MwLogRegisterBackends() executes plugin code within the frontend’s address space - any failure in this function can corrupt the backend registration table or crash the process.

REQ-SAFE-4: Pre-dlopen() ELF Section Version Marker (CI/Deploy-Time Gate)#

Each plugin .so SHALL embed a version integer in a dedicated ELF section .mwlog_abi at build time. This marker is intended for offline verification - it is NOT read at runtime by the dynamic backend loader.

CI/deploy-time enforcement: A CI gate or deployment validation script SHALL read the .mwlog_abi section from each backend .so (using readelf -x .mwlog_abi) and verify that the embedded version matches the MW_LOG_ABI_VERSION compiled into libmwlog.so. Backend .so files with mismatched versions SHALL NOT be deployed to the target filesystem.

This check catches version mismatches before deployment, preventing a scenario where dlopen() executes plugin constructors (REQ-SAFE-2) from an incompatible binary before the application can call MwLogVersion(). The runtime MwLogVersion() check (REQ-DD-2) remains the defense-in-depth mechanism for detecting mismatches that escape the CI gate.

Reasoning: dlopen() executes plugin constructors before the application can call MwLogVersion(). A pre-deployment check avoids running any plugin code from an incompatible binary on the target. Runtime ELF section parsing was considered but rejected due to implementation complexity (requires ELF header parsing in application code) and marginal benefit over the deploy-time gate combined with pathtrust/qtsafefs as the primary protection against untrusted binaries.

Note on section naming: A custom section name .mwlog_abi is used instead of a .note.* prefix. The ELF .note section format requires a structured header (namesz, descsz, type, name, desc) per the ELF specification. Placing a raw uint32_t into a .note.*-prefixed section without this structure would confuse tools like readelf -n that expect proper note formatting. Since the CI gate uses readelf -x (hex dump), the simpler custom section approach is sufficient and avoids misleading section naming.

References:

// Plugin side - static marker (readable offline via readelf/objdump, not loaded at runtime)
extern "C" {
    const uint32_t kMwLogAbiVersion __attribute__((section(".mwlog_abi"))) = 1U;
}

CI gate example:

#!/bin/bash
# Verify ABI version in backend .so matches libmwlog.so
EXPECTED_VERSION=$(readelf -x .mwlog_abi libmwlog.so | awk '...')
PLUGIN_VERSION=$(readelf -x .mwlog_abi "$1" | awk '...')
if [ "$EXPECTED_VERSION" != "$PLUGIN_VERSION" ]; then
    echo "FAIL: ABI version mismatch in $1 (expected $EXPECTED_VERSION, got $PLUGIN_VERSION)"
    exit 1
fi

2.2 Verification Requirements#

REQ-SAFE-V1: dlopen() Failure Path Testing on Target ECU#

Execute REQ-DD-V3 scenarios on target ECU to confirm that all dlopen() failure paths behave correctly on actual hardware.

Verification method: ITF

REQ-SAFE-V2: Execution Management (EM)/ Plaftorm Health Management (PHM) monitoring regressions#

All existing ASIL B init sequence - EM/PHM checkpoint tests shall be re-executed with dynamic plugin loading active

Verification method: ITF

REQ-SAFE-V3: Stub Logging Detection#

Verify that in a fully deployed production system, the EmptyRecorder stub is never the active recorder.

Verification method: ITF

REQ-SAFE-V4: No mw::log Usage in Plugin Constructors#

Verify that loading a plugin whose constructor calls mw::log does not deadlock or crash the init sequence.

Verification method: Manual Analysis.


3. Security Requirements#

3.1 Detailed Design#

REQ-SEC-1: Absolute Path for dlopen()#

dynamic backend loader shall call dlopen() with a fully-qualified absolute path constructed by joining the backend directory path and the configured filename. Relative paths and bare filenames shall not be passed to dlopen().

Reasoning: Relative paths cause the runtime linker to search LD_LIBRARY_PATH and _CS_LIBPATH, which may point to untrusted directories. Absolute paths bypass the search entirely, eliminating CWE-426: Untrusted Search Path.

References:

REQ-SEC-2: qtsafefs Enforcement for production software runnning QNX#

Reasoning: A path-prefix check alone is insufficient - anyone could mount a non-qtsafefs filesystem at the expected path.

Should be satisfied by AOU-1. This is a security enforced requirement.

REQ-SEC-3: Compensating Controls for Omitted RTLD_NOSHARE#

dlopen() shall use RTLD_NOW | RTLD_LOCAL (without RTLD_NOSHARE). The decision to omit RTLD_NOSHARE is justified by the following compensating controls, ALL of which shall be enforced:

#

Compensating Control

Requirement

Threat Mitigated

1

pathtrust + qtsafefs

REQ-SEC-2, AOU-1, AOU-2

Prevents loading tampered/untrusted .so files at OS level

2

secpol: PROCMGR_AID_UNTRUSTED_EXEC denied

REQ-SEC-8

Makes pathtrust mandatory - dlopen() cannot bypass trust verification

3

setuid bit on process

REQ-SEC-8

Runtime linker automatically unsets LD_PRELOAD, LD_LIBRARY_PATH before any user code

4

procnto -mX

REQ-SEC-9

Prevents PROT_EXEC on files without +x - blocks loading from /dev/shmem, /tmp

5

Configuration-driven loading

REQ-DD-3

Only explicitly listed .so files are loaded - no glob-scan, no auto-discovery

Without RTLD_NOSHARE, the following attack is theoretically possible: If a compromised component calls dlopen(“libmwlog_remote_backend.so”, …) with a relative path before dynamic backend loader runs, the linker may return the already-loaded (malicious) handle. With all five compensating controls in place, this attack requires a build-chain compromise of a pathtrust-verified binary on a qtsafefs filesystem - a significantly higher bar than the RTLD_NOSHARE scenario alone addresses.

Reasoning: RTLD_NOSHARE creates a private libc/libstdc++ copy for the plugin, making C++ types unusable across the boundary. Since the design choice is to preserve the existing C++ backend implementation (REQ-DD-1, REQ-DD-6), RTLD_NOSHARE is incompatible with the architecture. The five compensating controls collectively provide equivalent or stronger security guarantees for the threat model.

References:

REQ-SEC-4: RPATH Hardening (Plugin and Transitive Dependencies)#

Each backend .so shall be built with:

  • -Wl,–disable-new-dtags - ensures RPATH is used (not RUNPATH). RPATH is not overridden by LD_LIBRARY_PATH.

  • An explicit, absolute RPATH pointing only to qtsafefs-backed library directories (E.g.: -Wl,-rpath,/opt/libmwlog/backends). No $ORIGIN-relative paths.

Reasoning: When dlopen() loads a backend .so, the runtime linker resolves its DT_NEEDED transitive dependencies using the search order: RPATH -> LD_LIBRARY_PATH -> _CS_LIBPATH. If RUNPATH is used instead of RPATH, LD_LIBRARY_PATH takes precedence, allowing an attacker to inject transitive dependencies. Absolute RPATH with –disable-new-dtags ensures transitive deps are resolved only from trusted paths.

References:

REQ-SEC-5: Exported Symbol Minimization#

Each plugin .so shall export only MwLogVersion and MwLogRegisterBackends (both extern “C”). All other symbols shall be hidden via -fvisibility=hidden and a linker version script:

{
    global:
        MwLogVersion;
        MwLogRegisterBackends;
    local:
        *;
};

Reasoning: Every exported symbol is an attack surface and a potential source of symbol collision (CWE-114). Minimizing exports hides internal implementation, eliminates interposition risk, and reduces the ABI surface that must remain stable.

References:

REQ-SEC-6: Environment Variable Integrity Check (Needs further investigation)#

At init, the dynamic backend loader should snapshot the values of LD_PRELOAD, LD_LIBRARY_PATH, DL_DEBUG, and LD_DEBUG. Before each dlopen() call, it should verify these values have not changed. If any have been modified, a critical diagnostic shall be logged.

Known limitation (TOCTOU): This check is subject to a time-of-check time-of-use race condition. A concurrent thread calling setenv(“LD_LIBRARY_PATH”, “/attacker/path”) between the snapshot verification and the dlopen() call can still succeed. This check is therefore a diagnostic aid, not a reliable security control. It MUST not be relied upon as the sole mitigation for environment variable manipulation.

The primary mitigation is the setuid bit (REQ-SEC-8), which causes the runtime linker to automatically unset LD_LIBRARY_PATH, LD_PRELOAD, DL_DEBUG, and LD_DEBUG before any user code runs - including library constructors. REQ-SEC-8 eliminates the TOCTOU race entirely because the variables are never present in the process environment.

Reasoning: On QNX 8.0, LD_LIBRARY_PATH is re-read on every dlopen() call. The snapshot-and-recheck approach provides observability (detecting unexpected environment mutations) but cannot guarantee atomicity with respect to dlopen(). The setuid bit (REQ-SEC-8) is the authoritative control.

References:

void AssertCleanEnvironment() noexcept {
    const char* vars[] = {"LD_PRELOAD", "LD_LIBRARY_PATH", "DL_DEBUG", "LD_DEBUG"};
    for (const char* var : vars) {
        const char* val = std::getenv(var);
        if (val != nullptr) {
            slogf(_SLOG_SETCODE(0, 0), _SLOG_CRITICAL,
                  "mw::log: %s is set - potential security risk", var); // slog buffers
        }
    }
}

REQ-SEC-7: dlerror() Output Sanitization#

dlerror() strings shall be sanitized before logging. They shall be logged at internal/verbose level only, never at a level accessible to unprivileged log consumers.

Reasoning: dlerror() may return filesystem paths and internal details that reveal system layout to an attacker with log access.

References:

  • POSIX dlerror() - specifies that dlerror() returns a human-readable string describing the last error.

REQ-SEC-8: QNX secpol and Ability Restrictions#

Processes using mw::log with dynamic loading shall have PROCMGR_AID_UNTRUSTED_EXEC denied via secpol. This ensures only pathtrust-verified libraries can be loaded by dlopen(). The process should run with the “setuid” bit set, causing the runtime linker to automatically unset LD_LIBRARY_PATH, LD_PRELOAD, DL_DEBUG, and LD_DEBUG before any user code runs.

Reasoning: pathtrust is the OS-level gate that prevents dlopen() from loading untrusted binaries. Denying PROCMGR_AID_UNTRUSTED_EXEC makes this gate mandatory. The setuid bit provides automatic environment variable sanitization by the runtime linker - a stronger guarantee than application-level checks (REQ-SEC-6) because it runs before any user code, including library constructors.

References:

REQ-SEC-9: PROT_EXEC Enforcement via procnto -mX#

Deployment shall require procnto -mX on the target ECU. All backend .so files shall have the +x (executable) permission bit set.

Reasoning: When procnto is started with -mX, it only allows PROT_EXEC on mmap() if the file has the +x bit set. This prevents loading .so files from writable directories like /dev/shmem or /tmp where an attacker could write a malicious library but would lack the ability to set the +x bit on a properly configured system.

References:

REQ-SEC-10: ELF Hardening Flags#

All backend .so files and libmwlog.so shall be built with:

Flag

Purpose

-Wl,-z,now

Full RELRO - all GOT (global offset table) entries resolved at load time, GOT marked read-only

-Wl,-z,relro

Partial RELRO (relocatable sections before GOT marked read-only)

-Wl,-z,noexecstack

Non-executable stack

-fstack-protector-strong

Stack canary protection

-fPIC

Position-independent code

NOTE: Flags (1) and (2) are complimentary.

Reasoning: Standard ELF hardening per Red Hat security hardening guidelines. Full RELRO prevents GOT overwrite attacks. Non-executable stack mitigates stack-based code injection. These are baseline requirements for any shared library in a safety-critical system.

References:

3.2 Verification Requirements#

REQ-SEC-V1: Absolute Path Enforcement#

Verify that dynamic backend loader rejects any attempt to load a plugin via a relative path or bare filename.

Verification method: Unit test

REQ-SEC-V2: Backend Directory Ownership Verification#

Verify that the backend directory has the the right mandatory access controls setup.

Reasoning: On qtsafefs, the filesystem is read-only and integrity-checked. On non-qtsafefs deployments (E.g.: development environments), a rw backend directory would allow any process to inject a wrong plugin.

Verification method: Integration test (ITF)

REQ-SEC-V3: Compensating Controls Enforcement#

Verify that all five compensating controls (REQ-SEC-3) are active and correctly prevent unauthorized library loading:

  1. pathtrust: Place a valid .so on a non-pathtrust filesystem would verify dlopen() fails.

  2. secpol: Verify process has PROCMGR_AID_UNTRUSTED_EXEC denied would untrusted .so cannot load.

  3. setuid: Verify LD_LIBRARY_PATH and LD_PRELOAD are unset by runtime linker before main().

  4. procnto -mX: Remove +x from a .so would verify dlopen() fails.

  5. Config-driven: Place an extra libmwlog_hacky_backend.so in the backend directory (not in config) would verify it is not loaded.

Verification method: Target integration test (ITF) on QNX

REQ-SEC-V4: Exported Symbol Check#

Verify that each backend .so exports only MwLogVersion and MwLogRegisterBackends (both extern “C”). All other symbols shall be hidden.

Verification method: CI gate - nm –defined-only –extern-only on each libmwlog_*_backend.so; fail if unexpected symbols are found beyond MwLogVersion and MwLogRegisterBackends.

REQ-SEC-V5: RPATH Verification#

Verify that each backend .so has RPATH (not RUNPATH) containing only approved absolute paths to qtsafefs-backed directories.

Verification method: CI gate - readelf -d on each backend .so; verify RPATH contains only approved paths and no RUNPATH entries exist.

REQ-SEC-V6: ELF Hardening Verification#

Verify that all .so files have GNU_RELRO segment, GNU_STACK without execute flag, and full RELRO binding.

Verification method: CI gate - readelf -l and readelf -d on each .so; verify GNU_RELRO present, GNU_STACK flags do not include E, and BIND_NOW is set.

REQ-SEC-V7: pathtrust Enforcement#

Verify that dlopen() fails to load a .so from a non-pathtrust filesystem and that the fallback chain activates correctly.

Verification method: Integration test (ITF) on QNX

REQ-SEC-V8: Execute Permission Enforcement#

Verify that a backend .so without the +x permission bit fails to load under procnto -mX.

Verification method: Target integration test (ITF) on QNX

REQ-SEC-V9: Environment Variable Mutation Detection#

Verify that dynamic backend loader detects a change to LD_LIBRARY_PATH between init and dlopen() and logs a diagnostic message.

Verification method: Component test

REQ-SEC-V10: dlerror() Sanitization#

Verify that dlerror() output logged by dynamic backend loader does not contain raw filesystem paths at user-accessible log levels.

Verification method: Unit test

REQ-SEC-V11: Double-Load Same Soname from Different Paths#

Empirically determine QNX 8.0 behavior when loading the same soname from two different absolute paths. Document results.

Verification method: Target integration test (ITF) on QNX


4. Performance Requirements#

4.1 Detailed Design#

REQ-PERF-1: Zero Steady-State Overhead#

After initialization, the dynamic-loading architecture shall introduce zero additional overhead compared to the static-link approach. The recorder factory is created once during init; all subsequent logging calls go through the same Recorder interface via virtual function dispatch - identical to the static-link architecture.

Reasoning: The backend’s Recorder object is held via std::unique_ptr - the same ownership model as the static-link case. No additional wrappers, adapters, or indirection layers are introduced. The dlopen() boundary is crossed only during init.

REQ-PERF-2: dlopen() with RTLD_NOW and RTLD_LOCAL#

Backend .so files shall be loaded with RTLD_NOW | RTLD_LOCAL (immediate symbol resolution, symbols not available to subsequently loaded libraries). RTLD_LAZY shall not be used. The full flag set is specified in REQ-SEC-3.

Reasoning: RTLD_NOW performs all symbol resolution at load time, exposing any missing symbol errors immediately during init. RTLD_LAZY defers resolution to first use, which could cause a crash on the first record() call - unacceptable for an ASIL B component. RTLD_LOCAL prevents backend symbols from polluting the global symbol namespace, reducing symbol collision risk. The latency cost is paid once during init, which is already covered as unbounded (TODO: Link existing AoU).

References:

4.2 Verification Requirements#

REQ-PERF-V1: dlopen() Latency Profiling on Target ECU#

Measure dlopen() latency on the target ECU for each per-backend .so file (file, remote, slog)

Document measured values alongside PHM timing budgets with margin.

Backend

Expected (ms)

libmwlog_file_backend.so

libmwlog_remote_backend.so

libmwlog_slog_backend.so

REQ-PERF-V2: Memory Footprint Comparison (Optional)#

Measure the .text + .rodata + RSS footprint for processes in the following configurations and compare against the previous static-link architecture:

Configuration

Expected footprint

Console-only (no plugins)

File-only

File + remote

All backends (previous static-link)

REQ-PERF-V3: Memory Footprint Improvement Validation (Optional)#

Measure the .text + .rodata footprint for processes that load only the backends they need (console-only apps no longer link remote/file backend code) and verify the expected memory savings vs. static-link.

REQ-PERF-V4: Toolchain Identity CI Gate Performance (Optional)#

Verify that the toolchain identity CI gate (REQ-DD-1) does not add measurable overhead to the build pipeline (< 5 seconds per backend .so verification).


5. Assumptions of Use (AoUs)#

These requirements define the operational context and constraints that the integrator, deployer, and plugin author must satisfy for the dynamic loading architecture to function correctly and safely.

AOU-1: qtsafefs Backend Directory#

The backend directory (integrator-defined, resolved via the backend_dir feature flag in //score/mw/log/flags, default /opt/libmwlog/backends/) shall reside on a qtsafefs-mounted filesystem with integrity checking enabled.

AOU-2: pathtrust-Enabled Filesystems#

All filesystems from which backend .so files and their transitive dependencies are loaded shall have pathtrust enabled.

AOU-3: procnto -mX Enabled#

The target ECU shall run procnto with the -mX flag to enforce PROT_EXEC restrictions on mmap(). Only files with the +x permission bit can be loaded as executable code.

AOU-4: secpol Configuration#

The process’s secpol configuration shall deny PROCMGR_AID_UNTRUSTED_EXEC. This ensures dlopen() only loads pathtrust-verified libraries.

AOU-5: Backend .so File Permissions#

All deployed backend .so files shall:

  • Have the +x (executable) permission bit set.

  • Be owned by root (or the designated system user).

  • Not be world-writable.

AOU-6: Environment Variable Integrity#

LD_PRELOAD, LD_LIBRARY_PATH, DL_DEBUG, LD_DEBUG, and PATH shall not be modified after process start. The process should use the setuid bit to have the runtime linker automatically unset LD_LIBRARY_PATH and LD_PRELOAD.

AOU-7: Logging Configuration File#

The logging configuration file (E.g.: backend_config.json) shall explicitly list the backend .so filenames to load. It shall reside on a qtsafefs-mounted filesystem that is RO to prevent tampering.

AOU-8: No mw::log in Plugin Constructors#

Plugin .so files shall not call mw::log APIs in attribute((constructor)) functions or static initializers. Plugin constructors shall not call setenv(), putenv(), signal(), or spawn threads.

AOU-9: Shared Memory Semantics#

Since RTLD_NOSHARE is not used, libc/libstdc++ are shared between libmwlog.so and all backend .so files. Memory allocated by the backend (E.g.: via std::make_unique) can be freed by the frontend and vice versa. Standard C++ ownership semantics (std::unique_ptr) apply normally across the dlopen() boundary. The backend’s Recorder destructor is the primary cleanup mechanism.

AOU-10: Plugin Vtable Lifetime#

The C++ virtual function table (vtable) of Recorder objects returned by the backend factory remains valid for the entire process lifetime. This is guaranteed by the no-dlclose() policy (REQ-SAFE-1) - the backend .so’s code pages are never unmapped.

AOU-11: Toolchain Identity for Backend Plugins#

All backend .so files shall be built with the identical toolchain as libmwlog.so:

  • Same GCC/Clang version

  • Same -std=c++XX flag

  • Same libstdc++/libc++ version

  • Same target architecture flags

AOU-12: Transitive Dependencies on Trusted Filesystems#

All shared libraries transitively required by backend .so files (i.e., their DT_NEEDED entries) shall reside on qtsafefs-mounted, pathtrust-enabled filesystems.

AOU-13: EM/PHM Timing Budget#

The integrator shall ensure that the EM and PHM checkpoint timing budget for init sequences that include dynamic plugin loading accounts for the measured worst-case dlopen() latency (including early startup with RTLD_NOW) with margin.

TODOs#

  1. The security requirements heavily focus on QNX (qtsafefs, pathtrust, secpol, procnto). Document security hardening for Linux-based targets or development environments.

  2. Measure memory footprint per application (static-link vs. dynamic).

  3. Measure dlopen() latency on target ECU flash.

  4. Investigate what Linux/QNX 8.0 does if we load the same soname from two different absolute paths.

  5. Documentation on handling updates to per-backend .so files.

  6. Document EM/PHM checkpoint timing budgets apply to the init sequence.

  7. Document abilities (secpol) required for processes additionally.