mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-03 03:25:39 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8cf1e60cc2 | ||
|
|
e3faee459f | ||
|
|
20df8b1858 | ||
|
|
4ab9635ceb |
No files matched your search
@@ -68,7 +68,6 @@ DroidDeck is [GPL-3.0](LICENSE). Steam and Proton belong to Valve Corporation. V
|
||||
- Runtime, shim, input and controller work build on WinNative and Bannerlator by maxjivi05.
|
||||
- mmap ring buffer controller input by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)).
|
||||
- [FEX](https://github.com/FEX-Emu/FEX) (MIT) runs x86 code. DroidDeck's build puts the platform name under `AT_PLATFORM` so [sharun](https://github.com/VHSgunzo/sharun) AppImages by VHSgunzo (MIT) start through its [userland-execve](https://crates.io/crates/userland-execve) loader (MIT), and its GL thunk hands X errors to the program's own error handler. FEX's code disk cache was checked in its source. The fix for host stack left behind when a program leaves a signal handler without returning follows the approach suggested in [FEX-Emu/FEX#2487](https://github.com/FEX-Emu/FEX/issues/2487). The host stack fix for system calls that end a block is a backport of Ryan Houdek's [FEX-Emu/FEX#6122](https://github.com/FEX-Emu/FEX/pull/6122).
|
||||
- Anti-cheat support under FEX is the work of [StonkGuy](https://github.com/StonkGuy): the x86-64 ptrace, seccomp and `/proc` emulation from his [FEX fork](https://github.com/StonkGuy/FEX) (`eac-2611` branch, MIT) is carried as build patch 0020 with his authorship, patches 0021 to 0026 build on it, and his `eac-tests` regression suite verifies them.
|
||||
- x86-64 programs on Wayland reach the GPU through FEX's Wayland client, wayland-egl and EGL thunks. The guest `wl_list` and `wl_array` helpers follow [libwayland](https://gitlab.freedesktop.org/wayland/wayland)'s `src/wayland-util.c` (MIT). The EGL extension table comes from the [Khronos EGL registry](https://github.com/KhronosGroup/EGL-Registry) (Apache-2.0) and Mesa's `egl_other.xml` (MIT).
|
||||
- x86 AppImages, and arm64 ones whose runtime can't unpack on Android, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence.
|
||||
- DwarFS AppImages are unpacked without proot by `dwarfsextract` from [DwarFS](https://github.com/mhx/dwarfs) by Marcus Holland-Moritz (MIT), the release binary uruntime embeds, taken out of its self-extracting wrapper and shipped with its licence.
|
||||
|
||||
@@ -481,5 +481,69 @@
|
||||
<service android:name=".runtime.GuestWorker61" android:exported="false" android:process=":g61" />
|
||||
<service android:name=".runtime.GuestWorker62" android:exported="false" android:process=":g62" />
|
||||
<service android:name=".runtime.GuestWorker63" android:exported="false" android:process=":g63" />
|
||||
<service android:name=".runtime.GuestWorker64" android:exported="false" android:process=":g64" />
|
||||
<service android:name=".runtime.GuestWorker65" android:exported="false" android:process=":g65" />
|
||||
<service android:name=".runtime.GuestWorker66" android:exported="false" android:process=":g66" />
|
||||
<service android:name=".runtime.GuestWorker67" android:exported="false" android:process=":g67" />
|
||||
<service android:name=".runtime.GuestWorker68" android:exported="false" android:process=":g68" />
|
||||
<service android:name=".runtime.GuestWorker69" android:exported="false" android:process=":g69" />
|
||||
<service android:name=".runtime.GuestWorker70" android:exported="false" android:process=":g70" />
|
||||
<service android:name=".runtime.GuestWorker71" android:exported="false" android:process=":g71" />
|
||||
<service android:name=".runtime.GuestWorker72" android:exported="false" android:process=":g72" />
|
||||
<service android:name=".runtime.GuestWorker73" android:exported="false" android:process=":g73" />
|
||||
<service android:name=".runtime.GuestWorker74" android:exported="false" android:process=":g74" />
|
||||
<service android:name=".runtime.GuestWorker75" android:exported="false" android:process=":g75" />
|
||||
<service android:name=".runtime.GuestWorker76" android:exported="false" android:process=":g76" />
|
||||
<service android:name=".runtime.GuestWorker77" android:exported="false" android:process=":g77" />
|
||||
<service android:name=".runtime.GuestWorker78" android:exported="false" android:process=":g78" />
|
||||
<service android:name=".runtime.GuestWorker79" android:exported="false" android:process=":g79" />
|
||||
<service android:name=".runtime.GuestWorker80" android:exported="false" android:process=":g80" />
|
||||
<service android:name=".runtime.GuestWorker81" android:exported="false" android:process=":g81" />
|
||||
<service android:name=".runtime.GuestWorker82" android:exported="false" android:process=":g82" />
|
||||
<service android:name=".runtime.GuestWorker83" android:exported="false" android:process=":g83" />
|
||||
<service android:name=".runtime.GuestWorker84" android:exported="false" android:process=":g84" />
|
||||
<service android:name=".runtime.GuestWorker85" android:exported="false" android:process=":g85" />
|
||||
<service android:name=".runtime.GuestWorker86" android:exported="false" android:process=":g86" />
|
||||
<service android:name=".runtime.GuestWorker87" android:exported="false" android:process=":g87" />
|
||||
<service android:name=".runtime.GuestWorker88" android:exported="false" android:process=":g88" />
|
||||
<service android:name=".runtime.GuestWorker89" android:exported="false" android:process=":g89" />
|
||||
<service android:name=".runtime.GuestWorker90" android:exported="false" android:process=":g90" />
|
||||
<service android:name=".runtime.GuestWorker91" android:exported="false" android:process=":g91" />
|
||||
<service android:name=".runtime.GuestWorker92" android:exported="false" android:process=":g92" />
|
||||
<service android:name=".runtime.GuestWorker93" android:exported="false" android:process=":g93" />
|
||||
<service android:name=".runtime.GuestWorker94" android:exported="false" android:process=":g94" />
|
||||
<service android:name=".runtime.GuestWorker95" android:exported="false" android:process=":g95" />
|
||||
<service android:name=".runtime.GuestWorker96" android:exported="false" android:process=":g96" />
|
||||
<service android:name=".runtime.GuestWorker97" android:exported="false" android:process=":g97" />
|
||||
<service android:name=".runtime.GuestWorker98" android:exported="false" android:process=":g98" />
|
||||
<service android:name=".runtime.GuestWorker99" android:exported="false" android:process=":g99" />
|
||||
<service android:name=".runtime.GuestWorker100" android:exported="false" android:process=":g100" />
|
||||
<service android:name=".runtime.GuestWorker101" android:exported="false" android:process=":g101" />
|
||||
<service android:name=".runtime.GuestWorker102" android:exported="false" android:process=":g102" />
|
||||
<service android:name=".runtime.GuestWorker103" android:exported="false" android:process=":g103" />
|
||||
<service android:name=".runtime.GuestWorker104" android:exported="false" android:process=":g104" />
|
||||
<service android:name=".runtime.GuestWorker105" android:exported="false" android:process=":g105" />
|
||||
<service android:name=".runtime.GuestWorker106" android:exported="false" android:process=":g106" />
|
||||
<service android:name=".runtime.GuestWorker107" android:exported="false" android:process=":g107" />
|
||||
<service android:name=".runtime.GuestWorker108" android:exported="false" android:process=":g108" />
|
||||
<service android:name=".runtime.GuestWorker109" android:exported="false" android:process=":g109" />
|
||||
<service android:name=".runtime.GuestWorker110" android:exported="false" android:process=":g110" />
|
||||
<service android:name=".runtime.GuestWorker111" android:exported="false" android:process=":g111" />
|
||||
<service android:name=".runtime.GuestWorker112" android:exported="false" android:process=":g112" />
|
||||
<service android:name=".runtime.GuestWorker113" android:exported="false" android:process=":g113" />
|
||||
<service android:name=".runtime.GuestWorker114" android:exported="false" android:process=":g114" />
|
||||
<service android:name=".runtime.GuestWorker115" android:exported="false" android:process=":g115" />
|
||||
<service android:name=".runtime.GuestWorker116" android:exported="false" android:process=":g116" />
|
||||
<service android:name=".runtime.GuestWorker117" android:exported="false" android:process=":g117" />
|
||||
<service android:name=".runtime.GuestWorker118" android:exported="false" android:process=":g118" />
|
||||
<service android:name=".runtime.GuestWorker119" android:exported="false" android:process=":g119" />
|
||||
<service android:name=".runtime.GuestWorker120" android:exported="false" android:process=":g120" />
|
||||
<service android:name=".runtime.GuestWorker121" android:exported="false" android:process=":g121" />
|
||||
<service android:name=".runtime.GuestWorker122" android:exported="false" android:process=":g122" />
|
||||
<service android:name=".runtime.GuestWorker123" android:exported="false" android:process=":g123" />
|
||||
<service android:name=".runtime.GuestWorker124" android:exported="false" android:process=":g124" />
|
||||
<service android:name=".runtime.GuestWorker125" android:exported="false" android:process=":g125" />
|
||||
<service android:name=".runtime.GuestWorker126" android:exported="false" android:process=":g126" />
|
||||
<service android:name=".runtime.GuestWorker127" android:exported="false" android:process=":g127" />
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -329,28 +329,16 @@ static constexpr int kWatchedFds = 1 << 16;
|
||||
static constexpr int kWatchedBits = sizeof(unsigned long) * 8;
|
||||
static std::atomic<unsigned long> watched_fds[kWatchedFds / kWatchedBits];
|
||||
static std::atomic<bool> watched_beyond{false};
|
||||
static std::atomic<int> watched_count{0};
|
||||
|
||||
static void watch_fd(int fd) {
|
||||
if (fd < 0) return;
|
||||
if (fd >= kWatchedFds) {
|
||||
watched_beyond.store(true, std::memory_order_release);
|
||||
return;
|
||||
}
|
||||
const unsigned long bit = 1UL << (fd % kWatchedBits);
|
||||
if (!(watched_fds[fd / kWatchedBits].fetch_or(bit, std::memory_order_acq_rel) & bit))
|
||||
watched_count.fetch_add(1, std::memory_order_acq_rel);
|
||||
if (fd >= kWatchedFds) watched_beyond.store(true, std::memory_order_release);
|
||||
else watched_fds[fd / kWatchedBits].fetch_or(1UL << (fd % kWatchedBits), std::memory_order_release);
|
||||
}
|
||||
|
||||
static void unwatch_fd(int fd) {
|
||||
if (fd < 0 || fd >= kWatchedFds) return;
|
||||
const unsigned long bit = 1UL << (fd % kWatchedBits);
|
||||
if (watched_fds[fd / kWatchedBits].fetch_and(~bit, std::memory_order_acq_rel) & bit)
|
||||
watched_count.fetch_sub(1, std::memory_order_acq_rel);
|
||||
}
|
||||
|
||||
static bool any_watched() {
|
||||
return watched_count.load(std::memory_order_acquire) > 0 || watched_beyond.load(std::memory_order_acquire);
|
||||
if (fd >= 0 && fd < kWatchedFds)
|
||||
watched_fds[fd / kWatchedBits].fetch_and(~(1UL << (fd % kWatchedBits)), std::memory_order_release);
|
||||
}
|
||||
|
||||
static bool watched(int fd) {
|
||||
@@ -4281,7 +4269,7 @@ static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
|
||||
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
|
||||
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||
|
||||
nfds_t first = any_watched() ? 0 : nfds;
|
||||
nfds_t first = 0;
|
||||
while (first < nfds && !watched(fds[first].fd)) first++;
|
||||
bool has_fake_fds = false;
|
||||
std::vector<struct pollfd> real_fds;
|
||||
@@ -4384,12 +4372,12 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
|
||||
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
|
||||
const struct timespec *timeout, const sigset_t *sigmask) {
|
||||
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
|
||||
for (nfds_t i = 0; any_watched() && i < nfds; ++i) {
|
||||
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
for (nfds_t i = 0; i < nfds; ++i) {
|
||||
if (!is_fake_input_fd(fds[i].fd)) continue;
|
||||
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
|
||||
errno = EINVAL;
|
||||
return -1;
|
||||
}
|
||||
if (!sigmask)
|
||||
return poll_fake(fds, nfds, static_cast<int>(timespec_to_ms(timeout)), nullptr);
|
||||
sigset_t all_signals, original_mask;
|
||||
@@ -4422,8 +4410,6 @@ EXPORT int __ppoll_chk(struct pollfd *fds, nfds_t nfds, const struct timespec *t
|
||||
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
|
||||
fd_set *exceptfds, struct timeval *timeout) {
|
||||
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
|
||||
if (!any_watched())
|
||||
return my_select ? my_select(nfds, readfds, writefds, exceptfds, timeout) : -1;
|
||||
|
||||
fd_set original_readfds;
|
||||
fd_set original_writefds;
|
||||
|
||||
@@ -224,6 +224,70 @@ class GuestWorker60 : GuestWorker()
|
||||
class GuestWorker61 : GuestWorker()
|
||||
class GuestWorker62 : GuestWorker()
|
||||
class GuestWorker63 : GuestWorker()
|
||||
class GuestWorker64 : GuestWorker()
|
||||
class GuestWorker65 : GuestWorker()
|
||||
class GuestWorker66 : GuestWorker()
|
||||
class GuestWorker67 : GuestWorker()
|
||||
class GuestWorker68 : GuestWorker()
|
||||
class GuestWorker69 : GuestWorker()
|
||||
class GuestWorker70 : GuestWorker()
|
||||
class GuestWorker71 : GuestWorker()
|
||||
class GuestWorker72 : GuestWorker()
|
||||
class GuestWorker73 : GuestWorker()
|
||||
class GuestWorker74 : GuestWorker()
|
||||
class GuestWorker75 : GuestWorker()
|
||||
class GuestWorker76 : GuestWorker()
|
||||
class GuestWorker77 : GuestWorker()
|
||||
class GuestWorker78 : GuestWorker()
|
||||
class GuestWorker79 : GuestWorker()
|
||||
class GuestWorker80 : GuestWorker()
|
||||
class GuestWorker81 : GuestWorker()
|
||||
class GuestWorker82 : GuestWorker()
|
||||
class GuestWorker83 : GuestWorker()
|
||||
class GuestWorker84 : GuestWorker()
|
||||
class GuestWorker85 : GuestWorker()
|
||||
class GuestWorker86 : GuestWorker()
|
||||
class GuestWorker87 : GuestWorker()
|
||||
class GuestWorker88 : GuestWorker()
|
||||
class GuestWorker89 : GuestWorker()
|
||||
class GuestWorker90 : GuestWorker()
|
||||
class GuestWorker91 : GuestWorker()
|
||||
class GuestWorker92 : GuestWorker()
|
||||
class GuestWorker93 : GuestWorker()
|
||||
class GuestWorker94 : GuestWorker()
|
||||
class GuestWorker95 : GuestWorker()
|
||||
class GuestWorker96 : GuestWorker()
|
||||
class GuestWorker97 : GuestWorker()
|
||||
class GuestWorker98 : GuestWorker()
|
||||
class GuestWorker99 : GuestWorker()
|
||||
class GuestWorker100 : GuestWorker()
|
||||
class GuestWorker101 : GuestWorker()
|
||||
class GuestWorker102 : GuestWorker()
|
||||
class GuestWorker103 : GuestWorker()
|
||||
class GuestWorker104 : GuestWorker()
|
||||
class GuestWorker105 : GuestWorker()
|
||||
class GuestWorker106 : GuestWorker()
|
||||
class GuestWorker107 : GuestWorker()
|
||||
class GuestWorker108 : GuestWorker()
|
||||
class GuestWorker109 : GuestWorker()
|
||||
class GuestWorker110 : GuestWorker()
|
||||
class GuestWorker111 : GuestWorker()
|
||||
class GuestWorker112 : GuestWorker()
|
||||
class GuestWorker113 : GuestWorker()
|
||||
class GuestWorker114 : GuestWorker()
|
||||
class GuestWorker115 : GuestWorker()
|
||||
class GuestWorker116 : GuestWorker()
|
||||
class GuestWorker117 : GuestWorker()
|
||||
class GuestWorker118 : GuestWorker()
|
||||
class GuestWorker119 : GuestWorker()
|
||||
class GuestWorker120 : GuestWorker()
|
||||
class GuestWorker121 : GuestWorker()
|
||||
class GuestWorker122 : GuestWorker()
|
||||
class GuestWorker123 : GuestWorker()
|
||||
class GuestWorker124 : GuestWorker()
|
||||
class GuestWorker125 : GuestWorker()
|
||||
class GuestWorker126 : GuestWorker()
|
||||
class GuestWorker127 : GuestWorker()
|
||||
|
||||
/** The pool of [GuestWorker] processes, and the socket guests ask it through (`droiddeck-spawn`). */
|
||||
object GuestWorkers {
|
||||
@@ -250,7 +314,28 @@ object GuestWorkers {
|
||||
GuestWorker54::class.java, GuestWorker55::class.java, GuestWorker56::class.java,
|
||||
GuestWorker57::class.java, GuestWorker58::class.java, GuestWorker59::class.java,
|
||||
GuestWorker60::class.java, GuestWorker61::class.java, GuestWorker62::class.java,
|
||||
GuestWorker63::class.java,
|
||||
GuestWorker63::class.java, GuestWorker64::class.java, GuestWorker65::class.java,
|
||||
GuestWorker66::class.java, GuestWorker67::class.java, GuestWorker68::class.java,
|
||||
GuestWorker69::class.java, GuestWorker70::class.java, GuestWorker71::class.java,
|
||||
GuestWorker72::class.java, GuestWorker73::class.java, GuestWorker74::class.java,
|
||||
GuestWorker75::class.java, GuestWorker76::class.java, GuestWorker77::class.java,
|
||||
GuestWorker78::class.java, GuestWorker79::class.java, GuestWorker80::class.java,
|
||||
GuestWorker81::class.java, GuestWorker82::class.java, GuestWorker83::class.java,
|
||||
GuestWorker84::class.java, GuestWorker85::class.java, GuestWorker86::class.java,
|
||||
GuestWorker87::class.java, GuestWorker88::class.java, GuestWorker89::class.java,
|
||||
GuestWorker90::class.java, GuestWorker91::class.java, GuestWorker92::class.java,
|
||||
GuestWorker93::class.java, GuestWorker94::class.java, GuestWorker95::class.java,
|
||||
GuestWorker96::class.java, GuestWorker97::class.java, GuestWorker98::class.java,
|
||||
GuestWorker99::class.java, GuestWorker100::class.java, GuestWorker101::class.java,
|
||||
GuestWorker102::class.java, GuestWorker103::class.java, GuestWorker104::class.java,
|
||||
GuestWorker105::class.java, GuestWorker106::class.java, GuestWorker107::class.java,
|
||||
GuestWorker108::class.java, GuestWorker109::class.java, GuestWorker110::class.java,
|
||||
GuestWorker111::class.java, GuestWorker112::class.java, GuestWorker113::class.java,
|
||||
GuestWorker114::class.java, GuestWorker115::class.java, GuestWorker116::class.java,
|
||||
GuestWorker117::class.java, GuestWorker118::class.java, GuestWorker119::class.java,
|
||||
GuestWorker120::class.java, GuestWorker121::class.java, GuestWorker122::class.java,
|
||||
GuestWorker123::class.java, GuestWorker124::class.java, GuestWorker125::class.java,
|
||||
GuestWorker126::class.java, GuestWorker127::class.java,
|
||||
)
|
||||
|
||||
private class Slot(val index: Int) {
|
||||
|
||||
@@ -35,9 +35,40 @@ object LegacyNames {
|
||||
@Synchronized
|
||||
fun migrateEtc(root: File) {
|
||||
for ((old, new) in LINKED_DIRS) moveAndLink(File(root, old), File(root, new))
|
||||
File(root, "etc/droiddeck/empty").mkdirs()
|
||||
clearEmptyStandIn(root)
|
||||
File(root, NO_THERMAL).mkdirs()
|
||||
}
|
||||
|
||||
/**
|
||||
* It stands in for /sys/bus/pci/devices, and libpci exits the whole process on an entry it cannot
|
||||
* parse; older builds let thermal bind mount points leak into it. The guest can write here, so a
|
||||
* link is never followed: one in place of the folder is removed, and one above it stops the cleanup.
|
||||
*/
|
||||
private fun clearEmptyStandIn(root: File) {
|
||||
val linkedAbove = listOf("etc", "etc/droiddeck").firstOrNull { Files.isSymbolicLink(File(root, it).toPath()) }
|
||||
if (linkedAbove != null) {
|
||||
Log.w(TAG, "not clearing the empty stand-in: $linkedAbove is a link")
|
||||
return
|
||||
}
|
||||
val empty = File(root, "etc/droiddeck/empty")
|
||||
if (Files.isSymbolicLink(empty.toPath())) runCatching { Files.delete(empty.toPath()) }
|
||||
.onFailure { Log.w(TAG, "could not remove the link at $empty", it); return }
|
||||
empty.mkdirs()
|
||||
empty.listFiles()?.forEach { entry ->
|
||||
runCatching { deleteWithoutFollowing(entry.toPath()) }.onFailure { Log.w(TAG, "could not clear $entry", it) }
|
||||
}
|
||||
}
|
||||
|
||||
private fun deleteWithoutFollowing(path: java.nio.file.Path) {
|
||||
if (Files.isDirectory(path, java.nio.file.LinkOption.NOFOLLOW_LINKS)) {
|
||||
Files.newDirectoryStream(path).use { entries -> entries.forEach(::deleteWithoutFollowing) }
|
||||
}
|
||||
Files.deleteIfExists(path)
|
||||
}
|
||||
|
||||
/** Stands in for a /sys/class/thermal the kernel won't list; proot adds the bound zones' mount points to it. */
|
||||
const val NO_THERMAL = "etc/droiddeck/no-thermal"
|
||||
|
||||
@Synchronized
|
||||
fun migrateRootfs(root: File) {
|
||||
migrateEtc(root)
|
||||
|
||||
@@ -248,7 +248,7 @@ public final class LinuxRuntime {
|
||||
// A kernel that refuses to list /sys/class/thermal (Pixel 10, Android 17) made mangoapp abort
|
||||
// at start ("filesystem_error ... Permission denied: '/sys/class/thermal/'") until its
|
||||
// wrapper gave up: it lists the directory for CPU temperatures. Empty there instead.
|
||||
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, "etc/droiddeck/empty").getPath() + ":/sys/class/thermal");
|
||||
if (new File("/sys/class/thermal").list() == null) bind(cmd, new File(root, LegacyNames.NO_THERMAL).getPath() + ":/sys/class/thermal");
|
||||
bind(cmd, context.getFilesDir().getPath());
|
||||
bind(cmd, context.getCacheDir().getPath());
|
||||
bind(cmd, liveDir(context).getPath());
|
||||
|
||||
@@ -66,14 +66,11 @@ object ProtonExtras {
|
||||
|
||||
internal fun installedIn(dir: File, tool: Tool): List<String> =
|
||||
dir.listFiles()
|
||||
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && !x86_64Build(it) && usable(it) }
|
||||
?.filter { it.isDirectory && it.name.startsWith(tool.prefix) && usable(it) }
|
||||
?.map { it.name }
|
||||
?.sortedWith { a, b -> compareVersions(a, b) }
|
||||
?: emptyList()
|
||||
|
||||
internal fun x86_64Build(dir: File): Boolean =
|
||||
File(dir, "files/lib/wine/x86_64-unix").isDirectory && !File(dir, "files/bin-arm64").isDirectory
|
||||
|
||||
private fun usable(dir: File): Boolean {
|
||||
val manifest = runCatching { File(dir, "toolmanifest.vdf").readText() }.getOrNull() ?: return false
|
||||
val command = Regex("\\\"commandline\\\"\\s+\\\"/?([^\\\" ]+)").find(manifest)?.groupValues?.getOrNull(1) ?: return false
|
||||
|
||||
@@ -41,8 +41,73 @@ internal fun FrameGenMenu(
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val engines = listOf(FrameGen.ENGINE_LSFG to "LSFG", FrameGen.ENGINE_DDFG to "DDFG")
|
||||
|
||||
if (legacyButtons) {
|
||||
val context = LocalContext.current
|
||||
val options = buildList {
|
||||
add(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier))
|
||||
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_DDFG, it)) }
|
||||
(2..4).forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, it)) }
|
||||
FrameGen.ADAPTIVE_TARGETS.forEach { add(FrameGen.Mode(FrameGen.ENGINE_LSFG, target = it)) }
|
||||
}
|
||||
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, bottom = 8.dp)) {
|
||||
options.forEachIndexed { index, option ->
|
||||
val selected = mode == option ||
|
||||
(option.engine == FrameGen.ENGINE_OFF && selectedEngine == null)
|
||||
val enabled = option.engine != FrameGen.ENGINE_LSFG || lossless.ready || selected
|
||||
val pick = { onPick(option) }
|
||||
OutlinedButton(
|
||||
onClick = pick,
|
||||
enabled = enabled,
|
||||
modifier = (if (index == 0) focusModifier else Modifier).fillMaxWidth()
|
||||
.padding(top = if (index == 0) 0.dp else 6.dp)
|
||||
.controllerConfirm(enabled = enabled, onClick = pick),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
colors = ButtonDefaults.outlinedButtonColors(
|
||||
containerColor = if (selected) colors.primary.copy(alpha = 0.16f) else colors.surface,
|
||||
contentColor = if (selected) colors.primary else colors.onSurface,
|
||||
),
|
||||
) { Text(FrameGen.label(context, option)) }
|
||||
}
|
||||
if (selectedEngine == FrameGen.ENGINE_LSFG && !lossless.ready) {
|
||||
Text(
|
||||
need.orEmpty(),
|
||||
color = colors.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
modifier = Modifier.padding(top = 6.dp),
|
||||
)
|
||||
}
|
||||
if (gameProfileId != null) {
|
||||
val resetGame = onResetGame
|
||||
OutlinedButton(
|
||||
onClick = resetGame,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
|
||||
.controllerConfirm(onClick = resetGame),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.comp_game_use_general) + if (hasGameOverride) "" else " ✓")
|
||||
}
|
||||
}
|
||||
if (lossless.owned) {
|
||||
val using = when (lossless.source) {
|
||||
Lossless.Source.STEAM -> stringResource(R.string.lsfg_using_steam)
|
||||
Lossless.Source.IMPORT -> stringResource(R.string.lsfg_using_import)
|
||||
Lossless.Source.NONE -> null
|
||||
}
|
||||
OutlinedButton(
|
||||
onClick = onImportLossless,
|
||||
modifier = Modifier.fillMaxWidth().padding(top = 6.dp)
|
||||
.controllerConfirm(onClick = onImportLossless),
|
||||
contentPadding = PaddingValues(horizontal = 12.dp, vertical = 8.dp),
|
||||
) {
|
||||
Text(stringResource(R.string.lsfg_import) + (using?.let { " · $it" } ?: ""))
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Column(Modifier.fillMaxWidth().padding(start = 10.dp, end = 10.dp, top = 0.dp, bottom = 8.dp)) {
|
||||
if (!legacyButtons) OutlinedButton(
|
||||
OutlinedButton(
|
||||
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
|
||||
modifier = Modifier.fillMaxWidth().controllerConfirm(
|
||||
onClick = { onPick(FrameGen.Mode.OFF.copy(multiplier = mode.multiplier)) },
|
||||
@@ -54,7 +119,7 @@ internal fun FrameGenMenu(
|
||||
),
|
||||
) { Text(offLabel) }
|
||||
|
||||
Row(Modifier.fillMaxWidth().then(if (legacyButtons) Modifier else Modifier.padding(top = 8.dp)), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
val focusIndex = engines.indexOfFirst { (engine, _) ->
|
||||
selectedEngine == engine || engine != FrameGen.ENGINE_LSFG || lossless.ready
|
||||
}
|
||||
|
||||
@@ -887,6 +887,34 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
val steamCard: (@Composable (Modifier) -> Unit)? = if (game != null && steamScope != null) { m ->
|
||||
Box(m) { GameSettingsCard(host, game, steamScope) }
|
||||
} else null
|
||||
val frameGenMenuContent: @Composable () -> Unit = {
|
||||
FrameGenMenu(
|
||||
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
|
||||
lossless = s.lossless,
|
||||
onPick = { mode ->
|
||||
val key = frameGenProfileKey
|
||||
if (key == null) {
|
||||
a.onFrameGenPick(mode)
|
||||
} else {
|
||||
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
|
||||
gameFrameGenMode = mode
|
||||
gameFrameGenOverride = true
|
||||
}
|
||||
},
|
||||
onImportLossless = a.onImportLossless,
|
||||
legacyButtons = true,
|
||||
gameProfileId = frameGenProfileKey,
|
||||
hasGameOverride = gameFrameGenOverride,
|
||||
onResetGame = {
|
||||
val key = frameGenProfileKey
|
||||
if (key != null) {
|
||||
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
|
||||
gameFrameGenMode = com.droiddeck.launcher.gpu.FrameGen.mode(context)
|
||||
gameFrameGenOverride = false
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
val cards = if (game?.library == com.droiddeck.launcher.frontend.Library.EPIC_LAUNCHER) listOfNotNull(steamCard) else buildList<@Composable (Modifier) -> Unit> {
|
||||
add { m ->
|
||||
val back = stringResource(R.string.hop_from_games)
|
||||
@@ -908,33 +936,7 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
) {
|
||||
host.open = if (host.open == "fg") null else "fg"
|
||||
}
|
||||
if (host.open == "fg") FrameGenMenu(
|
||||
mode = if (frameGenProfileKey != null) gameFrameGenMode else s.frameGen,
|
||||
lossless = s.lossless,
|
||||
onPick = { mode ->
|
||||
val key = frameGenProfileKey
|
||||
if (key == null) {
|
||||
a.onFrameGenPick(mode)
|
||||
} else {
|
||||
com.droiddeck.launcher.gpu.FrameGen.setForGame(context, key, mode)
|
||||
gameFrameGenMode = mode
|
||||
gameFrameGenOverride = true
|
||||
}
|
||||
},
|
||||
onImportLossless = a.onImportLossless,
|
||||
legacyButtons = true,
|
||||
gameProfileId = frameGenProfileKey,
|
||||
hasGameOverride = gameFrameGenOverride,
|
||||
onResetGame = {
|
||||
val key = frameGenProfileKey
|
||||
if (key != null) {
|
||||
com.droiddeck.launcher.gpu.FrameGen.clearGame(context, key)
|
||||
gameFrameGenMode =
|
||||
com.droiddeck.launcher.gpu.FrameGen.mode(context)
|
||||
gameFrameGenOverride = false
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
}
|
||||
}
|
||||
if (controller != null) add { m -> SettingCard(stringResource(R.string.setup_card_controls), stringResource(R.string.setup_card_controls_hint), "card:controls", m, controller.onMapping) }
|
||||
@@ -966,6 +968,11 @@ internal fun LaunchSettings(s: FrontEndState, a: FrontEndActions, host: MenuHost
|
||||
repeat(columns - row.size) { Spacer(Modifier.weight(1f)) }
|
||||
}
|
||||
}
|
||||
if (host.open == "fg") {
|
||||
Box(Modifier.fillMaxWidth().padding(top = 4.dp)) {
|
||||
frameGenMenuContent()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,10 @@ package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.focusRequester
|
||||
import androidx.compose.ui.res.stringResource
|
||||
import androidx.compose.ui.unit.dp
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
|
||||
@@ -12,8 +15,30 @@ internal fun FrameGenGroup(s: FrontEndState, a: FrontEndActions) {
|
||||
SettingsGroup(stringResource(R.string.frame_gen_title)) {
|
||||
SettingsRow(stringResource(R.string.frame_gen_title), stringResource(R.string.frame_gen_hint), highlighted = host.open == "fg") {
|
||||
Box {
|
||||
ValueChip(s.frameGenLabel, host.open == "fg") { host.open = if (host.open == "fg") null else "fg" }
|
||||
if (host.open == "fg") FrameGenMenu(s.frameGen, s.lossless, a.onFrameGenPick, a.onImportLossless)
|
||||
val open = host.open == "fg"
|
||||
ValueChip(s.frameGenLabel, open) { host.open = if (open) null else "fg" }
|
||||
AnchoredMenu(
|
||||
open = open,
|
||||
onDismiss = { if (host.open == "fg") host.open = null },
|
||||
title = stringResource(R.string.frame_gen_title),
|
||||
compact = true,
|
||||
minWidth = 220.dp,
|
||||
) { firstItemFocus ->
|
||||
FrameGenMenu(
|
||||
mode = s.frameGen,
|
||||
lossless = s.lossless,
|
||||
onPick = { mode ->
|
||||
a.onFrameGenPick(mode)
|
||||
host.open = null
|
||||
},
|
||||
onImportLossless = {
|
||||
a.onImportLossless()
|
||||
host.open = null
|
||||
},
|
||||
focusModifier = Modifier.focusRequester(firstItemFocus),
|
||||
legacyButtons = true,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,37 @@ class LegacyNamesTest {
|
||||
assertEquals("droiddeck", link("etc/bannerlator"))
|
||||
}
|
||||
|
||||
@Test fun theEmptyStandInIsEmptiedAndThermalZonesGetTheirOwn() {
|
||||
write("etc/droiddeck/empty/thermal_zone26/temp", "")
|
||||
LegacyNames.migrateEtc(root)
|
||||
assertEquals(emptyList<String>(), File(root, "etc/droiddeck/empty").list()!!.toList())
|
||||
assertTrue(File(root, LegacyNames.NO_THERMAL).isDirectory)
|
||||
}
|
||||
|
||||
@Test fun clearingTheEmptyStandInRemovesLinksWithoutTouchingWhatTheyPointAt() {
|
||||
write("home/keep/file", "kept")
|
||||
val links = File(root, "etc/droiddeck/empty").apply { mkdirs() }
|
||||
val made = runCatching {
|
||||
Files.createSymbolicLink(File(links, "dir").toPath(), File(root, "home/keep").toPath())
|
||||
Files.createSymbolicLink(File(links, "dangling").toPath(), File(root, "missing").toPath())
|
||||
}.isSuccess
|
||||
org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made)
|
||||
LegacyNames.migrateEtc(root)
|
||||
assertEquals(emptyList<String>(), links.list()!!.toList())
|
||||
assertEquals("kept", File(root, "home/keep/file").readText())
|
||||
}
|
||||
|
||||
@Test fun aLinkInPlaceOfTheEmptyStandInIsReplacedWithoutTouchingItsTarget() {
|
||||
write("home/keep/file", "kept")
|
||||
val empty = File(root, "etc/droiddeck/empty").also { it.parentFile!!.mkdirs() }
|
||||
val made = runCatching { Files.createSymbolicLink(empty.toPath(), File(root, "home/keep").toPath()) }.isSuccess
|
||||
org.junit.Assume.assumeTrue("this file system cannot make symbolic links", made)
|
||||
LegacyNames.migrateEtc(root)
|
||||
assertFalse(Files.isSymbolicLink(empty.toPath()))
|
||||
assertEquals(emptyList<String>(), empty.list()!!.toList())
|
||||
assertEquals("kept", File(root, "home/keep/file").readText())
|
||||
}
|
||||
|
||||
@Test fun aFreshRuntimeGetsNoOldNames() {
|
||||
write("usr/local/bin/droiddeck-session", "new")
|
||||
LegacyNames.migrateRootfs(root)
|
||||
|
||||
@@ -181,17 +181,6 @@ class ProtonExtrasTest {
|
||||
assertEquals(emptyList<String>(), ProtonExtras.installedIn(File(tools, "missing"), tool("ge")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun x86_64BuildsAreNotTakenForTheArm64Tool() {
|
||||
val tools = temp.newFolder("compatibilitytools.d")
|
||||
for (name in listOf("DroidDeck-Proton 11-7.5", "DroidDeck-Proton-11-14.2-x86_64")) installTool(tools, name)
|
||||
File(tools, "DroidDeck-Proton-11-14.2-x86_64/files/lib/wine/x86_64-unix").mkdirs()
|
||||
File(tools, "DroidDeck-Proton 11-7.5/files/lib/wine/x86_64-unix").mkdirs()
|
||||
File(tools, "DroidDeck-Proton 11-7.5/files/bin-arm64").mkdirs()
|
||||
assertEquals(listOf("DroidDeck-Proton 11-7.5"), ProtonExtras.installedIn(tools, tool("droiddeck")))
|
||||
assertTrue(ProtonExtras.x86_64Build(File(tools, "DroidDeck-Proton-11-14.2-x86_64")))
|
||||
}
|
||||
|
||||
@Test
|
||||
fun interruptedBuildsAreNotReportedAsInstalled() {
|
||||
val tools = temp.newFolder("compatibilitytools.d")
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
# Easy Anti-Cheat and BattlEye
|
||||
|
||||
On a Steam Deck, Proton loads Valve's anti-cheat runtimes (Proton EasyAntiCheat Runtime, app 1826330, and
|
||||
Proton BattlEye Runtime, app 1161040). Their bridge libraries are x86 only, so the ARM64 DroidDeck-Proton
|
||||
cannot load them. Games that need them run an x86-64 DroidDeck-Proton under FEX instead.
|
||||
|
||||
## Routing
|
||||
|
||||
The Proton launchers (`steam-compatibility`: the built-in DroidDeck-Proton launcher and the wrapper put around
|
||||
every tool in `compatibilitytools.d`) check each `run` and `waitforexitandrun` before any ARM64 setup:
|
||||
|
||||
- **Condition.** The game folder (`STEAM_COMPAT_INSTALL_PATH`, three levels deep) holds one of
|
||||
`EasyAntiCheat/Settings.json`, `easyanticheat_x64.so`, `BEClient_x64.so` or `BEService_x64.exe`. No
|
||||
title, app ID or device list is involved.
|
||||
- **Tool.** The newest `compatibilitytools.d/DroidDeck-Proton*` whose layout is x86-64
|
||||
(`files/lib/wine/x86_64-unix`, no `files/bin-arm64`).
|
||||
- **Runtime.** `PROTON_EAC_RUNTIME` or `PROTON_BATTLEYE_RUNTIME` when it already points at a folder with the
|
||||
bridge libraries, otherwise the runtime's folder in any Steam library.
|
||||
- **Launch.** `droiddeck-fex proton <tool>/proton <verb> <args>`: FEX with the Steam Linux Runtime rootfs,
|
||||
keeping the game's own `STEAM_COMPAT_DATA_PATH` prefix.
|
||||
|
||||
Without the x86-64 tool or the runtime files the launch stays on ARM64 and the launcher logs why.
|
||||
`DROIDDECK_ANTICHEAT=off` in the game's launch options keeps it on ARM64. Picking the x86-64 tool for a
|
||||
game in Steam always runs it under FEX.
|
||||
|
||||
## Why the x86-64 build needs its own Wine patches
|
||||
|
||||
Android kernels use 39-bit user address spaces. Easy Anti-Cheat's launcher maps fixed memory at
|
||||
`0x7001_0000_0000`, which FEX serves from emulated guest pages (`tools/fex/patches/0026`). The x86-64 Wine
|
||||
in DroidDeck-Proton carries `ntdll-fixed-allocations-above-host-address-limit.patch` (fixed mappings above
|
||||
the host limit go to the emulator) and `ntdll-keep-libc-in-native-syscall-dispatch-range.patch` (the
|
||||
re-armed syscall user dispatch range keeps libc native). Stock x86-64 Proton stops after "Hack native
|
||||
syscalls" on the same game.
|
||||
@@ -172,7 +172,7 @@ there.
|
||||
|
||||
### B. Exec-in-place workers for long-lived processes
|
||||
|
||||
Declare a pool of `android:process` services (`:g0`…`:g95`). Each long-lived program runs as the
|
||||
Declare a pool of `android:process` services (`:g0`…`:g127`). Each long-lived program runs as the
|
||||
main process of one worker (Gap 2): full app privileges, direct GPU, normal signals and `/proc`
|
||||
(same uid and SELinux domain), and the app hears its exit through binder death. Costs and limits:
|
||||
|
||||
@@ -262,8 +262,29 @@ vfork-safe (Python's subprocess execs under `vfork`). Details that mattered:
|
||||
session (KDE Plasma, 17–19 counted at rest), a Konsole running 40 `sleep 600 &` jobs peaked at
|
||||
61 counted and lost 27 processes to Android's limit (Konsole, D-Bus, the portal) before this, and
|
||||
at 20 with no kills after. Still counted, and not handed off: a terminal's foreground jobs (a
|
||||
`make -j` and its compilers), the D-Bus daemon's activation helpers (forks that never exec) and
|
||||
the desktop's own programs started by KDE's launchers.
|
||||
`make -j` and its compilers) and the D-Bus daemon's activation helpers (forks that never exec).
|
||||
- **The desktop.** Plasma's own programs are listed (`startplasma-wayland`, `plasma_session`,
|
||||
KWin, `kded6`, `ksmserver`, `plasmashell`, PowerDevil, KDE Connect, the KIO workers, the D-Bus
|
||||
activated portal, dconf and activity manager) along with DroidDeck's desktop helpers. Discover's
|
||||
update notifier, GeoClue's demo agent and the global-menu proxy are off in the user's Autostart.
|
||||
A program a desktop launcher starts (`DD_HANDOFF_LAUNCHERS`: Plasma's shell, KRunner, Dolphin)
|
||||
goes to a worker when it is a plain fork and exec: in the launcher's process group and session,
|
||||
with no controlling terminal. Those launchers are Qt programs, which wait with `waitpid()` once
|
||||
the hook has taken their pidfds away. A terminal's shell (its own session and terminal) stays.
|
||||
Firefox runs with fission off, at most two web content processes and no crash helper. The
|
||||
desktop and its apps use about 80 workers with Steam and a game running, hence 128.
|
||||
|
||||
Counted children on the Thor (main: the session as #3338 and #3594 left it):
|
||||
|
||||
| | main | this |
|
||||
|---|---|---|
|
||||
| desktop at rest | 30 | 0 |
|
||||
| Dolphin, Konsole, Firefox, Kate and System Settings open | not measured (49 on a Pocket FIT without Firefox, the terminal running 40 jobs) | 7 |
|
||||
| those, the desktop's Steam client and Bully running | not measured | 20 (30 with 64 workers: Wine's services were refused one) |
|
||||
|
||||
With Bully running, six scans forced with the stock limit of 32 killed nothing. What stays
|
||||
counted then: Steam's client and launch chain (10), Firefox's helpers (6), Konsole's shell,
|
||||
Proton's script and `wineserver`.
|
||||
|
||||
Default list: the portals, at-spi, `python3`, PipeWire, WirePlumber, Decky's PluginLoader, the log's
|
||||
`gnudd`, `xprop -spy`, the web helper's renderers, `wine`, `wine-preloader`, `wineserver`.
|
||||
@@ -510,6 +531,35 @@ the old behavior and the old requirement.
|
||||
7. A (the isolated tier) only if B stops working on a future Android; it needs a file and socket
|
||||
broker and keeps the GPU outside.
|
||||
|
||||
## Zombies
|
||||
|
||||
Every session process is a child subreaper (`tools/linuxfs/preload/subreaper.c`, so that a
|
||||
double-forked Xwayland is not left to init, which some vendor kernels kill), and most programs
|
||||
never wait for a child they did not fork. What they adopted stayed a zombie: the grandchildren of
|
||||
Qt's `startDetached()` under Plasma's shell, KWin and kaccess, Wine's double-forked processes,
|
||||
wlroots' Xwayland under gamescope. A parent that never waits at all (Plasma's shell, for what it
|
||||
launches) also kept the forked child of each program it handed off. On the Thor, main had 4
|
||||
zombies in Steam mode at rest and 19 in Bully, and the desktop gained one per app closed.
|
||||
|
||||
The hook now reaps them from SIGCHLD (`ddh_reap_unclaimed()`):
|
||||
|
||||
- **Adopted:** each process records, at its pid, the parent that started it and its own start
|
||||
time, in one file for the session (`DD_PARENTS`). A fork's child does it at the fork, any other
|
||||
program at its start. A zombie child whose record names another parent was adopted. An own child
|
||||
(recorded with this parent, or with no record, such as a static program a `vfork()` started) is
|
||||
left for its program's wait.
|
||||
- **A handed-off program's forked child,** as a wait's look reaps it: the program's exit stays in
|
||||
the table for the parent's wait.
|
||||
|
||||
The program's SIGCHLD action runs first, and `sigaction()` shows it as the program set it.
|
||||
`SIG_IGN` and `SA_NOCLDWAIT` stay the kernel's. A program that leaves SIGCHLD alone gets the
|
||||
handler only when `DD_REAP_ADOPTED` names it (Plasma's programs, D-Bus, gamescope, Wine's
|
||||
launchers, Decky's loader): with a handler, `poll()`, `sleep()` and the like return `EINTR` when a
|
||||
child exits. With these changes there are no zombies left in either mode, Bully included.
|
||||
|
||||
qemu-user has no `PR_SET_CHILD_SUBREAPER`, so the adoption tests skip under it (CI) and were run on
|
||||
the Thor's kernel.
|
||||
|
||||
## Robustness
|
||||
|
||||
- Gap 1's path mismatch is a bug that could be fixed; the app-zygote skip is deliberate. Use app
|
||||
|
||||
@@ -87,6 +87,11 @@ static const char *rewrite_path(const char *path, char *out, size_t size) {
|
||||
return path;
|
||||
}
|
||||
|
||||
// The native hook's SIGCHLD handling (hook/signals.c) is not part of this shim: its programs record their
|
||||
// first parent for the session's subreapers, and reap nothing themselves.
|
||||
static void ddnatv_manage_sigchld(void) {}
|
||||
static void ddh_reap_unclaimed(void) __attribute__((unused));
|
||||
|
||||
#include "../nativeguest/hook/kept.c"
|
||||
#include "../nativeguest/hook/handoff.c"
|
||||
|
||||
@@ -315,12 +320,14 @@ pid_t fork(void) {
|
||||
}
|
||||
ddh_prepare();
|
||||
pid_t forker = (pid_t)syscall(SYS_gettid);
|
||||
pid_t forking = (pid_t)syscall(SYS_getpid);
|
||||
pid_t pid = orig_fork();
|
||||
if (pid == 0) {
|
||||
kept_forked();
|
||||
kept_close_forked();
|
||||
ddh_drop_worker_binder();
|
||||
ddh_forked(forker);
|
||||
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
|
||||
} else if (pid > 0) {
|
||||
ddh_child_created(pid, 1);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,132 +0,0 @@
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Subject: [PATCH] List only guest mappings in /proc/<pid>/maps on hosts below 47 address bits
|
||||
|
||||
Builds on StonkGuy's /proc emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index 1b2396b01..156e3964c 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -17,7 +17,11 @@ $end_info$
|
||||
#include <FEXCore/Config/Config.h>
|
||||
#include <FEXCore/Core/Context.h>
|
||||
#include <FEXCore/Core/CPUID.h>
|
||||
+#include <FEXCore/Utils/Allocator.h>
|
||||
#include <FEXCore/Utils/LogManager.h>
|
||||
+#include <FEXCore/Utils/SignalScopeGuards.h>
|
||||
+#include <FEXCore/fextl/unordered_map.h>
|
||||
+#include <FEXCore/fextl/vector.h>
|
||||
#include <FEXCore/fextl/fmt.h>
|
||||
#include <FEXCore/fextl/string.h>
|
||||
#include <FEXCore/fextl/sstream.h>
|
||||
@@ -25,9 +29,13 @@ $end_info$
|
||||
|
||||
#include <git_version.h>
|
||||
|
||||
+#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
+#include <elf.h>
|
||||
+#include <mutex>
|
||||
+#include <shared_mutex>
|
||||
#include <fcntl.h>
|
||||
#include <filesystem>
|
||||
#include <ostream>
|
||||
@@ -608,6 +616,37 @@ EmulatedFDManager::EmulatedFDManager(FEXCore::Context::Context* ctx)
|
||||
|
||||
EmulatedFDManager::~EmulatedFDManager() {}
|
||||
|
||||
+static bool IsSelfProcPath(const char* Path) {
|
||||
+ const char* P = Path + 6;
|
||||
+ if (!isdigit(*P)) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ return strtol(P, nullptr, 10) == ::getpid();
|
||||
+}
|
||||
+
|
||||
+static bool IsHostArchModule(const char* Path, fextl::unordered_map<fextl::string, bool>& Seen) {
|
||||
+ auto Known = Seen.find(Path);
|
||||
+ if (Known != Seen.end()) {
|
||||
+ return Known->second;
|
||||
+ }
|
||||
+ bool Host = false;
|
||||
+ int FD = ::open(Path, O_RDONLY | O_CLOEXEC);
|
||||
+ if (FD >= 0) {
|
||||
+ Elf64_Ehdr Header {};
|
||||
+ if (::pread(FD, &Header, sizeof(Header), 0) >= static_cast<ssize_t>(offsetof(Elf64_Ehdr, e_version)) &&
|
||||
+ memcmp(Header.e_ident, ELFMAG, SELFMAG) == 0) {
|
||||
+#if defined(__aarch64__)
|
||||
+ Host = Header.e_machine == EM_AARCH64;
|
||||
+#else
|
||||
+ Host = Header.e_machine != EM_X86_64 && Header.e_machine != EM_386;
|
||||
+#endif
|
||||
+ }
|
||||
+ ::close(FD);
|
||||
+ }
|
||||
+ Seen.emplace(Path, Host);
|
||||
+ return Host;
|
||||
+}
|
||||
+
|
||||
static bool IsProcMapsPath(const char* Path) {
|
||||
if (strncmp(Path, "/proc/", 6) != 0) {
|
||||
return false;
|
||||
@@ -660,14 +699,56 @@ int32_t EmulatedFDManager::ProcMaps(FEXCore::Context::Context* ctx, int32_t fd,
|
||||
::close(HostFD);
|
||||
|
||||
constexpr uint64_t X86_64TaskSizeMax = (1ULL << 47) - 4096;
|
||||
+ const bool HostSharesGuestRange = FEXCore::Allocator::GetHostVABits() < 47;
|
||||
+ const bool Self = IsSelfProcPath(pathname);
|
||||
+ fextl::vector<std::pair<uint64_t, uint64_t>> GuestRanges;
|
||||
+ if (HostSharesGuestRange && Self && FEX::HLE::_SyscallHandler) {
|
||||
+ auto lk = FEXCore::MaskSignalsAndLockMutex<std::shared_lock>(FEX::HLE::_SyscallHandler->VMATracking.Mutex);
|
||||
+ GuestRanges.reserve(FEX::HLE::_SyscallHandler->VMATracking.VMAs.size());
|
||||
+ for (const auto& [Base, VMA] : FEX::HLE::_SyscallHandler->VMATracking.VMAs) {
|
||||
+ if (!GuestRanges.empty() && GuestRanges.back().second >= Base) {
|
||||
+ GuestRanges.back().second = std::max(GuestRanges.back().second, Base + VMA.Length);
|
||||
+ } else {
|
||||
+ GuestRanges.emplace_back(Base, Base + VMA.Length);
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ auto IsGuestRange = [&GuestRanges](uint64_t Start, uint64_t End) {
|
||||
+ auto It = std::upper_bound(GuestRanges.begin(), GuestRanges.end(), Start,
|
||||
+ [](uint64_t Value, const std::pair<uint64_t, uint64_t>& Range) { return Value < Range.first; });
|
||||
+ if (It != GuestRanges.begin() && std::prev(It)->second > Start) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ return It != GuestRanges.end() && It->first < End;
|
||||
+ };
|
||||
+ fextl::unordered_map<fextl::string, bool> ModuleArch;
|
||||
fextl::string Out;
|
||||
Out.reserve(In.size());
|
||||
size_t Pos = 0;
|
||||
while (Pos < In.size()) {
|
||||
size_t Eol = In.find('\n', Pos);
|
||||
const size_t End = Eol == fextl::string::npos ? In.size() : Eol + 1;
|
||||
- const uint64_t Start = strtoull(In.c_str() + Pos, nullptr, 16);
|
||||
- if (Start < X86_64TaskSizeMax) {
|
||||
+ char* Cursor {};
|
||||
+ const uint64_t Start = strtoull(In.c_str() + Pos, &Cursor, 16);
|
||||
+ const uint64_t Stop = *Cursor == '-' ? strtoull(Cursor + 1, nullptr, 16) : Start;
|
||||
+ bool Keep = Start < X86_64TaskSizeMax;
|
||||
+ if (Keep && HostSharesGuestRange) {
|
||||
+ if (Self) {
|
||||
+ Keep = IsGuestRange(Start, Stop);
|
||||
+ } else {
|
||||
+ const size_t LineEnd = Eol == fextl::string::npos ? In.size() : Eol;
|
||||
+ size_t Name = In.find_first_of("/[", Pos);
|
||||
+ if (Name != fextl::string::npos && Name < LineEnd) {
|
||||
+ fextl::string Path(In, Name, LineEnd - Name);
|
||||
+ if (Path.starts_with("[anon:FEX")) {
|
||||
+ Keep = false;
|
||||
+ } else if (Path[0] == '/') {
|
||||
+ Keep = !IsHostArchModule(Path.c_str(), ModuleArch);
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+ if (Keep) {
|
||||
Out.append(In, Pos, End - Pos);
|
||||
}
|
||||
Pos = End;
|
||||
@@ -1,53 +0,0 @@
|
||||
From 597bfab6ff068e0f6c08f63d6940486446967b0d Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:21:23 -0500
|
||||
Subject: [PATCH] Report the calling thread's seccomp mode in /proc/self/status
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
.../LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp | 6 +++++-
|
||||
.../Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h | 10 ++++++++++
|
||||
2 files changed, 15 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index 156e3964c..c1a91d122 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -796,7 +796,11 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
|
||||
Buf[Len] = '\0';
|
||||
|
||||
uint32_t SeccompMode = SECCOMP_MODE_DISABLED;
|
||||
- if (auto* Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject()) {
|
||||
+ auto* Thread = FEX::HLE::_SyscallHandler ? FEX::HLE::_SyscallHandler->TM.FindThreadByTID(::gettid()) : nullptr;
|
||||
+ if (!Thread) {
|
||||
+ Thread = FEX::HLE::ThreadManager::GetCurrentThreadObject();
|
||||
+ }
|
||||
+ if (Thread) {
|
||||
SeccompMode = Thread->SeccompMode;
|
||||
}
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
index c5bfe3c25..657de6ceb 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
@@ -289,6 +289,16 @@ public:
|
||||
return &Threads;
|
||||
}
|
||||
|
||||
+ FEX::HLE::ThreadStateObject* FindThreadByTID(uint32_t TID) {
|
||||
+ std::lock_guard lk(ThreadCreationMutex);
|
||||
+ for (auto* Thread : Threads) {
|
||||
+ if (Thread->ThreadInfo.TID == TID) {
|
||||
+ return Thread;
|
||||
+ }
|
||||
+ }
|
||||
+ return nullptr;
|
||||
+ }
|
||||
+
|
||||
private:
|
||||
struct InvalidationStats {
|
||||
explicit InvalidationStats(FEXCore::Core::InternalThreadState* Thread)
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -1,105 +0,0 @@
|
||||
From ab6a01db9e93e7f143b9a3da5b40dcb160b960f3 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:25:20 -0500
|
||||
Subject: [PATCH] Read FEX's own /proc/self/status with a direct openat system
|
||||
call
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
FEXHeaderUtils/FEXHeaderUtils/Syscalls.h | 30 +++++++++++++++++++
|
||||
.../EmulatedFiles/EmulatedFiles.cpp | 3 +-
|
||||
.../LinuxSyscalls/PtraceEmu.cpp | 3 +-
|
||||
3 files changed, 34 insertions(+), 2 deletions(-)
|
||||
|
||||
diff --git a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
index dae3d3bcc..c0f3eb3ed 100644
|
||||
--- a/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
+++ b/FEXHeaderUtils/FEXHeaderUtils/Syscalls.h
|
||||
@@ -4,6 +4,7 @@
|
||||
#include <FEXCore/Utils/LogManager.h>
|
||||
|
||||
#include <cstdint>
|
||||
+#include <errno.h>
|
||||
#include <sched.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
@@ -123,4 +124,33 @@ inline int32_t gettid() {
|
||||
|
||||
#endif
|
||||
|
||||
+#ifndef _WIN32
|
||||
+inline int32_t openat_kernel(int dirfd, const char* pathname, int flags) {
|
||||
+#if defined(__aarch64__)
|
||||
+ register long x0 asm("x0") = dirfd;
|
||||
+ register long x1 asm("x1") = reinterpret_cast<long>(pathname);
|
||||
+ register long x2 asm("x2") = flags;
|
||||
+ register long x3 asm("x3") = 0;
|
||||
+ register long x8 asm("x8") = SYS_openat;
|
||||
+ asm volatile("svc #0" : "+r"(x0) : "r"(x1), "r"(x2), "r"(x3), "r"(x8) : "memory");
|
||||
+ if (x0 < 0) {
|
||||
+ errno = static_cast<int>(-x0);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ return static_cast<int32_t>(x0);
|
||||
+#elif defined(__x86_64__)
|
||||
+ long ret;
|
||||
+ register long r10 asm("r10") = 0;
|
||||
+ asm volatile("syscall" : "=a"(ret) : "a"(SYS_openat), "D"(dirfd), "S"(pathname), "d"(flags), "r"(r10) : "rcx", "r11", "memory");
|
||||
+ if (ret < 0) {
|
||||
+ errno = static_cast<int>(-ret);
|
||||
+ return -1;
|
||||
+ }
|
||||
+ return static_cast<int32_t>(ret);
|
||||
+#else
|
||||
+ return static_cast<int32_t>(::syscall(SYS_openat, dirfd, pathname, flags));
|
||||
+#endif
|
||||
+}
|
||||
+#endif
|
||||
+
|
||||
} // namespace FHU::Syscalls
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
index c1a91d122..49adaaa66 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/EmulatedFiles/EmulatedFiles.cpp
|
||||
@@ -14,6 +14,7 @@ $end_info$
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
#include "LinuxSyscalls/EmulatedFiles/EmulatedFiles.h"
|
||||
|
||||
+#include <FEXHeaderUtils/Syscalls.h>
|
||||
#include <FEXCore/Config/Config.h>
|
||||
#include <FEXCore/Core/Context.h>
|
||||
#include <FEXCore/Core/CPUID.h>
|
||||
@@ -784,7 +785,7 @@ int32_t EmulatedFDManager::ProcStatus(FEXCore::Context::Context* ctx, int32_t fd
|
||||
char Buf[8192];
|
||||
ssize_t Len = 0;
|
||||
{
|
||||
- int HostFD = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
+ int HostFD = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
if (HostFD >= 0) {
|
||||
Len = ::read(HostFD, Buf, sizeof(Buf) - 1);
|
||||
::close(HostFD);
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
index ca4c86063..49ece24a3 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
@@ -3,6 +3,7 @@
|
||||
#include "LinuxSyscalls/PtraceEmu.h"
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
|
||||
+#include <FEXHeaderUtils/Syscalls.h>
|
||||
#include <FEXCore/Core/CoreState.h>
|
||||
#include <FEXCore/Core/X86Enums.h>
|
||||
|
||||
@@ -133,7 +134,7 @@ namespace {
|
||||
}
|
||||
|
||||
bool HasHostTracer() {
|
||||
- const int fd = ::open("/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
+ const int fd = FHU::Syscalls::openat_kernel(AT_FDCWD, "/proc/self/status", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) {
|
||||
return true;
|
||||
}
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
From 38ee3ef08d9bfd8312fccff688290572da82ef2a Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:41:52 -0500
|
||||
Subject: [PATCH] Hand the tracee's ptrace state across exec
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
|
||||
---
|
||||
.../LinuxSyscalls/PtraceEmu.cpp | 54 ++++++++++++++++++-
|
||||
1 file changed, 53 insertions(+), 1 deletion(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
index 49ece24a3..62acdb0da 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/PtraceEmu.cpp
|
||||
@@ -266,6 +266,38 @@ namespace {
|
||||
::close(fd);
|
||||
}
|
||||
|
||||
+ bool AdoptionTried = false;
|
||||
+
|
||||
+ void AdoptSharedPage() {
|
||||
+ if (AdoptionTried || Current != &StaticState || !IsMainThread()) {
|
||||
+ return;
|
||||
+ }
|
||||
+ AdoptionTried = true;
|
||||
+ const int fd = OpenSidecar("state", ::getpid(), O_RDWR);
|
||||
+ if (fd < 0) {
|
||||
+ return;
|
||||
+ }
|
||||
+ if (!HasHostTracer()) {
|
||||
+ ::close(fd);
|
||||
+ return;
|
||||
+ }
|
||||
+ void* Page = ::mmap(nullptr, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
+ ::close(fd);
|
||||
+ if (Page == MAP_FAILED) {
|
||||
+ return;
|
||||
+ }
|
||||
+ auto* S = static_cast<SharedState*>(Page);
|
||||
+ if (S->Magic != SharedState::MagicValue) {
|
||||
+ ::munmap(Page, 4096);
|
||||
+ return;
|
||||
+ }
|
||||
+ S->Pending = 0;
|
||||
+ S->DirtyMask = 0;
|
||||
+ S->SignalNumber = 0;
|
||||
+ S->FlushLen = 0;
|
||||
+ Current = S;
|
||||
+ }
|
||||
+
|
||||
struct Remote {
|
||||
uint8_t* Mapped = nullptr;
|
||||
uintptr_t StaticAddr = 0;
|
||||
@@ -332,6 +364,22 @@ namespace {
|
||||
return &Remotes.emplace(Pid, std::move(R)).first->second;
|
||||
}
|
||||
|
||||
+ bool KeepAcrossExec(pid_t Pid) {
|
||||
+ {
|
||||
+ std::lock_guard lk(RemotesLock);
|
||||
+ auto It = Remotes.find(Pid);
|
||||
+ if (It != Remotes.end()) {
|
||||
+ return It->second.Mapped != nullptr;
|
||||
+ }
|
||||
+ }
|
||||
+ const int fd = OpenSidecar("state", Pid, O_RDONLY);
|
||||
+ if (fd < 0) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ ::close(fd);
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
void Forget(pid_t Pid, bool Exited) {
|
||||
std::lock_guard lk(RemotesLock);
|
||||
auto It = Remotes.find(Pid);
|
||||
@@ -470,10 +518,12 @@ namespace {
|
||||
|
||||
|
||||
bool IsAttached() {
|
||||
+ AdoptSharedPage();
|
||||
return Current->Attached != 0;
|
||||
}
|
||||
|
||||
bool WantsSyscallStops() {
|
||||
+ AdoptSharedPage();
|
||||
return Current->SyscallStops && IsMainThread();
|
||||
}
|
||||
|
||||
@@ -610,7 +660,9 @@ bool FixupWaitStatus(pid_t Pid, int* Status) {
|
||||
|
||||
if ((St >> 16) == X86_PTRACE_EVENT_EXEC) {
|
||||
CaptureExecPath(Pid);
|
||||
- Forget(Pid, false);
|
||||
+ if (!KeepAcrossExec(Pid)) {
|
||||
+ Forget(Pid, false);
|
||||
+ }
|
||||
}
|
||||
|
||||
if (WSTOPSIG(St) == SIGSTOP) {
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
From 834075bdee10fb0a1c7a7f499a0bb97162370b5d Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 18:58:13 -0500
|
||||
Subject: [PATCH] Serve emulated proc files by the requested path when the host
|
||||
returns a memfd
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
---
|
||||
.../LinuxEmulation/LinuxSyscalls/FileManagement.cpp | 11 +++++++----
|
||||
.../LinuxEmulation/LinuxSyscalls/FileManagement.h | 2 +-
|
||||
2 files changed, 8 insertions(+), 5 deletions(-)
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
index 62b6a2d27..b76e96e58 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.cpp
|
||||
@@ -785,7 +785,7 @@ static int OpenatWithoutOpenat2(int DirFD, const char* Pathname, int Flags, uint
|
||||
return ::syscall(SYSCALL_DEF(openat), DirFD, Resolved, Flags, Mode);
|
||||
}
|
||||
|
||||
-bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
|
||||
+bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath) {
|
||||
char Tmp[PATH_MAX + 1];
|
||||
|
||||
if (fd < 0) {
|
||||
@@ -801,6 +801,9 @@ bool FileManager::ReplaceEmuFd(int fd, int flags, uint32_t mode) {
|
||||
|
||||
// And try to open via EmuFD
|
||||
auto EmuFd = EmuFD.Open(Tmp, flags, mode);
|
||||
+ if (EmuFd == -1 && RequestedPath && RequestedPath[0] == '/' && strncmp(Tmp, "/memfd:", 7) == 0) {
|
||||
+ EmuFd = EmuFD.Open(RequestedPath, flags, mode);
|
||||
+ }
|
||||
if (EmuFd == -1) {
|
||||
return false;
|
||||
}
|
||||
@@ -841,7 +844,7 @@ uint64_t FileManager::Open(const char* pathname, int flags, uint32_t mode) {
|
||||
fd = ::open(SelfPath, flags, mode);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, flags, mode);
|
||||
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
|
||||
} else {
|
||||
fd = ::open(SelfPath, flags, mode);
|
||||
}
|
||||
@@ -1135,7 +1138,7 @@ uint64_t FileManager::Openat([[maybe_unused]] int dirfs, const char* pathname, i
|
||||
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, flags, mode);
|
||||
+ ReplaceEmuFd(fd, flags, mode, SelfPath);
|
||||
} else {
|
||||
fd = ::syscall(SYSCALL_DEF(openat), dirfs, SelfPath, flags, mode);
|
||||
}
|
||||
@@ -1173,7 +1176,7 @@ uint64_t FileManager::Openat2(int dirfs, const char* pathname, FEX::HLE::open_ho
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
|
||||
}
|
||||
|
||||
- ReplaceEmuFd(fd, how->flags, how->mode);
|
||||
+ ReplaceEmuFd(fd, how->flags, how->mode, SelfPath);
|
||||
} else {
|
||||
fd = ::syscall(SYSCALL_DEF(openat2), dirfs, SelfPath, how, usize);
|
||||
}
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
index b11f096f7..a86539972 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/FileManagement.h
|
||||
@@ -102,7 +102,7 @@ public:
|
||||
fextl::string GetEmulatedPath(const char* pathname, bool FollowSymlink = false) const;
|
||||
fextl::string GetHostPath(fextl::string& Path, bool AliasedOnly) const;
|
||||
|
||||
- bool ReplaceEmuFd(int fd, int flags, uint32_t mode);
|
||||
+ bool ReplaceEmuFd(int fd, int flags, uint32_t mode, const char* RequestedPath);
|
||||
|
||||
#if defined(ASSERTIONS_ENABLED) && ASSERTIONS_ENABLED
|
||||
void TrackFEXFD(int FD) noexcept {
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -1,781 +0,0 @@
|
||||
From 4e237204720bf57c8e4b7dae1ff74b5e341763e6 Mon Sep 17 00:00:00 2001
|
||||
From: maxjivi05 <maxjividen@gmail.com>
|
||||
Date: Wed, 2 Dec 2026 20:01:44 -0500
|
||||
Subject: [PATCH] Map fixed guest memory above a small host address space
|
||||
|
||||
Hosts with 39-bit or 42-bit user address spaces cannot place x86-64
|
||||
mappings that ask for a fixed address above that limit. Such mappings
|
||||
are now backed by host memory at any address, and guest accesses to
|
||||
them are redirected through a per-thread single-instruction trampoline.
|
||||
Syscall arguments that point into these mappings are translated, and
|
||||
writes to code in them invalidate translated blocks.
|
||||
|
||||
Builds on StonkGuy's anti-cheat emulation from https://github.com/StonkGuy/FEX (eac-2611, MIT).
|
||||
---
|
||||
Source/Tools/LinuxEmulation/CMakeLists.txt | 1 +
|
||||
.../LinuxSyscalls/GuestHighMemory.cpp | 439 ++++++++++++++++++
|
||||
.../LinuxSyscalls/GuestHighMemory.h | 26 ++
|
||||
.../LinuxSyscalls/SignalDelegator.cpp | 5 +
|
||||
.../LinuxEmulation/LinuxSyscalls/Syscalls.cpp | 30 +-
|
||||
.../LinuxSyscalls/SyscallsSMCTracking.cpp | 58 ++-
|
||||
.../LinuxSyscalls/ThreadManager.cpp | 2 +
|
||||
.../LinuxSyscalls/ThreadManager.h | 12 +
|
||||
8 files changed, 551 insertions(+), 22 deletions(-)
|
||||
create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
|
||||
create mode 100644 Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/CMakeLists.txt b/Source/Tools/LinuxEmulation/CMakeLists.txt
|
||||
index 3f02104ea..acf4c4c13 100644
|
||||
--- a/Source/Tools/LinuxEmulation/CMakeLists.txt
|
||||
+++ b/Source/Tools/LinuxEmulation/CMakeLists.txt
|
||||
@@ -18,6 +18,7 @@ add_library(LinuxEmulation STATIC
|
||||
LinuxSyscalls/Seccomp/BPFEmitter.cpp
|
||||
LinuxSyscalls/Seccomp/Dumper.cpp
|
||||
LinuxSyscalls/SignalDelegator.cpp
|
||||
+ LinuxSyscalls/GuestHighMemory.cpp
|
||||
LinuxSyscalls/Syscalls.cpp
|
||||
LinuxSyscalls/SyscallsSMCTracking.cpp
|
||||
LinuxSyscalls/SyscallsVMATracking.cpp
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
|
||||
new file mode 100644
|
||||
index 000000000..a097f97fa
|
||||
--- /dev/null
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.cpp
|
||||
@@ -0,0 +1,439 @@
|
||||
+#include "LinuxSyscalls/GuestHighMemory.h"
|
||||
+#include "LinuxSyscalls/Syscalls.h"
|
||||
+#include "LinuxSyscalls/SignalDelegator.h"
|
||||
+#include "LinuxSyscalls/ThreadManager.h"
|
||||
+#include "ArchHelpers/MContext.h"
|
||||
+
|
||||
+#include <FEXCore/Debug/InternalThreadState.h>
|
||||
+#include <FEXCore/Utils/Allocator.h>
|
||||
+#include <FEXCore/Utils/AllocatorHooks.h>
|
||||
+#include <FEXCore/Utils/MathUtils.h>
|
||||
+#include <FEXCore/Utils/TypeDefines.h>
|
||||
+
|
||||
+#include <algorithm>
|
||||
+#include <atomic>
|
||||
+#include <cerrno>
|
||||
+#include <csignal>
|
||||
+#include <cstring>
|
||||
+#include <sys/mman.h>
|
||||
+
|
||||
+namespace FEX::HLE::GuestHighMemory {
|
||||
+namespace {
|
||||
+ constexpr uint64_t TaskTop = (1ULL << 47) - FEXCore::Utils::FEX_PAGE_SIZE;
|
||||
+ constexpr uint32_t MaxRegions = 1024;
|
||||
+
|
||||
+ struct Region {
|
||||
+ std::atomic<uint64_t> Guest;
|
||||
+ std::atomic<uint64_t> Size;
|
||||
+ std::atomic<uint64_t> Host;
|
||||
+ std::atomic<bool> Code;
|
||||
+ };
|
||||
+
|
||||
+ struct RegionView {
|
||||
+ uint64_t Guest;
|
||||
+ uint64_t Size;
|
||||
+ uint64_t Host;
|
||||
+ uint32_t Index;
|
||||
+ bool Code;
|
||||
+ };
|
||||
+
|
||||
+ Region Regions[MaxRegions];
|
||||
+ std::atomic<uint32_t> Count {0};
|
||||
+ std::atomic<uint32_t> Sequence {0};
|
||||
+
|
||||
+ uint64_t HostLimit() {
|
||||
+ static const uint64_t Limit = [] {
|
||||
+ const auto Bits = FEXCore::Allocator::GetHostVABits();
|
||||
+ return Bits >= 47 ? TaskTop : (1ULL << Bits);
|
||||
+ }();
|
||||
+ return Limit;
|
||||
+ }
|
||||
+
|
||||
+ void BeginWrite() {
|
||||
+ Sequence.fetch_add(1, std::memory_order_acq_rel);
|
||||
+ }
|
||||
+
|
||||
+ void EndWrite() {
|
||||
+ Sequence.fetch_add(1, std::memory_order_release);
|
||||
+ }
|
||||
+
|
||||
+ bool Lookup(uint64_t Address, RegionView* Out) {
|
||||
+ for (;;) {
|
||||
+ const auto Before = Sequence.load(std::memory_order_acquire);
|
||||
+ if (Before & 1) {
|
||||
+ continue;
|
||||
+ }
|
||||
+ bool Found = false;
|
||||
+ const auto Entries = Count.load(std::memory_order_acquire);
|
||||
+ for (uint32_t i = 0; i < Entries; ++i) {
|
||||
+ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed);
|
||||
+ const auto Size = Regions[i].Size.load(std::memory_order_relaxed);
|
||||
+ if (Address >= Guest && Address - Guest < Size) {
|
||||
+ Out->Guest = Guest;
|
||||
+ Out->Size = Size;
|
||||
+ Out->Host = Regions[i].Host.load(std::memory_order_relaxed);
|
||||
+ Out->Code = Regions[i].Code.load(std::memory_order_relaxed);
|
||||
+ Out->Index = i;
|
||||
+ Found = true;
|
||||
+ break;
|
||||
+ }
|
||||
+ }
|
||||
+ std::atomic_thread_fence(std::memory_order_acquire);
|
||||
+ if (Sequence.load(std::memory_order_relaxed) == Before) {
|
||||
+ return Found;
|
||||
+ }
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ void SetEntry(uint32_t i, uint64_t Guest, uint64_t Size, uint64_t Host, bool Code) {
|
||||
+ Regions[i].Guest.store(Guest, std::memory_order_relaxed);
|
||||
+ Regions[i].Size.store(Size, std::memory_order_relaxed);
|
||||
+ Regions[i].Host.store(Host, std::memory_order_relaxed);
|
||||
+ Regions[i].Code.store(Code, std::memory_order_relaxed);
|
||||
+ }
|
||||
+
|
||||
+ void RemoveEntry(uint32_t i) {
|
||||
+ const auto Last = Count.load(std::memory_order_relaxed) - 1;
|
||||
+ if (i != Last) {
|
||||
+ SetEntry(i, Regions[Last].Guest.load(std::memory_order_relaxed), Regions[Last].Size.load(std::memory_order_relaxed),
|
||||
+ Regions[Last].Host.load(std::memory_order_relaxed), Regions[Last].Code.load(std::memory_order_relaxed));
|
||||
+ }
|
||||
+ Count.store(Last, std::memory_order_release);
|
||||
+ }
|
||||
+
|
||||
+ bool AddEntry(uint64_t Guest, uint64_t Size, uint64_t Host, bool Code) {
|
||||
+ const auto Entries = Count.load(std::memory_order_relaxed);
|
||||
+ if (Entries >= MaxRegions) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ SetEntry(Entries, Guest, Size, Host, Code);
|
||||
+ Count.store(Entries + 1, std::memory_order_release);
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
+ bool UnmapLocked(uint64_t Address, uint64_t Length) {
|
||||
+ const auto End = Address + Length;
|
||||
+ uint32_t i = 0;
|
||||
+ while (i < Count.load(std::memory_order_relaxed)) {
|
||||
+ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed);
|
||||
+ const auto Size = Regions[i].Size.load(std::memory_order_relaxed);
|
||||
+ const auto Host = Regions[i].Host.load(std::memory_order_relaxed);
|
||||
+ const auto Code = Regions[i].Code.load(std::memory_order_relaxed);
|
||||
+ const auto RegionEnd = Guest + Size;
|
||||
+ if (RegionEnd <= Address || Guest >= End) {
|
||||
+ ++i;
|
||||
+ continue;
|
||||
+ }
|
||||
+ const auto OverlapStart = std::max(Guest, Address);
|
||||
+ const auto OverlapEnd = std::min(RegionEnd, End);
|
||||
+ ::munmap(reinterpret_cast<void*>(Host + (OverlapStart - Guest)), OverlapEnd - OverlapStart);
|
||||
+
|
||||
+ if (OverlapStart == Guest && OverlapEnd == RegionEnd) {
|
||||
+ RemoveEntry(i);
|
||||
+ continue;
|
||||
+ }
|
||||
+ if (OverlapStart == Guest) {
|
||||
+ SetEntry(i, OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code);
|
||||
+ } else if (OverlapEnd == RegionEnd) {
|
||||
+ SetEntry(i, Guest, OverlapStart - Guest, Host, Code);
|
||||
+ } else {
|
||||
+ if (!AddEntry(OverlapEnd, RegionEnd - OverlapEnd, Host + (OverlapEnd - Guest), Code)) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ SetEntry(i, Guest, OverlapStart - Guest, Host, Code);
|
||||
+ }
|
||||
+ ++i;
|
||||
+ }
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
+ constexpr uint32_t RtField(uint32_t Insn) {
|
||||
+ return Insn & 0x1f;
|
||||
+ }
|
||||
+
|
||||
+ constexpr uint32_t RnField(uint32_t Insn) {
|
||||
+ return (Insn >> 5) & 0x1f;
|
||||
+ }
|
||||
+
|
||||
+ constexpr uint32_t Rt2Field(uint32_t Insn) {
|
||||
+ return (Insn >> 10) & 0x1f;
|
||||
+ }
|
||||
+
|
||||
+ constexpr uint32_t RsField(uint32_t Insn) {
|
||||
+ return (Insn >> 16) & 0x1f;
|
||||
+ }
|
||||
+
|
||||
+ constexpr bool IsLoadStore(uint32_t Insn) {
|
||||
+ return (Insn & 0x0a000000) == 0x08000000;
|
||||
+ }
|
||||
+
|
||||
+ constexpr bool IsLiteralLoad(uint32_t Insn) {
|
||||
+ return (Insn & 0x3b000000) == 0x18000000;
|
||||
+ }
|
||||
+
|
||||
+ constexpr bool IsWrite(uint32_t Insn) {
|
||||
+ if ((Insn & 0x3b200c00) == 0x38200000) {
|
||||
+ return ((Insn >> 12) & 0xf) != 0xc;
|
||||
+ }
|
||||
+ if ((Insn & 0x3f200000) == 0x08200000 && Rt2Field(Insn) == 0x1f) {
|
||||
+ return true;
|
||||
+ }
|
||||
+ return (Insn & (1U << 22)) == 0;
|
||||
+ }
|
||||
+
|
||||
+ int PickScratch(uint32_t Insn) {
|
||||
+ constexpr int Candidates[] = {16, 17, 9, 10, 11, 12, 13, 14, 15, 8, 7, 6, 5, 4, 3, 2};
|
||||
+ for (auto Reg : Candidates) {
|
||||
+ const auto R = static_cast<uint32_t>(Reg);
|
||||
+ if (R != RtField(Insn) && R != RnField(Insn) && R != Rt2Field(Insn) && R != RsField(Insn)) {
|
||||
+ return Reg;
|
||||
+ }
|
||||
+ }
|
||||
+ return -1;
|
||||
+ }
|
||||
+
|
||||
+ constexpr uint64_t SynchronousSignalMask() {
|
||||
+ uint64_t Mask = 0;
|
||||
+ for (int Sig : {SIGSEGV, SIGBUS, SIGILL, SIGTRAP, SIGFPE}) {
|
||||
+ Mask |= 1ULL << (Sig - 1);
|
||||
+ }
|
||||
+ return Mask;
|
||||
+ }
|
||||
+
|
||||
+ constexpr uint32_t TrapInstruction = 0xd4200000 | (0xf3e << 5);
|
||||
+} // namespace
|
||||
+
|
||||
+bool Contains(uint64_t Address) {
|
||||
+ return Address >= HostLimit() && Address < TaskTop;
|
||||
+}
|
||||
+
|
||||
+bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags) {
|
||||
+ if (!(Flags & MAP_FIXED) || (Flags & MAP_FIXED_NOREPLACE) || Length == 0) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE);
|
||||
+ return Contains(Address) && Size <= TaskTop - Address;
|
||||
+}
|
||||
+
|
||||
+uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset) {
|
||||
+ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE);
|
||||
+ const int HostFlags = Flags & ~(MAP_FIXED | MAP_FIXED_NOREPLACE);
|
||||
+ void* Host = ::mmap(nullptr, Size, Prot, HostFlags, FD, Offset);
|
||||
+ if (Host == MAP_FAILED) {
|
||||
+ return -errno;
|
||||
+ }
|
||||
+
|
||||
+ BeginWrite();
|
||||
+ bool Ok = UnmapLocked(Address, Size) && AddEntry(Address, Size, reinterpret_cast<uint64_t>(Host), false);
|
||||
+ EndWrite();
|
||||
+ if (!Ok) {
|
||||
+ ::munmap(Host, Size);
|
||||
+ return -ENOMEM;
|
||||
+ }
|
||||
+ return Address;
|
||||
+}
|
||||
+
|
||||
+uint64_t Unmap(uint64_t Address, uint64_t Length) {
|
||||
+ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) {
|
||||
+ return -EINVAL;
|
||||
+ }
|
||||
+ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE);
|
||||
+ if (Size == 0 || Size > TaskTop - Address) {
|
||||
+ return -EINVAL;
|
||||
+ }
|
||||
+ BeginWrite();
|
||||
+ bool Ok = UnmapLocked(Address, Size);
|
||||
+ EndWrite();
|
||||
+ return Ok ? 0 : -ENOMEM;
|
||||
+}
|
||||
+
|
||||
+uint64_t Protect(uint64_t Address, uint64_t Length, int Prot) {
|
||||
+ if (Address & (FEXCore::Utils::FEX_PAGE_SIZE - 1)) {
|
||||
+ return -EINVAL;
|
||||
+ }
|
||||
+ const auto Size = FEXCore::AlignUp(Length, FEXCore::Utils::FEX_PAGE_SIZE);
|
||||
+ if (Size == 0) {
|
||||
+ return 0;
|
||||
+ }
|
||||
+ const auto End = Address + Size;
|
||||
+ uint64_t Covered = 0;
|
||||
+ const auto Entries = Count.load(std::memory_order_acquire);
|
||||
+ for (uint32_t i = 0; i < Entries; ++i) {
|
||||
+ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed);
|
||||
+ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed);
|
||||
+ if (RegionEnd <= Address || Guest >= End) {
|
||||
+ continue;
|
||||
+ }
|
||||
+ const auto OverlapStart = std::max(Guest, Address);
|
||||
+ const auto OverlapEnd = std::min(RegionEnd, End);
|
||||
+ const auto Host = Regions[i].Host.load(std::memory_order_relaxed) + (OverlapStart - Guest);
|
||||
+ if (::mprotect(reinterpret_cast<void*>(Host), OverlapEnd - OverlapStart, Prot) != 0) {
|
||||
+ return -errno;
|
||||
+ }
|
||||
+ Covered += OverlapEnd - OverlapStart;
|
||||
+ }
|
||||
+ return Covered == Size ? 0 : -ENOMEM;
|
||||
+}
|
||||
+
|
||||
+uint64_t ToHost(uint64_t Address) {
|
||||
+ RegionView View;
|
||||
+ if (!Contains(Address) || !Lookup(Address, &View)) {
|
||||
+ return Address;
|
||||
+ }
|
||||
+ return View.Host + (Address - View.Guest);
|
||||
+}
|
||||
+
|
||||
+void MarkCode(uint64_t Address, uint64_t Length) {
|
||||
+ const auto End = Address + Length;
|
||||
+ const auto Entries = Count.load(std::memory_order_acquire);
|
||||
+ for (uint32_t i = 0; i < Entries; ++i) {
|
||||
+ const auto Guest = Regions[i].Guest.load(std::memory_order_relaxed);
|
||||
+ const auto RegionEnd = Guest + Regions[i].Size.load(std::memory_order_relaxed);
|
||||
+ if (RegionEnd > Address && Guest < End) {
|
||||
+ Regions[i].Code.store(true, std::memory_order_relaxed);
|
||||
+ }
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+void TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t NumArgs) {
|
||||
+ if (Count.load(std::memory_order_relaxed) == 0) [[likely]] {
|
||||
+ return;
|
||||
+ }
|
||||
+ switch (Syscall) {
|
||||
+ case 9:
|
||||
+ case 10:
|
||||
+ case 11:
|
||||
+ case 12:
|
||||
+ case 15:
|
||||
+ case 25:
|
||||
+ case 30:
|
||||
+ case 56:
|
||||
+ case 67:
|
||||
+ case 101:
|
||||
+ case 157:
|
||||
+ case 158:
|
||||
+ case 218:
|
||||
+ case 273:
|
||||
+ case 310:
|
||||
+ case 311:
|
||||
+ case 435: return;
|
||||
+ default: break;
|
||||
+ }
|
||||
+ for (uint32_t i = 0; i < NumArgs; ++i) {
|
||||
+ Args[i] = ToHost(Args[i]);
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
+bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) {
|
||||
+ auto* SigInfo = static_cast<siginfo_t*>(Info);
|
||||
+ const auto FaultAddress = reinterpret_cast<uint64_t>(SigInfo->si_addr);
|
||||
+ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread);
|
||||
+ auto& Trap = ThreadObject->HighMemoryTrap;
|
||||
+ const auto PC = ArchHelpers::Context::GetPc(UContext);
|
||||
+
|
||||
+ if (Trap.Active && PC == reinterpret_cast<uint64_t>(Trap.Code)) {
|
||||
+ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch);
|
||||
+ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, Trap.BaseBefore);
|
||||
+ ArchHelpers::Context::SetPc(UContext, Trap.ResumePC - 4);
|
||||
+ memcpy(&ArchHelpers::Context::GetUContext(UContext)->uc_sigmask, &Trap.SavedMask, sizeof(Trap.SavedMask));
|
||||
+ SigInfo->si_addr = reinterpret_cast<void*>(FaultAddress - Trap.Delta);
|
||||
+ Trap.Active = false;
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ if (!Contains(FaultAddress) || Trap.Active) {
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ RegionView View;
|
||||
+ if (!Lookup(FaultAddress, &View)) {
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ const auto Insn = *reinterpret_cast<const uint32_t*>(PC);
|
||||
+ if (!IsLoadStore(Insn) || IsLiteralLoad(Insn) || RnField(Insn) == 31) {
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ if (View.Code && IsWrite(Insn)) {
|
||||
+ const auto FaultBase = FEXCore::AlignDown(FaultAddress, FEXCore::Utils::FEX_PAGE_SIZE);
|
||||
+ FEX::HLE::_SyscallHandler->TM.InvalidateGuestCodeRange(Thread, FaultBase, FEXCore::Utils::FEX_PAGE_SIZE);
|
||||
+
|
||||
+ constexpr uint64_t MaxStoreSize = 64;
|
||||
+ const uint64_t StoreWindowStart = FaultAddress - MaxStoreSize;
|
||||
+ auto CTX = Thread->CTX;
|
||||
+ if (CTX->IsAddressInCodeBuffer(Thread, PC) && !CTX->IsCurrentBlockSingleInst(Thread) &&
|
||||
+ CTX->IsAddressInCurrentBlock(Thread, StoreWindowStart, 2 * MaxStoreSize)) {
|
||||
+ ThreadObject->SignalInfo.Delegator->SpillSRA(Thread, UContext, Thread->CurrentFrame->InSyscallInfo & 0xFFFF);
|
||||
+ const auto& Config = ThreadObject->SignalInfo.Delegator->GetConfig();
|
||||
+ ArchHelpers::Context::SetPc(UContext, Config.AbsoluteLoopTopAddressFillSRA);
|
||||
+ ArchHelpers::Context::SetArmReg(UContext, 1, 1);
|
||||
+ return true;
|
||||
+ }
|
||||
+ }
|
||||
+
|
||||
+ const int Scratch = PickScratch(Insn);
|
||||
+ if (Scratch < 0) {
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ if (!Trap.Code) {
|
||||
+ void* Page = FEXCore::Allocator::VirtualAlloc(FEXCore::Utils::FEX_PAGE_SIZE, true);
|
||||
+ if (Page == MAP_FAILED || Page == nullptr) {
|
||||
+ return false;
|
||||
+ }
|
||||
+ Trap.Code = static_cast<uint8_t*>(Page);
|
||||
+ }
|
||||
+
|
||||
+ const auto Base = RnField(Insn);
|
||||
+ auto* Code = reinterpret_cast<uint32_t*>(Trap.Code);
|
||||
+ Code[0] = (Insn & ~(0x1fU << 5)) | (static_cast<uint32_t>(Scratch) << 5);
|
||||
+ Code[1] = TrapInstruction;
|
||||
+ __builtin___clear_cache(reinterpret_cast<char*>(Code), reinterpret_cast<char*>(Code + 2));
|
||||
+
|
||||
+ Trap.Scratch = Scratch;
|
||||
+ Trap.Base = Base;
|
||||
+ Trap.SavedScratch = ArchHelpers::Context::GetArmReg(UContext, Scratch);
|
||||
+ Trap.BaseBefore = ArchHelpers::Context::GetArmReg(UContext, Base);
|
||||
+ Trap.Delta = View.Host - View.Guest;
|
||||
+ Trap.ResumePC = PC + 4;
|
||||
+
|
||||
+ auto* Mask = &ArchHelpers::Context::GetUContext(UContext)->uc_sigmask;
|
||||
+ memcpy(&Trap.SavedMask, Mask, sizeof(Trap.SavedMask));
|
||||
+ const uint64_t Blocked = ~SynchronousSignalMask();
|
||||
+ memcpy(Mask, &Blocked, sizeof(Blocked));
|
||||
+
|
||||
+ ArchHelpers::Context::SetArmReg(UContext, Scratch, Trap.BaseBefore + Trap.Delta);
|
||||
+ ArchHelpers::Context::SetPc(UContext, reinterpret_cast<uint64_t>(Code));
|
||||
+ Trap.Active = true;
|
||||
+ return true;
|
||||
+}
|
||||
+
|
||||
+bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) {
|
||||
+ auto ThreadObject = FEX::HLE::ThreadManager::GetStateObjectFromFEXCoreThread(Thread);
|
||||
+ auto& Trap = ThreadObject->HighMemoryTrap;
|
||||
+ if (!Trap.Active || ArchHelpers::Context::GetPc(UContext) != reinterpret_cast<uint64_t>(Trap.Code) + 4) {
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
+ const auto ScratchAfter = ArchHelpers::Context::GetArmReg(UContext, Trap.Scratch);
|
||||
+ if (ScratchAfter != Trap.BaseBefore + Trap.Delta) {
|
||||
+ ArchHelpers::Context::SetArmReg(UContext, Trap.Base, ScratchAfter - Trap.Delta);
|
||||
+ }
|
||||
+ ArchHelpers::Context::SetArmReg(UContext, Trap.Scratch, Trap.SavedScratch);
|
||||
+ memcpy(&ArchHelpers::Context::GetUContext(UContext)->uc_sigmask, &Trap.SavedMask, sizeof(Trap.SavedMask));
|
||||
+ ArchHelpers::Context::SetPc(UContext, Trap.ResumePC);
|
||||
+ Trap.Active = false;
|
||||
+ return true;
|
||||
+}
|
||||
+
|
||||
+void ReleaseThread(FEX::HLE::ThreadStateObject* Thread) {
|
||||
+ if (Thread->HighMemoryTrap.Code) {
|
||||
+ FEXCore::Allocator::munmap(Thread->HighMemoryTrap.Code, FEXCore::Utils::FEX_PAGE_SIZE);
|
||||
+ Thread->HighMemoryTrap.Code = nullptr;
|
||||
+ }
|
||||
+}
|
||||
+} // namespace FEX::HLE::GuestHighMemory
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
|
||||
new file mode 100644
|
||||
index 000000000..326b1a37d
|
||||
--- /dev/null
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/GuestHighMemory.h
|
||||
@@ -0,0 +1,26 @@
|
||||
+#pragma once
|
||||
+
|
||||
+#include <cstdint>
|
||||
+#include <sys/types.h>
|
||||
+
|
||||
+namespace FEXCore::Core {
|
||||
+struct InternalThreadState;
|
||||
+}
|
||||
+
|
||||
+namespace FEX::HLE {
|
||||
+struct ThreadStateObject;
|
||||
+}
|
||||
+
|
||||
+namespace FEX::HLE::GuestHighMemory {
|
||||
+bool Contains(uint64_t Address);
|
||||
+bool ClaimsMapping(uint64_t Address, uint64_t Length, int Flags);
|
||||
+uint64_t Map(uint64_t Address, uint64_t Length, int Prot, int Flags, int FD, off_t Offset);
|
||||
+uint64_t Unmap(uint64_t Address, uint64_t Length);
|
||||
+uint64_t Protect(uint64_t Address, uint64_t Length, int Prot);
|
||||
+uint64_t ToHost(uint64_t Address);
|
||||
+void MarkCode(uint64_t Address, uint64_t Length);
|
||||
+void TranslateSyscallArguments(uint64_t Syscall, uint64_t* Args, uint32_t Count);
|
||||
+bool HandleFault(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext);
|
||||
+bool HandleTrap(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext);
|
||||
+void ReleaseThread(FEX::HLE::ThreadStateObject* Thread);
|
||||
+} // namespace FEX::HLE::GuestHighMemory
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
index efe49dbf1..e8723e8f1 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SignalDelegator.cpp
|
||||
@@ -7,6 +7,7 @@ $end_info$
|
||||
*/
|
||||
|
||||
#include "LinuxSyscalls/SignalDelegator.h"
|
||||
+#include "LinuxSyscalls/GuestHighMemory.h"
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
#include "LinuxSyscalls/PtraceEmu.h"
|
||||
#include "LinuxSyscalls/SignalTrace.h"
|
||||
@@ -748,6 +749,10 @@ uint64_t SignalDelegator::GetNewSigMask(int Signal) const {
|
||||
}
|
||||
|
||||
bool SignalDelegator::HandleFrontendSIGSEGV(FEXCore::Core::InternalThreadState* Thread, int Signal, void* Info, void* UContext) {
|
||||
+ if (FEX::HLE::GuestHighMemory::HandleFault(Thread, Signal, Info, UContext)) {
|
||||
+ return true;
|
||||
+ }
|
||||
+
|
||||
auto SigInfo = *static_cast<siginfo_t*>(Info);
|
||||
|
||||
if (FaultSafeUserMemAccess::TryHandleSafeFault(Signal, SigInfo, UContext)) {
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
index 607ab0b97..078faedac 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/Syscalls.cpp
|
||||
@@ -16,6 +16,7 @@ $end_info$
|
||||
#include "LinuxSyscalls/LinuxAllocator.h"
|
||||
#include "LinuxSyscalls/SignalDelegator.h"
|
||||
#include "LinuxSyscalls/PtraceEmu.h"
|
||||
+#include "LinuxSyscalls/GuestHighMemory.h"
|
||||
#include <limits.h>
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
#include "LinuxSyscalls/Syscalls/Thread.h"
|
||||
@@ -820,6 +821,7 @@ SyscallHandler::SyscallHandler(FEXCore::Context::Context* _CTX, FEX::HLE::Signal
|
||||
|
||||
SignalDelegation->RegisterHostSignalHandler(SIGSEGV, HandleSegfault, true);
|
||||
|
||||
+ SignalDelegation->RegisterHostSignalHandler(SIGTRAP, FEX::HLE::GuestHighMemory::HandleTrap, true);
|
||||
SignalDelegation->RegisterHostSignalHandler(
|
||||
SIGTRAP, [](FEXCore::Core::InternalThreadState*, int, void*, void*) { return false; }, true);
|
||||
|
||||
@@ -894,24 +896,22 @@ void SyscallHandler::HandleSyscallImpl(FEXCore::Core::CpuStateFrame* Frame, uint
|
||||
}
|
||||
|
||||
auto& Def = Definitions[SyscallNum];
|
||||
+ uint64_t A[7] {};
|
||||
+ for (unsigned i = 1; i < 7; ++i) {
|
||||
+ A[i] = GetArg(Is64Bit, Frame, i);
|
||||
+ }
|
||||
+ if constexpr (Is64Bit) {
|
||||
+ FEX::HLE::GuestHighMemory::TranslateSyscallArguments(SyscallNum, &A[1], 6);
|
||||
+ }
|
||||
uint64_t Result {};
|
||||
switch (Def.NumArgs) {
|
||||
case 0: Result = std::invoke(Def.Ptr0, Frame); break;
|
||||
- case 1: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 1)); break;
|
||||
- case 2: Result = std::invoke(Def.Ptr2, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2)); break;
|
||||
- case 3: Result = std::invoke(Def.Ptr3, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3)); break;
|
||||
- case 4:
|
||||
- Result =
|
||||
- std::invoke(Def.Ptr4, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3), GetArg(Is64Bit, Frame, 4));
|
||||
- break;
|
||||
- case 5:
|
||||
- Result = std::invoke(Def.Ptr5, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3),
|
||||
- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5));
|
||||
- break;
|
||||
- case 6:
|
||||
- Result = std::invoke(Def.Ptr6, Frame, GetArg(Is64Bit, Frame, 1), GetArg(Is64Bit, Frame, 2), GetArg(Is64Bit, Frame, 3),
|
||||
- GetArg(Is64Bit, Frame, 4), GetArg(Is64Bit, Frame, 5), GetArg(Is64Bit, Frame, 6));
|
||||
- break;
|
||||
+ case 1: Result = std::invoke(Def.Ptr1, Frame, A[1]); break;
|
||||
+ case 2: Result = std::invoke(Def.Ptr2, Frame, A[1], A[2]); break;
|
||||
+ case 3: Result = std::invoke(Def.Ptr3, Frame, A[1], A[2], A[3]); break;
|
||||
+ case 4: Result = std::invoke(Def.Ptr4, Frame, A[1], A[2], A[3], A[4]); break;
|
||||
+ case 5: Result = std::invoke(Def.Ptr5, Frame, A[1], A[2], A[3], A[4], A[5]); break;
|
||||
+ case 6: Result = std::invoke(Def.Ptr6, Frame, A[1], A[2], A[3], A[4], A[5], A[6]); break;
|
||||
// for missing syscalls
|
||||
case 255: Result = std::invoke(Def.Ptr1, Frame, GetArg(Is64Bit, Frame, 0)); break;
|
||||
default:
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
|
||||
index f9e85a26f..bebdfd300 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/SyscallsSMCTracking.cpp
|
||||
@@ -21,6 +21,7 @@ $end_info$
|
||||
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
#include "LinuxSyscalls/SignalDelegator.h"
|
||||
+#include "LinuxSyscalls/GuestHighMemory.h"
|
||||
|
||||
#include <FEXCore/Debug/InternalThreadState.h>
|
||||
#include <FEXCore/Utils/LogManager.h>
|
||||
@@ -45,6 +46,9 @@ static void HandleSegfaultForCodeCacheFinalization(FEXCore::Core::InternalThread
|
||||
void SyscallHandler::InvalidateWrittenCodePage(FEXCore::Core::InternalThreadState* Thread, uint64_t FaultBase, uint64_t EntryBase,
|
||||
const FEX::HLE::VMATracking::VMAEntry& Mapping) {
|
||||
auto UnprotectRegionCallback = [](uintptr_t Start, uintptr_t Length) {
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(Start)) {
|
||||
+ return;
|
||||
+ }
|
||||
auto rv = mprotect((void*)Start, Length, PROT_READ | PROT_WRITE);
|
||||
LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length);
|
||||
};
|
||||
@@ -93,6 +97,10 @@ bool SyscallHandler::HandleSegfault(FEXCore::Core::InternalThreadState* Thread,
|
||||
}
|
||||
}
|
||||
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(FaultAddress)) {
|
||||
+ return false;
|
||||
+ }
|
||||
+
|
||||
{
|
||||
// Can't use the deferred signal lock in the SIGSEGV handler.
|
||||
auto lk = FEXCore::MaskSignalsAndLockMutex<std::shared_lock>(_SyscallHandler->VMATracking.Mutex);
|
||||
@@ -176,6 +184,9 @@ void SyscallHandler::PrepareGuestBufferForKernelWrite(FEXCore::Core::InternalThr
|
||||
}
|
||||
} else {
|
||||
TM.InvalidateGuestCodeRange(Thread, From, To - From, [](uintptr_t Start, uintptr_t Length) {
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(Start)) {
|
||||
+ return;
|
||||
+ }
|
||||
auto rv = mprotect(reinterpret_cast<void*>(Start), Length, PROT_READ | PROT_WRITE);
|
||||
LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", Start, Length);
|
||||
});
|
||||
@@ -227,7 +238,9 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState
|
||||
const auto ProtectBase = std::max(MapBase, Base);
|
||||
const auto ProtectSize = std::min(MapTop, Top) - ProtectBase;
|
||||
|
||||
- if (Mapping->second.Flags.Shared) {
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(ProtectBase)) {
|
||||
+ FEX::HLE::GuestHighMemory::MarkCode(ProtectBase, ProtectSize);
|
||||
+ } else if (Mapping->second.Flags.Shared) {
|
||||
LOGMAN_THROW_A_FMT(Mapping->second.Resource, "VMA tracking error");
|
||||
|
||||
const auto OffsetBase = ProtectBase - Mapping->first + Mapping->second.Offset;
|
||||
@@ -245,6 +258,10 @@ void SyscallHandler::MarkGuestExecutableRange(FEXCore::Core::InternalThreadState
|
||||
|
||||
const auto MirroredBase = std::max(VMAOffsetBase, OffsetBase);
|
||||
const auto MirroredSize = std::min(OffsetTop, VMAOffsetTop) - MirroredBase;
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(MirroredBase - VMAOffsetBase + VMABase)) {
|
||||
+ FEX::HLE::GuestHighMemory::MarkCode(MirroredBase - VMAOffsetBase + VMABase, MirroredSize);
|
||||
+ continue;
|
||||
+ }
|
||||
|
||||
auto rv = mprotect((void*)(MirroredBase - VMAOffsetBase + VMABase), MirroredSize, PROT_READ);
|
||||
LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", MirroredBase, MirroredSize);
|
||||
@@ -293,6 +310,10 @@ void SyscallHandler::ProtectWritableAliasOfCode(uint64_t Base, uint64_t Length)
|
||||
|
||||
const auto OverlapBase = std::max(VMA->Offset, OffsetBase);
|
||||
const auto OverlapTop = std::min(VMA->Offset + VMA->Length, OffsetTop);
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(MapBase + (OverlapBase - OffsetBase))) {
|
||||
+ FEX::HLE::GuestHighMemory::MarkCode(MapBase + (OverlapBase - OffsetBase), OverlapTop - OverlapBase);
|
||||
+ continue;
|
||||
+ }
|
||||
auto rv = mprotect((void*)(MapBase + (OverlapBase - OffsetBase)), OverlapTop - OverlapBase, PROT_READ);
|
||||
LogMan::Throw::AFmt(rv == 0, "mprotect({}, {}) failed", OverlapBase, OverlapTop - OverlapBase);
|
||||
}
|
||||
@@ -429,6 +450,11 @@ void* SyscallHandler::GuestMmap(bool Is64Bit, FEXCore::Core::InternalThreadState
|
||||
return reinterpret_cast<void*>(Result);
|
||||
}
|
||||
LOGMAN_THROW_A_FMT(Is64Bit || (Result >> 32) == 0 || (Result >> 32) == 0xFFFFFFFF, "values must fit to 32 bits");
|
||||
+ } else if (FEX::HLE::GuestHighMemory::ClaimsMapping(reinterpret_cast<uint64_t>(addr), length, flags)) {
|
||||
+ Result = FEX::HLE::GuestHighMemory::Map(reinterpret_cast<uint64_t>(addr), length, prot, flags, fd, offset);
|
||||
+ if (FEX::HLE::HasSyscallError(Result)) {
|
||||
+ return reinterpret_cast<void*>(Result);
|
||||
+ }
|
||||
} else {
|
||||
Result = reinterpret_cast<uint64_t>(::mmap(reinterpret_cast<void*>(addr), length, prot, flags, fd, offset));
|
||||
if (Result == ~0ULL) {
|
||||
@@ -483,9 +509,16 @@ uint64_t SyscallHandler::GuestMunmap(bool Is64Bit, FEXCore::Core::InternalThread
|
||||
if (Addr > X86_64TaskSizeMax || Size > X86_64TaskSizeMax - Addr || (length != 0 && Size == 0)) {
|
||||
return -EINVAL;
|
||||
}
|
||||
- Result = ::munmap(addr, length);
|
||||
- if (Result == -1) {
|
||||
- return -errno;
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(Addr)) {
|
||||
+ Result = FEX::HLE::GuestHighMemory::Unmap(Addr, length);
|
||||
+ if (FEX::HLE::HasSyscallError(Result)) {
|
||||
+ return Result;
|
||||
+ }
|
||||
+ } else {
|
||||
+ Result = ::munmap(addr, length);
|
||||
+ if (Result == -1) {
|
||||
+ return -errno;
|
||||
+ }
|
||||
}
|
||||
if (reinterpret_cast<uintptr_t>(addr) < 0x1'0000'0000ULL) {
|
||||
Get32BitAllocator()->TrackUnmapped(addr, length);
|
||||
@@ -511,6 +544,10 @@ uint64_t SyscallHandler::GuestMremap(bool Is64Bit, FEXCore::Core::InternalThread
|
||||
{
|
||||
auto lk = FEXCore::GuardSignalDeferringSection(VMATracking.Mutex, Thread);
|
||||
if (Is64Bit) {
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast<uint64_t>(old_address)) ||
|
||||
+ ((flags & MREMAP_FIXED) && FEX::HLE::GuestHighMemory::Contains(reinterpret_cast<uint64_t>(new_address)))) {
|
||||
+ return -EINVAL;
|
||||
+ }
|
||||
Result = reinterpret_cast<uint64_t>(::mremap(old_address, old_size, new_size, flags, new_address));
|
||||
if (Result == -1) {
|
||||
return -errno;
|
||||
@@ -602,9 +639,16 @@ uint64_t SyscallHandler::GuestMprotect(FEXCore::Core::InternalThreadState* Threa
|
||||
}
|
||||
}
|
||||
|
||||
- Result = ::mprotect(addr, len, prot);
|
||||
- if (Result == -1) {
|
||||
- return -errno;
|
||||
+ if (FEX::HLE::GuestHighMemory::Contains(reinterpret_cast<uint64_t>(addr))) {
|
||||
+ Result = FEX::HLE::GuestHighMemory::Protect(reinterpret_cast<uint64_t>(addr), len, prot);
|
||||
+ if (FEX::HLE::HasSyscallError(Result)) {
|
||||
+ return Result;
|
||||
+ }
|
||||
+ } else {
|
||||
+ Result = ::mprotect(addr, len, prot);
|
||||
+ if (Result == -1) {
|
||||
+ return -errno;
|
||||
+ }
|
||||
}
|
||||
|
||||
TrackMprotect(Thread, addr, len, prot);
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
|
||||
index e13cb1ca9..49df38c30 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.cpp
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#include "LinuxSyscalls/ThreadManager.h"
|
||||
+#include "LinuxSyscalls/GuestHighMemory.h"
|
||||
#include "LinuxSyscalls/SamplingProfiler.h"
|
||||
|
||||
#include "LinuxSyscalls/Syscalls.h"
|
||||
@@ -330,6 +331,7 @@ void ThreadManager::HandleThreadDeletion(FEX::HLE::ThreadStateObject* Thread, bo
|
||||
FEXCore::Allocator::munmap(Thread->ldt_entries, Thread->ldt_entry_count * FEX::HLE::SyscallHandler::LDT_ENTRY_SIZE);
|
||||
}
|
||||
|
||||
+ FEX::HLE::GuestHighMemory::ReleaseThread(Thread);
|
||||
CTX->DestroyThread(Thread->Thread);
|
||||
FEX::HLE::_SyscallHandler->SeccompEmulator.FreeSeccompFilters(Thread);
|
||||
|
||||
diff --git a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
index 657de6ceb..16ef19209 100644
|
||||
--- a/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
+++ b/Source/Tools/LinuxEmulation/LinuxSyscalls/ThreadManager.h
|
||||
@@ -103,6 +103,18 @@ struct ThreadStateObject : public FEXCore::Allocator::FEXAllocOperators {
|
||||
bool Enabled;
|
||||
} SyscallUserDispatch {};
|
||||
|
||||
+ struct {
|
||||
+ uint8_t* Code;
|
||||
+ uint64_t ResumePC;
|
||||
+ uint64_t SavedScratch;
|
||||
+ uint64_t BaseBefore;
|
||||
+ uint64_t Delta;
|
||||
+ uint64_t SavedMask;
|
||||
+ uint32_t Scratch;
|
||||
+ uint32_t Base;
|
||||
+ bool Active;
|
||||
+ } HighMemoryTrap {};
|
||||
+
|
||||
uint64_t JITStackSP {};
|
||||
|
||||
struct TrapSignalFrame {
|
||||
--
|
||||
2.43.0
|
||||
|
||||
@@ -9,7 +9,7 @@ export MOZ_ENABLE_WAYLAND=1 MOZ_USE_XINPUT2=1
|
||||
export SHELL=/bin/bash
|
||||
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
|
||||
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
|
||||
export MOZ_SHM_NO_SEALS=1
|
||||
export MOZ_SHM_NO_SEALS=1 MOZ_CRASHREPORTER_DISABLE=1
|
||||
export QTWEBENGINE_DISABLE_SANDBOX=1
|
||||
export KWIN_COMPOSE=Q QT_QUICK_BACKEND=software LIBGL_ALWAYS_SOFTWARE=1 GALLIUM_DRIVER=llvmpipe
|
||||
export KWIN_USE_OVERLAYS=0
|
||||
@@ -142,11 +142,10 @@ Exec=konsole -e /usr/local/bin/droiddeck-steam-x64
|
||||
Icon=steam
|
||||
Categories=System;
|
||||
ENTRY
|
||||
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'
|
||||
( while sleep 30; do python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 | sed 's/^/[pads] /'; done ) &
|
||||
python3 /usr/local/bin/droiddeck-pad-defaults --every 30 &
|
||||
python3 /usr/local/bin/droiddeck-desktop-gpu 2>&1 | sed 's/^/[gpu] /'
|
||||
/usr/local/bin/droiddeck-desktop-window-rules 2>&1 | sed 's/^/[rules] /'
|
||||
( python3 /usr/local/bin/droiddeck-library-perms 2>&1 | sed 's/^/[perms] /' ) &
|
||||
python3 /usr/local/bin/droiddeck-library-perms 2>&1 &
|
||||
mkdir -p /usr/local/share/applications
|
||||
cat > /usr/local/share/applications/droiddeck-ime.desktop <<'ENTRY'
|
||||
[Desktop Entry]
|
||||
@@ -175,6 +174,15 @@ fi
|
||||
if command -v flatpak >/dev/null 2>&1 && [ ! -d /var/lib/pacman ]; then
|
||||
FLATPAK_BWRAP=/usr/local/bin/droiddeck-bwrap flatpak remote-add --user --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo >/dev/null 2>&1 &
|
||||
fi
|
||||
# Android counts the desktop's programs against an app's limit of 32. Off unless the user turns them
|
||||
# back on in Autostart: Discover's update notifier (the packages follow DroidDeck's releases, and it
|
||||
# keeps PackageKit running as root), GeoClue's demo agent (nothing asks for a location) and the
|
||||
# global-menu proxy (the panel has no global menu).
|
||||
mkdir -p "$HOME/.config/autostart"
|
||||
for entry in org.kde.discover.notifier geoclue-demo-agent gmenudbusmenuproxy; do
|
||||
[ -e "$HOME/.config/autostart/$entry.desktop" ] ||
|
||||
printf '[Desktop Entry]\nType=Application\nName=%s\nHidden=true\n' "$entry" > "$HOME/.config/autostart/$entry.desktop"
|
||||
done
|
||||
skel_done=$HOME/.local/share/droiddeck/skel-copied
|
||||
if [ -d /etc/skel ] && [ ! -e "$skel_done" ]; then
|
||||
cp -rn /etc/skel/. "$HOME/" 2>/dev/null
|
||||
|
||||
@@ -9,3 +9,11 @@ pref("datareporting.policy.dataSubmissionEnabled", false);
|
||||
pref("browser.aboutwelcome.enabled", false);
|
||||
pref("browser.startup.homepage", "about:blank");
|
||||
pref("layout.css.devPixelsPerPx", "1.25");
|
||||
// Android counts each of Firefox's processes against the app's limit of 32: one web content process
|
||||
// per two tabs' worth of sites rather than one per site, none started ahead, and extensions and
|
||||
// about: pages in the processes that already exist.
|
||||
pref("fission.autostart", false);
|
||||
pref("dom.ipc.processCount", 2);
|
||||
pref("dom.ipc.processPrelaunch.enabled", false);
|
||||
pref("browser.tabs.remote.separatePrivilegedContentProcess", false);
|
||||
pref("extensions.webextensions.remote", false);
|
||||
@@ -664,7 +664,7 @@ def data_dir(env):
|
||||
return DATA_DIR
|
||||
|
||||
|
||||
def guest_environment(fex, env, keep_compat=False):
|
||||
def guest_environment(fex, env):
|
||||
result = dict(env)
|
||||
data = data_dir(env)
|
||||
for directory in (CONFIG_DIR, data, CACHE_DIR):
|
||||
@@ -672,7 +672,7 @@ def guest_environment(fex, env, keep_compat=False):
|
||||
result["FEX_APP_CONFIG_LOCATION"] = CONFIG_DIR + "/"
|
||||
result["FEX_APP_DATA_LOCATION"] = data + "/"
|
||||
result["FEX_APP_CACHE_LOCATION"] = CACHE_DIR + "/"
|
||||
if result.get("STEAM_COMPAT_DATA_PATH") and not keep_compat:
|
||||
if result.get("STEAM_COMPAT_DATA_PATH"):
|
||||
short = data if data != DATA_DIR else "/tmp/fex"
|
||||
os.makedirs(short, exist_ok=True)
|
||||
result["STEAM_COMPAT_DATA_PATH"] = short
|
||||
@@ -761,7 +761,7 @@ def resolve(program, env):
|
||||
return shutil.which(program, path=env.get("PATH")) or program
|
||||
|
||||
|
||||
def launch(command, env, mode, decide=None, keep_compat=False):
|
||||
def launch(command, env, mode, decide=None):
|
||||
program = resolve(command[0], env)
|
||||
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
|
||||
if not use:
|
||||
@@ -769,7 +769,7 @@ def launch(command, env, mode, decide=None, keep_compat=False):
|
||||
fex = prepare(required_runtime(program))
|
||||
if fex is None:
|
||||
return 126
|
||||
guest = guest_environment(fex, env, keep_compat)
|
||||
guest = guest_environment(fex, env)
|
||||
x86_64 = elf_arch(program) != "i386"
|
||||
thunks = "on" if "FEX_THUNKCONFIG" in guest else "off"
|
||||
folder = decide if decide and os.path.isdir(decide) else os.path.dirname(program)
|
||||
@@ -963,7 +963,7 @@ def parse_run(args):
|
||||
|
||||
def main(argv):
|
||||
if not argv:
|
||||
say("usage: droiddeck-fex steam VERB CMD... | proton PROTON VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status")
|
||||
say("usage: droiddeck-fex steam VERB CMD... | run [--mode auto|on|off] [--for PATH] [--] CMD... | needs PATH | extract IMAGE | prepare | status")
|
||||
return 2
|
||||
action, args = argv[0], list(argv[1:])
|
||||
if action == "steam":
|
||||
@@ -975,10 +975,6 @@ def main(argv):
|
||||
if not command:
|
||||
return 2
|
||||
return launch(command, game_environment(dict(os.environ), command), os.environ.get("DROIDDECK_FEX", "auto"))
|
||||
if action == "proton":
|
||||
if len(args) < 2:
|
||||
return 2
|
||||
return launch(args, game_environment(dict(os.environ), args[2:] or args), "on", keep_compat=True)
|
||||
if action == "run":
|
||||
try:
|
||||
mode, decide, command = parse_run(args)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#!/usr/bin/python3
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
|
||||
HOME = os.environ.get("HOME", "/root")
|
||||
CONFIG = os.environ.get("XDG_CONFIG_HOME", os.path.join(HOME, ".config"))
|
||||
@@ -1048,8 +1050,19 @@ def switch_emulators():
|
||||
print(f"droiddeck-pad-defaults: {name}: Player 1 on the controller ({cfg})")
|
||||
|
||||
|
||||
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
|
||||
try:
|
||||
step()
|
||||
except Exception as e:
|
||||
print(f"droiddeck-pad-defaults: {step.__name__}: {e}")
|
||||
def run_all():
|
||||
for step in (rpcs3, duckstation, pcsx2, armsx2, dolphin, cemu, melonds, ppsspp, retroarch, switch_emulators):
|
||||
try:
|
||||
step()
|
||||
except Exception as e:
|
||||
print(f"droiddeck-pad-defaults: {step.__name__}: {e}", flush=True)
|
||||
|
||||
|
||||
# --every SECONDS: again at that interval, for emulators set up while the desktop runs. One process
|
||||
# for the whole desktop session rather than a shell loop starting a new one each time.
|
||||
sys.stdout.reconfigure(line_buffering=True)
|
||||
run_all()
|
||||
if len(sys.argv) == 3 and sys.argv[1] == "--every":
|
||||
while True:
|
||||
time.sleep(float(sys.argv[2]))
|
||||
run_all()
|
||||
@@ -63,9 +63,16 @@ dd_job() {
|
||||
# window's app by walking its process's parents) or its utility processes (the client only accepts
|
||||
# its transport from its own children).
|
||||
if [ "${DD_SPAWN_DAEMONS:-1}" = 1 ] && [ -n "${DD_SPAWN:-}" ]; then
|
||||
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver}
|
||||
export DD_HANDOFF=${DD_HANDOFF-xdg-desktop-portal:xdg-permission-store:xdg-desktop-portal-gtk:at-spi-bus-launcher:at-spi2-registryd:plasma_waitforname:bash+dd-job:droiddeck-log-writer:gamescope:gamescopereaper:droiddeck-session+steam:Xwayland:dbus-launch:droiddeck-agent:droiddeck-launcher-cores:droiddeck-pace-cores:droiddeck-documents:droiddeck-steam-games+watch:droiddeck-steam-compat:dbus-daemon+--nofork:proton:pipewire:wireplumber:PluginLoader:PluginLoader.real:xprop+-spy:gnudd:steamwebhelper+--type=renderer:wine:wine-preloader:wine64:wine64-preloader:wineserver:droiddeck-login1:droiddeck-snapd:droiddeck-polkitd:droiddeck-root+/usr/libexec/packagekitd:droiddeck-desktop-clipboard:droiddeck-ime:droiddeck-pad-defaults+--every:droiddeck-library-perms:droiddeck-clipboard:dbus-run-session:startplasma-wayland:plasma_session:kwin_wayland_wrapper:kwin_wayland:kded6:ksmserver:kglobalacceld:plasmashell:krunner:org_kde_powerdevil:xembedsniproxy:kaccess:xsettingsd:kdeconnectd:kunifiedpush-distributor:kactivitymanagerd:xdg-desktop-portal-kde:dconf-service:polkit-kde-authentication-agent-1:plasma-welcome:kioworker}
|
||||
# The programs these start for the user (an app from the panel, a file opened in Dolphin)
|
||||
export DD_HANDOFF_LAUNCHERS=${DD_HANDOFF_LAUNCHERS-plasmashell:krunner:dolphin}
|
||||
# Each process's first parent, so that a process can reap the zombies it adopts as a subreaper, and
|
||||
# the programs that reap them even while they leave SIGCHLD alone (hook/signals.c)
|
||||
rm -f /run/droiddeck-parents.* 2>/dev/null
|
||||
export DD_PARENTS=/run/droiddeck-parents.$$
|
||||
export DD_REAP_ADOPTED=${DD_REAP_ADOPTED-plasmashell:plasma_session:kwin_wayland:kwin_wayland_wrapper:kaccess:ksmserver:kded6:krunner:dolphin:dbus-daemon:startplasma-wayland:gamescope:wine:wine64:wine-preloader:wine64-preloader:wineserver:PluginLoader:PluginLoader.real}
|
||||
else
|
||||
unset DD_HANDOFF
|
||||
unset DD_HANDOFF DD_HANDOFF_LAUNCHERS DD_PARENTS DD_REAP_ADOPTED
|
||||
fi
|
||||
steam_setup_failed() {
|
||||
echo "== steam: the Steam client could not be set up (status $1)"
|
||||
|
||||
@@ -318,59 +318,12 @@ dd_vacdiag() {
|
||||
}
|
||||
"""
|
||||
|
||||
DD_ANTICHEAT_SETUP = """
|
||||
dd_anticheat_runtime() {
|
||||
local current=$1 name=$2 library
|
||||
if [ -n "$current" ] && [ -n "$(find "$current" -name '*.so' -print -quit 2>/dev/null)" ]; then
|
||||
printf '%s' "$current"; return 0
|
||||
fi
|
||||
while IFS= read -r library; do
|
||||
[ -n "$(find "$library/steamapps/common/$name" -name '*.so' -print -quit 2>/dev/null)" ] || continue
|
||||
printf '%s' "$library/steamapps/common/$name"; return 0
|
||||
done < <(printf '%s\\n' "$DD_AC_ROOT" /mnt/droiddeck-sd; sed -n 's/^[[:space:]]*"path"[[:space:]]*"\\(.*\\)"[[:space:]]*$/\\1/p' "$DD_AC_ROOT/steamapps/libraryfolders.vdf" 2>/dev/null)
|
||||
return 1
|
||||
}
|
||||
|
||||
dd_x86_64_proton() {
|
||||
[ -d "$1/files/lib/wine/x86_64-unix" ] && [ ! -d "$1/files/bin-arm64" ]
|
||||
}
|
||||
|
||||
dd_anticheat() {
|
||||
case ${verb:-} in waitforexitandrun | run) ;; *) return 0 ;; esac
|
||||
case ${DROIDDECK_ANTICHEAT:-auto} in off | 0 | false) return 0 ;; esac
|
||||
local game=${STEAM_COMPAT_INSTALL_PATH:-} found tool runtime
|
||||
[ -d "$game" ] || return 0
|
||||
found=$(find "$game" -maxdepth 3 \\( -ipath '*/easyanticheat/settings.json' -o -iname 'easyanticheat_x64.so' \\
|
||||
-o -iname 'beclient_x64.so' -o -iname 'beservice_x64.exe' \\) -print -quit 2>/dev/null)
|
||||
[ -n "$found" ] || return 0
|
||||
DD_AC_ROOT=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
|
||||
tool=$(cd "$DD_AC_ROOT/compatibilitytools.d" 2>/dev/null && for d in DroidDeck-Proton*; do
|
||||
[ -x "$d/proton" ] && dd_x86_64_proton "$d" && printf '%s/%s\\n' "$PWD" "$d"
|
||||
done | sort -V | tail -n 1)
|
||||
if [ -z "$tool" ]; then
|
||||
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; no x86-64 DroidDeck-Proton is installed, so this launch stays on ARM64" >&2
|
||||
return 0
|
||||
fi
|
||||
case ${found,,} in
|
||||
*easyanticheat*) runtime=$(dd_anticheat_runtime "${PROTON_EAC_RUNTIME:-}" "Proton EasyAntiCheat Runtime") && export PROTON_EAC_RUNTIME="$runtime" ;;
|
||||
*) runtime=$(dd_anticheat_runtime "${PROTON_BATTLEYE_RUNTIME:-}" "Proton BattlEye Runtime") && export PROTON_BATTLEYE_RUNTIME="$runtime" ;;
|
||||
esac
|
||||
if [ -z "$runtime" ]; then
|
||||
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; its Proton runtime is not installed, so this launch stays on ARM64" >&2
|
||||
return 0
|
||||
fi
|
||||
dd_game_cpus
|
||||
echo "droiddeck-proton: anti-cheat files in ${found#$game/}; running ${tool##*/} under FEX" >&2
|
||||
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$tool/proton" "$verb" "$@"
|
||||
}
|
||||
"""
|
||||
|
||||
# DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the
|
||||
# newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set.
|
||||
DD_BIONIC_PROOT_FALLBACK = """
|
||||
if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then
|
||||
dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do
|
||||
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] && ! dd_x86_64_proton "$d" || continue
|
||||
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue
|
||||
v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d"
|
||||
done | sort -V | tail -n 1 | cut -f 2-)
|
||||
if [ -n "$dd_fallback" ]; then
|
||||
@@ -508,7 +461,6 @@ for name in %s; do
|
||||
[ -n "$depot" ] && break
|
||||
done
|
||||
if [ -n "$depot" ]; then
|
||||
dd_anticheat "$@"
|
||||
dd_components "$depot"
|
||||
dd_directaudio "$depot" "$@"
|
||||
dd_game_cpus
|
||||
@@ -529,7 +481,7 @@ LAUNCHER_TEMPLATE = LAUNCHER_SH
|
||||
def launcher_sh(sources=SOURCES):
|
||||
return (LAUNCHER_TEMPLATE % " ".join('"%s"' % n for n in sources)).replace(
|
||||
"verb=$1; shift", "verb=$1; shift\n" + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP + DD_IDTECH3_SETUP
|
||||
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP + DD_ANTICHEAT_SETUP, 1)
|
||||
+ DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
|
||||
|
||||
|
||||
LAUNCHER_SH = launcher_sh()
|
||||
@@ -564,11 +516,6 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
|
||||
*) LD_AUDIT="$audit${LD_AUDIT:+:$LD_AUDIT}"; export LD_AUDIT ;;
|
||||
esac
|
||||
fi
|
||||
if dd_x86_64_proton "$here"; then
|
||||
dd_game_cpus
|
||||
exec ${DD_TASKSET:-} /usr/local/bin/droiddeck-fex proton "$here/%s" "$verb" "$@"
|
||||
fi
|
||||
dd_anticheat "$@"
|
||||
dd_components "$here"
|
||||
dd_directaudio "$here" "$@"
|
||||
dd_game_cpus
|
||||
@@ -583,9 +530,9 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
|
||||
|
||||
|
||||
def extra_wrapper_sh(entry_point):
|
||||
return (EXTRA_WRAPPER_SH % (entry_point, entry_point)).replace(
|
||||
return (EXTRA_WRAPPER_SH % entry_point).replace(
|
||||
'here=$(dirname "$0")',
|
||||
'here=$(dirname "$0")\n' + DD_ANTICHEAT_SETUP + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
|
||||
'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
|
||||
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
|
||||
|
||||
|
||||
|
||||
@@ -957,9 +957,8 @@ __attribute__((visibility("hidden"))) void dd_vdec_closed(int fd) {
|
||||
|
||||
__attribute__((visibility("hidden"))) int dd_vdec_poll(struct pollfd *fds, nfds_t n, int timeout_ms,
|
||||
int (*real)(struct pollfd *, nfds_t, int), int *ret) {
|
||||
if (n != 1 || __atomic_load_n(&vd_open_count, __ATOMIC_ACQUIRE) == 0) return 0;
|
||||
if (n != 1 || vd_find(fds[0].fd) == NULL) return 0;
|
||||
struct vdec *v = vd_find(fds[0].fd);
|
||||
if (v == NULL) return 0;
|
||||
pthread_mutex_lock(&vd_lock);
|
||||
short ready = (v->n_cap_done ? POLLIN | POLLRDNORM : 0) | (v->n_out_done ? POLLOUT | POLLWRNORM : 0);
|
||||
pthread_mutex_unlock(&vd_lock);
|
||||
|
||||
@@ -374,7 +374,6 @@ static int ddnatv_execve(const char *filename, char *const argv[], char *const e
|
||||
errno = ENOSYS;
|
||||
return -1;
|
||||
}
|
||||
if (is_proc_self_exe(filename) && g_real_exe[0] != '\0') filename = g_real_exe;
|
||||
if (depth == 0 && !in_exec_rehearsal()) ddh_try(filename, argv, envp);
|
||||
|
||||
// Scripts get the path exactly as the caller wrote it ("./x.sh" stays "./x.sh" in $0),
|
||||
@@ -662,12 +661,14 @@ pid_t fork(void) {
|
||||
}
|
||||
ddh_prepare();
|
||||
pid_t forker = (pid_t)syscall(SYS_gettid);
|
||||
pid_t forking = (pid_t)syscall(SYS_getpid);
|
||||
pid_t pid = orig_fork();
|
||||
if (pid == 0) {
|
||||
kept_forked();
|
||||
kept_close_forked();
|
||||
ddh_drop_worker_binder();
|
||||
ddh_forked(forker);
|
||||
ddh_record_parent((pid_t)syscall(SYS_getpid), forking);
|
||||
} else if (pid > 0) {
|
||||
ddh_child_created(pid, 1);
|
||||
}
|
||||
|
||||
@@ -878,6 +878,9 @@ static void ddh_apply_inherited(void) {
|
||||
}
|
||||
}
|
||||
|
||||
static void ddh_open_parents(void);
|
||||
static void ddh_record_own_parent(void);
|
||||
|
||||
__attribute__((constructor)) static void ddh_init(void) {
|
||||
ddh_apply_inherited();
|
||||
ddh_find_worker_binder();
|
||||
@@ -885,6 +888,9 @@ __attribute__((constructor)) static void ddh_init(void) {
|
||||
ddh_find_parent_table();
|
||||
// tests only: as when the table could not be made here, and the first fork makes it
|
||||
if (!getenv("DDH_TEST_LATE_TABLE")) ddh_prepare();
|
||||
ddh_open_parents();
|
||||
ddh_record_own_parent();
|
||||
ddnatv_manage_sigchld();
|
||||
}
|
||||
|
||||
static int ddh_has_arg(char *const argv[], const char *prefix, size_t len) {
|
||||
@@ -1274,6 +1280,30 @@ static int ddh_job_control_job(void) {
|
||||
return ddh_waiter(parent) && (pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent);
|
||||
}
|
||||
|
||||
// Whether this is a program a desktop launcher starts for the user (DD_HANDOFF_LAUNCHERS names the
|
||||
// launchers: Plasma's shell, KRunner, Dolphin): a plain fork and exec, still in the launcher's process
|
||||
// group and session, with no controlling terminal. Those launchers are Qt programs, which wait with
|
||||
// waitpid() once they have no pidfds (privileged.c), so the program's exit reaches them. A child the
|
||||
// launcher set up as a terminal's (a session and a terminal of its own) stays its own child.
|
||||
static int ddh_launched(const char *filename, char *const argv[], char *const envp[]) {
|
||||
const char *list = ddh_env(envp, "DD_HANDOFF_LAUNCHERS");
|
||||
if (!list || !*list || ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv)) return 0;
|
||||
pid_t parent = (pid_t)syscall(SYS_getppid);
|
||||
char path[48], name[32];
|
||||
snprintf(path, sizeof(path), "/proc/%d/comm", (int)parent);
|
||||
if (ddh_read_proc(path, name, sizeof(name)) <= 0) return 0;
|
||||
name[strcspn(name, "\n")] = 0;
|
||||
if (!ddh_listed(list, name, NULL)) return 0;
|
||||
if ((pid_t)syscall(SYS_getpgid, 0) != (pid_t)syscall(SYS_getpgid, parent) ||
|
||||
(pid_t)syscall(SYS_getsid, 0) != (pid_t)syscall(SYS_getsid, parent))
|
||||
return 0;
|
||||
// /dev/tty opens only for a process with a controlling terminal
|
||||
int tty = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/dev/tty",
|
||||
O_RDONLY | O_NOCTTY | O_NONBLOCK | O_CLOEXEC, 0, 0, 0);
|
||||
if (tty >= 0) syscall(SYS_close, tty);
|
||||
return tty < 0;
|
||||
}
|
||||
|
||||
static int ddh_pressed(const char *filename, char *const argv[], char *const envp[]) {
|
||||
if (ddh_exec_stub(filename) || ddh_pressure_keeps(filename, argv) || !ddh_waiter((pid_t)syscall(SYS_getppid))) return 0;
|
||||
// Not a job in the foreground of its controlling terminal: a handed-off program has none (the
|
||||
@@ -1302,7 +1332,11 @@ static void ddh_debug(char *const envp[], const char *what, const char *filename
|
||||
struct ddh_buf b = {line, 0, sizeof(line) - 1};
|
||||
ddh_puts(&b, "ddnatv handoff: ");
|
||||
ddh_putint(&b, getpid());
|
||||
ddh_puts(&b, " ");
|
||||
ddh_puts(&b, " (parent ");
|
||||
ddh_putint(&b, (long)syscall(SYS_getppid));
|
||||
ddh_puts(&b, ", session ");
|
||||
ddh_putint(&b, (long)syscall(SYS_getsid, 0));
|
||||
ddh_puts(&b, ") ");
|
||||
ddh_puts(&b, what);
|
||||
ddh_puts(&b, " ");
|
||||
ddh_puts(&b, filename ? filename : "?");
|
||||
@@ -1364,7 +1398,8 @@ static void ddh_try_as(const char *filename, char *const argv[], char *const env
|
||||
ddh_debug(envp, "a job-control job:", filename);
|
||||
return;
|
||||
}
|
||||
if (!ddh_program_listed(list, match_file, match_argv) && !ddh_pressed(match_file, match_argv, envp)) {
|
||||
if (!ddh_program_listed(list, match_file, match_argv) && !ddh_launched(match_file, match_argv, envp) &&
|
||||
!ddh_pressed(match_file, match_argv, envp)) {
|
||||
ddh_debug(envp, "not listed:", filename);
|
||||
return;
|
||||
}
|
||||
@@ -1644,6 +1679,158 @@ static int32_t ddh_gen_of(const struct ddh_entry *e, pid_t child) {
|
||||
return (st == DDH_HANDED || st == DDH_EXITED || st == DDH_TAKEN) && e->child == child ? gen : 0;
|
||||
}
|
||||
|
||||
// ---- children no wait will come for ------------------------------------------------------------
|
||||
//
|
||||
// Every session process is a child subreaper (tools/linuxfs/preload/subreaper.c): a process whose
|
||||
// parent exits goes to its nearest ancestor in the session, not to init, which some vendor kernels
|
||||
// kill. Most programs never wait for a child they did not fork, so what they adopt stays a zombie (the
|
||||
// grandchildren of Qt's startDetached() under Plasma's shell, KWin and kaccess). Each process records
|
||||
// here, at its pid, the parent that started it and its own start time (DD_PARENTS, one file for the
|
||||
// session): a zombie whose record names another parent was adopted.
|
||||
static uint64_t *g_ddh_parents;
|
||||
|
||||
static void ddh_open_parents(void) {
|
||||
const char *name = getenv("DD_PARENTS");
|
||||
if (!name || !*name || __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE)) return;
|
||||
char path[PATH_MAX];
|
||||
const char *real = rewrite_path(name, path, sizeof(path));
|
||||
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)real,
|
||||
O_RDWR | O_CREAT | O_CLOEXEC, 0600, 0, 0);
|
||||
if (fd < 0) return;
|
||||
size_t size = (size_t)DDH_FORKS * sizeof(uint64_t);
|
||||
struct stat st;
|
||||
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size < size)
|
||||
call_orig_syscall(SYS_ftruncate, (unsigned long)fd, size, 0, 0, 0, 0);
|
||||
// past the file's end a page would fault (SIGBUS): mapped only once the file has its size
|
||||
void *map = MAP_FAILED;
|
||||
if (call_orig_syscall(SYS_fstat, (unsigned long)fd, (unsigned long)&st, 0, 0, 0, 0) == 0 && (size_t)st.st_size >= size)
|
||||
map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
|
||||
syscall(SYS_close, fd);
|
||||
if (map == MAP_FAILED) return;
|
||||
uint64_t *none = NULL;
|
||||
if (!__atomic_compare_exchange_n(&g_ddh_parents, &none, (uint64_t *)map, 0, __ATOMIC_ACQ_REL, __ATOMIC_ACQUIRE))
|
||||
munmap(map, size);
|
||||
}
|
||||
|
||||
static uint64_t ddh_parent_record(pid_t parent, long start) { return (uint64_t)(uint32_t)parent << 32 | (uint32_t)start; }
|
||||
|
||||
static void ddh_record_parent(pid_t me, pid_t parent) {
|
||||
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
|
||||
if (!map || me <= 0) return;
|
||||
int saved = errno;
|
||||
long start = ddh_start_time(me);
|
||||
errno = saved;
|
||||
if (start > 0) __atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record(parent, start), __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
// At a program's start, unless its fork recorded it: the child of a vfork(), of glibc's own
|
||||
// posix_spawn() (popen(), system()) or of a raw clone() records the parent it has now, which is
|
||||
// still the one that started it (a vfork()'s waits for the exec).
|
||||
static void ddh_record_own_parent(void) {
|
||||
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
|
||||
if (!map) return;
|
||||
pid_t me = (pid_t)syscall(SYS_getpid);
|
||||
int saved = errno;
|
||||
long start = ddh_start_time(me);
|
||||
errno = saved;
|
||||
if (start <= 0) return;
|
||||
uint64_t r = __atomic_load_n(&map[(uint32_t)me % DDH_FORKS], __ATOMIC_ACQUIRE);
|
||||
if ((uint32_t)r == (uint32_t)start && r >> 32) return;
|
||||
__atomic_store_n(&map[(uint32_t)me % DDH_FORKS], ddh_parent_record((pid_t)syscall(SYS_getppid), start), __ATOMIC_RELEASE);
|
||||
}
|
||||
|
||||
// /proc/PID/stat's state and start time, from a signal handler: 0 when it cannot be read.
|
||||
static int ddh_proc_state(pid_t pid, char *state, long *start, pid_t *ppid) {
|
||||
char path[48] = "/proc/", digits[16], stat[512];
|
||||
int n = 0, len = 6;
|
||||
for (unsigned int v = (unsigned int)pid; v || !n; v /= 10) digits[n++] = (char)('0' + v % 10);
|
||||
while (n) path[len++] = digits[--n];
|
||||
memcpy(path + len, "/stat", 6);
|
||||
int fd = (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)path, O_RDONLY | O_CLOEXEC, 0, 0, 0);
|
||||
if (fd < 0) return 0;
|
||||
long got = call_orig_syscall(SYS_read, (unsigned long)fd, (unsigned long)stat, sizeof(stat) - 1, 0, 0, 0);
|
||||
call_orig_syscall(SYS_close, (unsigned long)fd, 0, 0, 0, 0, 0);
|
||||
if (got <= 0) return 0;
|
||||
stat[got] = 0;
|
||||
char *p = strrchr(stat, ')');
|
||||
if (!p || p[1] != ' ' || !p[2]) return 0;
|
||||
*state = p[2];
|
||||
// ") S PPID": field 4; starttime is field 22
|
||||
long parent = 0;
|
||||
for (const char *q = p + 4; *q >= '0' && *q <= '9'; q++) parent = parent * 10 + (*q - '0');
|
||||
*ppid = (pid_t)parent;
|
||||
for (int field = 2; p && field < 22; field++) p = strchr(p + 1, ' ');
|
||||
long t = 0;
|
||||
for (const char *q = p ? p + 1 : ""; *q >= '0' && *q <= '9'; q++) t = t * 10 + (*q - '0');
|
||||
*start = t;
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Reaps child if no wait will come for it: the forked child of a handed-off program (its program's
|
||||
// exit stays in the table for the program's own waits, as when a wait reaps it), or a child this
|
||||
// process adopted. 1 when it did.
|
||||
static int ddh_reap_unwaited(pid_t me, pid_t child) {
|
||||
char state = 0;
|
||||
long start = 0;
|
||||
pid_t ppid = 0;
|
||||
if (!ddh_proc_state(child, &state, &start, &ppid) || state != 'Z' || ppid != me) return 0;
|
||||
struct ddh_entry *e = ddh_find(child);
|
||||
int32_t gen = e ? ddh_gen_of(e, child) : 0;
|
||||
if (gen) {
|
||||
if (ddh_reaped(e) || call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) != child) return 0;
|
||||
ddh_mark_reaped(e, gen);
|
||||
return 1;
|
||||
}
|
||||
uint64_t *map = __atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE);
|
||||
uint64_t r = map ? __atomic_load_n(&map[(uint32_t)child % DDH_FORKS], __ATOMIC_ACQUIRE) : 0;
|
||||
if (!r || (uint32_t)r != (uint32_t)start || (pid_t)(r >> 32) == me || !(r >> 32)) return 0;
|
||||
return call_orig_syscall(SYS_wait4, (unsigned long)child, 0, WNOHANG, 0, 0, 0) == child;
|
||||
}
|
||||
|
||||
// From the SIGCHLD handler (signals.c): the zombies among this process's children that no wait will
|
||||
// come for. The kernel names one zombie at a time; past one the program will reap itself, /proc.
|
||||
static void ddh_reap_unclaimed(void) {
|
||||
if (!__atomic_load_n(&g_ddh_parents, __ATOMIC_ACQUIRE) && !__atomic_load_n(&g_ddh, __ATOMIC_ACQUIRE)) return;
|
||||
int saved = errno;
|
||||
pid_t me = (pid_t)call_orig_syscall(SYS_getpid, 0, 0, 0, 0, 0, 0);
|
||||
// past 64 reaped this way, the rest from /proc too
|
||||
int scan = 1;
|
||||
for (int i = 0; i < 64; i++) {
|
||||
siginfo_t si;
|
||||
memset(&si, 0, sizeof(si));
|
||||
if (call_orig_syscall(SYS_waitid, P_ALL, 0, (unsigned long)&si, WEXITED | WNOHANG | WNOWAIT, 0, 0) != 0 || si.si_pid <= 0) {
|
||||
scan = 0;
|
||||
break;
|
||||
}
|
||||
if (!ddh_reap_unwaited(me, si.si_pid)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
int dir = scan ? (int)call_orig_syscall(SYS_openat, (unsigned long)AT_FDCWD, (unsigned long)"/proc",
|
||||
O_RDONLY | O_DIRECTORY | O_CLOEXEC, 0, 0, 0) : -1;
|
||||
char buf[2048];
|
||||
while (dir >= 0) {
|
||||
long n = call_orig_syscall(SYS_getdents64, (unsigned long)dir, (unsigned long)buf, sizeof(buf), 0, 0, 0);
|
||||
if (n <= 0) break;
|
||||
for (long off = 0; off < n;) {
|
||||
struct ddh_reap_dirent {
|
||||
uint64_t ino;
|
||||
int64_t off;
|
||||
unsigned short reclen;
|
||||
unsigned char type;
|
||||
char name[];
|
||||
} *d = (struct ddh_reap_dirent *)(buf + off);
|
||||
off += d->reclen;
|
||||
long pid = 0;
|
||||
const char *c = d->name;
|
||||
for (; *c >= '0' && *c <= '9'; c++) pid = pid * 10 + (*c - '0');
|
||||
if (!*c && pid > 0 && pid != me) ddh_reap_unwaited(me, (pid_t)pid);
|
||||
}
|
||||
}
|
||||
if (dir >= 0) call_orig_syscall(SYS_close, (unsigned long)dir, 0, 0, 0, 0, 0);
|
||||
errno = saved;
|
||||
}
|
||||
|
||||
// Takes e's exit for one waiter (EXITED to TAKEN): 0 when another waiter has it.
|
||||
static int ddh_take(struct ddh_entry *e) {
|
||||
int expected = DDH_EXITED;
|
||||
|
||||
@@ -660,19 +660,6 @@ long syscall(long number, ...) {
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef __NR_execve
|
||||
if (number == __NR_execve) {
|
||||
return (long)execve((const char *)arg1, (char *const *)arg2, (char *const *)arg3);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef __NR_execveat
|
||||
if (number == __NR_execveat && arg2 && ((const char *)arg2)[0] != '\0' &&
|
||||
(((const char *)arg2)[0] == '/' || (int)arg1 == AT_FDCWD) && (arg5 & ~(unsigned long)AT_EMPTY_PATH) == 0) {
|
||||
return (long)execve((const char *)arg2, (char *const *)arg3, (char *const *)arg4);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef __NR_clone3
|
||||
if (number == __NR_clone3) {
|
||||
errno = ENOSYS;
|
||||
|
||||
@@ -10,12 +10,6 @@
|
||||
#define SYS_SECCOMP 1
|
||||
#endif
|
||||
|
||||
#if defined(__aarch64__)
|
||||
#define DDNATV_HOST_AUDIT_ARCH 0xC00000B7U
|
||||
#else
|
||||
#define DDNATV_HOST_AUDIT_ARCH 0x40000028U
|
||||
#endif
|
||||
|
||||
static int (*get_real_sigaction(void))(int, const struct sigaction *, struct sigaction *);
|
||||
|
||||
// A program's own SIGSYS handler, for the traps of a seccomp filter it installed itself (Firefox's
|
||||
@@ -63,13 +57,7 @@ static long sigsys_id_change(int nr, const unsigned long long *regs, long ret_va
|
||||
// Intercept SECCOMP blocked syscalls (SIGSYS), resolve sandbox/landlock gracefully, and advance PC
|
||||
static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
|
||||
if (!ctx || !info) return;
|
||||
int host_trap = info->si_code == SYS_SECCOMP && info->si_errno == 0 && info->si_arch == DDNATV_HOST_AUDIT_ARCH;
|
||||
if (!host_trap && g_app_sigsys_set) {
|
||||
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
|
||||
else g_app_sigsys.sa_handler(sig);
|
||||
return;
|
||||
}
|
||||
if (!host_trap) {
|
||||
if (info->si_code != SYS_SECCOMP) {
|
||||
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
|
||||
if (real_sig) {
|
||||
struct sigaction sa_dfl;
|
||||
@@ -81,6 +69,11 @@ static void ddnatv_sigsys_handler(int sig, siginfo_t *info, void *ctx) {
|
||||
raise(sig);
|
||||
return;
|
||||
}
|
||||
if (info->si_errno != 0 && g_app_sigsys_set) {
|
||||
if (g_app_sigsys.sa_flags & SA_SIGINFO) g_app_sigsys.sa_sigaction(sig, info, ctx);
|
||||
else g_app_sigsys.sa_handler(sig);
|
||||
return;
|
||||
}
|
||||
ucontext_t *uctx = (ucontext_t *)ctx;
|
||||
|
||||
int sys_nr = info->si_syscall;
|
||||
@@ -181,10 +174,83 @@ __attribute__((constructor(101))) static void install_sigsys_handler(void) {
|
||||
real_sig(SIGSYS, &sa, NULL);
|
||||
}
|
||||
|
||||
// SIGCHLD in a session with a parents file (handoff.c, DD_PARENTS): the program's action as it set it
|
||||
// runs from ddnatv_sigchld_handler(), which then reaps the children no wait will come for
|
||||
// (ddh_reap_unclaimed()). sigaction() shows the program its own action. A program that leaves SIGCHLD
|
||||
// alone gets the handler only when DD_REAP_ADOPTED names it: with a handler, poll(), sleep() and the
|
||||
// like return EINTR when a child exits, which a program that never had one may not expect.
|
||||
static struct sigaction g_app_sigchld;
|
||||
static int g_sigchld_managed;
|
||||
static int g_sigchld_on_default;
|
||||
|
||||
static void ddh_reap_unclaimed(void);
|
||||
static int ddh_listed(const char *list, const char *name, char *const argv[]);
|
||||
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *));
|
||||
|
||||
static void ddnatv_sigchld_handler(int sig, siginfo_t *info, void *ctx) {
|
||||
struct sigaction app = g_app_sigchld;
|
||||
if (app.sa_handler != SIG_DFL && app.sa_handler != SIG_IGN) {
|
||||
if (app.sa_flags & SA_RESETHAND) {
|
||||
// as the kernel would: the default from now on, with the handler only for a named program
|
||||
g_app_sigchld.sa_handler = SIG_DFL;
|
||||
g_app_sigchld.sa_flags &= ~(SA_SIGINFO | SA_RESETHAND);
|
||||
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
|
||||
int saved = errno;
|
||||
if (real_sig) ddnatv_apply_sigchld(real_sig);
|
||||
errno = saved;
|
||||
}
|
||||
if (app.sa_flags & SA_SIGINFO) app.sa_sigaction(sig, info, ctx);
|
||||
else app.sa_handler(sig);
|
||||
}
|
||||
ddh_reap_unclaimed();
|
||||
}
|
||||
|
||||
// Puts g_app_sigchld into effect: as it is where the kernel reaps every child itself (SIG_IGN,
|
||||
// SA_NOCLDWAIT) or the program wants no handler and is not named, else through the handler above.
|
||||
static int ddnatv_apply_sigchld(int (*real_sig)(int, const struct sigaction *, struct sigaction *)) {
|
||||
const struct sigaction *app = &g_app_sigchld;
|
||||
int handler = app->sa_handler != SIG_DFL && app->sa_handler != SIG_IGN;
|
||||
if (app->sa_handler == SIG_IGN || (app->sa_flags & SA_NOCLDWAIT) || (!handler && !g_sigchld_on_default))
|
||||
return real_sig(SIGCHLD, app, NULL);
|
||||
struct sigaction k;
|
||||
memset(&k, 0, sizeof(k));
|
||||
k.sa_sigaction = ddnatv_sigchld_handler;
|
||||
k.sa_mask = app->sa_mask;
|
||||
k.sa_flags = SA_SIGINFO | (handler ? (app->sa_flags & ~(SA_SIGINFO | SA_RESETHAND)) : (SA_RESTART | SA_NOCLDSTOP));
|
||||
return real_sig(SIGCHLD, &k, NULL);
|
||||
}
|
||||
|
||||
static int ddnatv_sigchld_action(int (*real_sig)(int, const struct sigaction *, struct sigaction *),
|
||||
const struct sigaction *act, struct sigaction *oldact) {
|
||||
struct sigaction prev = g_app_sigchld;
|
||||
if (act) {
|
||||
g_app_sigchld = *act;
|
||||
if (ddnatv_apply_sigchld(real_sig) != 0) {
|
||||
int err = errno;
|
||||
g_app_sigchld = prev;
|
||||
errno = err;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
if (oldact) *oldact = prev;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// From the hook's start (handoff.c), once the parents file is open
|
||||
static void ddnatv_manage_sigchld(void) {
|
||||
if (!getenv("DD_PARENTS")) return;
|
||||
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
|
||||
if (!real_sig || real_sig(SIGCHLD, NULL, &g_app_sigchld) != 0) return;
|
||||
const char *named = getenv("DD_REAP_ADOPTED");
|
||||
g_sigchld_on_default = named && ddh_listed(named, program_invocation_short_name, NULL);
|
||||
if (ddnatv_apply_sigchld(real_sig) == 0) g_sigchld_managed = 1;
|
||||
}
|
||||
|
||||
int sigaction(int signum, const struct sigaction *act, struct sigaction *oldact) {
|
||||
int (*real_sig)(int, const struct sigaction *, struct sigaction *) = get_real_sigaction();
|
||||
if (!real_sig) return -1;
|
||||
|
||||
if (signum == SIGCHLD && g_sigchld_managed) return ddnatv_sigchld_action(real_sig, act, oldact);
|
||||
if (signum == SIGSYS) {
|
||||
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
|
||||
return real_sig(signum, act, oldact);
|
||||
@@ -199,6 +265,7 @@ int rt_sigaction(int signum, const struct sigaction *act, struct sigaction *olda
|
||||
static int (*orig_rt_sigaction)(int, const struct sigaction *, struct sigaction *, size_t) = NULL;
|
||||
if (!orig_rt_sigaction) orig_rt_sigaction = (int (*)(int, const struct sigaction *, struct sigaction *, size_t))dlsym(RTLD_NEXT, "rt_sigaction");
|
||||
|
||||
if (signum == SIGCHLD && g_sigchld_managed) return sigaction(signum, act, oldact);
|
||||
if (signum == SIGSYS) {
|
||||
if (act && act->sa_sigaction == ddnatv_sigsys_handler) {
|
||||
return orig_rt_sigaction ? orig_rt_sigaction(signum, act, oldact, sigsetsize) : 0;
|
||||
@@ -217,6 +284,16 @@ typedef void (*sighandler_t)(int);
|
||||
sighandler_t signal(int signum, sighandler_t handler) {
|
||||
static sighandler_t (*orig_signal)(int, sighandler_t) = NULL;
|
||||
if (!orig_signal) orig_signal = (sighandler_t (*)(int, sighandler_t))dlsym(RTLD_NEXT, "signal");
|
||||
if (signum == SIGCHLD && g_sigchld_managed) {
|
||||
// glibc's signal(): BSD semantics
|
||||
struct sigaction act, old;
|
||||
memset(&act, 0, sizeof(act));
|
||||
act.sa_handler = handler;
|
||||
act.sa_flags = SA_RESTART;
|
||||
sigemptyset(&act.sa_mask);
|
||||
sigaddset(&act.sa_mask, SIGCHLD);
|
||||
return sigaction(SIGCHLD, &act, &old) == 0 ? old.sa_handler : SIG_ERR;
|
||||
}
|
||||
if (signum == SIGSYS) {
|
||||
struct sigaction act, old;
|
||||
memset(&act, 0, sizeof(act));
|
||||
|
||||
@@ -1,147 +0,0 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
BIN = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin"
|
||||
COMPAT = runpy.run_path(str(BIN / "steam-compatibility"), run_name="steam_compatibility")
|
||||
SETUP = COMPAT["DD_ANTICHEAT_SETUP"]
|
||||
|
||||
|
||||
class AntiCheatRoutingTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(temp.cleanup)
|
||||
self.root = Path(temp.name)
|
||||
self.steam = self.root / "Steam"
|
||||
self.common = self.steam / "steamapps" / "common"
|
||||
self.tools = self.steam / "compatibilitytools.d"
|
||||
self.game = self.common / "Some Game"
|
||||
self.game.mkdir(parents=True)
|
||||
self.tools.mkdir(parents=True)
|
||||
self.record = self.root / "record.json"
|
||||
self.fex = self.root / "droiddeck-fex"
|
||||
self.fex.write_text("#!/bin/bash\npython3 -c 'import json,os,sys; json.dump({\"argv\": sys.argv[2:], "
|
||||
"\"eac\": os.environ.get(\"PROTON_EAC_RUNTIME\"), \"be\": os.environ.get(\"PROTON_BATTLEYE_RUNTIME\")}, "
|
||||
"open(sys.argv[1], \"w\"))' \"$DD_RECORD\" \"$@\"\n")
|
||||
self.fex.chmod(0o755)
|
||||
|
||||
def tool(self, name, x86_64=True):
|
||||
tool = self.tools / name
|
||||
(tool / "files" / "lib" / "wine" / ("x86_64-unix" if x86_64 else "aarch64-unix")).mkdir(parents=True)
|
||||
if not x86_64:
|
||||
(tool / "files" / "bin-arm64").mkdir()
|
||||
(tool / "proton").write_text("#!/bin/sh\n")
|
||||
(tool / "proton").chmod(0o755)
|
||||
return tool
|
||||
|
||||
def runtime(self, name, library):
|
||||
folder = self.common / name / "v2" / "lib64"
|
||||
folder.mkdir(parents=True)
|
||||
(folder / library).write_text("")
|
||||
return self.common / name
|
||||
|
||||
def file(self, relative):
|
||||
path = self.game / relative
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text("{}")
|
||||
|
||||
def launch(self, verb="waitforexitandrun", extra=None):
|
||||
script = SETUP.replace("/usr/local/bin/droiddeck-fex", str(self.fex)) + (
|
||||
"dd_game_cpus() { :; }\n"
|
||||
"verb=$1; shift\n"
|
||||
"dd_anticheat \"$@\"\n"
|
||||
"echo stayed\n")
|
||||
env = {"PATH": os.environ["PATH"], "HOME": str(self.root), "DD_RECORD": str(self.record),
|
||||
"STEAM_COMPAT_INSTALL_PATH": str(self.game), "STEAM_COMPAT_CLIENT_INSTALL_PATH": str(self.steam)}
|
||||
env.update(extra or {})
|
||||
result = subprocess.run(["bash", "-c", script, "launcher", verb, str(self.game / "game.exe")],
|
||||
env=env, capture_output=True, text=True, timeout=30)
|
||||
routed = json.loads(self.record.read_text()) if self.record.exists() else None
|
||||
return result, routed
|
||||
|
||||
def test_eos_easy_anti_cheat_runs_the_newest_x86_64_build_under_fex(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
newest = self.tool("DroidDeck-Proton-11.0-10-x86_64")
|
||||
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
|
||||
runtime = self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertNotIn("stayed", result.stdout)
|
||||
self.assertEqual(routed["argv"], ["proton", str(newest / "proton"), "waitforexitandrun", str(self.game / "game.exe")])
|
||||
self.assertEqual(routed["eac"], str(runtime))
|
||||
self.assertIn("running DroidDeck-Proton-11.0-10-x86_64 under FEX", result.stderr)
|
||||
|
||||
def test_battleye_sets_its_own_runtime(self):
|
||||
self.file("BattlEye/BEClient_x64.so")
|
||||
tool = self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
runtime = self.runtime("Proton BattlEye Runtime", "beclient_x64.so")
|
||||
_, routed = self.launch()
|
||||
self.assertEqual((routed["argv"][1], routed["be"], routed["eac"]), (str(tool / "proton"), str(runtime), None))
|
||||
|
||||
def test_a_runtime_already_set_with_files_is_kept(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
own = self.root / "own-eac"
|
||||
(own / "v2").mkdir(parents=True)
|
||||
(own / "v2" / "easyanticheat_x64.so").write_text("")
|
||||
_, routed = self.launch(extra={"PROTON_EAC_RUNTIME": str(own)})
|
||||
self.assertEqual(routed["eac"], str(own))
|
||||
|
||||
def test_games_without_anti_cheat_files_stay_on_arm64(self):
|
||||
self.file("Data/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertEqual(result.stderr, "")
|
||||
|
||||
def test_without_an_x86_64_build_the_launch_stays_on_arm64(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-20", x86_64=False)
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
self.assertIn("no x86-64 DroidDeck-Proton is installed", result.stderr)
|
||||
|
||||
def test_without_the_runtime_files_the_launch_stays_on_arm64(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
(self.common / "Proton EasyAntiCheat Runtime").mkdir(parents=True)
|
||||
result, routed = self.launch()
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("its Proton runtime is not installed", result.stderr)
|
||||
|
||||
def test_the_user_can_turn_routing_off(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch(extra={"DROIDDECK_ANTICHEAT": "off"})
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
|
||||
def test_other_verbs_are_left_alone(self):
|
||||
self.file("EasyAntiCheat/Settings.json")
|
||||
self.tool("DroidDeck-Proton-11.0-1-x86_64")
|
||||
self.runtime("Proton EasyAntiCheat Runtime", "easyanticheat_x64.so")
|
||||
result, routed = self.launch(verb="getcompatpath")
|
||||
self.assertIsNone(routed)
|
||||
self.assertIn("stayed", result.stdout)
|
||||
|
||||
def test_launchers_check_before_arm64_setup_and_x86_64_tools_run_under_fex(self):
|
||||
launcher = COMPAT["LAUNCHER_SH"]
|
||||
self.assertLess(launcher.index('dd_anticheat "$@"'), launcher.index('dd_components "$depot"'))
|
||||
wrapper = COMPAT["extra_wrapper_sh"]("proton")
|
||||
self.assertLess(wrapper.index("dd_x86_64_proton() {"), wrapper.index("dd_fallback="))
|
||||
self.assertLess(wrapper.index('droiddeck-fex proton "$here/proton"'), wrapper.index('dd_components "$here"'))
|
||||
self.assertIn('! dd_x86_64_proton "$d"', wrapper)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1235,20 +1235,6 @@ class LaunchTest(FexTestCase):
|
||||
self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files"))
|
||||
self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350")
|
||||
|
||||
def test_proton_action_keeps_the_prefix_and_runs_under_fex(self):
|
||||
self.fex_tool()
|
||||
self.runtime()
|
||||
proton = self.proton("1628350")
|
||||
prefix = str(self.tmp / "compatdata" / "730")
|
||||
env = {"STEAM_COMPAT_DATA_PATH": prefix}
|
||||
with mock.patch.dict(os.environ, env, clear=False), mock.patch("os.execve") as emulated:
|
||||
self.quiet(FEX["main"], ["proton", str(proton), "waitforexitandrun", "game.exe"])
|
||||
command, guest = emulated.call_args[0][1], emulated.call_args[0][2]
|
||||
self.assertEqual(command[1:], [str(proton), "waitforexitandrun", "game.exe"])
|
||||
self.assertEqual(guest["STEAM_COMPAT_DATA_PATH"], prefix)
|
||||
self.assertNotEqual(FEX["guest_environment"]({"portable": True}, env)["STEAM_COMPAT_DATA_PATH"], prefix)
|
||||
self.assertEqual(FEX["main"](["proton", str(proton)]), 2)
|
||||
|
||||
def test_native_programs_run_directly(self):
|
||||
program = self.write(self.tmp / "native", elf(183), 0o755)
|
||||
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
|
||||
|
||||
@@ -1025,6 +1025,19 @@ int main(int argc, char **argv) {
|
||||
errno = 0;
|
||||
printf("intmin\t%d\n", (int)waitpid(-2147483647 - 1, &status, WNOHANG) == -1 && errno == ESRCH);
|
||||
}
|
||||
if (strcmp(argv[1], "nowait") == 0) {
|
||||
// no wait until the program has long exited, as Plasma's shell never waits for what it launches
|
||||
usleep(2000000);
|
||||
char path[64], line[256] = "";
|
||||
snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (f) {
|
||||
if (!fgets(line, sizeof(line), f)) line[0] = 0;
|
||||
fclose(f);
|
||||
}
|
||||
char *s = strrchr(line, ')');
|
||||
printf("zombie\t%d\n", s && s[1] == ' ' && s[2] == 'Z');
|
||||
}
|
||||
int group = strcmp(argv[1], "group") == 0;
|
||||
if (group) {
|
||||
setpgid(pid, pid);
|
||||
@@ -1139,6 +1152,93 @@ int main(void) {
|
||||
}
|
||||
"""
|
||||
|
||||
# A child subreaper, as every session process is (preload/subreaper.c), that never waits for a child
|
||||
# it did not fork. adopt: a child that exits at once leaves a grandchild, which exits once the child is
|
||||
# gone; own: its own child, which it waits for only later; vfork: one vfork() made, its program static
|
||||
# (no hook, so no record of it); handler: as adopt, with a SIGCHLD handler of its own; ignore: SIGCHLD
|
||||
# ignored, so the kernel reaps.
|
||||
ORPHANS = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/prctl.h>
|
||||
#include <sys/wait.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static volatile sig_atomic_t calls;
|
||||
static void counted(int sig) { (void)sig; calls++; }
|
||||
|
||||
static void nap(long ms) {
|
||||
struct timespec t = {ms / 1000, (ms % 1000) * 1000000L};
|
||||
while (nanosleep(&t, &t) != 0 && errno == EINTR) {}
|
||||
}
|
||||
|
||||
static int zombie(pid_t pid) {
|
||||
char path[64], line[256] = "";
|
||||
snprintf(path, sizeof(path), "/proc/%d/stat", (int)pid);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (!f) return 0;
|
||||
if (!fgets(line, sizeof(line), f)) line[0] = 0;
|
||||
fclose(f);
|
||||
char *s = strrchr(line, ')');
|
||||
return s && s[1] == ' ' && s[2] == 'Z';
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const char *mode = argv[1];
|
||||
int subreaper = 0;
|
||||
printf("subreaper\t%d\n", prctl(PR_SET_CHILD_SUBREAPER, 1) == 0 && prctl(PR_GET_CHILD_SUBREAPER, &subreaper) == 0 && subreaper);
|
||||
fflush(stdout);
|
||||
if (strcmp(mode, "handler") == 0) {
|
||||
struct sigaction sa, seen;
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_handler = counted;
|
||||
sa.sa_flags = SA_RESTART;
|
||||
sigaction(SIGCHLD, &sa, NULL);
|
||||
sigaction(SIGCHLD, NULL, &seen);
|
||||
printf("view\t%d\n", seen.sa_handler == counted);
|
||||
}
|
||||
if (strcmp(mode, "ignore") == 0) signal(SIGCHLD, SIG_IGN);
|
||||
if (strcmp(mode, "own") == 0 || strcmp(mode, "vfork") == 0) {
|
||||
pid_t child = strcmp(mode, "vfork") == 0 ? vfork() : fork();
|
||||
if (child == 0) {
|
||||
if (argc > 2) execl(argv[2], "target", "7", (char *)NULL);
|
||||
_exit(7);
|
||||
}
|
||||
nap(1500);
|
||||
int status = 0;
|
||||
pid_t r = waitpid(child, &status, 0);
|
||||
printf("own\t%d\n", r == child && WIFEXITED(status) ? WEXITSTATUS(status) : -1);
|
||||
return 0;
|
||||
}
|
||||
int pipefd[2];
|
||||
if (pipe(pipefd) != 0) return 1;
|
||||
pid_t middle = fork();
|
||||
if (middle == 0) {
|
||||
pid_t grandchild = fork();
|
||||
if (grandchild == 0) {
|
||||
nap(300); // its parent is gone by then
|
||||
_exit(5);
|
||||
}
|
||||
if (write(pipefd[1], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) _exit(1);
|
||||
_exit(0);
|
||||
}
|
||||
pid_t grandchild = 0;
|
||||
if (read(pipefd[0], &grandchild, sizeof(grandchild)) != sizeof(grandchild)) return 1;
|
||||
int status = 0;
|
||||
printf("middle\t%d\n", waitpid(middle, &status, 0) == middle);
|
||||
nap(1500);
|
||||
printf("orphan\t%d\n", zombie(grandchild));
|
||||
printf("adopted\t%d\n", waitpid(grandchild, &status, WNOHANG) == grandchild);
|
||||
if (strcmp(mode, "handler") == 0) printf("calls\t%d\n", calls > 0);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
DUPRACE = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
@@ -1480,7 +1580,7 @@ class NativeHookHandoffTest(unittest.TestCase):
|
||||
raise RuntimeError("workers that may still run: %s" % failed)
|
||||
|
||||
def run_parent(self, *argv, handoff="target", hook=True, reports=True, pressure=None, as_shell=False, terminal=False,
|
||||
delay=0, extra_env=None):
|
||||
delay=0, extra_env=None, parent_name=None):
|
||||
name = "dd-handoff-test-%d-%s-%s-%d" % (os.getpid(), self.id().rsplit(".", 1)[-1], handoff, hook)
|
||||
spawner = FakeSpawner(name, self.prefix or [], self.root, reports, delay)
|
||||
spawner.start()
|
||||
@@ -1496,9 +1596,9 @@ class NativeHookHandoffTest(unittest.TestCase):
|
||||
hook_env["QEMU_LD_PREFIX"] = self.prefix[self.prefix.index("-L") + 1]
|
||||
env = {k: v for k, v in os.environ.items() if k not in hook_env}
|
||||
prefix, parent = list(self.prefix or []), str(self.parent)
|
||||
if as_shell:
|
||||
# the hook tells a shell's child by its parent's name (qemu-user takes the program's)
|
||||
shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / "bash"
|
||||
if as_shell or parent_name:
|
||||
# the hook tells a shell's or a launcher's child by its parent's name (qemu-user takes the program's)
|
||||
shell = Path(self.tmp.name) / ("shell-%s" % self.id().rsplit(".", 1)[-1]) / (parent_name or "bash")
|
||||
shell.parent.mkdir(exist_ok=True)
|
||||
shutil.copy(parent, shell)
|
||||
parent = str(shell)
|
||||
@@ -1707,6 +1807,41 @@ class NativeHookHandoffTest(unittest.TestCase):
|
||||
self.assertEqual([], requests)
|
||||
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
||||
|
||||
def run_launcher(self, *argv, parent_name="plasmashell", **kwargs):
|
||||
return self.run_parent(*argv, handoff="other", pressure=1000, parent_name=parent_name,
|
||||
extra_env={"DD_HANDOFF_LAUNCHERS": "plasmashell:krunner"}, **kwargs)
|
||||
|
||||
def test_a_program_a_desktop_launcher_starts_is_handed_off(self):
|
||||
# an app from Plasma's panel: unlisted, far from the limit, still its own app process
|
||||
result, requests, out = self.run_launcher("wait", "7")
|
||||
self.assertEqual(1, len(requests), out.stderr)
|
||||
self.assertEqual(["target", "7"], requests[0]["argv"])
|
||||
self.assertEqual("7", result.get("exit"), out.stdout)
|
||||
|
||||
def test_a_child_of_a_program_not_named_a_launcher_is_not(self):
|
||||
result, requests, out = self.run_launcher("wait", "3", parent_name="konsole")
|
||||
self.assertEqual([], requests, out.stderr)
|
||||
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
||||
|
||||
def test_a_launchers_child_in_a_process_group_of_its_own_is_not(self):
|
||||
result, requests, out = self.run_launcher("group", "4")
|
||||
self.assertEqual([], requests, out.stderr)
|
||||
self.assertEqual("4" if self.child_status == "3" else "127", result.get("exit"), out.stdout)
|
||||
|
||||
def test_a_launchers_child_on_a_terminal_is_not(self):
|
||||
# a terminal's shell, set up by its launcher (Konsole's part in Dolphin): the terminal is its own
|
||||
result, requests, out = self.run_launcher("wait", "3", terminal=True)
|
||||
self.assertEqual([], requests, out.stderr)
|
||||
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
||||
|
||||
def test_the_steam_client_a_launcher_starts_is_not(self):
|
||||
steam = self.root / "bin/steam"
|
||||
if not steam.exists():
|
||||
shutil.copy(self.root / "bin/target", steam)
|
||||
result, requests, out = self.run_launcher("wait", "3", "/bin/steam")
|
||||
self.assertEqual([], requests, out.stderr)
|
||||
self.assertEqual(self.child_status, result.get("exit"), out.stdout)
|
||||
|
||||
def test_near_the_limit_a_child_of_another_program_is_not(self):
|
||||
result, requests, out = self.run_parent("wait", "3", handoff="other", pressure=0)
|
||||
self.assertEqual([], requests)
|
||||
@@ -2245,6 +2380,79 @@ class NativeHookHandoffTest(unittest.TestCase):
|
||||
pass_fds=(table,))
|
||||
return parent, dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line), out
|
||||
|
||||
def run_orphans(self, mode, named=True, parents=True, *args):
|
||||
tmp = Path(self.tmp.name)
|
||||
probe = tmp / "orphans"
|
||||
if not probe.exists():
|
||||
(tmp / "orphans.c").write_text(ORPHANS)
|
||||
subprocess.run([self.cc, "-O1", "-o", str(probe), str(tmp / "orphans.c")], check=True)
|
||||
(self.root / "run").mkdir(exist_ok=True)
|
||||
env = {"LD_PRELOAD": str(self.hook), "DDNATV_ROOT": str(self.root)}
|
||||
if parents:
|
||||
env["DD_PARENTS"] = "/run/parents-%s" % self.id().rsplit(".", 1)[-1]
|
||||
if named:
|
||||
env["DD_REAP_ADOPTED"] = "other:orphans"
|
||||
# not a session's own settings, when run inside one
|
||||
inherited = {k: v for k, v in os.environ.items() if k not in ("DD_PARENTS", "DD_REAP_ADOPTED")}
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + [arg for key, value in env.items() for arg in ("-E", f"{key}={value}")]
|
||||
run_env = inherited
|
||||
else:
|
||||
cmd = []
|
||||
run_env = dict(inherited, **env)
|
||||
out = subprocess.run(cmd + [str(probe), mode, *args], env=run_env, capture_output=True, text=True, timeout=60)
|
||||
result = dict(line.split("\t", 1) for line in out.stdout.splitlines() if "\t" in line)
|
||||
if mode == "adopt" and result.get("subreaper") != "1":
|
||||
self.skipTest("no child subreaper here (qemu-user has no PR_SET_CHILD_SUBREAPER)")
|
||||
return result, out
|
||||
|
||||
def test_a_subreaper_reaps_the_zombie_it_adopted(self):
|
||||
result, out = self.run_orphans("adopt")
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual("1", result.get("middle"), out.stdout)
|
||||
self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr)
|
||||
self.assertEqual("0", result.get("adopted"), out.stdout)
|
||||
|
||||
def test_a_program_not_named_keeps_its_default_sigchld_and_its_adopted_zombie(self):
|
||||
result, out = self.run_orphans("adopt", False)
|
||||
self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr)
|
||||
self.assertEqual("1", result.get("adopted"), out.stdout)
|
||||
|
||||
def test_without_a_parents_file_nothing_is_reaped(self):
|
||||
result, out = self.run_orphans("adopt", True, False)
|
||||
self.assertEqual("1", result.get("orphan"), out.stdout + out.stderr)
|
||||
|
||||
def test_a_subreapers_own_child_waits_for_its_wait(self):
|
||||
result, out = self.run_orphans("own")
|
||||
self.assertEqual("7", result.get("own"), out.stdout + out.stderr)
|
||||
|
||||
def test_a_vfork_child_with_no_record_waits_for_its_parents_wait(self):
|
||||
result, out = self.run_orphans("vfork", True, True, "/bin/target")
|
||||
self.assertEqual("7", result.get("own"), out.stdout + out.stderr)
|
||||
|
||||
def test_a_programs_own_sigchld_handler_runs_and_shows_as_its_own(self):
|
||||
result, out = self.run_orphans("handler", False)
|
||||
self.assertEqual("1", result.get("view"), out.stdout + out.stderr)
|
||||
self.assertEqual("1", result.get("calls"), out.stdout)
|
||||
if result.get("subreaper") == "1":
|
||||
self.assertEqual("0", result.get("orphan"), out.stdout)
|
||||
|
||||
def test_an_ignored_sigchld_stays_the_kernels(self):
|
||||
result, out = self.run_orphans("ignore")
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
self.assertEqual("0", result.get("orphan"), out.stdout + out.stderr)
|
||||
|
||||
def test_an_unwaited_handoffs_child_is_reaped(self):
|
||||
# a parent that never waits until its program has long exited, as Plasma's shell
|
||||
(self.root / "run").mkdir(exist_ok=True)
|
||||
env = {"DD_PARENTS": "/run/parents-nowait", "DD_REAP_ADOPTED": "parent"}
|
||||
result, requests, out = self.run_parent("nowait", "6", extra_env=env)
|
||||
self.assertEqual(1, len(requests), out.stderr)
|
||||
self.assertEqual("0", result.get("zombie"), out.stdout + out.stderr)
|
||||
# its program's exit, still there for the wait that comes at last
|
||||
self.assertEqual("1", result.get("same"), out.stdout)
|
||||
self.assertEqual("6", result.get("exit"), out.stdout)
|
||||
|
||||
def test_a_guest_sees_no_pidfd_support_so_its_waits_go_through_the_handoff(self):
|
||||
parent, result, out = self.run_worker_program("pidfd", PIDFD_PROBE)
|
||||
self.assertEqual(0, out.returncode, out.stderr)
|
||||
|
||||
Reference in new issue
Block a user