From c36a69c1b8b7ccbe7cc6c0190ac6b74af537db0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20Fu=C3=9Fberger?= Date: Thu, 26 Nov 2026 13:34:57 +0100 Subject: [PATCH 1/4] Move fork code to osal --- .../launch_manager/src/daemon/src/osal/BUILD | 97 +++- .../src/osal/details/linux/start_process.cpp | 309 ++++++++++ .../osal/details/linux/start_process_UT.cpp | 543 ++++++++++++++++++ .../daemon/src/osal/mock_start_process.hpp | 54 ++ .../src/process_group_manager/details/BUILD | 9 +- .../details/process_launcher.cpp | 268 +-------- .../details/process_launcher.hpp | 10 - .../details/process_launcher_UT.cpp | 489 ++-------------- .../src/process_group_manager/iprocess.hpp | 13 - 9 files changed, 1037 insertions(+), 755 deletions(-) create mode 100644 score/launch_manager/src/daemon/src/osal/details/linux/start_process.cpp create mode 100644 score/launch_manager/src/daemon/src/osal/details/linux/start_process_UT.cpp create mode 100644 score/launch_manager/src/daemon/src/osal/mock_start_process.hpp diff --git a/score/launch_manager/src/daemon/src/osal/BUILD b/score/launch_manager/src/daemon/src/osal/BUILD index 8dbd959a50..21db6f7da1 100644 --- a/score/launch_manager/src/daemon/src/osal/BUILD +++ b/score/launch_manager/src/daemon/src/osal/BUILD @@ -195,29 +195,83 @@ cc_library( cc_library( name = "start_process", - srcs = ["details/qnx/start_process.cpp"], - hdrs = [ - "details/qnx/start_process_internal.hpp", - "start_process.hpp", - ], + srcs = select({ + "@platforms//os:linux": ["details/linux/start_process.cpp"], + "@platforms//os:qnx": ["details/qnx/start_process.cpp"], + }), + hdrs = ["start_process.hpp"] + select({ + "@platforms//os:linux": [], + "@platforms//os:qnx": ["details/qnx/start_process_internal.hpp"], + }), include_prefix = "score/mw/launch_manager/osal", - linkopts = ["-lsecpol"], + linkopts = select({ + "@platforms//os:qnx": ["-lsecpol"], + "//conditions:default": [], + }), strip_include_prefix = "/score/launch_manager/src/daemon/src/osal", - target_compatible_with = ["@platforms//os:qnx"], visibility = ["//score:__subpackages__"], deps = [ ":ipc_comms", ":return_types", "//score/launch_manager/src/daemon/src/common:log", "//score/launch_manager/src/daemon/src/configuration:component_config", - "@score_baselibs//score/os:errno", - "@score_baselibs//score/os:fcntl", - "@score_baselibs//score/os:sched", - "@score_baselibs//score/os:spawn", - "@score_baselibs//score/os:unistd", - "@score_baselibs//score/os/qnx:secpol", - "@score_baselibs//score/os/qnx:unistd", - "@score_baselibs//score/os/utils:signal", + ] + select({ + "@platforms//os:linux": [ + ":security_policy", + ":set_affinity", + ":set_groups", + ":sys_exit", + "//score/launch_manager/src/daemon/src/common:signal_safe_log", + "@score_baselibs//score/language/futurecpp", + ], + "@platforms//os:qnx": [ + "@score_baselibs//score/os:errno", + "@score_baselibs//score/os:fcntl", + "@score_baselibs//score/os:sched", + "@score_baselibs//score/os:spawn", + "@score_baselibs//score/os:unistd", + "@score_baselibs//score/os/qnx:secpol", + "@score_baselibs//score/os/qnx:unistd", + "@score_baselibs//score/os/utils:signal", + ], + }), +) + +lm_cc_test( + name = "start_process_linux_UT", + srcs = ["details/linux/start_process_UT.cpp"], + linkopts = [ + "-Wl,--wrap=fork", + "-Wl,--wrap=execve", + "-Wl,--wrap=kill", + "-Wl,--wrap=wait", + "-Wl,--wrap=access", + "-Wl,--wrap=shm_open", + "-Wl,--wrap=ftruncate", + "-Wl,--wrap=shm_unlink", + "-Wl,--wrap=mmap", + "-Wl,--wrap=munmap", + "-Wl,--wrap=setpgid", + "-Wl,--wrap=setgid", + "-Wl,--wrap=setuid", + "-Wl,--wrap=sched_setscheduler", + "-Wl,--wrap=chdir", + "-Wl,--wrap=setrlimit", + "-Wl,--wrap=getpid", + "-Wl,--wrap=fcntl", + "-Wl,--wrap=sem_destroy", + "-Wl,--wrap=msync", + "-Wl,--wrap=close", + "-Wl,--wrap=fstat", + "-Wl,--wrap=clock_gettime", + "-Wl,--wrap=clock_getres", + ], + linkstatic = True, + target_compatible_with = ["@platforms//os:linux"], + deps = [ + ":start_process", + "//tests/utils/mocks:mock_syscalls", + "@googletest//:gtest_main", ], ) @@ -241,6 +295,19 @@ lm_cc_test( ], ) +cc_library( + name = "mock_start_process", + testonly = True, + hdrs = ["mock_start_process.hpp"], + include_prefix = "score/mw/launch_manager/osal", + strip_include_prefix = "/score/launch_manager/src/daemon/src/osal", + visibility = ["//score:__subpackages__"], + deps = [ + ":start_process", + "@googletest//:gtest", + ], +) + cc_library( name = "osal", visibility = ["//score:__subpackages__"], diff --git a/score/launch_manager/src/daemon/src/osal/details/linux/start_process.cpp b/score/launch_manager/src/daemon/src/osal/details/linux/start_process.cpp new file mode 100644 index 0000000000..030adab138 --- /dev/null +++ b/score/launch_manager/src/daemon/src/osal/details/linux/start_process.cpp @@ -0,0 +1,309 @@ +/******************************************************************************** + * Copyright (c) 2025 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#include + +#include +#include +#include +#include +#include +#include + +#include "score/mw/launch_manager/common/log.hpp" +#include "score/mw/launch_manager/common/signal_safe_log.hpp" +#include "score/mw/launch_manager/osal/security_policy.hpp" +#include "score/mw/launch_manager/osal/set_affinity.hpp" +#include "score/mw/launch_manager/osal/set_groups.hpp" +#include "score/mw/launch_manager/osal/start_process.hpp" +#include "score/mw/launch_manager/osal/sys_exit.hpp" +#include +#include +#include + +namespace score::mw::lifecycle::internal::osal +{ + +namespace +{ + +constexpr int kPidZero = 0; // This value is used to check if the process ID (uses pid_t) is valid or not. +constexpr int kPosixSuccess = 0; + +/// @brief Struct to hold configuration parameters for the child process. +struct ChildProcessConfig +{ + /// @brief child process startup configurations + const configuration::ComponentConfig& config; + + /// @brief fd file descriptor of the shared memory segment. + int fd; + + /// @brief sync Pointer to the shared memory block + IpcCommsP shared_block; +}; + +/// @brief Applies the given limit. +/// @details The implementation should be async signal safe. +/// @warning This will sysexit if the set is not succesful. +void applyLimitOrDie(const int resource, const rlimit& limit, const std::string_view rlimit_name) noexcept(false) +{ + if (::setrlimit(resource, &limit) == -1) + { + static_cast(signal_safe_log_errno(errno, "Failed to apply rlimit ", rlimit_name)); + sysexit(EXIT_FAILURE); + } +} + +/// @brief Returns the RLIMIT_* macro name for the given platform resource constant, for use in +/// log messages only. +std::string_view rlimitResourceName(const int resource) noexcept +{ + switch (resource) + { + case RLIMIT_AS: + return "RLIMIT_AS"; + case RLIMIT_CORE: + return "RLIMIT_CORE"; + case RLIMIT_CPU: + return "RLIMIT_CPU"; + case RLIMIT_DATA: + return "RLIMIT_DATA"; + case RLIMIT_FSIZE: + return "RLIMIT_FSIZE"; + case RLIMIT_NOFILE: + return "RLIMIT_NOFILE"; + case RLIMIT_STACK: + return "RLIMIT_STACK"; + default: + return "RLIMIT_"; + } +} + +/// @details The implementation should be async signal safe. +void handleComms(ChildProcessConfig& param) +{ + if (!param.shared_block) + { + // Native process without comms, fds are CLOEXEC + return; + } + + param.fd = dup2(param.fd, param.shared_block->sync_fd); + + // Flag FD_CLOEXEC is cleared to ensure that sync_fd remains open after the execve call. + if (-1 == fcntl(IpcCommsSync::sync_fd, F_SETFD, 0)) + { + static_cast(signal_safe_log_errno(errno, "fcntl at line ", __LINE__, " failed")); + sysexit(EXIT_FAILURE); + } +} + +/// @details The implementation should be async signal safe. +void changeCurrentWorkingDirectory(const configuration::DeploymentConfig& config) +{ + // working_dir is set by configuration, so it should always be valid. + // If not, chdir will fail anyway and we will log an error and exit. + if (-1 == chdir(config.working_dir.c_str())) + { + static_cast(signal_safe_log_errno(errno, "chdir(", config.working_dir, ") failed.")); + sysexit(EXIT_FAILURE); + } +} + +// req-Id: comp_req__launch_man__process_rlimit_support +/// @brief Applies every configured resource limit. +/// @details The implementation should be async signal safe. Must run before the potential privilege drop in +/// setSchedulingAndSecurity(). +void applyResourceLimits(const configuration::Sandbox& config) +{ + for (const auto& rlimit_config : config.rlimits) + { + applyLimitOrDie(rlimit_config.resource, rlimit_config.limit, rlimitResourceName(rlimit_config.resource)); + } +} + +/// @details The implementation should be async signal safe. +void changeSecurityPolicy(const configuration::Sandbox& config) +{ + if (config.security_policy.has_value() && !config.security_policy.value().empty()) + { + if (setSecurityPolicy(config.security_policy.value().c_str()) != 0) + { + static_cast( + signal_safe_log_errno(errno, "changeSecurityPolicy(", config.security_policy.value(), ") failed")); + sysexit(EXIT_FAILURE); + } + } +} + +/// @brief Clears all signal handlers (where valid) and then unblocks them. This allows the child process to receive +/// signals even before execve() is reached. +void resetSignalHandlersAndUnblock() +{ + // If this static assert fails, pthread_sigmask will fail with EINVAL. See `man sigprocmask`. + // This is more a porting guard than a real life scenario (libc / kernel mismatch)... + static_assert( + sizeof(sigset_t) >= (_NSIG / 8), + "sigset_t is too small to fulfill the kernel's rt_sigprocmask size requirement"); + + // Reset all signal handlers to default except unblockable signals + struct sigaction act{}; + act.sa_handler = SIG_DFL; + + int err = 0; + for (int sig = 1; sig < _NSIG; ++sig) + { + if (sig == SIGKILL || sig == SIGSTOP) + continue; + err |= sigaction(sig, &act, NULL); + } + SCORE_LANGUAGE_FUTURECPP_ASSERT_DBG_MESSAGE(err == 0, "Failed to reset signal handlers"); + + // Unblock all signals by applying an empty mask + sigset_t mask; + err = sigemptyset(&mask); + SCORE_LANGUAGE_FUTURECPP_ASSERT_DBG_MESSAGE(err == 0, "Failed to build signal mask"); + + err = pthread_sigmask(SIG_SETMASK, &mask, NULL); + SCORE_LANGUAGE_FUTURECPP_ASSERT_DBG_MESSAGE(err == 0, "Invalid argument(s) to pthread_sigmask"); + static_cast(err); +} + +/// @brief Sets up all the scheduling and security parameters described in the config, for the current process. +/// @details The implementation should be async signal safe. +/// @param config the configuration to use +/// @return kFail if any operation fails, kSuccess otherwise +OsalReturnType setSchedulingAndSecurity(const configuration::Sandbox& config) +{ + OsalReturnType retval = OsalReturnType::kSuccess; + + // Set process group id to be equal to the pid + if (0 != setpgid(0, getpid())) + { + static_cast(signal_safe_log_errno(errno, "setpgid() failed")); + retval = OsalReturnType::kFail; + } + // Set scheduling policy with sched_setscheduler. + // The priority was clamped to the valid range of the policy when the configuration was loaded. + sched_param sch_param{}; + sch_param.sched_priority = config.scheduling_priority; + + if (-1 == sched_setscheduler(0, config.scheduling_policy, &sch_param)) + { + static_cast(signal_safe_log_errno(errno, "sched_setscheduler() failed")); + retval = OsalReturnType::kFail; + } + + // Set core affinity using OS specific functionality in osal + if (config.affinity_mask.has_value()) + { + if (-1 == setaffinity(config.affinity_mask.value())) + { + static_cast(signal_safe_log_errno(errno, "setaffinity failed")); + retval = OsalReturnType::kFail; + } + } + + // Set group ID + if (-1 == setgid(config.gid)) + { + static_cast(signal_safe_log_errno(errno, "setgid(", config.gid, ") failed")); + retval = OsalReturnType::kFail; + } + // Set supplementary group ids + size_t supplementary_gids_number = config.supplementary_group_ids.size(); + + // Note: the type of the first parameter of setgroups() differs in Linux and QNX, so we use osal + if (-1 == setgroups(supplementary_gids_number, config.supplementary_group_ids.data())) + { + static_cast(signal_safe_log_errno(errno, "setgroups() failed")); + retval = OsalReturnType::kFail; + } + + // Set user ID + if (-1 == setuid(config.uid)) + { + static_cast(signal_safe_log_errno(errno, "setuid(", config.uid, ") failed")); + retval = OsalReturnType::kFail; + } + + return retval; +} + +/// @brief Handles the execution of the child process after forking. +/// @details The implementation should be async signal safe. +/// @param[in] param Reference to child process configuration. +[[noreturn]] void handleChildProcess(ChildProcessConfig& param) +{ + resetSignalHandlersAndUnblock(); + + handleComms(param); + + applyResourceLimits(param.config.deployment_config.sandbox); + + if (OsalReturnType::kSuccess != setSchedulingAndSecurity(param.config.deployment_config.sandbox)) + { + sysexit(EXIT_FAILURE); + } + + changeCurrentWorkingDirectory(param.config.deployment_config); + changeSecurityPolicy(param.config.deployment_config.sandbox); + + const auto& process_command = param.config.deployment_config.process_command; + + // Get envp from Environment - it already provides a null-terminated array + char* const* envp = param.config.deployment_config.environmental_variables.envp(); + + // Finally, execute the process, passing all the arguments and environment variables + static_cast(execve(process_command.executablePath().c_str(), process_command.argv(), envp)); + // A successful execve replaces the process image; returning here always means failure. + static_cast(signal_safe_log_errno( + errno, "execve failed: Unable to execute the ", process_command.executablePath(), " app.")); + sysexit(EXIT_FAILURE); +} + +} // namespace + +OsalReturnType +startProcess(ProcessID& pid, const configuration::ComponentConfig& config, int comms_fd, const IpcCommsP& comms) +{ + OsalReturnType result = OsalReturnType::kFail; + + pid = fork(); + + if (pid == kPosixSuccess) + { + /* + * From this point on, only async signal safe functions can be + * used. `fork` only copies the current thread, so any locks + * which were held at that time will never be released. + * See `man 2 fork`. + */ + ChildProcessConfig param = {config, comms_fd, comms}; + handleChildProcess(param); + result = OsalReturnType::kSuccess; + } + else if (pid > kPidZero) + { + result = OsalReturnType::kSuccess; + } + else + { + LM_LOG_ERROR() << "Fork failed: Unable to create a new process."; + } + + return result; +} + +} // namespace score::mw::lifecycle::internal::osal diff --git a/score/launch_manager/src/daemon/src/osal/details/linux/start_process_UT.cpp b/score/launch_manager/src/daemon/src/osal/details/linux/start_process_UT.cpp new file mode 100644 index 0000000000..fbbc846898 --- /dev/null +++ b/score/launch_manager/src/daemon/src/osal/details/linux/start_process_UT.cpp @@ -0,0 +1,543 @@ +/******************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "score/mw/launch_manager/osal/start_process.hpp" +#include "tests/utils/mocks/mock_syscalls.hpp" + +using namespace testing; + +using namespace score::mw::lifecycle::internal::osal; +using namespace score::mw::lifecycle::internal; + +namespace +{ + +// The sysexit mock can throw this to interrupt execution +struct SysExitException +{ +}; + +/// @brief A successful execve() replaces the process image and never returns to its caller. +/// We mock this by throwing an exception to interrupt execution. +struct ExecveSuccess +{ +}; + +// Define a matcher that checks a null-terminated char** against a vector of strings +MATCHER_P(ArgvMatches, expected_args, "") +{ + for (size_t i = 0; i < expected_args.size(); ++i) + { + // Check if the argument is null prematurely, or if the string doesn't match + if (arg[i] == nullptr || std::string(arg[i]) != expected_args[i]) + { + *result_listener << "mismatch at index " << i << " (expected: \"" << expected_args[i] << "\", got: \"" + << (arg[i] ? arg[i] : "NULL") << "\")"; + return false; + } + } + // execve argv must be null-terminated; ensure the last expected element is followed by NULL + return arg[expected_args.size()] == nullptr; +} + +MATCHER_P(CArrayMatches, expected, "") +{ + for (size_t i = 0; i < expected.size(); ++i) + { + if (arg[i] != expected[i]) + { + *result_listener << "mismatch at index " << i << " (expected: " << expected[i] << ", got: " << arg[i] + << ")"; + return false; + } + } + return true; +} + +} // namespace + +class StartProcessTest : public ::testing::Test +{ + protected: + void SetUp() override + { + RecordProperty("TestType", "interface-test"); + RecordProperty("DerivationTechnique", "equivalence-classes"); + + g_syscall_mock = std::make_unique(); + + // Used by logging framework + ON_CALL(*g_syscall_mock, access).WillByDefault(Invoke(__real_access)); + ON_CALL(*g_syscall_mock, fcntl).WillByDefault(Invoke(__real_fcntl)); + EXPECT_CALL(*g_syscall_mock, access).Times(AnyNumber()); + EXPECT_CALL(*g_syscall_mock, fcntl).Times(AnyNumber()); + + ON_CALL(*g_syscall_mock, execve).WillByDefault(Throw(ExecveSuccess{})); + + EXPECT_CALL(*g_syscall_mock, getpid).Times(AnyNumber()).WillRepeatedly(Return(forked_pid_)); + + config_.name = "TestComponent"; + config_.component_properties.application_profile.application_type = configuration::ApplicationType::Native; + config_.deployment_config.process_command = configuration::ProcessCommand{"/bin/TestProcess", {}}; + config_.deployment_config.working_dir = "/tmp"; + config_.deployment_config.sandbox.security_policy = std::nullopt; + config_.deployment_config.sandbox.scheduling_priority = 1; + config_.deployment_config.sandbox.scheduling_policy = SCHED_RR; + config_.deployment_config.sandbox.gid = 1; + config_.deployment_config.sandbox.uid = 1; + config_.deployment_config.sandbox.supplementary_group_ids = {}; + } + + void TearDown() override + { + comms_.reset(); + g_syscall_mock.reset(); + } + + void ExpectChildProcessStarts() + { + EXPECT_CALL(*g_syscall_mock, fork).WillOnce(Return(0)); + } + + void ExpectSuccessfulSchedulingAndSecurity() + { + EXPECT_CALL(*g_syscall_mock, setpgid).Times(AnyNumber()).WillRepeatedly(Return(0)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).Times(AnyNumber()).WillRepeatedly(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgid).Times(AnyNumber()).WillRepeatedly(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid).Times(AnyNumber()).WillRepeatedly(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgroups).Times(AnyNumber()).WillRepeatedly(Return(0)); + } + + void ExpectSuccessfulChdir() + { + EXPECT_CALL(*g_syscall_mock, chdir).Times(AnyNumber()).WillRepeatedly(Return(0)); + } + + /// @brief Provides a comms block backed by a local buffer, as handed over by the ProcessLauncher for + /// communicating processes. + void UseComms() + { + std::memset(comms_buffer_.data(), 0, comms_buffer_.size()); + comms_ = IpcCommsP{reinterpret_cast(comms_buffer_.data()), [](IpcCommsSync*) { + }}; + } + + OsalReturnType StartProcess() + { + return startProcess(pid_, config_, comms_ ? kCommsFd : -1, comms_); + } + + static constexpr int kCommsFd = 123; + const pid_t forked_pid_ = 23; + + configuration::ComponentConfig config_ = {}; + ProcessID pid_ = -1; + IpcCommsP comms_; + + alignas(IpcCommsSync) std::array comms_buffer_; +}; + +TEST_F(StartProcessTest, startProcessForkFailed) +{ + RecordProperty("Description", "Test that startProcess returns a failure if fork fails"); + + EXPECT_CALL(*g_syscall_mock, fork).WillOnce(Return(-1)); + EXPECT_CALL(*g_syscall_mock, execve).Times(0); + + EXPECT_EQ(StartProcess(), OsalReturnType::kFail); +} + +TEST_F(StartProcessTest, startProcessParentSuccess) +{ + RecordProperty( + "Description", "Test that startProcess returns success and the pid of the child in the parent process"); + + EXPECT_CALL(*g_syscall_mock, fork).WillOnce(Return(forked_pid_)); + EXPECT_CALL(*g_syscall_mock, execve).Times(0); + EXPECT_CALL(*g_syscall_mock, sysexit).Times(0); + + EXPECT_EQ(StartProcess(), OsalReturnType::kSuccess); + EXPECT_EQ(pid_, forked_pid_); +} + +TEST_F(StartProcessTest, handleCommsFailsFnctl) +{ + RecordProperty( + "Description", "Verify that the forked process exits if setting up comms fails due to a syscall failure"); + + UseComms(); + ExpectChildProcessStarts(); + EXPECT_CALL(*g_syscall_mock, fcntl).WillOnce(Return(-1)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +class SetSchedulingAndSecurityTest : public StartProcessTest +{ + protected: + void SetUp() override + { + StartProcessTest::SetUp(); + + ExpectChildProcessStarts(); + ExpectSuccessfulChdir(); + EXPECT_CALL(*g_syscall_mock, execve).Times(AtMost(1)); + } +}; + +TEST_F(SetSchedulingAndSecurityTest, setpgidFails) +{ + RecordProperty("Description", "Verify that the forked process exits if setting pgid fails"); + + EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(-1)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(SetSchedulingAndSecurityTest, setgidFails) +{ + RecordProperty("Description", "Verify that the forked process exits if setting gid fails"); + + EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(-1)); + EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(SetSchedulingAndSecurityTest, setuidFails) +{ + RecordProperty("Description", "Verify that the forked process exits if setting uid fails"); + + EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(-1)); + EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(SetSchedulingAndSecurityTest, setschedFails) +{ + RecordProperty("Description", "Verify that the forked process exits if setting the scheduler fails"); + + EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(-1)); + EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(SetSchedulingAndSecurityTest, setgroupsFails) +{ + RecordProperty("Description", "Verify that if setting supplementary gids fails, the forked process exits"); + + config_.deployment_config.sandbox.supplementary_group_ids = {1, 2, 3}; + + EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(-1)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(SetSchedulingAndSecurityTest, setaffinityFails) +{ + RecordProperty("Description", "Verify that the forked process exits if setting the CPU affinity fails"); + + config_.deployment_config.sandbox.affinity_mask = 0x1U; + + EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setaffinity(0x1U)).WillOnce(SetErrnoAndReturn(EINVAL, -1)); + EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(SetSchedulingAndSecurityTest, setaffinityIgnore) +{ + RecordProperty("Description", "Verify that the CPU affinity is not changed if no affinity mask is configured"); + + config_.deployment_config.sandbox.affinity_mask = std::nullopt; + + EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setaffinity).Times(0); + EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); + + EXPECT_THROW(static_cast(StartProcess()), ExecveSuccess); +} + +TEST_F(SetSchedulingAndSecurityTest, supplementaryGroupsAreCleared) +{ + RecordProperty( + "Description", "Verify that supplementary group IDs are explicitly cleared when none are configured"); + + config_.deployment_config.sandbox.supplementary_group_ids = {}; + + ExpectSuccessfulSchedulingAndSecurity(); + EXPECT_CALL(*g_syscall_mock, setgroups(0, _)).WillOnce(Return(0)); + + EXPECT_THROW(static_cast(StartProcess()), ExecveSuccess); +} + +TEST_F(StartProcessTest, chdirFails) +{ + RecordProperty("Description", "Verify that the forked process exits if changing the working dir fails"); + + ExpectChildProcessStarts(); + ExpectSuccessfulSchedulingAndSecurity(); + EXPECT_CALL(*g_syscall_mock, chdir).WillOnce(Return(-1)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(StartProcessTest, changeSecurityPolicyFails) +{ + RecordProperty("Description", "Verify that the forked process exits if changing the security policy fails"); + + config_.deployment_config.sandbox.security_policy = "security"; + + ExpectChildProcessStarts(); + ExpectSuccessfulSchedulingAndSecurity(); + ExpectSuccessfulChdir(); + EXPECT_CALL(*g_syscall_mock, setSecurityPolicy).WillOnce(Return(-1)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(StartProcessTest, setRLimitFails) +{ + RecordProperty("Description", "Verify that the forked process exits if setting a limit fails"); + + config_.deployment_config.sandbox.rlimits = { + {RLIMIT_CPU, {500, 500}}, + }; + + ExpectChildProcessStarts(); + ExpectSuccessfulSchedulingAndSecurity(); + ExpectSuccessfulChdir(); + EXPECT_CALL(*g_syscall_mock, setrlimit).WillOnce(Return(-1)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(StartProcessTest, noRlimitsConfiguredSkipsSetrlimit) +{ + RecordProperty("Description", "Verify that setrlimit is not called when no rlimits are configured"); + + ExpectChildProcessStarts(); + ExpectSuccessfulSchedulingAndSecurity(); + ExpectSuccessfulChdir(); + EXPECT_CALL(*g_syscall_mock, setrlimit).Times(0); + EXPECT_CALL(*g_syscall_mock, execve).Times(AtMost(1)); + + EXPECT_THROW(static_cast(StartProcess()), ExecveSuccess); +} + +TEST_F(StartProcessTest, setRLimitZeroIsApplied) +{ + RecordProperty("Description", "Verify that a configured rlimit of 0 is applied via setrlimit"); + + config_.deployment_config.sandbox.rlimits = { + {RLIMIT_CORE, {0, 0}}, + }; + + ExpectChildProcessStarts(); + ExpectSuccessfulSchedulingAndSecurity(); + ExpectSuccessfulChdir(); + EXPECT_CALL( + *g_syscall_mock, setrlimit(RLIMIT_CORE, AllOf(Field(&rlimit::rlim_cur, 0U), Field(&rlimit::rlim_max, 0U)))) + .WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, execve).Times(AtMost(1)); + + EXPECT_THROW(static_cast(StartProcess()), ExecveSuccess); +} + +TEST_F(StartProcessTest, setRLimitPassesPreResolvedValuesUnchanged) +{ + RecordProperty( + "Description", + "Verify that applyResourceLimits() passes the resource and limit through to setrlimit() unchanged."); + + config_.deployment_config.sandbox.rlimits = { + {RLIMIT_FSIZE, {1024U, RLIM_INFINITY}}, + }; + + ExpectChildProcessStarts(); + ExpectSuccessfulSchedulingAndSecurity(); + ExpectSuccessfulChdir(); + EXPECT_CALL( + *g_syscall_mock, + setrlimit( + RLIMIT_FSIZE, + AllOf(Field(&rlimit::rlim_cur, static_cast(1024U)), Field(&rlimit::rlim_max, RLIM_INFINITY)))) + .WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, execve).Times(AtMost(1)); + + EXPECT_THROW(static_cast(StartProcess()), ExecveSuccess); +} + +TEST_F(StartProcessTest, rlimitsAppliedBeforePrivilegeDrop) +{ + RecordProperty( + "Description", + "Regression guard for the ordering defect where rlimits were applied after setuid()/setgid(): raising a " + "hard limit requires privilege, so setrlimit must be called before setuid."); + + config_.deployment_config.sandbox.rlimits = { + {RLIMIT_NOFILE, {1024, 1024}}, + }; + + ExpectChildProcessStarts(); + ExpectSuccessfulChdir(); + + EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); + + { + InSequence seq; + EXPECT_CALL(*g_syscall_mock, setrlimit(RLIMIT_NOFILE, _)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgroups(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); + } + + EXPECT_THROW(static_cast(StartProcess()), ExecveSuccess); +} + +TEST_F(StartProcessTest, execveFails) +{ + RecordProperty("Description", "Verify that the forked process exits if execve fails"); + + ExpectChildProcessStarts(); + ExpectSuccessfulSchedulingAndSecurity(); + ExpectSuccessfulChdir(); + EXPECT_CALL(*g_syscall_mock, execve).WillOnce(Return(-1)); + + EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + + EXPECT_THROW(static_cast(StartProcess()), SysExitException); +} + +TEST_F(StartProcessTest, startProcessChildSuccess) +{ + RecordProperty("Description", "Verify that when startProcess succeeds, the forked process is configured correctly"); + + const int scheduler = SCHED_FIFO; + const int uid = 11; + const int gid = 13; + const std::vector sgids = {1, 2, 3}; + const std::uint64_t mem_limit = 4096; + const std::uint32_t cpu_limit = 500; + const std::uint64_t affinity_mask = 0x8000000000000005U; + const std::string security_policy = "security"; + const std::vector args_in = {"-c 2", "--argument yes"}; + const std::vector expected_launch_args = { + config_.deployment_config.process_command.executablePath(), args_in[0], args_in[1]}; + + config_.component_properties.application_profile.application_type = configuration::ApplicationType::Reporting; + config_.deployment_config.sandbox.scheduling_policy = scheduler; + config_.deployment_config.sandbox.uid = uid; + config_.deployment_config.sandbox.gid = gid; + config_.deployment_config.sandbox.supplementary_group_ids = sgids; + config_.deployment_config.sandbox.rlimits = { + {RLIMIT_AS, {mem_limit, mem_limit}}, + {RLIMIT_CPU, {cpu_limit, RLIM_INFINITY}}, + }; + config_.deployment_config.sandbox.affinity_mask = affinity_mask; + config_.deployment_config.sandbox.security_policy = security_policy; + config_.deployment_config.environmental_variables.add("environment", "yes"); + config_.deployment_config.environmental_variables.add("errors", "no"); + config_.deployment_config.process_command = + configuration::ProcessCommand{config_.deployment_config.process_command.executablePath(), args_in}; + + UseComms(); + + EXPECT_CALL(*g_syscall_mock, fork).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, getpid).WillRepeatedly(Return(forked_pid_)); + EXPECT_CALL(*g_syscall_mock, fcntl(IpcCommsSync::sync_fd, F_SETFD, _)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setpgid(0, forked_pid_)); + EXPECT_CALL(*g_syscall_mock, sched_setscheduler(0, scheduler, _)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setaffinity(affinity_mask)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setuid(uid)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgid(gid)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, setgroups(sgids.size(), CArrayMatches(sgids))).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, chdir(StrEq("/tmp"))).WillOnce(Return(0)); + EXPECT_CALL( + *g_syscall_mock, + setrlimit(RLIMIT_AS, AllOf(Field(&rlimit::rlim_cur, mem_limit), Field(&rlimit::rlim_max, mem_limit)))); + EXPECT_CALL( + *g_syscall_mock, + setrlimit(RLIMIT_CPU, AllOf(Field(&rlimit::rlim_cur, cpu_limit), Field(&rlimit::rlim_max, RLIM_INFINITY)))); + EXPECT_CALL(*g_syscall_mock, setSecurityPolicy(StrEq(security_policy.data()))).WillOnce(Return(0)); + EXPECT_CALL( + *g_syscall_mock, + execve( + StrEq(expected_launch_args[0]), + ArgvMatches(expected_launch_args), + config_.deployment_config.environmental_variables.envp())) + .WillOnce(Throw(ExecveSuccess{})); + + EXPECT_CALL(*g_syscall_mock, sysexit).Times(0); // No failures + + EXPECT_THROW(static_cast(StartProcess()), ExecveSuccess); +} diff --git a/score/launch_manager/src/daemon/src/osal/mock_start_process.hpp b/score/launch_manager/src/daemon/src/osal/mock_start_process.hpp new file mode 100644 index 0000000000..8244bee789 --- /dev/null +++ b/score/launch_manager/src/daemon/src/osal/mock_start_process.hpp @@ -0,0 +1,54 @@ +/******************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Apache License Version 2.0 which is available at + * https://www.apache.org/licenses/LICENSE-2.0 + * + * SPDX-License-Identifier: Apache-2.0 + ********************************************************************************/ + +#ifndef OSAL_MOCK_START_PROCESS_HPP_INCLUDED +#define OSAL_MOCK_START_PROCESS_HPP_INCLUDED + +#include + +#include + +#include "score/mw/launch_manager/osal/start_process.hpp" + +// NOLINTBEGIN + +/// @brief Mock for osal::startProcess(). +/// @details This header defines osal::startProcess() and replaces the real implementation at link time, so it must +/// be included in exactly one translation unit of a statically linked test. +class StartProcessMock +{ + public: + MOCK_METHOD( + score::mw::lifecycle::internal::osal::OsalReturnType, + startProcess, + (score::mw::lifecycle::internal::osal::ProcessID & pid, + const score::mw::lifecycle::internal::configuration::ComponentConfig& config, + int comms_fd, + const score::mw::lifecycle::internal::osal::IpcCommsP& comms), + ()); +}; + +std::unique_ptr g_start_process_mock = nullptr; + +namespace score::mw::lifecycle::internal::osal +{ +OsalReturnType +startProcess(ProcessID& pid, const configuration::ComponentConfig& config, int comms_fd, const IpcCommsP& comms) +{ + return g_start_process_mock->startProcess(pid, config, comms_fd, comms); +} +} // namespace score::mw::lifecycle::internal::osal + +// NOLINTEND + +#endif // OSAL_MOCK_START_PROCESS_HPP_INCLUDED diff --git a/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD b/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD index 8485add879..d80f94db41 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD +++ b/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD @@ -562,16 +562,10 @@ cc_library( "//score/launch_manager/src/daemon/src/common:log", "//score/launch_manager/src/daemon/src/common:signal_safe_log", "//score/launch_manager/src/daemon/src/configuration:component_config", - "//score/launch_manager/src/daemon/src/configuration:environment_config", - "//score/launch_manager/src/daemon/src/configuration:process_command", "//score/launch_manager/src/daemon/src/osal:ipc_comms", "//score/launch_manager/src/daemon/src/osal:return_types", - "//score/launch_manager/src/daemon/src/osal:security_policy", - "//score/launch_manager/src/daemon/src/osal:semaphore", - "//score/launch_manager/src/daemon/src/osal:set_affinity", - "//score/launch_manager/src/daemon/src/osal:set_groups", "//score/launch_manager/src/daemon/src/osal:shm_open_anon", - "//score/launch_manager/src/daemon/src/osal:sys_exit", + "//score/launch_manager/src/daemon/src/osal:start_process", "//score/launch_manager/src/daemon/src/process_group_manager:iprocess", "@score_baselibs//score/language/futurecpp", ], @@ -609,6 +603,7 @@ lm_cc_test( linkstatic = True, deps = [ ":process_launcher", + "//score/launch_manager/src/daemon/src/osal:mock_start_process", "//tests/utils/mocks:mock_syscalls", "@googletest//:gtest_main", "@score_baselibs//score/os/mocklib:semaphore_mock", diff --git a/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.cpp b/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.cpp index 868b64465e..6febcc244d 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.cpp +++ b/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.cpp @@ -11,12 +11,7 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -#include - #include -#include -#include -#include #include #include #include @@ -25,168 +20,20 @@ #include "score/mw/launch_manager/common/log.hpp" #include "score/mw/launch_manager/common/signal_safe_log.hpp" #include "score/mw/launch_manager/configuration/component_config.hpp" -#include "score/mw/launch_manager/configuration/environment_config.hpp" -#include "score/mw/launch_manager/configuration/process_command.hpp" #include "score/mw/launch_manager/osal/ipc_comms.hpp" #include "score/mw/launch_manager/osal/return_types.hpp" -#include "score/mw/launch_manager/osal/security_policy.hpp" -#include "score/mw/launch_manager/osal/semaphore.hpp" -#include "score/mw/launch_manager/osal/set_affinity.hpp" -#include "score/mw/launch_manager/osal/set_groups.hpp" #include "score/mw/launch_manager/osal/shm_open_anon.hpp" -#include "score/mw/launch_manager/osal/sys_exit.hpp" +#include "score/mw/launch_manager/osal/start_process.hpp" #include "score/mw/launch_manager/process_group_manager/details/process_launcher.hpp" #include "score/mw/launch_manager/process_group_manager/iprocess.hpp" #include #include #include #include -#include -#include -#include -#include -#include constexpr int kPidZero = 0; // This value is used to check if the process ID (uses pid_t) is valid or not. constexpr int kPosixSuccess = 0; -namespace -{ - -using score::mw::lifecycle::internal::signal_safe_log; -using score::mw::lifecycle::internal::signal_safe_log_errno; -using score::mw::lifecycle::internal::osal::IpcCommsSync; -using score::mw::lifecycle::internal::osal::sysexit; - -/// @brief Applies the given limit. -/// @details The implementation should be async signal safe. -/// @warning This will sysexit if the set is not succesful. -void applyLimitOrDie(const int resource, const rlimit& limit, const std::string_view rlimit_name) noexcept(false) -{ - if (::setrlimit(resource, &limit) == -1) - { - static_cast(signal_safe_log_errno(errno, "Failed to apply rlimit ", rlimit_name)); - sysexit(EXIT_FAILURE); - } -} - -/// @brief Returns the RLIMIT_* macro name for the given platform resource constant, for use in -/// log messages only. -std::string_view rlimitResourceName(const int resource) noexcept -{ - switch (resource) - { - case RLIMIT_AS: - return "RLIMIT_AS"; - case RLIMIT_CORE: - return "RLIMIT_CORE"; - case RLIMIT_CPU: - return "RLIMIT_CPU"; - case RLIMIT_DATA: - return "RLIMIT_DATA"; - case RLIMIT_FSIZE: - return "RLIMIT_FSIZE"; - case RLIMIT_NOFILE: - return "RLIMIT_NOFILE"; - case RLIMIT_STACK: - return "RLIMIT_STACK"; - default: - return "RLIMIT_"; - } -} - -/// @details The implementation should be async signal safe. -void handleComms(score::mw::lifecycle::internal::osal::ChildProcessConfig& param) -{ - if (!param.shared_block) - { - // Native process without comms, fds are CLOEXEC - return; - } - - param.fd = dup2(param.fd, param.shared_block->sync_fd); - - // Flag FD_CLOEXEC is cleared to ensure that sync_fd remains open after the execve call. - if (-1 == fcntl(IpcCommsSync::sync_fd, F_SETFD, 0)) - { - static_cast(signal_safe_log_errno(errno, "fcntl at line ", __LINE__, " failed")); - sysexit(EXIT_FAILURE); - } -} - -/// @details The implementation should be async signal safe. -void changeCurrentWorkingDirectory(const score::mw::lifecycle::internal::configuration::DeploymentConfig& config) -{ - // working_dir is set by configuration, so it should always be valid. - // If not, chdir will fail anyway and we will log an error and exit. - if (-1 == chdir(config.working_dir.c_str())) - { - static_cast(signal_safe_log_errno(errno, "chdir(", config.working_dir, ") failed.")); - sysexit(EXIT_FAILURE); - } -} - -// req-Id: comp_req__launch_man__process_rlimit_support -/// @brief Applies every configured resource limit. -/// @details The implementation should be async signal safe. Must run before the potential privilege drop in -/// setSchedulingAndSecurity(). -void applyResourceLimits(const score::mw::lifecycle::internal::configuration::Sandbox& config) -{ - for (const auto& rlimit_config : config.rlimits) - { - applyLimitOrDie(rlimit_config.resource, rlimit_config.limit, rlimitResourceName(rlimit_config.resource)); - } -} - -/// @details The implementation should be async signal safe. -void changeSecurityPolicy(const score::mw::lifecycle::internal::configuration::Sandbox& config) -{ - if (config.security_policy.has_value() && !config.security_policy.value().empty()) - { - if (score::mw::lifecycle::internal::osal::setSecurityPolicy(config.security_policy.value().c_str()) != 0) - { - static_cast( - signal_safe_log_errno(errno, "changeSecurityPolicy(", config.security_policy.value(), ") failed")); - sysexit(EXIT_FAILURE); - } - } -} - -/// @brief Clears all signal handlers (where valid) and then unblocks them. This allows the child process to receive -/// signals even before execve() is reached. -void resetSignalHandlersAndUnblock() -{ - // If this static assert fails, pthread_sigmask will fail with EINVAL. See `man sigprocmask`. - // This is more a porting guard than a real life scenario (libc / kernel mismatch)... - static_assert( - sizeof(sigset_t) >= (_NSIG / 8), - "sigset_t is too small to fulfill the kernel's rt_sigprocmask size requirement"); - - // Reset all signal handlers to default except unblockable signals - struct sigaction act{}; - act.sa_handler = SIG_DFL; - - int err = 0; - for (int sig = 1; sig < _NSIG; ++sig) - { - if (sig == SIGKILL || sig == SIGSTOP) - continue; - err |= sigaction(sig, &act, NULL); - } - SCORE_LANGUAGE_FUTURECPP_ASSERT_DBG_MESSAGE(err == 0, "Failed to reset signal handlers"); - - // Unblock all signals by applying an empty mask - sigset_t mask; - err = sigemptyset(&mask); - SCORE_LANGUAGE_FUTURECPP_ASSERT_DBG_MESSAGE(err == 0, "Failed to build signal mask"); - - err = pthread_sigmask(SIG_SETMASK, &mask, NULL); - SCORE_LANGUAGE_FUTURECPP_ASSERT_DBG_MESSAGE(err == 0, "Invalid argument(s) to pthread_sigmask"); - static_cast(err); -} - -} // namespace - namespace score::mw::lifecycle::internal::osal { @@ -220,31 +67,10 @@ ProcessLauncher::startProcess(ProcessID& pid, IpcCommsP& block, const configurat { if (fflush(stdout) == EOF) { - LM_LOG_ERROR() << "Failed to flush stdout before forking."; + LM_LOG_ERROR() << "Failed to flush stdout before starting the process."; } - pid = fork(); - - if (pid == kPosixSuccess) - { - /* - * From this point on, only async signal safe functions can be - * used. `fork` only copies the current thread, so any locks - * which were held at that time will never be released. - * See `man 2 fork`. - */ - ChildProcessConfig param = {config, fd, block}; - handleChildProcess(param); - result = OsalReturnType::kSuccess; - } - else if (pid > kPidZero) - { - result = OsalReturnType::kSuccess; - } - else - { - LM_LOG_ERROR() << "Fork failed: Unable to create a new process."; - } + result = osal::startProcess(pid, config, fd, block); } else { @@ -292,94 +118,6 @@ bool ProcessLauncher::setupComms(IpcCommsP& block, int& fd, const configuration: return true; } -/// @details The implementation should be async signal safe. -OsalReturnType ProcessLauncher::setSchedulingAndSecurity(const configuration::Sandbox& config) -{ - OsalReturnType retval = OsalReturnType::kSuccess; - - // Set process group id to be equal to the pid - if (0 != setpgid(0, getpid())) - { - static_cast(signal_safe_log_errno(errno, "setpgid() failed")); - retval = OsalReturnType::kFail; - } - // Set scheduling policy with sched_setscheduler. - // The priority was clamped to the valid range of the policy when the configuration was loaded. - sched_param sch_param{}; - sch_param.sched_priority = config.scheduling_priority; - - if (-1 == sched_setscheduler(0, config.scheduling_policy, &sch_param)) - { - static_cast(signal_safe_log_errno(errno, "sched_setscheduler() failed")); - retval = OsalReturnType::kFail; - } - - // Set core affinity using OS specific functionality in osal - if (config.affinity_mask.has_value()) - { - if (-1 == osal::setaffinity(config.affinity_mask.value())) - { - static_cast(signal_safe_log_errno(errno, "setaffinity failed")); - retval = OsalReturnType::kFail; - } - } - - // Set group ID - if (-1 == setgid(config.gid)) - { - static_cast(signal_safe_log_errno(errno, "setgid(", config.gid, ") failed")); - retval = OsalReturnType::kFail; - } - // Set supplementary group ids - size_t supplementary_gids_number = config.supplementary_group_ids.size(); - - // Note: the type of the first parameter of setgroups() differs in Linux and QNX, so we use osal - if (-1 == osal::setgroups(supplementary_gids_number, config.supplementary_group_ids.data())) - { - static_cast(signal_safe_log_errno(errno, "setgroups() failed")); - retval = OsalReturnType::kFail; - } - - // Set user ID - if (-1 == setuid(config.uid)) - { - static_cast(signal_safe_log_errno(errno, "setuid(", config.uid, ") failed")); - retval = OsalReturnType::kFail; - } - - return retval; -} - -/// @details The implementation should be async signal safe. -void ProcessLauncher::handleChildProcess(ChildProcessConfig& param) -{ - resetSignalHandlersAndUnblock(); - - handleComms(param); - - applyResourceLimits(param.config.deployment_config.sandbox); - - if (OsalReturnType::kSuccess != setSchedulingAndSecurity(param.config.deployment_config.sandbox)) - { - sysexit(EXIT_FAILURE); - } - - changeCurrentWorkingDirectory(param.config.deployment_config); - changeSecurityPolicy(param.config.deployment_config.sandbox); - - const auto& process_command = param.config.deployment_config.process_command; - - // Get envp from Environment - it already provides a null-terminated array - char* const* envp = param.config.deployment_config.environmental_variables.envp(); - - // Finally, execute the process, passing all the arguments and environment variables - static_cast(execve(process_command.executablePath().c_str(), process_command.argv(), envp)); - // A successful execve replaces the process image; returning here always means failure. - static_cast(signal_safe_log_errno( - errno, "execve failed: Unable to execute the ", process_command.executablePath(), " app.")); - sysexit(EXIT_FAILURE); -} - OsalReturnType ProcessLauncher::requestTermination(ProcessID pid) { LM_LOG_DEBUG() << "Request termination received for" << pid; diff --git a/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.hpp b/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.hpp index 4957e408f5..b9a6973c37 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.hpp +++ b/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.hpp @@ -52,16 +52,6 @@ class ProcessLauncher final : public IProcess /// @return True if shared memory creation and initialization are successful, false otherwise. bool setupComms(IpcCommsP& sync, int& fd, const score::mw::lifecycle::internal::configuration::ComponentConfig& config); - - /// @brief Handles the execution of the child process after forking. - /// @param[in] param Reference to child process configuration. - [[noreturn]] void handleChildProcess(ChildProcessConfig& param); - - /// @brief Sets up all the scheduling and security parameters described in the config, for the current process. - /// @param config the configuration to use - /// @return kFail if any operation fails, kSuccess otherwise - static OsalReturnType setSchedulingAndSecurity( - const score::mw::lifecycle::internal::configuration::Sandbox& config); }; } // namespace score::mw::lifecycle::internal::osal diff --git a/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher_UT.cpp b/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher_UT.cpp index e18e412764..015d34172f 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher_UT.cpp +++ b/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher_UT.cpp @@ -18,6 +18,7 @@ #include #include +#include "score/mw/launch_manager/osal/mock_start_process.hpp" #include "score/mw/launch_manager/process_group_manager/details/process_launcher.hpp" #include "score/os/mocklib/semaphoremock.h" #include "tests/utils/mocks/mock_syscalls.hpp" @@ -222,17 +223,6 @@ TEST_F(TerminationTest, forceTerminationInvalid) EXPECT_EQ(res, OsalReturnType::kFail); } -// The sysexit mock can throw this to interrupt execution -struct SysExitException -{ -}; - -/// @brief A successful execve() replaces the process image and never returns to its caller. -/// We mock this by throwing an exception to interrupt execution. -struct ExecveSuccess -{ -}; - class StartProcessTest : public ProcessLauncherTest { protected: @@ -240,69 +230,34 @@ class StartProcessTest : public ProcessLauncherTest { ProcessLauncherTest::SetUp(); - ON_CALL(*g_syscall_mock, execve).WillByDefault(Throw(ExecveSuccess{})); - - EXPECT_CALL(*g_syscall_mock, getpid).Times(AnyNumber()).WillRepeatedly(Return(forked_pid_)); + g_start_process_mock = std::make_unique>(); config_.name = "TestComponent"; config_.component_properties.application_profile.application_type = configuration::ApplicationType::Native; config_.deployment_config.process_command = configuration::ProcessCommand{"/bin/TestProcess", {}}; - config_.deployment_config.working_dir = "/tmp"; - config_.deployment_config.sandbox.security_policy = std::nullopt; - config_.deployment_config.sandbox.scheduling_priority = 1; - config_.deployment_config.sandbox.scheduling_policy = SCHED_RR; - config_.deployment_config.sandbox.gid = 1; - config_.deployment_config.sandbox.uid = 1; - config_.deployment_config.sandbox.supplementary_group_ids = {}; } void TearDown() override { sync_.reset(); + g_start_process_mock.reset(); ProcessLauncherTest::TearDown(); } - void ExpectChildProcessStarts() - { - EXPECT_CALL(*g_syscall_mock, access).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, fork).WillOnce(Return(0)); - } - - void ExpectSuccessfulSchedulingAndSecurity() - { - EXPECT_CALL(*g_syscall_mock, setpgid).Times(AnyNumber()).WillRepeatedly(Return(0)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).Times(AnyNumber()).WillRepeatedly(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgid).Times(AnyNumber()).WillRepeatedly(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid).Times(AnyNumber()).WillRepeatedly(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgroups).Times(AnyNumber()).WillRepeatedly(Return(0)); - } - - void ExpectSuccessfulChdir() - { - EXPECT_CALL(*g_syscall_mock, chdir).Times(AnyNumber()).WillRepeatedly(Return(0)); - } - IpcCommsSync* StubShmObject() { - const int fd = 123; void* data = static_cast(test_buffer_.data()); - EXPECT_CALL(*g_syscall_mock, shm_open_anon).WillOnce(Return(fd)); - EXPECT_CALL(*g_syscall_mock, mmap(_, _, _, _, fd, _)).WillOnce(Return(data)); - EXPECT_CALL(*g_syscall_mock, ftruncate(fd, _)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, shm_open_anon).WillOnce(Return(kShmFd)); + EXPECT_CALL(*g_syscall_mock, mmap(_, _, _, _, kShmFd, _)).WillOnce(Return(data)); + EXPECT_CALL(*g_syscall_mock, ftruncate(kShmFd, _)).WillOnce(Return(0)); EXPECT_CALL(*g_syscall_mock, munmap(data, sizeof(IpcCommsSync))).WillOnce(Return(0)); return static_cast(data); } - void ExpectSetupComms() - { - StubShmObject(); - - EXPECT_CALL(*semaphore_mock_, sem_init).Times(AnyNumber()).WillRepeatedly(Return(kSemSuccess)); - } - - const pid_t forked_pid_ = 23; + static constexpr int kShmFd = 123; + const pid_t started_pid_ = 23; configuration::ComponentConfig config_ = {}; ProcessID pid_; @@ -314,33 +269,58 @@ TEST_F(StartProcessTest, startProcessNoFile) RecordProperty("Description", "Test that startProcess returns a failure if the provided path does not exist"); EXPECT_CALL(*g_syscall_mock, access(_, _)).WillOnce(Return(-1)); + EXPECT_CALL(*g_start_process_mock, startProcess).Times(0); EXPECT_EQ(process_launcher_->startProcess(pid_, sync_, config_), OsalReturnType::kFail); } -TEST_F(StartProcessTest, startProcessForkFailed) +TEST_F(StartProcessTest, startProcessOsalFailed) { - RecordProperty("Description", "Test that startProcess returns a failure if the provided path is empty"); + RecordProperty("Description", "Test that startProcess returns a failure if no process could be created"); EXPECT_CALL(*g_syscall_mock, access(_, _)).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, fork).WillOnce(Return(-1)); + EXPECT_CALL(*g_start_process_mock, startProcess).WillOnce(Return(OsalReturnType::kFail)); EXPECT_EQ(process_launcher_->startProcess(pid_, sync_, config_), OsalReturnType::kFail); } -TEST_F(StartProcessTest, handleCommsFailsFnctl) +TEST_F(StartProcessTest, startProcessNativeHasNoComms) { RecordProperty( - "Description", "Verify that the forked process exits if setting up comms fails due to a syscall failure"); + "Description", + "Test that a native process is started without a shared memory block and that its pid is returned"); + + EXPECT_CALL(*g_syscall_mock, access(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*g_syscall_mock, shm_open_anon).Times(0); + EXPECT_CALL(*g_start_process_mock, startProcess(_, Ref(config_), -1, IsNull())) + .WillOnce(DoAll(SetArgReferee<0>(started_pid_), Return(OsalReturnType::kSuccess))); + + EXPECT_EQ(process_launcher_->startProcess(pid_, sync_, config_), OsalReturnType::kSuccess); + EXPECT_EQ(pid_, started_pid_); + EXPECT_EQ(sync_, nullptr); +} + +TEST_F(StartProcessTest, startProcessReportingPassesComms) +{ + RecordProperty( + "Description", + "Test that a reporting process is started with the shared memory block and fd, and that the fd is closed " + "afterwards"); config_.component_properties.application_profile.application_type = configuration::ApplicationType::Reporting; - ExpectChildProcessStarts(); - ExpectSetupComms(); - EXPECT_CALL(*g_syscall_mock, fcntl).WillOnce(Return(-1)); - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); + IpcCommsSync* block = StubShmObject(); + EXPECT_CALL(*g_syscall_mock, access(_, _)).WillOnce(Return(0)); + EXPECT_CALL(*semaphore_mock_, sem_init).Times(1).WillRepeatedly(Return(kSemSuccess)); + EXPECT_CALL(*g_start_process_mock, startProcess(_, Ref(config_), kShmFd, Property(&IpcCommsP::get, block))) + .WillOnce(DoAll(SetArgReferee<0>(started_pid_), Return(OsalReturnType::kSuccess))); + EXPECT_CALL(*g_syscall_mock, close(kShmFd)).WillOnce(Return(0)); - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); + EXPECT_EQ(process_launcher_->startProcess(pid_, sync_, config_), OsalReturnType::kSuccess); + EXPECT_EQ(pid_, started_pid_); + EXPECT_EQ(sync_.get(), block); + EXPECT_EQ(block->magic_, IpcCommsSync::kMagic); + EXPECT_EQ(block->version_, IpcCommsSync::kLayoutVersion); } class SetupCommsTest : public StartProcessTest @@ -352,6 +332,7 @@ class SetupCommsTest : public StartProcessTest config_.component_properties.application_profile.application_type = configuration::ApplicationType::Reporting; EXPECT_CALL(*g_syscall_mock, access).WillOnce(Return(0)); + EXPECT_CALL(*g_start_process_mock, startProcess).Times(0); } }; @@ -451,388 +432,6 @@ TEST_F(ProcessLauncherTest, releasingCommsObjectSkipsDestroyOnInvalidMemory) block.reset(); } -class SetSchedulingAndSecurityTest : public StartProcessTest -{ - protected: - void SetUp() override - { - StartProcessTest::SetUp(); - - ExpectChildProcessStarts(); - ExpectSuccessfulChdir(); - EXPECT_CALL(*g_syscall_mock, execve).Times(AtMost(1)); - } -}; - -TEST_F(SetSchedulingAndSecurityTest, setpgidFails) -{ - RecordProperty("Description", "Verify that the forked process exits if setting pgid fails"); - - EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(-1)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(SetSchedulingAndSecurityTest, setgidFails) -{ - RecordProperty("Description", "Verify that the forked process exits if setting gid fails"); - - EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(-1)); - EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(SetSchedulingAndSecurityTest, setuidFails) -{ - RecordProperty("Description", "Verify that the forked process exits if setting uid fails"); - - EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(-1)); - EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(SetSchedulingAndSecurityTest, setschedFails) -{ - RecordProperty("Description", "Verify that the forked process exits if setting the scheduler fails"); - - EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(-1)); - EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(SetSchedulingAndSecurityTest, setgroupsFails) -{ - RecordProperty("Description", "Verify that if setting supplementary gids fails, the forked process exits"); - - config_.deployment_config.sandbox.supplementary_group_ids = {1, 2, 3}; - - EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(-1)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(SetSchedulingAndSecurityTest, setaffinityFails) -{ - RecordProperty("Description", "Verify that the forked process exits if setting the CPU affinity fails"); - - config_.deployment_config.sandbox.affinity_mask = 0x1U; - - EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setaffinity(0x1U)).WillOnce(SetErrnoAndReturn(EINVAL, -1)); - EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(SetSchedulingAndSecurityTest, setaffinityIgnore) -{ - RecordProperty("Description", "Verify that the CPU affinity is not changed if no affinity mask is configured"); - - config_.deployment_config.sandbox.affinity_mask = std::nullopt; - - EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setaffinity).Times(0); - EXPECT_CALL(*g_syscall_mock, setgroups).WillOnce(Return(0)); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), ExecveSuccess); -} - -TEST_F(SetSchedulingAndSecurityTest, supplementaryGroupsAreCleared) -{ - RecordProperty( - "Description", "Verify that supplementary group IDs are explicitly cleared when none are configured"); - - config_.deployment_config.sandbox.supplementary_group_ids = {}; - - ExpectSuccessfulSchedulingAndSecurity(); - EXPECT_CALL(*g_syscall_mock, setgroups(0, _)).WillOnce(Return(0)); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), ExecveSuccess); -} - -TEST_F(StartProcessTest, chdirFails) -{ - RecordProperty("Description", "Verify that the forked process exits if changing the working dir fails"); - - ExpectChildProcessStarts(); - ExpectSuccessfulSchedulingAndSecurity(); - EXPECT_CALL(*g_syscall_mock, chdir).WillOnce(Return(-1)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(StartProcessTest, changeSecurityPolicyFails) -{ - RecordProperty("Description", "Verify that the forked process exits if changing the security policy fails"); - - config_.deployment_config.sandbox.security_policy = "security"; - - ExpectChildProcessStarts(); - ExpectSuccessfulSchedulingAndSecurity(); - ExpectSuccessfulChdir(); - EXPECT_CALL(*g_syscall_mock, setSecurityPolicy).WillOnce(Return(-1)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(StartProcessTest, setRLimitFails) -{ - RecordProperty("Description", "Verify that the forked process exits if setting a limit fails"); - - config_.deployment_config.sandbox.rlimits = { - {RLIMIT_CPU, {500, 500}}, - }; - - ExpectChildProcessStarts(); - ExpectSuccessfulSchedulingAndSecurity(); - ExpectSuccessfulChdir(); - EXPECT_CALL(*g_syscall_mock, setrlimit).WillOnce(Return(-1)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -TEST_F(StartProcessTest, noRlimitsConfiguredSkipsSetrlimit) -{ - RecordProperty("Description", "Verify that setrlimit is not called when no rlimits are configured"); - - ExpectChildProcessStarts(); - ExpectSuccessfulSchedulingAndSecurity(); - ExpectSuccessfulChdir(); - EXPECT_CALL(*g_syscall_mock, setrlimit).Times(0); - EXPECT_CALL(*g_syscall_mock, execve).Times(AtMost(1)); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), ExecveSuccess); -} - -TEST_F(StartProcessTest, setRLimitZeroIsApplied) -{ - RecordProperty("Description", "Verify that a configured rlimit of 0 is applied via setrlimit"); - - config_.deployment_config.sandbox.rlimits = { - {RLIMIT_CORE, {0, 0}}, - }; - - ExpectChildProcessStarts(); - ExpectSuccessfulSchedulingAndSecurity(); - ExpectSuccessfulChdir(); - EXPECT_CALL( - *g_syscall_mock, setrlimit(RLIMIT_CORE, AllOf(Field(&rlimit::rlim_cur, 0U), Field(&rlimit::rlim_max, 0U)))) - .WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, execve).Times(AtMost(1)); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), ExecveSuccess); -} - -TEST_F(StartProcessTest, setRLimitPassesPreResolvedValuesUnchanged) -{ - RecordProperty( - "Description", - "Verify that applyResourceLimits() passes the resource and limit through to setrlimit() unchanged."); - - config_.deployment_config.sandbox.rlimits = { - {RLIMIT_FSIZE, {1024U, RLIM_INFINITY}}, - }; - - ExpectChildProcessStarts(); - ExpectSuccessfulSchedulingAndSecurity(); - ExpectSuccessfulChdir(); - EXPECT_CALL( - *g_syscall_mock, - setrlimit( - RLIMIT_FSIZE, - AllOf(Field(&rlimit::rlim_cur, static_cast(1024U)), Field(&rlimit::rlim_max, RLIM_INFINITY)))) - .WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, execve).Times(AtMost(1)); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), ExecveSuccess); -} - -TEST_F(StartProcessTest, rlimitsAppliedBeforePrivilegeDrop) -{ - RecordProperty( - "Description", - "Regression guard for the ordering defect where rlimits were applied after setuid()/setgid(): raising a " - "hard limit requires privilege, so setrlimit must be called before setuid."); - - config_.deployment_config.sandbox.rlimits = { - {RLIMIT_NOFILE, {1024, 1024}}, - }; - - ExpectChildProcessStarts(); - ExpectSuccessfulChdir(); - - EXPECT_CALL(*g_syscall_mock, setpgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler).WillOnce(Return(0)); - - { - InSequence seq; - EXPECT_CALL(*g_syscall_mock, setrlimit(RLIMIT_NOFILE, _)).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgid).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgroups(_, _)).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid).WillOnce(Return(0)); - } - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), ExecveSuccess); -} - -TEST_F(StartProcessTest, execveFails) -{ - RecordProperty("Description", "Verify that the forked process exits if execve fails"); - - ExpectChildProcessStarts(); - ExpectSuccessfulSchedulingAndSecurity(); - ExpectSuccessfulChdir(); - EXPECT_CALL(*g_syscall_mock, execve).WillOnce(Return(-1)); - - EXPECT_CALL(*g_syscall_mock, sysexit(EXIT_FAILURE)).WillOnce(Throw(SysExitException{})); - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), SysExitException); -} - -// Define a matcher that checks a null-terminated char** against a vector of strings -MATCHER_P(ArgvMatches, expected_args, "") -{ - for (size_t i = 0; i < expected_args.size(); ++i) - { - // Check if the argument is null prematurely, or if the string doesn't match - if (arg[i] == nullptr || std::string(arg[i]) != expected_args[i]) - { - *result_listener << "mismatch at index " << i << " (expected: \"" << expected_args[i] << "\", got: \"" - << (arg[i] ? arg[i] : "NULL") << "\")"; - return false; - } - } - // execve argv must be null-terminated; ensure the last expected element is followed by NULL - return arg[expected_args.size()] == nullptr; -} - -MATCHER_P(CArrayMatches, expected, "") -{ - for (size_t i = 0; i < expected.size(); ++i) - { - if (arg[i] != expected[i]) - { - *result_listener << "mismatch at index " << i << " (expected: " << expected[i] << ", got: " << arg[i] - << ")"; - return false; - } - } - return true; -} - -TEST_F(StartProcessTest, startProcessChildSuccess) -{ - RecordProperty("Description", "Verify that when startProcess succeeds, the forked process is configured correctly"); - - const int scheduler = SCHED_FIFO; - const int uid = 11; - const int gid = 13; - const std::vector sgids = {1, 2, 3}; - const std::uint64_t mem_limit = 4096; - const std::uint32_t cpu_limit = 500; - const std::uint64_t affinity_mask = 0x8000000000000005U; - const std::string security_policy = "security"; - const std::vector args_in = {"-c 2", "--argument yes"}; - const std::vector expected_launch_args = { - config_.deployment_config.process_command.executablePath(), args_in[0], args_in[1]}; - - config_.component_properties.application_profile.application_type = configuration::ApplicationType::Reporting; - config_.deployment_config.sandbox.scheduling_policy = scheduler; - config_.deployment_config.sandbox.uid = uid; - config_.deployment_config.sandbox.gid = gid; - config_.deployment_config.sandbox.supplementary_group_ids = sgids; - config_.deployment_config.sandbox.rlimits = { - {RLIMIT_AS, {mem_limit, mem_limit}}, - {RLIMIT_CPU, {cpu_limit, RLIM_INFINITY}}, - }; - config_.deployment_config.sandbox.affinity_mask = affinity_mask; - config_.deployment_config.sandbox.security_policy = security_policy; - config_.deployment_config.environmental_variables.add("environment", "yes"); - config_.deployment_config.environmental_variables.add("errors", "no"); - config_.deployment_config.process_command = - configuration::ProcessCommand{config_.deployment_config.process_command.executablePath(), args_in}; - - IpcCommsSync* block = StubShmObject(); - - EXPECT_CALL(*g_syscall_mock, access).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, fork).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, getpid).WillRepeatedly(Return(forked_pid_)); - EXPECT_CALL(*g_syscall_mock, fcntl).WillOnce(Return(0)); - EXPECT_CALL(*semaphore_mock_, sem_init).Times(1).WillRepeatedly(Return(kSemSuccess)); - EXPECT_CALL(*g_syscall_mock, setpgid(0, forked_pid_)); - EXPECT_CALL(*g_syscall_mock, sched_setscheduler(0, scheduler, _)).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setaffinity(affinity_mask)).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setuid(uid)).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgid(gid)).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, setgroups(sgids.size(), CArrayMatches(sgids))).WillOnce(Return(0)); - EXPECT_CALL(*g_syscall_mock, chdir(StrEq("/tmp"))).WillOnce(Return(0)); - EXPECT_CALL( - *g_syscall_mock, - setrlimit(RLIMIT_AS, AllOf(Field(&rlimit::rlim_cur, mem_limit), Field(&rlimit::rlim_max, mem_limit)))); - EXPECT_CALL( - *g_syscall_mock, - setrlimit(RLIMIT_CPU, AllOf(Field(&rlimit::rlim_cur, cpu_limit), Field(&rlimit::rlim_max, RLIM_INFINITY)))); - EXPECT_CALL(*g_syscall_mock, setSecurityPolicy(StrEq(security_policy.data()))).WillOnce(Return(0)); - EXPECT_CALL( - *g_syscall_mock, - execve( - StrEq(expected_launch_args[0]), - ArgvMatches(expected_launch_args), - config_.deployment_config.environmental_variables.envp())) - .WillOnce(Throw(ExecveSuccess{})); - - EXPECT_CALL(*g_syscall_mock, sysexit).Times(0); // No failures - - EXPECT_THROW(static_cast(process_launcher_->startProcess(pid_, sync_, config_)), ExecveSuccess); - - EXPECT_EQ(block->magic_, IpcCommsSync::kMagic); - EXPECT_EQ(block->version_, IpcCommsSync::kLayoutVersion); -} - class ClientMethodsTest : public ProcessLauncherTest { }; diff --git a/score/launch_manager/src/daemon/src/process_group_manager/iprocess.hpp b/score/launch_manager/src/daemon/src/process_group_manager/iprocess.hpp index 9515269cee..6b32303894 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/iprocess.hpp +++ b/score/launch_manager/src/daemon/src/process_group_manager/iprocess.hpp @@ -29,19 +29,6 @@ namespace score::mw::lifecycle::internal::osal { -/// @brief Struct to hold configuration parameters for the child process. -struct ChildProcessConfig -{ - /// @brief child process startup configurations - const score::mw::lifecycle::internal::configuration::ComponentConfig& config; - - /// @brief fd file descriptor of the shared memory segment. - int fd; - - /// @brief sync Pointer to the shared memory block - IpcCommsP shared_block; -}; - ///@brief This interface provides functionality that is needed to manage child processes. /// The `IProcess` interface provides functionality for child process management, which is required by Launch /// Manager. As a part of OSAL it also provides porting interface for LCM. From ae51992e8211222fd4973039164e6e536b313653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20Fu=C3=9Fberger?= Date: Thu, 26 Nov 2026 14:07:46 +0100 Subject: [PATCH 2/4] Fix iwyu findings --- score/launch_manager/src/daemon/src/osal/BUILD | 2 ++ .../daemon/src/osal/details/linux/start_process.cpp | 12 +++++++++--- .../daemon/src/process_group_manager/details/BUILD | 2 ++ .../details/process_launcher.cpp | 7 +++++-- 4 files changed, 18 insertions(+), 5 deletions(-) diff --git a/score/launch_manager/src/daemon/src/osal/BUILD b/score/launch_manager/src/daemon/src/osal/BUILD index 21db6f7da1..020a5f3bd2 100644 --- a/score/launch_manager/src/daemon/src/osal/BUILD +++ b/score/launch_manager/src/daemon/src/osal/BUILD @@ -222,6 +222,8 @@ cc_library( ":set_groups", ":sys_exit", "//score/launch_manager/src/daemon/src/common:signal_safe_log", + "//score/launch_manager/src/daemon/src/configuration:environment_config", + "//score/launch_manager/src/daemon/src/configuration:process_command", "@score_baselibs//score/language/futurecpp", ], "@platforms//os:qnx": [ diff --git a/score/launch_manager/src/daemon/src/osal/details/linux/start_process.cpp b/score/launch_manager/src/daemon/src/osal/details/linux/start_process.cpp index 030adab138..20972134d3 100644 --- a/score/launch_manager/src/daemon/src/osal/details/linux/start_process.cpp +++ b/score/launch_manager/src/daemon/src/osal/details/linux/start_process.cpp @@ -11,17 +11,19 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -#include - #include #include #include -#include #include #include #include "score/mw/launch_manager/common/log.hpp" #include "score/mw/launch_manager/common/signal_safe_log.hpp" +#include "score/mw/launch_manager/configuration/component_config.hpp" +#include "score/mw/launch_manager/configuration/environment_config.hpp" +#include "score/mw/launch_manager/configuration/process_command.hpp" +#include "score/mw/launch_manager/osal/ipc_comms.hpp" +#include "score/mw/launch_manager/osal/return_types.hpp" #include "score/mw/launch_manager/osal/security_policy.hpp" #include "score/mw/launch_manager/osal/set_affinity.hpp" #include "score/mw/launch_manager/osal/set_groups.hpp" @@ -30,6 +32,10 @@ #include #include #include +#include +#include +#include +#include namespace score::mw::lifecycle::internal::osal { diff --git a/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD b/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD index d80f94db41..d03aa5e81d 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD +++ b/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD @@ -562,8 +562,10 @@ cc_library( "//score/launch_manager/src/daemon/src/common:log", "//score/launch_manager/src/daemon/src/common:signal_safe_log", "//score/launch_manager/src/daemon/src/configuration:component_config", + "//score/launch_manager/src/daemon/src/configuration:process_command", "//score/launch_manager/src/daemon/src/osal:ipc_comms", "//score/launch_manager/src/daemon/src/osal:return_types", + "//score/launch_manager/src/daemon/src/osal:semaphore", "//score/launch_manager/src/daemon/src/osal:shm_open_anon", "//score/launch_manager/src/daemon/src/osal:start_process", "//score/launch_manager/src/daemon/src/process_group_manager:iprocess", diff --git a/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.cpp b/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.cpp index 6febcc244d..5deb455fa8 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.cpp +++ b/score/launch_manager/src/daemon/src/process_group_manager/details/process_launcher.cpp @@ -11,7 +11,7 @@ * SPDX-License-Identifier: Apache-2.0 ********************************************************************************/ -#include +#include #include #include #include @@ -20,16 +20,19 @@ #include "score/mw/launch_manager/common/log.hpp" #include "score/mw/launch_manager/common/signal_safe_log.hpp" #include "score/mw/launch_manager/configuration/component_config.hpp" +#include "score/mw/launch_manager/configuration/process_command.hpp" #include "score/mw/launch_manager/osal/ipc_comms.hpp" #include "score/mw/launch_manager/osal/return_types.hpp" +#include "score/mw/launch_manager/osal/semaphore.hpp" #include "score/mw/launch_manager/osal/shm_open_anon.hpp" #include "score/mw/launch_manager/osal/start_process.hpp" #include "score/mw/launch_manager/process_group_manager/details/process_launcher.hpp" -#include "score/mw/launch_manager/process_group_manager/iprocess.hpp" #include #include #include #include +#include +#include constexpr int kPidZero = 0; // This value is used to check if the process ID (uses pid_t) is valid or not. constexpr int kPosixSuccess = 0; From 323e965dcbe5d04087282ad178bffed72ff3833b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20Fu=C3=9Fberger?= Date: Fri, 27 Nov 2026 15:12:55 +0100 Subject: [PATCH 3/4] Implement review comments --- .../daemon/src/osal/mock_start_process.hpp | 6 +++ .../src/process_group_manager/details/BUILD | 28 +--------- tests/utils/mocks/mock_syscalls.bzl | 53 +++++++++++++++++++ 3 files changed, 61 insertions(+), 26 deletions(-) create mode 100644 tests/utils/mocks/mock_syscalls.bzl diff --git a/score/launch_manager/src/daemon/src/osal/mock_start_process.hpp b/score/launch_manager/src/daemon/src/osal/mock_start_process.hpp index 8244bee789..99107792bd 100644 --- a/score/launch_manager/src/daemon/src/osal/mock_start_process.hpp +++ b/score/launch_manager/src/daemon/src/osal/mock_start_process.hpp @@ -45,6 +45,12 @@ namespace score::mw::lifecycle::internal::osal OsalReturnType startProcess(ProcessID& pid, const configuration::ComponentConfig& config, int comms_fd, const IpcCommsP& comms) { + if (!g_start_process_mock) + { + ADD_FAILURE() << "osal::startProcess() called without g_start_process_mock being set"; + return OsalReturnType::kFail; + } + return g_start_process_mock->startProcess(pid, config, comms_fd, comms); } } // namespace score::mw::lifecycle::internal::osal diff --git a/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD b/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD index b309f643d6..4dc304cfec 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD +++ b/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD @@ -13,6 +13,7 @@ load("@rules_cc//cc:defs.bzl", "cc_library") load("//tests/utils/bazel:unit_test.bzl", "lm_cc_test") +load("//tests/utils/mocks:mock_syscalls.bzl", "MOCK_SYSCALLS_WRAPPED_SYMBOLS", "linker_wrap_symbols") cc_library( name = "component", @@ -539,32 +540,7 @@ cc_library( lm_cc_test( name = "process_launcher_UT", srcs = ["process_launcher_UT.cpp"], - linkopts = [ - "-Wl,--wrap=fork", - "-Wl,--wrap=execve", - "-Wl,--wrap=kill", - "-Wl,--wrap=wait", - "-Wl,--wrap=access", - "-Wl,--wrap=shm_open", - "-Wl,--wrap=ftruncate", - "-Wl,--wrap=shm_unlink", - "-Wl,--wrap=mmap", - "-Wl,--wrap=munmap", - "-Wl,--wrap=setpgid", - "-Wl,--wrap=setgid", - "-Wl,--wrap=setuid", - "-Wl,--wrap=sched_setscheduler", - "-Wl,--wrap=chdir", - "-Wl,--wrap=setrlimit", - "-Wl,--wrap=getpid", - "-Wl,--wrap=fcntl", - "-Wl,--wrap=sem_destroy", - "-Wl,--wrap=msync", - "-Wl,--wrap=close", - "-Wl,--wrap=fstat", - "-Wl,--wrap=clock_gettime", - "-Wl,--wrap=clock_getres", - ], + linkopts = linker_wrap_symbols(MOCK_SYSCALLS_WRAPPED_SYMBOLS), linkstatic = True, deps = [ ":process_launcher", diff --git a/tests/utils/mocks/mock_syscalls.bzl b/tests/utils/mocks/mock_syscalls.bzl new file mode 100644 index 0000000000..d575d89c72 --- /dev/null +++ b/tests/utils/mocks/mock_syscalls.bzl @@ -0,0 +1,53 @@ +# ******************************************************************************* +# Copyright (c) 2026 Contributors to the Eclipse Foundation +# +# See the NOTICE file(s) distributed with this work for additional +# information regarding copyright ownership. +# +# This program and the accompanying materials are made available under the +# terms of the Apache License Version 2.0 which is available at +# https://www.apache.org/licenses/LICENSE-2.0 +# +# SPDX-License-Identifier: Apache-2.0 +# ******************************************************************************* + +# Symbols for which mock_syscalls.hpp defines a __wrap_ that calls __real_. +# Every one of them must be wrapped, otherwise __real_ is unresolved at link time. +# Keep in sync with mock_syscalls.hpp. +MOCK_SYSCALLS_WRAPPED_SYMBOLS = [ + "fork", + "execve", + "kill", + "wait", + "access", + "shm_open", + "ftruncate", + "shm_unlink", + "mmap", + "munmap", + "setpgid", + "setgid", + "setuid", + "sched_setscheduler", + "chdir", + "setrlimit", + "getpid", + "fcntl", + "sem_destroy", + "msync", + "close", + "fstat", + "clock_gettime", + "clock_getres", +] + +def linker_wrap_symbols(symbols): + """Returns linkopts that make the linker wrap each of the given symbols. + + Args: + symbols: List of symbol names to wrap. + + Returns: + List of "-Wl,--wrap=" linker options. + """ + return ["-Wl,--wrap=" + symbol for symbol in symbols] From 9a6b40a908e001aaf286bba1b67c361de55c60f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nicolas=20Fu=C3=9Fberger?= Date: Fri, 27 Nov 2026 15:53:22 +0100 Subject: [PATCH 4/4] Use existing symbol wrapper --- .../launch_manager/src/daemon/src/osal/BUILD | 31 ++--------- .../src/process_group_manager/details/BUILD | 3 +- tests/utils/mocks/mock_syscalls.bzl | 53 ------------------- 3 files changed, 4 insertions(+), 83 deletions(-) delete mode 100644 tests/utils/mocks/mock_syscalls.bzl diff --git a/score/launch_manager/src/daemon/src/osal/BUILD b/score/launch_manager/src/daemon/src/osal/BUILD index d67a2c76ed..63b64f134c 100644 --- a/score/launch_manager/src/daemon/src/osal/BUILD +++ b/score/launch_manager/src/daemon/src/osal/BUILD @@ -11,7 +11,7 @@ # SPDX-License-Identifier: Apache-2.0 # ******************************************************************************* load("@rules_cc//cc:defs.bzl", "cc_library") -load("//tests/utils/bazel:unit_test.bzl", "lm_cc_test") +load("//tests/utils/bazel:unit_test.bzl", "MOCK_SYSCALLS_WRAPPED_SYMBOLS", "linker_wrap_symbols", "lm_cc_test") cc_library( name = "return_types", @@ -243,32 +243,7 @@ cc_library( lm_cc_test( name = "start_process_linux_UT", srcs = ["details/linux/start_process_UT.cpp"], - linkopts = [ - "-Wl,--wrap=fork", - "-Wl,--wrap=execve", - "-Wl,--wrap=kill", - "-Wl,--wrap=wait", - "-Wl,--wrap=access", - "-Wl,--wrap=shm_open", - "-Wl,--wrap=ftruncate", - "-Wl,--wrap=shm_unlink", - "-Wl,--wrap=mmap", - "-Wl,--wrap=munmap", - "-Wl,--wrap=setpgid", - "-Wl,--wrap=setgid", - "-Wl,--wrap=setuid", - "-Wl,--wrap=sched_setscheduler", - "-Wl,--wrap=chdir", - "-Wl,--wrap=setrlimit", - "-Wl,--wrap=getpid", - "-Wl,--wrap=fcntl", - "-Wl,--wrap=sem_destroy", - "-Wl,--wrap=msync", - "-Wl,--wrap=close", - "-Wl,--wrap=fstat", - "-Wl,--wrap=clock_gettime", - "-Wl,--wrap=clock_getres", - ], + linkopts = linker_wrap_symbols(MOCK_SYSCALLS_WRAPPED_SYMBOLS), linkstatic = True, target_compatible_with = ["@platforms//os:linux"], deps = [ @@ -282,7 +257,7 @@ lm_cc_test( name = "start_process_qnx_UT", srcs = ["details/qnx/start_process_UT.cpp"], # baselibs provides no abstraction for prlimit() - linkopts = ["-Wl,--wrap=prlimit"], + linkopts = linker_wrap_symbols(["prlimit"]), linkstatic = True, target_compatible_with = ["@platforms//os:qnx"], deps = [ diff --git a/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD b/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD index 4dc304cfec..920c7c5235 100644 --- a/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD +++ b/score/launch_manager/src/daemon/src/process_group_manager/details/BUILD @@ -12,8 +12,7 @@ # ******************************************************************************* load("@rules_cc//cc:defs.bzl", "cc_library") -load("//tests/utils/bazel:unit_test.bzl", "lm_cc_test") -load("//tests/utils/mocks:mock_syscalls.bzl", "MOCK_SYSCALLS_WRAPPED_SYMBOLS", "linker_wrap_symbols") +load("//tests/utils/bazel:unit_test.bzl", "MOCK_SYSCALLS_WRAPPED_SYMBOLS", "linker_wrap_symbols", "lm_cc_test") cc_library( name = "component", diff --git a/tests/utils/mocks/mock_syscalls.bzl b/tests/utils/mocks/mock_syscalls.bzl deleted file mode 100644 index d575d89c72..0000000000 --- a/tests/utils/mocks/mock_syscalls.bzl +++ /dev/null @@ -1,53 +0,0 @@ -# ******************************************************************************* -# Copyright (c) 2026 Contributors to the Eclipse Foundation -# -# See the NOTICE file(s) distributed with this work for additional -# information regarding copyright ownership. -# -# This program and the accompanying materials are made available under the -# terms of the Apache License Version 2.0 which is available at -# https://www.apache.org/licenses/LICENSE-2.0 -# -# SPDX-License-Identifier: Apache-2.0 -# ******************************************************************************* - -# Symbols for which mock_syscalls.hpp defines a __wrap_ that calls __real_. -# Every one of them must be wrapped, otherwise __real_ is unresolved at link time. -# Keep in sync with mock_syscalls.hpp. -MOCK_SYSCALLS_WRAPPED_SYMBOLS = [ - "fork", - "execve", - "kill", - "wait", - "access", - "shm_open", - "ftruncate", - "shm_unlink", - "mmap", - "munmap", - "setpgid", - "setgid", - "setuid", - "sched_setscheduler", - "chdir", - "setrlimit", - "getpid", - "fcntl", - "sem_destroy", - "msync", - "close", - "fstat", - "clock_gettime", - "clock_getres", -] - -def linker_wrap_symbols(symbols): - """Returns linkopts that make the linker wrap each of the given symbols. - - Args: - symbols: List of symbol names to wrap. - - Returns: - List of "-Wl,--wrap=" linker options. - """ - return ["-Wl,--wrap=" + symbol for symbol in symbols]