mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 04:25:38 +00:00
Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
28a5423629 | ||
|
|
8ebba02688 | ||
|
|
4cbda4e51b | ||
|
|
b7bf189166 | ||
|
|
f3b5cadb7b | ||
|
|
ac0909eaa3 | ||
|
|
ffa40a15d5 | ||
|
|
74977d1738 | ||
|
|
184409f33c | ||
|
|
42239e0097 | ||
|
|
c117f6f4c7 | ||
|
|
4a93663d14 | ||
|
|
1ca2d9bd49 | ||
|
|
c8baca10e6 | ||
|
|
9922823090 | ||
|
|
a760aea276 | ||
|
|
e079f9602f | ||
|
|
dfc0b95557 | ||
|
|
30270ca654 | ||
|
|
8c16a04d8d | ||
|
|
0fd50d76b2 |
No files matched your search
@@ -601,7 +601,7 @@ jobs:
|
||||
- name: Install Python test dependencies
|
||||
run: |
|
||||
sudo apt-get update -qq
|
||||
sudo apt-get install -y -qq python3-yaml
|
||||
sudo apt-get install -y -qq python3-yaml gcc-aarch64-linux-gnu qemu-user
|
||||
|
||||
- name: Steam import and game environment tests
|
||||
run: python3 -m unittest discover -s tools/tests -p 'test_*.py'
|
||||
|
||||
@@ -47,7 +47,7 @@ Compatibility and performance vary by device; hardware validation is limited. De
|
||||
|
||||
## Credits and licence
|
||||
|
||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
|
||||
GPL-3.0. Runtime, shim, input, and controller work build on WinNative and Bannerlator (maxjivi05). Epic Games and GOG support build on [Phobos’s](https://github.com/phobos665) adaptation of [Legendary](https://github.com/legendary-gl/legendary) and [gogdl](https://github.com/Heroic-Games-Launcher/heroic-gogdl), respectively. The registry entries a GOG game's install script (`goggame-<id>.script`) sets are read the way [Heroic Games Launcher](https://github.com/Heroic-Games-Launcher/HeroicGamesLauncher)'s GOG setup (GPL-3.0) reads them. LSFG frame generation is from the work of Camille LaVey and the [Eden](https://eden-emu.dev) emulator project, following [lsfg-vk](https://github.com/PancakeTAS/lsfg-vk), ported to WinNative and DroidDeck by [@maxjivi05](https://github.com/maxjivi05); it needs your own copy of [Lossless Scaling](https://store.steampowered.com/app/993090/) and ships none of its shaders. x86 AppImages, and any whose own runtime cannot unpack them, are unpacked with [uruntime](https://github.com/VHSgunzo/uruntime) by VHSgunzo (MIT), shipped unmodified with its licence, which also starts the arm64 emulator AppImages whose own runtime cannot run its extractor on Android. The Steam client's audio goes through [@The412Banner](https://github.com/The412Banner)'s [DirectAudio](https://github.com/The412Banner/directaudio) PulseAudio sink (LGPL-2.1-or-later), built from `tools/directaudio/sink` with its request size kept to its ring so clients are not asked to queue 100 ms ahead. mmap ring-buffer controller input was developed by ribbit384 ([WinNative #345](https://github.com/WinNative-Emu/WinNative/pull/345)). Why the x86-64 Steam client refused the arm64 client's sign-in was checked by reading Steam's saved token with the `ConnectCache` format from [deadlock-api-ingest](https://github.com/deadlock-api/deadlock-api-ingest). x86 programs that link OpenSSL 3 under FEX use the copy in the [Steam Linux Runtime 4.0](https://gitlab.steamos.cloud/steamrt/steamrt) platform. Hooks written with `WriteProcessMemory` into code [FEX](https://github.com/FEX-Emu/FEX) has translated go through `/proc/<pid>/mem` again when the kernel refuses `process_vm_writev`, as [Wine](https://gitlab.winehq.org/wine/wine)'s `server/ptrace.c` wrote them before Wine 11. x86 Linux games under FEX get the same `/etc/asound.conf` that [pressure-vessel](https://gitlab.steamos.cloud/steamrt/steam-runtime-tools) writes into the Steam Linux Runtime, so ALSA plays through PulseAudio. Games render with [Mesa](https://gitlab.freedesktop.org/mesa/mesa) Turnip's own per-render-pass choice between tile memory and system memory, while the Steam client keeps `TU_DEBUG=sysmem`; [FEX](https://github.com/FEX-Emu/FEX)'s code disk cache was checked in its source and is already on through Proton. The proot fast path picks the guest name of a host file bound under several names in the order [PRoot](https://github.com/proot-me/proot)'s `path/binding.c` (GPL-2.0-or-later) sorts its bindings, so links and `/proc/self/fd` read back as they do through proot. The session's [PipeWire](https://gitlab.freedesktop.org/pipewire/pipewire) (MIT) opens its sockets with the per-socket access settings documented in its `module-access.c`, and [WirePlumber](https://gitlab.freedesktop.org/pipewire/wireplumber) (MIT) keeps those clients at full permissions through its `access.rules`. Wine write watches use the userfaultfd support in [Proton](https://github.com/ValveSoftware/wine)'s `dlls/ntdll/unix/virtual.c` (LGPL-2.1-or-later): libblsession gives it the arm64 syscall number and answers its `PAGEMAP_SCAN` from `/proc/self/pagemap` where Android refuses the ioctl. Wine on arm64 sets a thread's full context by raising `SIGUSR2` from `syscall_dispatcher_return_slowpath` in [Wine](https://gitlab.winehq.org/wine/wine)'s `dlls/ntdll/unix/signal_arm64.c` (LGPL-2.1-or-later); libblsession runs that handler in place on a frame laid out as the [Linux](https://github.com/torvalds/linux) kernel's `arch/arm64/kernel/signal.c` builds it and returns through `rt_sigreturn`, so proot does not stop the thread for it. Wine's process list reads each process's memory counters from `/proc/<pid>/status` in `fill_vm_counters` ([Wine](https://gitlab.winehq.org/wine/wine) `dlls/ntdll/unix/process.c`, LGPL-2.1-or-later), so libblsession gives those reads the kernel's file instead of a copy with `TracerPid` cleared. See [LICENSE](LICENSE). Steam and Proton belong to Valve Corporation; this project is not affiliated with Valve.
|
||||
|
||||
XR glasses support builds on WinNative's VITURE glasses work. VITURE protocol details were checked against [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) by [@wheaney](https://github.com/wheaney), including the VITURE protocol header it ships, [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) by [@badicsalex](https://github.com/badicsalex) and the [go-macos/iokit VITURE package](https://pkg.go.dev/github.com/go-macos/iokit/viture); the optional VITURE SDK belongs to VITURE and is not included. RayNeo support adapts [@informalTechCode](https://github.com/informalTechCode)'s [RayNeo-Air-Series-3DoF-Scaffold](https://github.com/informalTechCode/RayNeo-Air-Series-3DoF-Scaffold) (Apache-2.0) and references [@verncat](https://github.com/verncat)'s [RayNeo-Air-3S-Pro-OpenVR](https://github.com/verncat/RayNeo-Air-3S-Pro-OpenVR) (MIT) and [Monado](https://gitlab.freedesktop.org/monado/monado) (BSL-1.0); see [docs/third-party/rayneo](docs/third-party/rayneo/README.md). XREAL 1S support references [XRLinuxDriver](https://github.com/wheaney/XRLinuxDriver) and [xrealOneDeviceKit](https://github.com/wheaney/xrealOneDeviceKit) by @wheaney, [xreal_one_driver](https://github.com/rohitsangwan01/xreal_one_driver) by [@rohitsangwan01](https://github.com/rohitsangwan01) (MIT) and [xr-tools](https://github.com/0xcaff/xr-tools) by [@0xcaff](https://github.com/0xcaff). Rokid support follows the Rokid protocol notes in [ar-drivers-rs](https://github.com/badicsalex/ar-drivers-rs) and @badicsalex's [Void Computing write-ups](https://voidcomputing.hu/blog/worse-better-prettier/), and [Monado](https://gitlab.freedesktop.org/monado/monado)'s Rokid driver. The REDMAGIC glasses-display findings draw on [@mekhontsev](https://github.com/mekhontsev)'s [MagicDesk investigation](https://github.com/mekhontsev/magicdesk/blob/main/docs/xr-resolution-fix.md) and [@Coding-BR](https://github.com/Coding-BR)'s [decompiled Nubia kernel](https://github.com/Coding-BR/android_kernel_nubia_sm8850_qwjujube). VITURE, RayNeo, XREAL, Rokid and REDMAGIC are trademarks of their owners; this project is not affiliated with them.
|
||||
|
||||
|
||||
+2
-2
@@ -115,13 +115,13 @@ def variantSuffixes = rootProject.file('tools/release/variants.txt').readLines()
|
||||
|
||||
android {
|
||||
namespace 'com.droiddeck.launcher'
|
||||
compileSdk 34
|
||||
compileSdk 36
|
||||
ndkVersion project.findProperty('ndkVersion') ?: '27.3.13750724'
|
||||
|
||||
defaultConfig {
|
||||
applicationId "com.droiddeck.launcher"
|
||||
minSdkVersion 26
|
||||
targetSdkVersion 28
|
||||
targetSdkVersion 36
|
||||
versionCode 15
|
||||
versionName "0.6.0"
|
||||
buildConfigField "String", "BUILD_LABEL", "\"${escapedBuildLabel}\""
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />
|
||||
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
|
||||
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
|
||||
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
|
||||
@@ -19,7 +21,8 @@
|
||||
<uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
|
||||
<uses-permission android:name="android.permission.RECORD_AUDIO" />
|
||||
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
|
||||
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
|
||||
<uses-permission android:name="android.permission.CAMERA" />
|
||||
|
||||
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
|
||||
@@ -40,6 +43,7 @@
|
||||
android:hardwareAccelerated="true"
|
||||
android:largeHeap="true"
|
||||
android:extractNativeLibs="true"
|
||||
android:requestLegacyExternalStorage="true"
|
||||
android:appCategory="game"
|
||||
android:isGame="true">
|
||||
|
||||
@@ -190,13 +194,24 @@
|
||||
<service
|
||||
android:name=".session.SessionService"
|
||||
android:exported="false"
|
||||
android:stopWithTask="false" />
|
||||
android:foregroundServiceType="specialUse"
|
||||
android:stopWithTask="false">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Runs the user's Linux game session (compositor, Steam client, audio) while the app is not on screen" />
|
||||
</service>
|
||||
<service
|
||||
android:name=".runtime.RuntimeInstallService"
|
||||
android:exported="false" />
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="dataSync" />
|
||||
<service
|
||||
android:name=".core.WirelessAdbPairingService"
|
||||
android:exported="false" />
|
||||
android:exported="false"
|
||||
android:foregroundServiceType="specialUse">
|
||||
<property
|
||||
android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"
|
||||
android:value="Waits for the wireless debugging pairing code the user enters from the notification" />
|
||||
</service>
|
||||
<service
|
||||
android:name=".stores.download.StoreDownloadService"
|
||||
android:exported="false"
|
||||
|
||||
@@ -410,6 +410,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
private var logsEnabled by mutableStateOf(true)
|
||||
private var vacDiagnostics by mutableStateOf(false)
|
||||
private var agentCommands by mutableStateOf(false)
|
||||
private var bluetoothAllowed by mutableStateOf<Boolean?>(null)
|
||||
private var allFilesAllowed by mutableStateOf<Boolean?>(null)
|
||||
private var showRoms by mutableStateOf(false)
|
||||
private var homeAppSelected by mutableStateOf(false)
|
||||
private var homeScreenEnabled by mutableStateOf(false)
|
||||
@@ -789,6 +791,7 @@ class FrontEndActivity : ComponentActivity() {
|
||||
offlineAccount = offlineAccount, offline = offline,
|
||||
frameGenLabel = frameGenLabel, romsDir = romsDir, logsEnabled = logsEnabled,
|
||||
vacDiagnostics = vacDiagnostics, agentCommands = agentCommands,
|
||||
bluetoothAllowed = bluetoothAllowed, allFilesAllowed = allFilesAllowed,
|
||||
steamGames = steamGames, steamGamesX64 = steamGamesX64, emulators = emulatorList, running = runningLabel,
|
||||
frameGen = FrameGen.mode(this),
|
||||
lossless = lossless,
|
||||
@@ -949,6 +952,8 @@ class FrontEndActivity : ComponentActivity() {
|
||||
com.droiddeck.launcher.agent.AgentAccess.setCommandsEnabled(this, !com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this))
|
||||
agentCommands = com.droiddeck.launcher.agent.AgentAccess.commandsEnabled(this)
|
||||
},
|
||||
onBluetoothAllowed = { askBluetooth() },
|
||||
onAllFilesAllowed = { com.droiddeck.launcher.core.AllFilesAccess.openSettings(this) },
|
||||
onShareLogs = {
|
||||
SessionLogShare.prepare(this, { SessionLogShare.latest(this) }) { zip ->
|
||||
if (zip == null) android.widget.Toast.makeText(this, R.string.main_no_logs_yet, android.widget.Toast.LENGTH_LONG).show()
|
||||
@@ -1182,15 +1187,28 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
val wanted = ArrayList<String>()
|
||||
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
|
||||
&& checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
wanted.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
|
||||
}
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && !SessionPrefs.bluetoothAsked(this)
|
||||
&& checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
|
||||
wanted.add(Manifest.permission.BLUETOOTH_CONNECT)
|
||||
SessionPrefs.setBluetoothAsked(this)
|
||||
}
|
||||
if (SessionPrefs.micEnabled(this) && !SessionPrefs.micAsked(this)
|
||||
&& checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
|
||||
wanted.add(Manifest.permission.RECORD_AUDIO)
|
||||
SessionPrefs.setMicAsked(this)
|
||||
}
|
||||
if (wanted.isNotEmpty()) requestPermissions(wanted.toTypedArray(), 1)
|
||||
else if (!com.droiddeck.launcher.core.AllFilesAccess.granted() && !SessionPrefs.allFilesAsked(this)) {
|
||||
Thread({
|
||||
if (com.droiddeck.launcher.core.AllFilesAccess.usesSharedStorage(this)) runOnUiThread {
|
||||
if (com.droiddeck.launcher.core.AllFilesAccess.ask(this)) SessionPrefs.setAllFilesAsked(this)
|
||||
}
|
||||
}, "all-files-access").start()
|
||||
}
|
||||
Thread({ com.droiddeck.launcher.stores.StoreAccounts.encryptAll(this) }, "store-credentials").start()
|
||||
if (!SessionState.running) Thread({
|
||||
com.droiddeck.launcher.session.LogMigration.run(this)
|
||||
@@ -1279,11 +1297,32 @@ class FrontEndActivity : ComponentActivity() {
|
||||
}
|
||||
}
|
||||
|
||||
private fun refreshPermissionRows() {
|
||||
bluetoothAllowed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S)
|
||||
checkSelfPermission(Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED else null
|
||||
allFilesAllowed = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) com.droiddeck.launcher.core.AllFilesAccess.granted() else null
|
||||
}
|
||||
|
||||
private fun askBluetooth() {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return
|
||||
val permission = Manifest.permission.BLUETOOTH_CONNECT
|
||||
val granted = checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
|
||||
if (granted || (SessionPrefs.bluetoothAsked(this) && !shouldShowRequestPermissionRationale(permission))) {
|
||||
runCatching {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, android.net.Uri.parse("package:$packageName")))
|
||||
}
|
||||
} else {
|
||||
SessionPrefs.setBluetoothAsked(this)
|
||||
requestPermissions(arrayOf(permission), 3)
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
orientation = SessionPrefs.orientation(this)
|
||||
requestedOrientation = orientation
|
||||
refreshWifiDiscovery()
|
||||
refreshPermissionRows()
|
||||
com.droiddeck.launcher.stores.StoresState.refresh(this)
|
||||
com.droiddeck.launcher.stores.StoresState.libraryListener = { refreshAddedGames(); refresh() }
|
||||
com.droiddeck.launcher.ui.Motion.refresh(this)
|
||||
|
||||
@@ -17,6 +17,8 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
private File logFile;
|
||||
private final File micFifoPath;
|
||||
private volatile int pid = -1;
|
||||
private final Object micLock = new Object();
|
||||
private boolean micHot;
|
||||
|
||||
public DirectAudioRelayComponent(File socketPath, File micFifoPath) {
|
||||
this.socketPath = socketPath;
|
||||
@@ -30,6 +32,9 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
@Override
|
||||
public void start() {
|
||||
stop();
|
||||
synchronized (micLock) {
|
||||
micHot = false;
|
||||
}
|
||||
File binary = new File(app().getApplicationInfo().nativeLibraryDir, BINARY);
|
||||
if (!binary.isFile()) {
|
||||
Log.w(TAG, "helper missing at " + binary + "; DirectAudio will report itself unavailable");
|
||||
@@ -79,12 +84,40 @@ public class DirectAudioRelayComponent extends SessionPart {
|
||||
app().getFilesDir(), null,
|
||||
line -> {
|
||||
Log.i(TAG, line);
|
||||
trackMic(line);
|
||||
if (log != null) synchronized (log) { log.println(line); log.flush(); }
|
||||
});
|
||||
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
|
||||
+ (micFifoPath != null ? " mic=" + micFifoPath : " (no microphone)"));
|
||||
}
|
||||
|
||||
private void trackMic(String line) {
|
||||
boolean start = line.startsWith("DA-Relay: mic start ");
|
||||
if (!start && !line.startsWith("DA-Relay: mic stop ")) return;
|
||||
synchronized (micLock) {
|
||||
micHot = start;
|
||||
micLock.notifyAll();
|
||||
}
|
||||
}
|
||||
|
||||
// Android keeps the input stream's wake lock while a frozen helper still has it started.
|
||||
public boolean awaitMicReleased(long timeoutMs) {
|
||||
long deadline = System.currentTimeMillis() + timeoutMs;
|
||||
synchronized (micLock) {
|
||||
while (micHot) {
|
||||
long left = deadline - System.currentTimeMillis();
|
||||
if (left <= 0) return false;
|
||||
try {
|
||||
micLock.wait(left);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
if (pid != -1) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import java.util.concurrent.TimeUnit;
|
||||
public class PulseAudioComponent extends SessionPart {
|
||||
private static final String TAG = "PulseAudio";
|
||||
public static final String SOCKET_NAME = "PS0";
|
||||
private static final String MIC_SOURCE = "DirectAudioMic";
|
||||
private static final String BUNDLE_STAMP = "2026-10-08-pa13-directaudio-native";
|
||||
|
||||
|
||||
@@ -97,9 +98,9 @@ public class PulseAudioComponent extends SessionPart {
|
||||
config.add("set-default-sink DirectAudio");
|
||||
config.add(".fail");
|
||||
if (micFifoPath != null && !micFifoPath.isEmpty()) {
|
||||
config.add("load-module module-pipe-source source_name=DirectAudioMic file=\""
|
||||
config.add("load-module module-pipe-source source_name=" + MIC_SOURCE + " file=\""
|
||||
+ micFifoPath + "\" format=s16le rate=48000 channels=1");
|
||||
config.add("set-default-source DirectAudioMic");
|
||||
config.add("set-default-source " + MIC_SOURCE);
|
||||
}
|
||||
FileUtils.writeString(new File(workingDir, "default.pa"), String.join("\n", config));
|
||||
|
||||
@@ -109,7 +110,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
env.add("HOME=" + workingDir);
|
||||
env.add("TMPDIR=" + workingDir);
|
||||
|
||||
String command = workingDir.getAbsolutePath() + "/libpulseaudio.so"
|
||||
String command = HostProcess.LINKER + " " + workingDir.getAbsolutePath() + "/libpulseaudio.so"
|
||||
+ " --system=false --disable-shm=true --fail=false"
|
||||
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
|
||||
+ " --log-level=info";
|
||||
@@ -158,6 +159,7 @@ public class PulseAudioComponent extends SessionPart {
|
||||
try {
|
||||
File modules = new File(workingDir, "modules/arm64");
|
||||
ArrayList<String> cmd = new ArrayList<>();
|
||||
cmd.add(HostProcess.LINKER);
|
||||
cmd.add(pactl.getAbsolutePath());
|
||||
java.util.Collections.addAll(cmd, args);
|
||||
ProcessBuilder builder = new ProcessBuilder(cmd);
|
||||
@@ -202,16 +204,24 @@ public class PulseAudioComponent extends SessionPart {
|
||||
}
|
||||
|
||||
public boolean setSinkSuspended(boolean suspended) {
|
||||
return suspend("sink", "@DEFAULT_SINK@", suspended);
|
||||
}
|
||||
|
||||
public boolean setMicSuspended(boolean suspended) {
|
||||
return micFifoPath == null || micFifoPath.isEmpty() || suspend("source", MIC_SOURCE, suspended);
|
||||
}
|
||||
|
||||
private boolean suspend(String kind, String name, boolean suspended) {
|
||||
File pactl = new File(workingDir, "pactl");
|
||||
if (!pactl.isFile() || pid <= 1) {
|
||||
Log.w(TAG, "cannot change sink state: PulseAudio control client or server unavailable");
|
||||
Log.w(TAG, "cannot change " + kind + " state: PulseAudio control client or server unavailable");
|
||||
return false;
|
||||
}
|
||||
java.lang.Process process = null;
|
||||
try {
|
||||
File modules = new File(workingDir, "modules/arm64");
|
||||
ProcessBuilder builder = new ProcessBuilder(
|
||||
pactl.getAbsolutePath(), "suspend-sink", "@DEFAULT_SINK@", Boolean.toString(suspended));
|
||||
HostProcess.LINKER, pactl.getAbsolutePath(), "suspend-" + kind, name, Boolean.toString(suspended));
|
||||
builder.directory(workingDir);
|
||||
builder.redirectErrorStream(true);
|
||||
builder.redirectOutput(new File("/dev/null"));
|
||||
@@ -222,18 +232,18 @@ public class PulseAudioComponent extends SessionPart {
|
||||
process = builder.start();
|
||||
if (!process.waitFor(5, TimeUnit.SECONDS)) {
|
||||
process.destroyForcibly();
|
||||
Log.w(TAG, "timed out changing sink state to suspended=" + suspended);
|
||||
Log.w(TAG, "timed out changing " + kind + " state to suspended=" + suspended);
|
||||
return false;
|
||||
}
|
||||
int status = process.exitValue();
|
||||
if (status != 0) Log.w(TAG, "sink state change failed with exit " + status);
|
||||
if (status != 0) Log.w(TAG, kind + " state change failed with exit " + status);
|
||||
return status == 0;
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
Log.w(TAG, "interrupted changing sink state", e);
|
||||
Log.w(TAG, "interrupted changing " + kind + " state", e);
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
Log.w(TAG, "could not change sink state", e);
|
||||
Log.w(TAG, "could not change " + kind + " state", e);
|
||||
return false;
|
||||
} finally {
|
||||
if (process != null && process.isAlive()) process.destroyForcibly();
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.Settings
|
||||
import com.droiddeck.launcher.R
|
||||
import com.droiddeck.launcher.frontend.AddedExes
|
||||
import com.droiddeck.launcher.stores.StoreInstallRoot
|
||||
|
||||
object AllFilesAccess {
|
||||
fun granted(): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.R || Environment.isExternalStorageManager()
|
||||
|
||||
fun usesSharedStorage(context: Context): Boolean {
|
||||
val own = (listOf(context.filesDir.parentFile) + context.getExternalFilesDirs(null).map { it?.parentFile })
|
||||
.filterNotNull().map { it.absolutePath + "/" }
|
||||
fun shared(path: String) = own.none { (path + "/").startsWith(it) }
|
||||
return AddedExes.list(context).any { shared(it.folder) } ||
|
||||
StoreInstallRoot.roots(context).any { shared(it.absolutePath) }
|
||||
}
|
||||
|
||||
fun ask(activity: Activity): Boolean {
|
||||
if (granted() || activity.isFinishing) return false
|
||||
AlertDialog.Builder(activity)
|
||||
.setTitle(R.string.all_files_title)
|
||||
.setMessage(R.string.all_files_message)
|
||||
.setPositiveButton(R.string.all_files_allow) { _, _ -> openSettings(activity) }
|
||||
.setNegativeButton(R.string.all_files_later, null)
|
||||
.show()
|
||||
return true
|
||||
}
|
||||
|
||||
fun openSettings(activity: Activity) {
|
||||
val forApp = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + activity.packageName))
|
||||
try {
|
||||
activity.startActivity(forApp)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
runCatching { activity.startActivity(Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION)) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -67,9 +67,11 @@ public final class Downloader {
|
||||
String expectedSha256, java.util.function.Consumer<Float> progress) {
|
||||
Identity identity = loadIdentity(destination, resume, expectedSha256);
|
||||
for (int i = 0; i < sources.size(); i++) {
|
||||
if (Thread.currentThread().isInterrupted()) return false;
|
||||
String source = sources.get(i);
|
||||
if (i > 0) Log.i(TAG, "retrying " + original + " via " + source);
|
||||
Outcome outcome = attempt(source, destination, resume, identity, expectedSha256, progress);
|
||||
if (Thread.currentThread().isInterrupted()) return false;
|
||||
if (outcome == Outcome.DONE) {
|
||||
if (expectedSha256 != null && !expectedSha256.equalsIgnoreCase(Hashes.sha256(destination))) {
|
||||
Log.w(TAG, "checksum mismatch from " + source + "; trying another source");
|
||||
@@ -212,6 +214,7 @@ public final class Downloader {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
long lastReport = 0;
|
||||
for (int read = in.read(buffer); read > 0; read = in.read(buffer)) {
|
||||
if (Thread.currentThread().isInterrupted()) return Outcome.RETRY;
|
||||
out.write(buffer, 0, read);
|
||||
written += read;
|
||||
if (progress != null && written - lastReport > (1 << 20)) {
|
||||
|
||||
@@ -5,6 +5,8 @@ import java.io.File
|
||||
import java.util.function.Consumer
|
||||
|
||||
object HostProcess {
|
||||
const val LINKER = "/system/bin/linker64"
|
||||
|
||||
private const val TAG = "HostProcess"
|
||||
|
||||
@JvmStatic
|
||||
|
||||
@@ -10,9 +10,10 @@ import com.droiddeck.launcher.session.SessionPrefs
|
||||
object WifiDiscovery {
|
||||
val permissions = arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
|
||||
fun permissionGranted(context: Context): Boolean = permissions.any {
|
||||
context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
fun permissionGranted(context: Context): Boolean =
|
||||
(if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) arrayOf(Manifest.permission.ACCESS_FINE_LOCATION) else permissions).any {
|
||||
context.checkSelfPermission(it) == PackageManager.PERMISSION_GRANTED
|
||||
}
|
||||
|
||||
fun locationEnabled(context: Context): Boolean = Build.VERSION.SDK_INT < Build.VERSION_CODES.P ||
|
||||
(context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager)?.isLocationEnabled == true
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.droiddeck.launcher.files
|
||||
|
||||
import android.Manifest
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
@@ -22,7 +23,9 @@ class FileManagerActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
com.droiddeck.launcher.core.AllFilesAccess.ask(this)
|
||||
} else if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
val initialDir = intent.getStringExtra(EXTRA_START_DIR)?.let(::File)
|
||||
|
||||
@@ -4,6 +4,7 @@ import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import androidx.activity.ComponentActivity
|
||||
import androidx.activity.compose.setContent
|
||||
@@ -26,7 +27,9 @@ class FilePickerActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
requestedOrientation = com.droiddeck.launcher.session.SessionPrefs.orientation(this)
|
||||
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||
com.droiddeck.launcher.core.AllFilesAccess.ask(this)
|
||||
} else if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
|
||||
requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1)
|
||||
}
|
||||
|
||||
|
||||
@@ -442,9 +442,12 @@ object AddedGames {
|
||||
}
|
||||
}
|
||||
|
||||
fun listingFile(context: Context): File = File(context.filesDir, "session/added-games.json")
|
||||
|
||||
@Synchronized
|
||||
fun writeListing(context: Context, games: List<Game>,
|
||||
extra: List<JSONObject> = listOfNotNull(com.droiddeck.launcher.stores.epic.EpicClient.steamListing(context))): File {
|
||||
val file = File(context.filesDir, "session/added-games.json").apply { parentFile?.mkdirs() }
|
||||
val file = listingFile(context).apply { parentFile?.mkdirs() }
|
||||
val json = StringBuilder("[")
|
||||
games.forEachIndexed { i, g ->
|
||||
if (i > 0) json.append(',')
|
||||
@@ -464,7 +467,13 @@ object AddedGames {
|
||||
if (games.isNotEmpty() || i > 0) json.append(',')
|
||||
json.append(entry.toString())
|
||||
}
|
||||
file.writeText(json.append(']').toString())
|
||||
val staged = File(file.path + ".tmp")
|
||||
staged.writeText(json.append(']').toString())
|
||||
java.nio.file.Files.move(
|
||||
staged.toPath(), file.toPath(),
|
||||
java.nio.file.StandardCopyOption.ATOMIC_MOVE,
|
||||
java.nio.file.StandardCopyOption.REPLACE_EXISTING,
|
||||
)
|
||||
return file
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@ package com.droiddeck.launcher.frontend
|
||||
import android.content.Context
|
||||
import android.util.Log
|
||||
import androidx.annotation.VisibleForTesting
|
||||
import org.json.JSONArray
|
||||
import java.util.concurrent.Executors
|
||||
import java.util.concurrent.TimeUnit
|
||||
|
||||
object AddedGamesPublisher {
|
||||
private const val TAG = "AddedGamesPublisher"
|
||||
@@ -13,6 +15,7 @@ object AddedGamesPublisher {
|
||||
internal var now = false
|
||||
|
||||
private val worker = Executors.newSingleThreadExecutor { r -> Thread(r, "added-games-publish") }
|
||||
private val retries = Executors.newSingleThreadScheduledExecutor { r -> Thread(r, "added-games-publish-retry") }
|
||||
|
||||
fun later(context: Context, live: () -> Unit = {}) {
|
||||
val app = context.applicationContext
|
||||
@@ -23,6 +26,42 @@ object AddedGamesPublisher {
|
||||
if (now) work.run() else worker.execute(work)
|
||||
}
|
||||
|
||||
fun refreshDuringSession(context: Context) {
|
||||
val app = context.applicationContext
|
||||
worker.execute {
|
||||
try {
|
||||
val before = AddedGames.listingFile(app).takeIf { it.isFile }?.readText().orEmpty()
|
||||
val known = runCatching {
|
||||
val listing = JSONArray(before)
|
||||
List(listing.length()) { listing.getJSONObject(it).optString("exe") }.toSet()
|
||||
}.getOrDefault(emptySet())
|
||||
val games = AddedGames.scan(app)
|
||||
AddedGames.writeListing(app, games)
|
||||
val arch = com.droiddeck.launcher.session.SessionPrefs.activeSteamClientArch(app)
|
||||
LibraryCache.save(app, Library.launchableGames(app, added = games, arch = arch), arch == "x86_64")
|
||||
val fresh = games.filter { it.guestExe !in known }
|
||||
if (fresh.isEmpty()) return@execute
|
||||
Log.i(TAG, "session refresh: ${fresh.size} game(s) not in the listing the session started with")
|
||||
val attempts = java.util.concurrent.atomic.AtomicInteger()
|
||||
val retry = retries.scheduleWithFixedDelay({
|
||||
try {
|
||||
if (com.droiddeck.launcher.stores.SteamLiveShortcuts.sync(app, fresh) { true } ||
|
||||
!com.droiddeck.launcher.session.SessionState.running || attempts.incrementAndGet() >= 36) {
|
||||
throw java.util.concurrent.CancellationException()
|
||||
}
|
||||
} catch (e: java.util.concurrent.CancellationException) {
|
||||
throw e
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "session shortcut retry: ${e.message}")
|
||||
}
|
||||
}, 5, 5, TimeUnit.SECONDS)
|
||||
retries.schedule({ retry.cancel(false) }, 180, TimeUnit.SECONDS)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "session refresh: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun republish(context: Context) {
|
||||
val games = AddedGames.scan(context)
|
||||
AddedGames.writeListing(context, games)
|
||||
|
||||
@@ -22,6 +22,7 @@ import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InterruptedIOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -69,6 +70,7 @@ public final class LinuxRuntimeInstaller {
|
||||
volatile Step step = Step.OTHER;
|
||||
volatile int percent = -1;
|
||||
volatile boolean ok;
|
||||
volatile Thread worker;
|
||||
final boolean removal;
|
||||
boolean maintenance;
|
||||
Job(boolean removal, String stage) { this.removal = removal; this.stage = stage; }
|
||||
@@ -113,6 +115,7 @@ public final class LinuxRuntimeInstaller {
|
||||
owner = running == null;
|
||||
if (owner) { running = new Job(false, context.getString(R.string.user_apps_starting)); removalError = null; }
|
||||
job = running;
|
||||
if (owner) job.worker = Thread.currentThread();
|
||||
if (listener != null) job.listeners.add(listener);
|
||||
}
|
||||
if (!owner) return join(job, listener);
|
||||
@@ -148,6 +151,12 @@ public final class LinuxRuntimeInstaller {
|
||||
synchronized (JOB_LOCK) { return running != null; }
|
||||
}
|
||||
|
||||
public static void cancelActiveOperation() {
|
||||
synchronized (JOB_LOCK) {
|
||||
if (running != null && running.worker != null) running.worker.interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isRemoving() {
|
||||
synchronized (JOB_LOCK) { return running != null && running.removal; }
|
||||
}
|
||||
@@ -275,6 +284,7 @@ public final class LinuxRuntimeInstaller {
|
||||
keepPartial = true;
|
||||
return false;
|
||||
}
|
||||
requireNotInterrupted();
|
||||
|
||||
if (listener != null) listener.onProgress(Step.VERIFYING, context.getString(R.string.rtinst_verifying), -1);
|
||||
String actual = Hashes.sha256(archive);
|
||||
@@ -293,6 +303,7 @@ public final class LinuxRuntimeInstaller {
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
return false;
|
||||
}
|
||||
requireNotInterrupted();
|
||||
FileUtils.writeString(new File(staging, VERSION_FILE), release.version);
|
||||
|
||||
if (!discard(old, null)) {
|
||||
@@ -303,6 +314,11 @@ public final class LinuxRuntimeInstaller {
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
return false;
|
||||
}
|
||||
if (Thread.currentThread().isInterrupted()) {
|
||||
if (old.isDirectory()) old.renameTo(root);
|
||||
RuntimeFileTree.delete(staging, null);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
RuntimeFileTree.carryHome(old, staging);
|
||||
@@ -314,7 +330,7 @@ public final class LinuxRuntimeInstaller {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!staging.renameTo(root)) {
|
||||
if (Thread.currentThread().isInterrupted() || !staging.renameTo(root)) {
|
||||
File keptTo = new File(staging, USER_DATA);
|
||||
if (keptTo.isDirectory() && old.isDirectory()) keptTo.renameTo(new File(old, USER_DATA));
|
||||
if (old.isDirectory()) old.renameTo(root);
|
||||
@@ -470,6 +486,7 @@ public final class LinuxRuntimeInstaller {
|
||||
TarArchiveInputStream tar = new TarArchiveInputStream(in)) {
|
||||
TarArchiveEntry entry;
|
||||
while ((entry = tar.getNextTarEntry()) != null) {
|
||||
requireNotInterrupted();
|
||||
File file = ArchivePaths.inside(destination, entry.getName());
|
||||
if (file == null) {
|
||||
Log.w(TAG, "skipping entry outside the rootfs: " + entry.getName());
|
||||
@@ -508,7 +525,10 @@ public final class LinuxRuntimeInstaller {
|
||||
try (OutputStream out = new FileOutputStream(part)) {
|
||||
byte[] buffer = new byte[1 << 16];
|
||||
int read;
|
||||
while ((read = tar.read(buffer)) != -1) out.write(buffer, 0, read);
|
||||
while ((read = tar.read(buffer)) != -1) {
|
||||
requireNotInterrupted();
|
||||
out.write(buffer, 0, read);
|
||||
}
|
||||
}
|
||||
if ((entry.getMode() & 0111) != 0) part.setExecutable(true, false);
|
||||
place(part, file);
|
||||
@@ -538,6 +558,10 @@ public final class LinuxRuntimeInstaller {
|
||||
}
|
||||
}
|
||||
|
||||
private static void requireNotInterrupted() throws InterruptedIOException {
|
||||
if (Thread.currentThread().isInterrupted()) throw new InterruptedIOException("Runtime installation was interrupted");
|
||||
}
|
||||
|
||||
static File partFile(File file) {
|
||||
return new File(file.getParentFile(), ".dd-part-" + Integer.toHexString(file.getName().hashCode()));
|
||||
}
|
||||
|
||||
@@ -13,11 +13,21 @@ import com.droiddeck.launcher.FrontEndActivity
|
||||
import com.droiddeck.launcher.R
|
||||
|
||||
class RuntimeInstallService : Service() {
|
||||
@Volatile private var activeWork: Thread? = null
|
||||
@Volatile private var timedOut = false
|
||||
override fun attachBaseContext(newBase: android.content.Context) =
|
||||
super.attachBaseContext(com.droiddeck.launcher.core.AppLanguage.wrap(newBase))
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onTimeout(startId: Int, fgsType: Int) {
|
||||
timedOut = true
|
||||
LinuxRuntimeInstaller.cancelActiveOperation()
|
||||
activeWork?.interrupt()
|
||||
stopForeground(STOP_FOREGROUND_DETACH)
|
||||
stopSelf()
|
||||
}
|
||||
|
||||
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
|
||||
if (intent?.action == ACTION_PACKAGE) return holdPackage(startId)
|
||||
val removal = intent?.action == ACTION_REMOVE
|
||||
@@ -27,7 +37,7 @@ class RuntimeInstallService : Service() {
|
||||
stopSelf(startId)
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
Thread({
|
||||
activeWork = Thread({
|
||||
val manager = getSystemService(NotificationManager::class.java)
|
||||
var shown = ""
|
||||
val progress = LinuxRuntimeInstaller.ProgressListener { stage, percent ->
|
||||
@@ -38,10 +48,12 @@ class RuntimeInstallService : Service() {
|
||||
}
|
||||
if (removal) LinuxRuntimeInstaller.attach(progress)
|
||||
else LinuxRuntimeInstaller.install(applicationContext, release!!, progress)
|
||||
@Suppress("DEPRECATION")
|
||||
stopForeground(true)
|
||||
stopSelf(startId)
|
||||
}, "runtime-install").start()
|
||||
if (!timedOut) {
|
||||
@Suppress("DEPRECATION")
|
||||
stopForeground(true)
|
||||
stopSelf(startId)
|
||||
}
|
||||
}, "runtime-install").also { it.start() }
|
||||
return START_NOT_STICKY
|
||||
}
|
||||
|
||||
|
||||
@@ -325,6 +325,18 @@ object SessionPrefs {
|
||||
prefs(context).edit().putBoolean("micAsked", true).apply()
|
||||
}
|
||||
|
||||
fun allFilesAsked(context: Context): Boolean = prefs(context).getBoolean("allFilesAsked", false)
|
||||
|
||||
fun setAllFilesAsked(context: Context) {
|
||||
prefs(context).edit().putBoolean("allFilesAsked", true).apply()
|
||||
}
|
||||
|
||||
fun bluetoothAsked(context: Context): Boolean = prefs(context).getBoolean("bluetoothAsked", false)
|
||||
|
||||
fun setBluetoothAsked(context: Context) {
|
||||
prefs(context).edit().putBoolean("bluetoothAsked", true).apply()
|
||||
}
|
||||
|
||||
fun setMicEnabled(context: Context, on: Boolean) {
|
||||
prefs(context).edit().putBoolean("mic", on).apply()
|
||||
}
|
||||
|
||||
@@ -475,12 +475,19 @@ class SessionService : Service() {
|
||||
.onFailure { Log.w(TAG, "Epic install directory setup failed", it) }
|
||||
}
|
||||
if (steamHere || noSteamGame) {
|
||||
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
|
||||
val listing = com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
|
||||
val cached = com.droiddeck.launcher.frontend.AddedGames.listingFile(this)
|
||||
val listing = if (steamHere && cached.isFile) {
|
||||
com.droiddeck.launcher.frontend.AddedGamesPublisher.refreshDuringSession(this)
|
||||
Log.i(TAG, "added games: the last listing, refreshed in the background")
|
||||
cached
|
||||
} else {
|
||||
val added = com.droiddeck.launcher.frontend.AddedGames.scan(this)
|
||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||
com.droiddeck.launcher.frontend.AddedGames.writeListing(this, added)
|
||||
}
|
||||
guest.add("BL_ADDED_GAMES=" + listing.path)
|
||||
if (OfflineMode.enabled(this)) guest.add("BL_STEAM_OFFLINE=1")
|
||||
if (com.droiddeck.launcher.gpu.Lossless.owned(this)) guest.add("BL_LOSSLESS_OWNED=1")
|
||||
if (added.isNotEmpty()) Log.i(TAG, "added games: " + added.joinToString { "${it.name} (${it.exe.name})" })
|
||||
}
|
||||
guest.add("BL_LAUNCH_DIR=" + sessionRoot.path)
|
||||
GameStorage.effective(this)?.let { guest.add("BL_LIBRARY_LABEL=" + it.label.replace('"', ' ')) }
|
||||
@@ -615,9 +622,15 @@ class SessionService : Service() {
|
||||
helperRoots = { components.mapNotNull { it.suspendPid().takeIf { pid -> pid > 1 } } },
|
||||
suspendAudio = {
|
||||
if (!pulse.setSinkSuspended(true)) Log.w(TAG, "could not suspend audio sink")
|
||||
if (!pulse.setMicSuspended(true)) Log.w(TAG, "could not suspend microphone source")
|
||||
val relay = components.firstNotNullOfOrNull { it as? DirectAudioRelayComponent }
|
||||
if (relay != null && !relay.awaitMicReleased(MIC_RELEASE_TIMEOUT_MS)) {
|
||||
Log.w(TAG, "microphone still open after ${MIC_RELEASE_TIMEOUT_MS} ms; suspending anyway")
|
||||
}
|
||||
},
|
||||
resumeAudio = {
|
||||
if (!pulse.setSinkSuspended(false)) Log.w(TAG, "could not resume audio sink")
|
||||
if (!pulse.setMicSuspended(false)) Log.w(TAG, "could not resume microphone source")
|
||||
},
|
||||
zramControl = File(filesDir, "${LinuxRuntime.DIR}/tmp/.bl-zram"),
|
||||
pagedOut = { processes, unacknowledged, residentKb, swapKb, swapBeforeKb, millis ->
|
||||
@@ -1884,6 +1897,7 @@ class SessionService : Service() {
|
||||
companion object {
|
||||
private const val TAG = "SessionService"
|
||||
private const val TRACER_NICE = -6
|
||||
private const val MIC_RELEASE_TIMEOUT_MS = 5_000L
|
||||
private const val TU_DEBUG_SWITCH = "Download/droiddeck-tu-debug"
|
||||
private const val GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
|
||||
private const val LEGACY_ENV_SWITCH = "Download/droiddeck-env"
|
||||
|
||||
@@ -19,9 +19,10 @@ object SteamLiveShortcuts {
|
||||
private const val EVAL_TIMEOUT_MS = 20_000L
|
||||
private const val THAW_WAIT_MS = 15_000L
|
||||
|
||||
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }) {
|
||||
fun sync(context: Context, games: List<AddedGames.Game>, include: (AddedGames.Game) -> Boolean = { it.source != Library.ADDED }): Boolean {
|
||||
val wanted = games.filter(include)
|
||||
if (wanted.isEmpty() || !clientRunning()) return
|
||||
if (wanted.isEmpty()) return true
|
||||
if (!clientRunning()) return false
|
||||
val list = JSONArray()
|
||||
for (g in wanted) list.put(JSONObject().put("name", g.name).put("exe", g.guestExe).put("dir", g.guestDir).put("appid", g.appId and 0xFFFFFFFFL))
|
||||
val js = """
|
||||
@@ -35,9 +36,10 @@ object SteamLiveShortcuts {
|
||||
return added;
|
||||
})()
|
||||
""".trimIndent()
|
||||
val result = evaluate(context, js) ?: return
|
||||
val result = evaluate(context, js) ?: return false
|
||||
Log.i(TAG, "live shortcuts: $result added")
|
||||
if (result != "0") StoresState.logLine("Steam: $result shortcut(s) added to the running client")
|
||||
return true
|
||||
}
|
||||
|
||||
fun ensure(context: Context, name: String, exe: String, dir: String, compat: Boolean, appId: Long? = null): Long? {
|
||||
|
||||
@@ -70,6 +70,15 @@ class StoreDownloadService : Service() {
|
||||
|
||||
override fun onBind(intent: Intent?): IBinder? = null
|
||||
|
||||
override fun onTimeout(startId: Int, fgsType: Int) {
|
||||
Log.w(TAG, "data sync time used up; pausing downloads")
|
||||
StoresState.latestDownloads.filter { it.state == DownloadState.RUNNING }.forEach {
|
||||
DownloadQueue.pause(it.key)
|
||||
pausedNote(this, it.key)
|
||||
}
|
||||
stopNow()
|
||||
}
|
||||
|
||||
private fun pending(action: String, key: String, code: Int): PendingIntent {
|
||||
val i = Intent(this, StoreDownloadService::class.java).setAction(action).putExtra(EXTRA_KEY, key)
|
||||
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) PendingIntent.getForegroundService(this, code, i, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT)
|
||||
|
||||
@@ -100,6 +100,8 @@ class FrontEndState(
|
||||
val logsEnabled: Boolean,
|
||||
val vacDiagnostics: Boolean = false,
|
||||
val agentCommands: Boolean = false,
|
||||
val bluetoothAllowed: Boolean? = null,
|
||||
val allFilesAllowed: Boolean? = null,
|
||||
val steamGames: List<Library.SteamGame>,
|
||||
val steamGamesX64: Boolean = false,
|
||||
val emulators: List<Library.Emulator>,
|
||||
@@ -200,6 +202,8 @@ class FrontEndActions(
|
||||
val onLogs: () -> Unit,
|
||||
val onVacDiagnostics: () -> Unit = {},
|
||||
val onAgentCommands: () -> Unit = {},
|
||||
val onBluetoothAllowed: () -> Unit = {},
|
||||
val onAllFilesAllowed: () -> Unit = {},
|
||||
val onShareLogs: () -> Unit = {},
|
||||
val onClearLogs: () -> Unit = {},
|
||||
val onResetSettings: () -> Unit = {},
|
||||
|
||||
@@ -451,6 +451,12 @@ internal fun SetupPanel(
|
||||
ToggleRow(host, "logs", stringResource(R.string.setup_logs), stringResource(R.string.setup_logs_hint), s.logsEnabled) { a.onLogs() }
|
||||
ToggleRow(host, "vacdiag", stringResource(R.string.setup_vac_diag), stringResource(R.string.setup_vac_diag_hint), s.vacDiagnostics) { a.onVacDiagnostics() }
|
||||
ToggleRow(host, "agent-commands", stringResource(R.string.setup_agent_commands), null, s.agentCommands) { a.onAgentCommands() }
|
||||
s.allFilesAllowed?.let { on ->
|
||||
ToggleRow(host, "all-files", stringResource(R.string.setup_all_files), stringResource(R.string.setup_all_files_hint), on) { a.onAllFilesAllowed() }
|
||||
}
|
||||
s.bluetoothAllowed?.let { on ->
|
||||
ToggleRow(host, "bluetooth", stringResource(R.string.setup_bluetooth), stringResource(R.string.setup_bluetooth_hint), on) { a.onBluetoothAllowed() }
|
||||
}
|
||||
ActionRow(stringResource(R.string.setup_latest_logs), stringResource(R.string.drawer_logs_hint), stringResource(R.string.drawer_share_logs), a.onShareLogs,
|
||||
progress = com.droiddeck.launcher.session.SessionLogShare.progress)
|
||||
ActionRow(stringResource(R.string.setup_saved_logs), stringResource(R.string.setup_saved_logs_hint, com.droiddeck.launcher.session.SessionPaths.KEEP_SESSIONS), stringResource(R.string.setup_clear_logs), a.onClearLogs)
|
||||
|
||||
@@ -1791,6 +1791,14 @@
|
||||
<string name="adbpair_waiting_long">Turn on Wireless debugging, then tap “Pair device with pairing code”. Stay in Settings: the code goes in this notification.</string>
|
||||
<string name="adbpair_code_label">6-digit pairing code</string>
|
||||
<string name="adbpair_code_hint">Tap Enter code and type the 6 digits shown in Settings.</string>
|
||||
<string name="setup_all_files">All files access</string>
|
||||
<string name="setup_all_files_hint">Lets DroidDeck see games and programs on your storage and SD card</string>
|
||||
<string name="setup_bluetooth">Bluetooth Steam Controller</string>
|
||||
<string name="setup_bluetooth_hint">Lets DroidDeck find a paired Steam Controller (Nearby devices)</string>
|
||||
<string name="all_files_title">Allow access to your game folders</string>
|
||||
<string name="all_files_message">DroidDeck runs games and programs from your phone\'s storage and SD card. Android only lets it see those files with All files access, which you can turn on for DroidDeck on the next screen.</string>
|
||||
<string name="all_files_allow">Open settings</string>
|
||||
<string name="all_files_later">Not now</string>
|
||||
<string name="adbpair_title_code">Enter the Wi-Fi pairing code</string>
|
||||
<string name="adbpair_title_retry">Try the code again</string>
|
||||
<string name="adbpair_enter_code">Enter code</string>
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
sdk=35
|
||||
@@ -122,6 +122,7 @@ if [ -n "${BL_VK_DRIVER:-}" ]; then
|
||||
unset bl_icd_lib
|
||||
fi
|
||||
export GAMESCOPE_FORCE_VULKAN_REALTIME=${BL_GAMESCOPE_REALTIME:-0}
|
||||
rm -rf /tmp/.droiddeck-rx
|
||||
|
||||
start_agent() {
|
||||
[ -n "${BL_LAUNCH_DIR:-}" ] && [ -x /usr/local/bin/droiddeck-agent ] || return 0
|
||||
|
||||
@@ -3,8 +3,15 @@
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/auxv.h>
|
||||
#include <sys/stat.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/statvfs.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
#include <limits.h>
|
||||
|
||||
#if defined(__aarch64__) || defined(NOEXEC_TEST)
|
||||
|
||||
@@ -36,11 +43,145 @@ __attribute__((constructor)) static void noexec_init(void) {
|
||||
real_mprotect = (int (*)(void *, size_t, int))dlsym(RTLD_NEXT, "mprotect");
|
||||
}
|
||||
|
||||
static int private_file_mapping(uintptr_t start, uintptr_t end) {
|
||||
int fd = (int)syscall(SYS_openat, AT_FDCWD, "/proc/self/maps", O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return 0;
|
||||
char buf[4096], line[1024];
|
||||
size_t used = 0;
|
||||
int found = 0, done = 0;
|
||||
ssize_t n;
|
||||
while (!done && (n = syscall(SYS_read, fd, buf, sizeof buf)) > 0) {
|
||||
for (ssize_t i = 0; i < n && !done; i++) {
|
||||
if (buf[i] != '\n') {
|
||||
if (used < sizeof line - 1) line[used++] = buf[i];
|
||||
continue;
|
||||
}
|
||||
line[used] = 0;
|
||||
used = 0;
|
||||
char *p = line;
|
||||
uintptr_t lo = strtoull(p, &p, 16), hi = strtoull(p + 1, &p, 16);
|
||||
if (start < lo || start >= hi) continue;
|
||||
done = 1;
|
||||
char *perms = p + 1;
|
||||
if (end > hi || perms[3] != 'p') break;
|
||||
char *path = strchr(perms, '/');
|
||||
struct statvfs vfs;
|
||||
found = path && !(statvfs(path, &vfs) == 0 && (vfs.f_flag & ST_NOEXEC));
|
||||
}
|
||||
}
|
||||
syscall(SYS_close, fd);
|
||||
return found;
|
||||
}
|
||||
|
||||
static const char default_rx_dir[] = "/tmp/.droiddeck-rx";
|
||||
|
||||
static const char *rx_directory(void) {
|
||||
#ifdef NOEXEC_TEST
|
||||
const char *directory = getenv("DROIDDECK_NOEXEC_CACHE_DIR");
|
||||
if (directory && *directory) return directory;
|
||||
#endif
|
||||
return default_rx_dir;
|
||||
}
|
||||
|
||||
static uint64_t fnv1a(const unsigned char *p, size_t n) {
|
||||
uint64_t h = 1469598103934665603ULL;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
h ^= p[i];
|
||||
h *= 1099511628211ULL;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
static char *put_hex(char *out, uint64_t v) {
|
||||
for (int shift = 60; shift >= 0; shift -= 4) *out++ = "0123456789abcdef"[(v >> shift) & 15];
|
||||
return out;
|
||||
}
|
||||
|
||||
static int same_content(int fd, const unsigned char *p, size_t len) {
|
||||
char buf[16384];
|
||||
for (size_t off = 0; off < len;) {
|
||||
size_t want = len - off < sizeof buf ? len - off : sizeof buf;
|
||||
if (syscall(SYS_pread64, fd, buf, want, off) != (long)want || memcmp(buf, p + off, want)) return 0;
|
||||
off += want;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int write_all(int fd, const unsigned char *p, size_t len) {
|
||||
for (size_t off = 0; off < len;) {
|
||||
long n = syscall(SYS_write, fd, p + off, len - off);
|
||||
if (n <= 0) return -1;
|
||||
off += (size_t)n;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int rebake_shared(void *addr, size_t len, int prot) {
|
||||
const char *directory = rx_directory();
|
||||
size_t directory_len = strlen(directory);
|
||||
if (!directory_len || directory_len + 40 >= PATH_MAX) return -1;
|
||||
char path[PATH_MAX], staged[PATH_MAX];
|
||||
char *end = path + directory_len;
|
||||
memcpy(path, directory, directory_len);
|
||||
if (end[-1] != '/') *end++ = '/';
|
||||
*end++ = '/';
|
||||
end = put_hex(end, fnv1a(addr, len));
|
||||
*end++ = '-';
|
||||
end = put_hex(end, len);
|
||||
*end = 0;
|
||||
int fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd >= 0 && !same_content(fd, addr, len)) {
|
||||
syscall(SYS_close, fd);
|
||||
return -1;
|
||||
}
|
||||
if (fd < 0) {
|
||||
syscall(SYS_mkdirat, AT_FDCWD, directory, 0700);
|
||||
memcpy(staged, path, (size_t)(end - path));
|
||||
char *tail = put_hex(staged + (end - path), (uint64_t)syscall(SYS_gettid));
|
||||
*tail = 0;
|
||||
int out = (int)syscall(SYS_openat, AT_FDCWD, staged, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0600);
|
||||
if (out < 0) return -1;
|
||||
int bad = write_all(out, addr, len);
|
||||
syscall(SYS_close, out);
|
||||
if (bad || syscall(SYS_renameat, AT_FDCWD, staged, AT_FDCWD, path)) {
|
||||
syscall(SYS_unlinkat, AT_FDCWD, staged, 0);
|
||||
return -1;
|
||||
}
|
||||
fd = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (fd < 0) return -1;
|
||||
}
|
||||
long mapped = syscall(SYS_mmap, addr, len, prot, MAP_PRIVATE | MAP_FIXED, fd, 0);
|
||||
syscall(SYS_close, fd);
|
||||
return mapped == (long)addr ? 0 : -1;
|
||||
}
|
||||
|
||||
static int rebake(void *addr, size_t len, int prot) {
|
||||
size_t page = getauxval(AT_PAGESZ);
|
||||
if (page) len = (len + page - 1) & ~(page - 1);
|
||||
if (real_mprotect(addr, len, PROT_READ)) return -1;
|
||||
if (!rebake_shared(addr, len, prot)) return 0;
|
||||
void *copy = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (copy == MAP_FAILED) return -1;
|
||||
memcpy(copy, addr, len);
|
||||
if (mmap(addr, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED, -1, 0) == MAP_FAILED) {
|
||||
munmap(copy, len);
|
||||
return -1;
|
||||
}
|
||||
memcpy(addr, copy, len);
|
||||
munmap(copy, len);
|
||||
__builtin___clear_cache((char *)addr, (char *)addr + len);
|
||||
return real_mprotect(addr, len, prot);
|
||||
}
|
||||
|
||||
int mprotect(void *addr, size_t len, int prot) {
|
||||
if (!real_mprotect) noexec_init();
|
||||
int result = real_mprotect(addr, len, prot);
|
||||
if (result && errno == EACCES && (prot & PROT_EXEC) && in_fex()) {
|
||||
result = real_mprotect(addr, len, prot & ~PROT_EXEC);
|
||||
if (result && errno == EACCES && (prot & PROT_EXEC)) {
|
||||
if (in_fex()) {
|
||||
result = real_mprotect(addr, len, prot & ~PROT_EXEC);
|
||||
} else if (len && private_file_mapping((uintptr_t)addr, (uintptr_t)addr + len)) {
|
||||
result = rebake(addr, len, prot);
|
||||
}
|
||||
if (result) errno = EACCES;
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
#define STATUS_MAX 16384
|
||||
#define TRACER_FIELD "\nTracerPid:\t"
|
||||
|
||||
int bl_from_ntdll(const void *caller) __attribute__((visibility("hidden")));
|
||||
|
||||
static const char *skip_digits(const char *s) {
|
||||
const char *end = s;
|
||||
while (isdigit((unsigned char)*end)) end++;
|
||||
@@ -77,7 +79,8 @@ __attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *p
|
||||
int out = -1;
|
||||
|
||||
long pid;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller)) return -1;
|
||||
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller) || bl_from_ntdll(caller))
|
||||
return -1;
|
||||
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
if (in < 0) goto done;
|
||||
for (;;) {
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
#define _GNU_SOURCE
|
||||
#include <dlfcn.h>
|
||||
#include <link.h>
|
||||
#include <signal.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <sys/auxv.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static uintptr_t ntdll_lo, ntdll_hi;
|
||||
|
||||
static int find_ntdll(struct dl_phdr_info *info, size_t size, void *data) {
|
||||
(void)size;
|
||||
(void)data;
|
||||
const char *slash = strrchr(info->dlpi_name, '/');
|
||||
if (strcmp(slash ? slash + 1 : info->dlpi_name, "ntdll.so") != 0) return 0;
|
||||
for (int i = 0; i < info->dlpi_phnum; i++) {
|
||||
const ElfW(Phdr) *ph = &info->dlpi_phdr[i];
|
||||
if (ph->p_type != PT_LOAD || !(ph->p_flags & PF_X)) continue;
|
||||
uintptr_t lo = info->dlpi_addr + ph->p_vaddr;
|
||||
__atomic_store_n(&ntdll_hi, lo + ph->p_memsz, __ATOMIC_RELAXED);
|
||||
__atomic_store_n(&ntdll_lo, lo, __ATOMIC_RELEASE);
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
__attribute__((visibility("hidden"))) int bl_from_ntdll(const void *caller) {
|
||||
uintptr_t pc = (uintptr_t)caller, lo = __atomic_load_n(&ntdll_lo, __ATOMIC_ACQUIRE);
|
||||
if (!lo) {
|
||||
dl_iterate_phdr(find_ntdll, NULL);
|
||||
lo = __atomic_load_n(&ntdll_lo, __ATOMIC_ACQUIRE);
|
||||
if (!lo) return 0;
|
||||
}
|
||||
return pc >= lo && pc < __atomic_load_n(&ntdll_hi, __ATOMIC_RELAXED);
|
||||
}
|
||||
|
||||
#if defined(__aarch64__)
|
||||
#include <asm/hwcap.h>
|
||||
#include <asm/sigcontext.h>
|
||||
|
||||
#define BL_STR2(x) #x
|
||||
#define BL_STR(x) BL_STR2(x)
|
||||
|
||||
#define BL_HWCAP_GCS (1UL << 32)
|
||||
#define BL_FRAME_SIZE 4688
|
||||
#define BL_REGS 312
|
||||
#define BL_SP 560
|
||||
#define BL_PC 568
|
||||
#define BL_PSTATE 576
|
||||
#define BL_FPSIMD 592
|
||||
|
||||
struct bl_sigframe {
|
||||
siginfo_t info;
|
||||
ucontext_t uc;
|
||||
};
|
||||
|
||||
struct bl_kernel_sigaction {
|
||||
void (*handler)(int, siginfo_t *, void *);
|
||||
unsigned long flags;
|
||||
void *restorer;
|
||||
uint64_t mask;
|
||||
};
|
||||
|
||||
struct bl_usr2_call {
|
||||
void (*handler)(int, siginfo_t *, void *);
|
||||
uint64_t old_mask;
|
||||
};
|
||||
|
||||
_Static_assert(sizeof(struct bl_sigframe) == BL_FRAME_SIZE, "rt_sigframe size");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.regs) == BL_REGS, "regs offset");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.sp) == BL_SP, "sp offset");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.pc) == BL_PC, "pc offset");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.pstate) == BL_PSTATE, "pstate offset");
|
||||
_Static_assert(offsetof(struct bl_sigframe, uc.uc_mcontext.__reserved) == BL_FPSIMD, "reserved offset");
|
||||
_Static_assert(sizeof(struct fpsimd_context) + sizeof(struct _aarch64_ctx) <=
|
||||
sizeof(((mcontext_t *)0)->__reserved), "reserved space");
|
||||
|
||||
__attribute__((visibility("hidden"))) void bl_usr2_frame(struct bl_usr2_call *call);
|
||||
__attribute__((visibility("hidden"), used)) void bl_usr2_run(struct bl_usr2_call *call, struct bl_sigframe *frame);
|
||||
|
||||
__asm__(".text\n"
|
||||
".p2align 2\n"
|
||||
".type bl_usr2_frame, %function\n"
|
||||
"bl_usr2_frame:\n"
|
||||
" mov x16, #" BL_STR(BL_FRAME_SIZE) "\n"
|
||||
" sub sp, sp, x16\n"
|
||||
" add x17, sp, #" BL_STR(BL_REGS) "\n"
|
||||
" stp x0, x1, [x17, #0]\n"
|
||||
" stp x2, x3, [x17, #16]\n"
|
||||
" stp x4, x5, [x17, #32]\n"
|
||||
" stp x6, x7, [x17, #48]\n"
|
||||
" stp x8, x9, [x17, #64]\n"
|
||||
" stp x10, x11, [x17, #80]\n"
|
||||
" stp x12, x13, [x17, #96]\n"
|
||||
" stp x14, x15, [x17, #112]\n"
|
||||
" stp xzr, xzr, [x17, #128]\n"
|
||||
" stp x18, x19, [x17, #144]\n"
|
||||
" stp x20, x21, [x17, #160]\n"
|
||||
" stp x22, x23, [x17, #176]\n"
|
||||
" stp x24, x25, [x17, #192]\n"
|
||||
" stp x26, x27, [x17, #208]\n"
|
||||
" stp x28, x29, [x17, #224]\n"
|
||||
" str x30, [x17, #240]\n"
|
||||
" str xzr, [x17, #0]\n"
|
||||
" add x16, sp, x16\n"
|
||||
" str x16, [sp, #" BL_STR(BL_SP) "]\n"
|
||||
" adr x16, 1f\n"
|
||||
" str x16, [sp, #" BL_STR(BL_PC) "]\n"
|
||||
" mrs x16, nzcv\n"
|
||||
" str x16, [sp, #" BL_STR(BL_PSTATE) "]\n"
|
||||
" add x17, sp, #" BL_STR(BL_FPSIMD) "\n"
|
||||
" mrs x16, fpsr\n"
|
||||
" str w16, [x17, #8]\n"
|
||||
" mrs x16, fpcr\n"
|
||||
" str w16, [x17, #12]\n"
|
||||
" stp q0, q1, [x17, #16]\n"
|
||||
" stp q2, q3, [x17, #48]\n"
|
||||
" stp q4, q5, [x17, #80]\n"
|
||||
" stp q6, q7, [x17, #112]\n"
|
||||
" stp q8, q9, [x17, #144]\n"
|
||||
" stp q10, q11, [x17, #176]\n"
|
||||
" stp q12, q13, [x17, #208]\n"
|
||||
" stp q14, q15, [x17, #240]\n"
|
||||
" stp q16, q17, [x17, #272]\n"
|
||||
" stp q18, q19, [x17, #304]\n"
|
||||
" stp q20, q21, [x17, #336]\n"
|
||||
" stp q22, q23, [x17, #368]\n"
|
||||
" stp q24, q25, [x17, #400]\n"
|
||||
" stp q26, q27, [x17, #432]\n"
|
||||
" stp q28, q29, [x17, #464]\n"
|
||||
" stp q30, q31, [x17, #496]\n"
|
||||
" mov x1, sp\n"
|
||||
" bl bl_usr2_run\n"
|
||||
" mov x8, #" BL_STR(__NR_rt_sigreturn) "\n"
|
||||
" svc #0\n"
|
||||
" brk #0\n"
|
||||
"1:\n"
|
||||
" ret\n"
|
||||
".size bl_usr2_frame, .-bl_usr2_frame\n");
|
||||
|
||||
static int (*usr2_real_raise)(int);
|
||||
|
||||
static long usr2_sys(long nr, long a, long b, long c, long d) {
|
||||
register long x8 __asm__("x8") = nr;
|
||||
register long x0 __asm__("x0") = a;
|
||||
register long x1 __asm__("x1") = b;
|
||||
register long x2 __asm__("x2") = c;
|
||||
register long x3 __asm__("x3") = d;
|
||||
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3) : "memory");
|
||||
return x0;
|
||||
}
|
||||
|
||||
static uint64_t usr2_ssbs(void) {
|
||||
uint64_t value = 0;
|
||||
if (getauxval(AT_HWCAP) & HWCAP_SSBS) __asm__ volatile("mrs %0, s3_3_c4_c2_6" : "=r"(value));
|
||||
return value & (1UL << 12);
|
||||
}
|
||||
|
||||
void bl_usr2_run(struct bl_usr2_call *call, struct bl_sigframe *frame) {
|
||||
struct fpsimd_context *fp = (struct fpsimd_context *)frame->uc.uc_mcontext.__reserved;
|
||||
struct _aarch64_ctx *end = (struct _aarch64_ctx *)(fp + 1);
|
||||
|
||||
memset(&frame->info, 0, sizeof(frame->info));
|
||||
frame->info.si_signo = SIGUSR2;
|
||||
frame->info.si_code = SI_TKILL;
|
||||
frame->info.si_pid = (pid_t)usr2_sys(__NR_getpid, 0, 0, 0, 0);
|
||||
frame->info.si_uid = (uid_t)usr2_sys(__NR_getuid, 0, 0, 0, 0);
|
||||
frame->uc.uc_flags = 0;
|
||||
frame->uc.uc_link = NULL;
|
||||
if (usr2_sys(__NR_sigaltstack, 0, (long)&frame->uc.uc_stack, 0, 0) != 0) {
|
||||
memset(&frame->uc.uc_stack, 0, sizeof(frame->uc.uc_stack));
|
||||
frame->uc.uc_stack.ss_flags = SS_DISABLE;
|
||||
}
|
||||
memset(&frame->uc.uc_sigmask, 0, sizeof(frame->uc.uc_sigmask));
|
||||
memcpy(&frame->uc.uc_sigmask, &call->old_mask, sizeof(call->old_mask));
|
||||
frame->uc.uc_mcontext.fault_address = 0;
|
||||
frame->uc.uc_mcontext.pstate |= usr2_ssbs();
|
||||
fp->head.magic = FPSIMD_MAGIC;
|
||||
fp->head.size = sizeof(*fp);
|
||||
end->magic = 0;
|
||||
end->size = 0;
|
||||
call->handler(SIGUSR2, &frame->info, &frame->uc);
|
||||
}
|
||||
|
||||
int raise(int sig) {
|
||||
int (*real)(int) = __atomic_load_n(&usr2_real_raise, __ATOMIC_ACQUIRE);
|
||||
if (!real) {
|
||||
real = (int (*)(int))dlsym(RTLD_NEXT, "raise");
|
||||
__atomic_store_n(&usr2_real_raise, real, __ATOMIC_RELEASE);
|
||||
}
|
||||
if (sig != SIGUSR2 || (getauxval(AT_HWCAP) & BL_HWCAP_GCS) || !bl_from_ntdll(__builtin_return_address(0))) {
|
||||
return real(sig);
|
||||
}
|
||||
|
||||
struct bl_kernel_sigaction action;
|
||||
if (usr2_sys(__NR_rt_sigaction, SIGUSR2, 0, (long)&action, sizeof(action.mask)) != 0) return real(sig);
|
||||
if (!(action.flags & SA_SIGINFO) || (action.flags & SA_RESETHAND) || (uintptr_t)action.handler <= 1) {
|
||||
return real(sig);
|
||||
}
|
||||
|
||||
uint64_t bit = 1ULL << (SIGUSR2 - 1);
|
||||
uint64_t block = action.mask | ((action.flags & SA_NODEFER) ? 0 : bit);
|
||||
struct bl_usr2_call call = {action.handler, 0};
|
||||
if (usr2_sys(__NR_rt_sigprocmask, SIG_BLOCK, (long)&block, (long)&call.old_mask, sizeof(block)) != 0) {
|
||||
return real(sig);
|
||||
}
|
||||
if (call.old_mask & bit) {
|
||||
usr2_sys(__NR_rt_sigprocmask, SIG_SETMASK, (long)&call.old_mask, 0, sizeof(call.old_mask));
|
||||
return real(sig);
|
||||
}
|
||||
bl_usr2_frame(&call);
|
||||
return 0;
|
||||
}
|
||||
#endif
|
||||
@@ -4,7 +4,7 @@ from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from check_authorship import BOT, COAUTHOR, check_revision
|
||||
from check_authorship import COAUTHOR, check_revision, is_bot
|
||||
|
||||
|
||||
def main():
|
||||
@@ -23,13 +23,13 @@ def main():
|
||||
return 1
|
||||
else:
|
||||
identity = subprocess.check_output(["git", "var", "GIT_AUTHOR_IDENT"], text=True)
|
||||
if BOT.search(identity):
|
||||
if is_bot(identity):
|
||||
print("Bot commit author is forbidden: " + identity.strip(), file=sys.stderr)
|
||||
return 1
|
||||
message = Path(args[0])
|
||||
original = message.read_text(encoding="utf-8")
|
||||
cleaned = "".join(line for line in original.splitlines(keepends=True)
|
||||
if not (COAUTHOR.match(line) and BOT.search(line)))
|
||||
if not (COAUTHOR.match(line) and is_bot(line)))
|
||||
if cleaned != original:
|
||||
message.write_text(cleaned, encoding="utf-8")
|
||||
print("Removed bot co-author trailers; human credits preserved.", file=sys.stderr)
|
||||
|
||||
@@ -6,15 +6,34 @@ import re
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
BOT = re.compile(
|
||||
r"Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|"
|
||||
r"Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\]|github-actions|"
|
||||
r"dependabot|renovate(?:\[bot\])?",
|
||||
PRODUCT = re.compile(
|
||||
r"(?<![a-z0-9])(?:Anthropic|OpenAI|ChatGPT|GPT(?:-?\d[\w.]*)?|Copilot|Codex|Codeium|Windsurf|"
|
||||
r"Amazon Q|Tabnine|github-actions|dependabot|renovate)(?![a-z0-9])|\[bot\]",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
# These are also people's names, so they only count alone or followed by a product word.
|
||||
ASSISTANT = r"(?:Claude|Cursor|Devin|Cody|Gemini)"
|
||||
ASSISTANT_ALONE = re.compile(ASSISTANT, re.IGNORECASE)
|
||||
ASSISTANT_PRODUCT = re.compile(
|
||||
ASSISTANT + r"[\s_-]+(?:Code|Opus|Sonnet|Haiku|Fable|Instant|AI|Agent|Bot|Assistant|CLI|Pro|Flash|Ultra|\d)(?![a-z])",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
BOT_DOMAIN = re.compile(
|
||||
r"@(?:[\w-]+\.)*(?:anthropic\.com|openai\.com|cursor\.(?:com|sh)|cognition\.ai|sourcegraph\.com|"
|
||||
r"codeium\.com|tabnine\.com)$",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
COAUTHOR = re.compile(r"^\s*Co-authored-by\s*:", re.IGNORECASE)
|
||||
|
||||
|
||||
def is_bot(identity):
|
||||
name, _, rest = identity.partition("<")
|
||||
email = rest.partition(">")[0].strip()
|
||||
name = COAUTHOR.sub("", name).strip()
|
||||
return bool(PRODUCT.search(name) or PRODUCT.search(email) or BOT_DOMAIN.search(email)
|
||||
or ASSISTANT_ALONE.fullmatch(name) or ASSISTANT_PRODUCT.search(name))
|
||||
|
||||
|
||||
def commit_violations(commit, raw):
|
||||
header, separator, message = raw.partition(b"\n\n")
|
||||
if not separator:
|
||||
@@ -24,10 +43,10 @@ def commit_violations(commit, raw):
|
||||
return [f"{commit}: expected one author"]
|
||||
identity = authors[0].decode("utf-8", errors="replace")
|
||||
errors = []
|
||||
if BOT.search(identity):
|
||||
if is_bot(identity):
|
||||
errors.append(f"{commit}: bot author: {identity}")
|
||||
for line in message.decode("utf-8", errors="replace").splitlines():
|
||||
if COAUTHOR.match(line) and BOT.search(line):
|
||||
if COAUTHOR.match(line) and is_bot(line):
|
||||
errors.append(f"{commit}: bot co-author: {line.strip()}")
|
||||
return errors
|
||||
|
||||
@@ -36,11 +55,11 @@ def event_violations(event):
|
||||
pr = event.get("pull_request", {})
|
||||
user = pr.get("user", {})
|
||||
errors = []
|
||||
if user.get("type") == "Bot" or BOT.search(user.get("login", "")):
|
||||
if user.get("type") == "Bot" or is_bot(user.get("login", "")):
|
||||
errors.append("pull request: bot authorship is forbidden")
|
||||
for field in ("title", "body"):
|
||||
for line in (pr.get(field) or "").splitlines():
|
||||
if COAUTHOR.match(line) and BOT.search(line):
|
||||
if COAUTHOR.match(line) and is_bot(line):
|
||||
errors.append(f"pull request {field}: bot co-author trailer")
|
||||
return errors
|
||||
|
||||
|
||||
@@ -40,6 +40,27 @@ class AuthorshipTest(unittest.TestCase):
|
||||
def test_bot_pr_author_is_rejected(self):
|
||||
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}}))
|
||||
|
||||
def test_people_named_like_assistants_are_not_bots(self):
|
||||
for author in ("Claudemirovsky <63046606+Claudemirovsky@users.noreply.github.com>",
|
||||
"Claude Monet <claude@example.com>", "Devin Smith <devin@example.com>",
|
||||
"Cody Allen <cody@example.com>", "Gemini Patel <gp@example.com>"):
|
||||
with self.subTest(author=author):
|
||||
self.assertEqual([], check.commit_violations("abc", self.commit(author=author)))
|
||||
self.assertEqual([], check.event_violations({"pull_request": {"user": {"login": "Claudemirovsky", "type": "User"}}}))
|
||||
|
||||
def test_assistant_identities_are_still_bots(self):
|
||||
for author in ("Claude Opus 5.5 <noreply@anthropic.com>", "Claude Code <cc@example.com>",
|
||||
"Cursor Agent <cursoragent@cursor.com>",
|
||||
"Devin AI <devin-ai-integration[bot]@users.noreply.github.com>",
|
||||
"Gemini <gemini@example.com>", "GPT-5 <a@example.com>"):
|
||||
with self.subTest(author=author):
|
||||
self.assertTrue(check.commit_violations("abc", self.commit(author=author)))
|
||||
for login in ("chatgpt-codex-connector", "Copilot", "claude"):
|
||||
with self.subTest(login=login):
|
||||
self.assertTrue(check.event_violations({"pull_request": {"user": {"login": login, "type": "User"}}}))
|
||||
message = "Fix\n\nCo-authored-by: Claude Opus 5.5 <noreply@anthropic.com>\n"
|
||||
self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message))))
|
||||
|
||||
def test_missing_author_fails_closed(self):
|
||||
self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n"))
|
||||
|
||||
|
||||
@@ -70,5 +70,125 @@ class NoexecPreloadTest(unittest.TestCase):
|
||||
self.assertEqual(refused[1:], ["protect 13", "read -"])
|
||||
|
||||
|
||||
EXECMOD = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int private_file(void *addr) {
|
||||
FILE *maps = fopen("/proc/self/maps", "r");
|
||||
char line[512];
|
||||
int found = 0;
|
||||
while (maps && fgets(line, sizeof line, maps)) {
|
||||
unsigned long lo, hi;
|
||||
char perms[5];
|
||||
if (sscanf(line, "%lx-%lx %4s", &lo, &hi, perms) != 3) continue;
|
||||
if ((unsigned long)addr >= lo && (unsigned long)addr < hi) {
|
||||
found = perms[3] == 'p' && strchr(line, '/') != NULL;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (maps) fclose(maps);
|
||||
return found;
|
||||
}
|
||||
|
||||
int mprotect(void *addr, size_t len, int prot) {
|
||||
if ((prot & PROT_EXEC) && private_file(addr)) {
|
||||
errno = EACCES;
|
||||
return -1;
|
||||
}
|
||||
return (int)syscall(SYS_mprotect, addr, len, prot);
|
||||
}
|
||||
"""
|
||||
|
||||
CALLER = r"""
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
int fd = open(argv[1], O_RDWR);
|
||||
unsigned char *code = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);
|
||||
#if defined(__aarch64__)
|
||||
static const unsigned int body[] = {0x52800540, 0xd65f03c0};
|
||||
#else
|
||||
static const unsigned char body[] = {0xb8, 0x2a, 0x00, 0x00, 0x00, 0xc3};
|
||||
#endif
|
||||
memcpy(code + 64, body, sizeof body);
|
||||
int result = mprotect(code, 4096, PROT_READ | PROT_EXEC);
|
||||
printf("protect %d\n", result ? errno : 0);
|
||||
__builtin___clear_cache((char *)code, (char *)code + 4096);
|
||||
if (!result) printf("call %d\n", ((int (*)(void))(code + 64))());
|
||||
printf("data %d\n", code[0]);
|
||||
char line[512];
|
||||
FILE *maps = fopen("/proc/self/maps", "r");
|
||||
while (maps && fgets(line, sizeof line, maps)) {
|
||||
unsigned long lo, hi;
|
||||
if (sscanf(line, "%lx-%lx", &lo, &hi) == 2 && (unsigned long)code >= lo && (unsigned long)code < hi)
|
||||
printf("shared %d\n", strstr(line, ".droiddeck-rx") != NULL);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@unittest.skipUnless(shutil.which("cc") and os.uname().sysname == "Linux", "needs cc on Linux")
|
||||
class ExecmodRebakeTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.tmp = Path(tempfile.mkdtemp())
|
||||
cls.lib = cls.tmp / "libnoexec.so"
|
||||
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-DNOEXEC_TEST", "-o", str(cls.lib),
|
||||
str(PRELOAD / "noexec.c"), str(PRELOAD / "fsync.c"), str(PRELOAD / "robust.c"), "-ldl"], check=True)
|
||||
(cls.tmp / "execmod.c").write_text(EXECMOD)
|
||||
cls.execmod = cls.tmp / "libexecmod.so"
|
||||
subprocess.run(["cc", "-O2", "-fPIC", "-shared", "-o", str(cls.execmod), str(cls.tmp / "execmod.c")], check=True)
|
||||
(cls.tmp / "caller.c").write_text(CALLER)
|
||||
cls.caller = cls.tmp / "wine"
|
||||
subprocess.run(["cc", "-O2", "-o", str(cls.caller), str(cls.tmp / "caller.c")], check=True)
|
||||
cls.image = cls.tmp / "ntdll.dll"
|
||||
cls.image.write_bytes(bytes([7]) + bytes(4095))
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
shutil.rmtree(cls.tmp, ignore_errors=True)
|
||||
|
||||
def setUp(self):
|
||||
self.cache = self.tmp / self._testMethodName / "rx"
|
||||
self.cache.mkdir(parents=True)
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.tmp / self._testMethodName, ignore_errors=True)
|
||||
|
||||
def run_with(self, *libs):
|
||||
env = dict(os.environ, LD_PRELOAD=":".join(str(lib) for lib in libs),
|
||||
DROIDDECK_NOEXEC_CACHE_DIR=str(self.cache))
|
||||
result = subprocess.run([str(self.caller), str(self.image)], env=env, capture_output=True, text=True, check=True)
|
||||
return result.stdout.split()
|
||||
|
||||
def test_a_refused_relocated_image_runs_from_anonymous_memory(self):
|
||||
self.assertEqual(self.run_with(self.lib, self.execmod), ["protect", "0", "call", "42", "data", "7", "shared", "1"])
|
||||
|
||||
def test_processes_share_one_copy_of_the_code(self):
|
||||
self.run_with(self.lib, self.execmod)
|
||||
self.run_with(self.lib, self.execmod)
|
||||
self.assertEqual(len(os.listdir(self.cache)), 1)
|
||||
|
||||
def test_without_the_preload_the_refusal_stands(self):
|
||||
self.assertEqual(self.run_with(self.execmod), ["protect", "13", "data", "7", "shared", "0"])
|
||||
|
||||
def test_the_file_itself_is_not_changed(self):
|
||||
self.run_with(self.lib, self.execmod)
|
||||
self.assertEqual(self.image.read_bytes()[:65], bytes([7]) + bytes(64))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,154 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
NTDLL = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
__attribute__((noinline)) int ntdll_open(const char *path) {
|
||||
int fd = open(path, O_RDONLY | O_CLOEXEC);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return fd;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) int ntdll_openat(const char *path) {
|
||||
int fd = openat(AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return fd;
|
||||
}
|
||||
|
||||
__attribute__((noinline)) FILE *ntdll_fopen(const char *path) {
|
||||
FILE *f = fopen(path, "r");
|
||||
__asm__ volatile("" ::: "memory");
|
||||
return f;
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/ptrace.h>
|
||||
#include <sys/wait.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int ntdll_open(const char *path);
|
||||
int ntdll_openat(const char *path);
|
||||
FILE *ntdll_fopen(const char *path);
|
||||
|
||||
static void report(const char *name, int fd) {
|
||||
char link[64], target[256] = "", text[16384], *field;
|
||||
ssize_t n;
|
||||
long tracer = -1;
|
||||
if (fd < 0) {
|
||||
printf("%s failed\n", name);
|
||||
return;
|
||||
}
|
||||
snprintf(link, sizeof(link), "/proc/self/fd/%d", fd);
|
||||
n = readlink(link, target, sizeof(target) - 1);
|
||||
target[n > 0 ? n : 0] = '\0';
|
||||
n = pread(fd, text, sizeof(text) - 1, 0);
|
||||
text[n > 0 ? n : 0] = '\0';
|
||||
if ((field = strstr(text, "\nTracerPid:\t")) != NULL) tracer = strtol(field + 12, NULL, 10);
|
||||
const char *kind = strncmp(target, "/proc/", 6) == 0 ? "proc"
|
||||
: strncmp(target, "/memfd:", 7) == 0 ? "memfd"
|
||||
: strncmp(target, "/tmp/.droiddeck-status-", 23) == 0 ? "copy" : target;
|
||||
printf("%s kind=%s tracer=%s rdonly=%d vm=%d\n", name, kind, tracer == 0 ? "hidden" : tracer > 0 ? "shown" : "missing",
|
||||
(fcntl(fd, F_GETFL) & O_ACCMODE) == O_RDONLY, strstr(text, "\nVmRSS:") != NULL);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
static void report_stream(const char *name, FILE *f) {
|
||||
if (f == NULL) {
|
||||
printf("%s failed\n", name);
|
||||
return;
|
||||
}
|
||||
report(name, dup(fileno(f)));
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
int ready[2];
|
||||
if (pipe(ready) != 0) return 1;
|
||||
pid_t child = fork();
|
||||
if (child == 0) {
|
||||
char ok = ptrace(PTRACE_TRACEME, 0, NULL, NULL) == 0;
|
||||
if (write(ready[1], &ok, 1) != 1) _exit(1);
|
||||
for (;;) pause();
|
||||
}
|
||||
char ok = 0;
|
||||
if (read(ready[0], &ok, 1) != 1 || !ok) {
|
||||
kill(child, SIGKILL);
|
||||
waitpid(child, NULL, 0);
|
||||
puts("no ptrace");
|
||||
return 0;
|
||||
}
|
||||
char other[64], self[64];
|
||||
snprintf(other, sizeof(other), "/proc/%d/status", (int)child);
|
||||
snprintf(self, sizeof(self), "/proc/%d/status", (int)getpid());
|
||||
report("main_other_open", open(other, O_RDONLY | O_CLOEXEC));
|
||||
report_stream("main_other_fopen", fopen(other, "r"));
|
||||
report("main_self_open", open("/proc/self/status", O_RDONLY | O_CLOEXEC));
|
||||
report("ntdll_other_open", ntdll_open(other));
|
||||
report("ntdll_other_openat", ntdll_openat(other));
|
||||
report_stream("ntdll_other_fopen", ntdll_fopen(other));
|
||||
report_stream("ntdll_self_fopen", ntdll_fopen(self));
|
||||
kill(child, SIGKILL);
|
||||
waitpid(child, NULL, 0);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
class TracerPreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
if not shutil.which("cc"):
|
||||
raise unittest.SkipTest("no compiler")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / "ntdll.c").write_text(NTDLL)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"), *sources, "-ldl"],
|
||||
check=True)
|
||||
subprocess.run(["cc", "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True)
|
||||
subprocess.run(["cc", "-O1", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"), "-Wl,-rpath," + str(tmp)],
|
||||
check=True)
|
||||
env = dict(os.environ, LD_PRELOAD=str(tmp / "libblsession.so"))
|
||||
out = subprocess.run([str(tmp / "prog")], env=env, capture_output=True, text=True, timeout=60)
|
||||
if out.returncode != 0:
|
||||
raise AssertionError(out.stdout + out.stderr)
|
||||
if "no ptrace" in out.stdout:
|
||||
raise unittest.SkipTest("ptrace not allowed")
|
||||
cls.lines = dict(line.split(" ", 1) for line in out.stdout.splitlines())
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def test_other_programs_still_see_no_tracer(self):
|
||||
self.assertEqual(self.lines["main_other_open"], "kind=copy tracer=hidden rdonly=1 vm=1")
|
||||
self.assertEqual(self.lines["main_other_fopen"], "kind=copy tracer=hidden rdonly=1 vm=1")
|
||||
self.assertEqual(self.lines["main_self_open"], "kind=memfd tracer=hidden rdonly=0 vm=1")
|
||||
|
||||
def test_wine_reads_the_real_status_file(self):
|
||||
for name in ("ntdll_other_open", "ntdll_other_openat", "ntdll_other_fopen"):
|
||||
self.assertEqual(self.lines[name], "kind=proc tracer=shown rdonly=1 vm=1", name)
|
||||
self.assertEqual(self.lines["ntdll_self_fopen"], "kind=proc tracer=hidden rdonly=1 vm=1")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,301 @@
|
||||
import ctypes
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
|
||||
|
||||
NTDLL = r"""
|
||||
#include <signal.h>
|
||||
__attribute__((noinline)) void syscall_dispatcher_return_slowpath(void) { raise(SIGUSR2); }
|
||||
void slowpath(void) {
|
||||
syscall_dispatcher_return_slowpath();
|
||||
__asm__ volatile("" ::: "memory");
|
||||
}
|
||||
void slowpath_other(int sig) {
|
||||
raise(sig);
|
||||
__asm__ volatile("" ::: "memory");
|
||||
}
|
||||
"""
|
||||
|
||||
PROGRAM = r"""
|
||||
#define _GNU_SOURCE
|
||||
#include <asm/sigcontext.h>
|
||||
#include <pthread.h>
|
||||
#include <setjmp.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <ucontext.h>
|
||||
#include <unistd.h>
|
||||
|
||||
void slowpath(void);
|
||||
void slowpath_other(int sig);
|
||||
|
||||
static char altstack[65536];
|
||||
static char landing_stack[65536] __attribute__((aligned(16)));
|
||||
static volatile int mode;
|
||||
static int calls;
|
||||
static volatile int on_alt, usr2_blocked, usr1_blocked, code_ok, stack_ok;
|
||||
static volatile long handler_sp;
|
||||
static jmp_buf back;
|
||||
static uint64_t saved[31];
|
||||
static unsigned __int128 saved_v[32];
|
||||
static uint32_t saved_fpsr;
|
||||
|
||||
void landing(void);
|
||||
__asm__(".text\n.globl landing\n.type landing, %function\nlanding:\n"
|
||||
" sub sp, sp, #784\n"
|
||||
" stp x0, x1, [sp, #0]\n stp x2, x3, [sp, #16]\n stp x4, x5, [sp, #32]\n stp x6, x7, [sp, #48]\n"
|
||||
" stp x8, x9, [sp, #64]\n stp x10, x11, [sp, #80]\n stp x12, x13, [sp, #96]\n stp x14, x15, [sp, #112]\n"
|
||||
" stp x16, x17, [sp, #128]\n stp x18, x19, [sp, #144]\n stp x20, x21, [sp, #160]\n stp x22, x23, [sp, #176]\n"
|
||||
" stp x24, x25, [sp, #192]\n stp x26, x27, [sp, #208]\n stp x28, x29, [sp, #224]\n str x30, [sp, #240]\n"
|
||||
" add x9, sp, #256\n"
|
||||
" stp q0, q1, [x9, #0]\n stp q2, q3, [x9, #32]\n stp q4, q5, [x9, #64]\n stp q6, q7, [x9, #96]\n"
|
||||
" stp q8, q9, [x9, #128]\n stp q10, q11, [x9, #160]\n stp q12, q13, [x9, #192]\n stp q14, q15, [x9, #224]\n"
|
||||
" stp q16, q17, [x9, #256]\n stp q18, q19, [x9, #288]\n stp q20, q21, [x9, #320]\n stp q22, q23, [x9, #352]\n"
|
||||
" stp q24, q25, [x9, #384]\n stp q26, q27, [x9, #416]\n stp q28, q29, [x9, #448]\n stp q30, q31, [x9, #480]\n"
|
||||
" mrs x10, fpsr\n str w10, [sp, #768]\n"
|
||||
" mov x0, sp\n bl landed\n brk #0\n");
|
||||
|
||||
void landed(uint64_t *regs) {
|
||||
memcpy(saved, regs, sizeof(saved));
|
||||
memcpy(saved_v, regs + 32, sizeof(saved_v));
|
||||
saved_fpsr = *(uint32_t *)(regs + 96);
|
||||
longjmp(back, 1);
|
||||
}
|
||||
|
||||
static struct fpsimd_context *fpsimd_of(ucontext_t *uc) {
|
||||
struct _aarch64_ctx *c = (struct _aarch64_ctx *)uc->uc_mcontext.__reserved;
|
||||
while (c->magic) {
|
||||
if (c->magic == FPSIMD_MAGIC) return (struct fpsimd_context *)c;
|
||||
c = (struct _aarch64_ctx *)((char *)c + c->size);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void handler(int sig, siginfo_t *info, void *ctx) {
|
||||
ucontext_t *uc = ctx;
|
||||
sigset_t now;
|
||||
long sp = (long)&now;
|
||||
__atomic_add_fetch(&calls, 1, __ATOMIC_RELAXED);
|
||||
handler_sp = sp;
|
||||
on_alt = sp >= (long)altstack && sp < (long)altstack + (long)sizeof(altstack);
|
||||
pthread_sigmask(SIG_BLOCK, NULL, &now);
|
||||
usr2_blocked = sigismember(&now, SIGUSR2);
|
||||
usr1_blocked = sigismember(&now, SIGUSR1);
|
||||
code_ok = sig == SIGUSR2 && info->si_signo == SIGUSR2 && info->si_code == SI_TKILL && info->si_pid == getpid();
|
||||
stack_ok = uc->uc_stack.ss_sp == altstack && uc->uc_stack.ss_size == sizeof(altstack) && !(uc->uc_stack.ss_flags & SS_DISABLE);
|
||||
if (mode == 1) {
|
||||
struct fpsimd_context *fp = fpsimd_of(uc);
|
||||
for (int i = 0; i <= 28; i++) uc->uc_mcontext.regs[i] = 0x1000 + i;
|
||||
uc->uc_mcontext.regs[29] = 0x2900;
|
||||
uc->uc_mcontext.regs[30] = 0x3000;
|
||||
uc->uc_mcontext.sp = (uint64_t)(landing_stack + sizeof(landing_stack));
|
||||
uc->uc_mcontext.pc = (uint64_t)landing;
|
||||
uc->uc_mcontext.pstate = 0x60000000;
|
||||
for (int i = 0; i < 32; i++) fp->vregs[i] = ((unsigned __int128)(0x7700 + i) << 64) | (0x5500 + i);
|
||||
fp->fpsr = 0x8;
|
||||
}
|
||||
}
|
||||
|
||||
static void usr1(int sig, siginfo_t *info, void *ctx) {
|
||||
(void)sig;
|
||||
(void)info;
|
||||
(void)ctx;
|
||||
}
|
||||
|
||||
uint64_t kept_x[10];
|
||||
double kept_d[8];
|
||||
|
||||
static int keep_callee_saved(void) {
|
||||
uint64_t *out = kept_x;
|
||||
double *d = kept_d;
|
||||
__asm__ volatile(
|
||||
"mov x19, #19\n mov x20, #20\n mov x21, #21\n mov x22, #22\n mov x23, #23\n"
|
||||
"mov x24, #24\n mov x25, #25\n mov x26, #26\n mov x27, #27\n mov x28, #28\n"
|
||||
"fmov d8, #1.0\n fmov d9, #2.0\n fmov d10, #3.0\n fmov d11, #4.0\n"
|
||||
"fmov d12, #5.0\n fmov d13, #6.0\n fmov d14, #7.0\n fmov d15, #8.0\n"
|
||||
"bl slowpath\n"
|
||||
"adrp x0, kept_x\n add x0, x0, :lo12:kept_x\n"
|
||||
"stp x19, x20, [x0, #0]\n stp x21, x22, [x0, #16]\n stp x23, x24, [x0, #32]\n"
|
||||
"stp x25, x26, [x0, #48]\n stp x27, x28, [x0, #64]\n"
|
||||
"adrp x0, kept_d\n add x0, x0, :lo12:kept_d\n"
|
||||
"stp d8, d9, [x0, #0]\n stp d10, d11, [x0, #16]\n stp d12, d13, [x0, #32]\n stp d14, d15, [x0, #48]\n"
|
||||
:
|
||||
:
|
||||
: "x0", "x1", "x2", "x3", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15",
|
||||
"x16", "x17", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28", "x30",
|
||||
"v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
|
||||
"v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30",
|
||||
"v31", "memory", "cc");
|
||||
for (int i = 0; i < 10; i++)
|
||||
if (out[i] != (uint64_t)(19 + i)) return 0;
|
||||
for (int i = 0; i < 8; i++)
|
||||
if (d[i] != (double)(i + 1)) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void *stress(void *arg) {
|
||||
(void)arg;
|
||||
for (int i = 0; i < 2000; i++) slowpath();
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
stack_t ss = {.ss_sp = altstack, .ss_size = sizeof(altstack), .ss_flags = 0};
|
||||
struct sigaction sa;
|
||||
sigset_t mask, now;
|
||||
sigaltstack(&ss, NULL);
|
||||
memset(&sa, 0, sizeof(sa));
|
||||
sa.sa_sigaction = handler;
|
||||
sa.sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaddset(&sa.sa_mask, SIGUSR1);
|
||||
sigaction(SIGUSR2, &sa, NULL);
|
||||
sa.sa_sigaction = usr1;
|
||||
sigemptyset(&sa.sa_mask);
|
||||
sigaction(SIGUSR1, &sa, NULL);
|
||||
|
||||
if (argc > 1 && strcmp(argv[1], "bench") == 0) {
|
||||
int n = argc > 2 ? atoi(argv[2]) : 20000;
|
||||
struct timespec a, b;
|
||||
clock_gettime(CLOCK_MONOTONIC, &a);
|
||||
for (int i = 0; i < n; i++) slowpath();
|
||||
clock_gettime(CLOCK_MONOTONIC, &b);
|
||||
printf("%.2f us per raise, alt %d\n", ((b.tv_sec - a.tv_sec) * 1e9 + (b.tv_nsec - a.tv_nsec)) / 1e3 / n, on_alt);
|
||||
return 0;
|
||||
}
|
||||
|
||||
mode = 0;
|
||||
calls = 0;
|
||||
int kept = keep_callee_saved();
|
||||
pthread_sigmask(SIG_BLOCK, NULL, &now);
|
||||
printf("returned calls=%d kept=%d usr2_blocked=%d usr1_blocked=%d code=%d stack=%d after_usr2=%d after_usr1=%d\n",
|
||||
calls, kept, usr2_blocked, usr1_blocked, code_ok, stack_ok, sigismember(&now, SIGUSR2),
|
||||
sigismember(&now, SIGUSR1));
|
||||
printf("path %s\n", on_alt ? "kernel" : "inline");
|
||||
|
||||
mode = 1;
|
||||
calls = 0;
|
||||
if (!setjmp(back)) {
|
||||
slowpath();
|
||||
printf("redirect did not happen\n");
|
||||
} else {
|
||||
int ok = 1;
|
||||
for (int i = 0; i <= 28; i++)
|
||||
if (saved[i] != (uint64_t)(0x1000 + i)) ok = 0;
|
||||
if (saved[29] != 0x2900 || saved[30] != 0x3000) ok = 0;
|
||||
for (int i = 0; i < 32; i++)
|
||||
if (saved_v[i] != (((unsigned __int128)(0x7700 + i) << 64) | (0x5500 + i))) ok = 0;
|
||||
printf("redirect calls=%d regs=%d fpsr=%u\n", calls, ok, saved_fpsr & 0x8);
|
||||
}
|
||||
mode = 0;
|
||||
|
||||
sigemptyset(&mask);
|
||||
sigaddset(&mask, SIGUSR2);
|
||||
pthread_sigmask(SIG_BLOCK, &mask, NULL);
|
||||
calls = 0;
|
||||
slowpath();
|
||||
int while_blocked = calls;
|
||||
pthread_sigmask(SIG_UNBLOCK, &mask, NULL);
|
||||
printf("blocked during=%d after=%d\n", while_blocked, calls);
|
||||
|
||||
calls = 0;
|
||||
slowpath_other(SIGUSR1);
|
||||
raise(SIGUSR2);
|
||||
printf("other calls=%d main_path=%s\n", calls, on_alt ? "kernel" : "inline");
|
||||
|
||||
calls = 0;
|
||||
pthread_t t[4];
|
||||
for (int i = 0; i < 4; i++) pthread_create(&t[i], NULL, stress, NULL);
|
||||
for (int i = 0; i < 4; i++) pthread_join(t[i], NULL);
|
||||
printf("threads calls=%d\n", calls);
|
||||
return 0;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def has_gcs_hwcap():
|
||||
try:
|
||||
getauxval = ctypes.CDLL(None).getauxval
|
||||
except (AttributeError, OSError):
|
||||
return False
|
||||
getauxval.restype = ctypes.c_ulong
|
||||
getauxval.argtypes = [ctypes.c_ulong]
|
||||
return bool(getauxval(16) & (1 << 32))
|
||||
|
||||
|
||||
def runner():
|
||||
if platform.machine() in ("aarch64", "arm64") and shutil.which("gcc") and not has_gcs_hwcap():
|
||||
return "gcc", []
|
||||
if shutil.which("aarch64-linux-gnu-gcc") and shutil.which("qemu-aarch64") and Path("/usr/aarch64-linux-gnu").is_dir():
|
||||
return "aarch64-linux-gnu-gcc", ["qemu-aarch64", "-cpu", "neoverse-n1", "-L", "/usr/aarch64-linux-gnu"]
|
||||
return None, None
|
||||
|
||||
|
||||
class Usr2PreloadTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.cc, cls.prefix = runner()
|
||||
if cls.cc is None:
|
||||
raise unittest.SkipTest("no aarch64 compiler and runner")
|
||||
cls.tmp = tempfile.TemporaryDirectory()
|
||||
tmp = Path(cls.tmp.name)
|
||||
(tmp / "ntdll.c").write_text(NTDLL)
|
||||
(tmp / "prog.c").write_text(PROGRAM)
|
||||
sources = sorted(str(p) for p in PRELOAD.glob("*.c"))
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-Wall", "-pthread", "-o", str(tmp / "libblsession.so"),
|
||||
*sources, "-ldl"], check=True)
|
||||
subprocess.run([cls.cc, "-shared", "-fPIC", "-O2", "-o", str(tmp / "ntdll.so"), str(tmp / "ntdll.c")], check=True)
|
||||
subprocess.run([cls.cc, "-O1", "-U_FORTIFY_SOURCE", "-pthread", "-o", str(tmp / "prog"), str(tmp / "prog.c"), str(tmp / "ntdll.so"),
|
||||
"-Wl,-rpath," + str(tmp)], check=True)
|
||||
cls.program = tmp / "prog"
|
||||
cls.preload = tmp / "libblsession.so"
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.tmp.cleanup()
|
||||
|
||||
def run_program(self, preload):
|
||||
env = dict(os.environ)
|
||||
env.pop("LD_PRELOAD", None)
|
||||
cmd = list(self.prefix) + [str(self.program)]
|
||||
if preload:
|
||||
if self.prefix:
|
||||
cmd = list(self.prefix) + ["-E", "LD_PRELOAD=" + str(self.preload), str(self.program)]
|
||||
else:
|
||||
env["LD_PRELOAD"] = str(self.preload)
|
||||
out = subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=120)
|
||||
self.assertEqual(out.returncode, 0, out.stderr)
|
||||
return out.stdout.splitlines()
|
||||
|
||||
def test_a_ntdll_raise_runs_the_handler_without_a_kernel_signal(self):
|
||||
lines = self.run_program(True)
|
||||
self.assertIn("path inline", lines)
|
||||
self.assertIn("returned calls=1 kept=1 usr2_blocked=1 usr1_blocked=1 code=1 stack=1 after_usr2=0 after_usr1=0", lines)
|
||||
|
||||
def test_b_context_the_handler_writes_is_the_one_that_resumes(self):
|
||||
self.assertIn("redirect calls=1 regs=1 fpsr=8", self.run_program(True))
|
||||
|
||||
def test_c_behaves_like_the_kernel_signal(self):
|
||||
stock = [line for line in self.run_program(False) if not line.startswith("path ")]
|
||||
inline = [line for line in self.run_program(True) if not line.startswith("path ")]
|
||||
self.assertIn("returned calls=1 kept=1 usr2_blocked=1 usr1_blocked=1 code=1 stack=1 after_usr2=0 after_usr1=0", stock)
|
||||
self.assertEqual(stock, inline)
|
||||
|
||||
def test_d_blocked_other_signals_and_other_callers_use_the_kernel(self):
|
||||
lines = self.run_program(True)
|
||||
self.assertIn("blocked during=0 after=1", lines)
|
||||
self.assertIn("other calls=1 main_path=kernel", lines)
|
||||
self.assertIn("threads calls=8000", lines)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user