Files
FEX-Emu--FEX/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
T
Ryan Houdek ac32876e4e LinuxEmulation: Implement support for seccomp
Seccomp is a relatively complex feature that was added to Linux back in
2005, and was further extended in 2013 to support BPF based protections.
Once seccomp is enabled, you can no longer disable seccomp but
additional protections can be placed on top of existing seccomp filters.
Additionally seccomp filters are inherited in child processes, which
ensures the process tree can't escape from the secure computing
environment through child processes.

The basis of this feature is a shim that lives between userspace and the
kernel at the syscall entrypoint.
In "strict" mode, seccomp only allows read, write, exit, exit_group, and {rt_,}sigreturn to function.
When in "filter" mode, a BPF filter is run on syscall entrypoint and
returns state about if the syscall should be allowed or not. Multiple
filters can be installed in this mode, all of which get executed. The
result that is the most restricted is the action that occurs at the end.

There are some significant limitations in filter mode that must be
adhered to which makes executing this code inside of kernel space a
non-issue and effectively limits how much cpu time is spent in the filters.
Although these filters are free to do basically anything with the
provided data, just can't do any loops.

FEX needs to implement seccomp because there are multiple applications
using the feature, the primary one being Chromium which some games embed
without disabling the sandbox. WINE also uses seccomp for capturing
games that do raw Windows system calls. Apparently Red Dead Redemption
is one of the games that requires this.

While FEX implements seccomp, it is not yet all encompassing, which is
one of the reasons why it isn't enabled by default and requires a config
option.

**seccomp_unotify is not implemented**
This is a relatively new feature for seccomp which lets the seccomp
filter signal an FD for multiple things. Luckily Chromium and WINE don't
use this. This will be tricky to implement under FEX since it
requires ioctl trapping and some other behaviour

**ptrace isn't supported**
One feature of seccomp is that it can raise ptrace events. Since FEX
doesn't support ptrace at all, this isn't handled. Again Chromium and
WINE don't use this.

**kill-thread not quite correct**
This isn't directly related to seccomp but more about how we do thread
shutdown in FEX. This will require some more changes around thread state
tracking before fully supporting this. Chromium and WINE don't use this.
kill-process also falls under this

Features that are supported:
- Strict mode and seccomp-bpf mode supported
- All BFP instructions that seccomp-bpf understands
- Inheriting seccomp through execve
   - This means we serialize and deserialize the calling thread's
     seccomp filters
   - An execve that escapes FEX will also escape seccomp. Not much we
     can do about it
- TSync - Allowing post-mortem seccomp insertion which allows threads to
  synchronize seccomp filters after the fact

Features that are not supported:
- Different arch qualifiers depending on syscall entrypoint
  - Just like our syscall handler, we are hardcoded to the arch that the
    application starts with
- user_notif
- ptrace
- Runtime code cache invalidation when seccomp is installed
  - Currently we must ensure all syscalls go through the frontend
    syscall handler
  - Runtime invalidation of code cache with inline syscalls will get
    fixed in the future.

This currently isn't enabled by default because of the minor feature
problems that haven't been resolved. Currently the Linux Kernel's test
application works for the features that FEX supports, and WINE's usage
can be handled by FEX. Chromium's sandbox doesn't yet work with this PR,
but it only fails due to features unrelated to seccomp.

Having this open for merging now so we can work to resolve the remaining
issues without this bitrotting.
2024-09-02 14:07:53 -07:00

155 lines
4.9 KiB
C++

// SPDX-License-Identifier: MIT
/*
$info$
tags: LinuxSyscalls|ThreadManager
desc: Frontend thread management
$end_info$
*/
#pragma once
#include "LinuxSyscalls/Types.h"
#include "LinuxSyscalls/Seccomp/SeccompEmulator.h"
#include <FEXCore/Core/Context.h>
#include <FEXCore/fextl/vector.h>
#include <FEXCore/Utils/SignalScopeGuards.h>
#include <cstdint>
#include <linux/seccomp.h>
namespace FEX::HLE {
class SyscallHandler;
class SignalDelegator;
struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
FEXCore::Core::InternalThreadState* Thread;
struct {
uint32_t parent_tid;
uint32_t PID;
std::atomic<uint32_t> TID;
int32_t* set_child_tid {0};
int32_t* clear_child_tid {0};
uint64_t robust_list_head {0};
} ThreadInfo {};
struct {
SignalDelegator* Delegator {};
void* AltStackPtr {};
stack_t GuestAltStack {
.ss_sp = nullptr,
.ss_flags = SS_DISABLE, // By default the guest alt stack is disabled
.ss_size = 0,
};
// This is the thread's current signal mask
FEX::HLE::GuestSAMask CurrentSignalMask {};
// The mask prior to a suspend
FEX::HLE::GuestSAMask PreviousSuspendMask {};
uint64_t PendingSignals {};
} SignalInfo {};
// Seccomp thread specific data.
uint32_t SeccompMode {SECCOMP_MODE_DISABLED};
fextl::vector<FEX::HLE::SeccompEmulator::FilterInformation*> Filters {};
};
class ThreadManager final {
public:
ThreadManager(FEXCore::Context::Context* CTX, FEX::HLE::SignalDelegator* SignalDelegation)
: CTX {CTX}
, SignalDelegation {SignalDelegation} {}
~ThreadManager();
///< Returns the ThreadStateObject from a CpuStateFrame object.
static inline FEX::HLE::ThreadStateObject* GetStateObjectFromCPUState(FEXCore::Core::CpuStateFrame* Frame) {
return static_cast<FEX::HLE::ThreadStateObject*>(Frame->Thread->FrontendPtr);
}
static inline FEX::HLE::ThreadStateObject* GetStateObjectFromFEXCoreThread(FEXCore::Core::InternalThreadState* Thread) {
return static_cast<FEX::HLE::ThreadStateObject*>(Thread->FrontendPtr);
}
FEX::HLE::ThreadStateObject* CreateThread(uint64_t InitialRIP, uint64_t StackPointer, FEXCore::Core::CPUState* NewThreadState = nullptr,
uint64_t ParentTID = 0, FEX::HLE::ThreadStateObject* InheritThread = nullptr);
void TrackThread(FEX::HLE::ThreadStateObject* Thread) {
std::lock_guard lk(ThreadCreationMutex);
Threads.emplace_back(Thread);
}
void DestroyThread(FEX::HLE::ThreadStateObject* Thread, bool NeedsTLSUninstall = false);
void StopThread(FEX::HLE::ThreadStateObject* Thread);
void RunThread(FEX::HLE::ThreadStateObject* Thread);
void Pause();
void Run();
void Step();
void Stop(bool IgnoreCurrentThread = false);
void WaitForIdle();
void WaitForIdleWithTimeout();
void WaitForThreadsToRun();
void SleepThread(FEXCore::Context::Context* CTX, FEXCore::Core::CpuStateFrame* Frame);
void UnlockAfterFork(FEXCore::Core::InternalThreadState* Thread, bool Child);
void IncrementIdleRefCount() {
++IdleWaitRefCount;
}
void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length) {
std::lock_guard lk(ThreadCreationMutex);
// Potential deferred since Thread might not be valid.
// Thread object isn't valid very early in frontend's initialization.
// To be more optimal the frontend should provide this code with a valid Thread object earlier.
auto CodeInvalidationlk = GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread);
for (auto& Thread : Threads) {
CTX->InvalidateGuestCodeRange(Thread->Thread, Start, Length);
}
}
void InvalidateGuestCodeRange(FEXCore::Core::InternalThreadState* CallingThread, uint64_t Start, uint64_t Length,
FEXCore::Context::CodeRangeInvalidationFn callback) {
std::lock_guard lk(ThreadCreationMutex);
// Potential deferred since Thread might not be valid.
// Thread object isn't valid very early in frontend's initialization.
// To be more optimal the frontend should provide this code with a valid Thread object earlier.
auto CodeInvalidationlk = GuardSignalDeferringSectionWithFallback(CTX->GetCodeInvalidationMutex(), CallingThread);
for (auto& Thread : Threads) {
CTX->InvalidateGuestCodeRange(Thread->Thread, Start, Length, callback);
}
}
const fextl::vector<FEX::HLE::ThreadStateObject*>* GetThreads() const {
return &Threads;
}
private:
FEXCore::Context::Context* CTX;
FEX::HLE::SignalDelegator* SignalDelegation;
FEXCore::ForkableUniqueMutex ThreadCreationMutex;
fextl::vector<FEX::HLE::ThreadStateObject*> Threads;
// Thread idling support.
bool Running {};
std::mutex IdleWaitMutex;
std::condition_variable IdleWaitCV;
std::atomic<uint32_t> IdleWaitRefCount {};
void HandleThreadDeletion(FEX::HLE::ThreadStateObject* Thread, bool NeedsTLSUninstall = false);
void NotifyPause();
};
} // namespace FEX::HLE