Compare commits

...
Author SHA1 Message Date
The412Banner 2ed7afd672 fix(logs): cap app.log and audio.log at 64 MB per session
A guest client reconnecting to PulseAudio thousands of times a second filled app.log to 1.4 GB and audio.log to 875 MB in 15 minutes. Both files now stop at 64 MB with a marker, keep their last 400 lines for the end of the file, and the audio daemon's lines stop going to logcat once audio.log is full.
2026-11-25 12:11:47 +00:00
MaxsTechReview d38fd373f0 fix(runtime): programs can open ProgramData folders a stale Windows owner locked (#3194)
* Unlock ProgramData entries a stale Windows owner locked

Wine builds the user SID from /etc/machine-id and the uid it runs as.
When either changes, descriptors stored in user.wine.sd keep the old
owner, and the next DACL change maps to mode 000 because no ACE matches
the token. Wine then cannot open the entry, so programs such as
Battle.net cannot repair their own folders.

Before each launch, clear stale local user owners under ProgramData and
give owner access back to entries they locked.

* Heal a locked ProgramData itself and keep read-only folders

* Serialise the ProgramData heal per prefix

* Launch even when the ProgramData owner check fails

* Read the machine ID as bytes the way Wine does

* Parse a signed machine ID the way Wine does
2026-11-25 05:48:37 -05:00
MaxsTechReview a6fe10d8ff fix(input): resolve fake input's real functions before any loader lock is held (#3193)
* Resolve fake input's real functions before any loader lock is held

Each hooked call looked up its real function through a function-local
static, and the x86 dlsym hook opened libc the same way. A thread that
entered a hook first held the static's guard while dlsym waited for the
loader lock, and a thread inside dlopen held the loader lock while its
constructor called the same hook and waited for the guard. Steam's update
window hung that way under FEX, so x86 Steam stopped at Installing update.

The real functions now live in lock-free slots filled by the library's
constructor, and the dlsym hook resolves dlvsym and libc there too.

* Use an atomic handshake in the loader lock test
2026-11-25 04:24:58 -05:00
MaxsTechReview 953549704a fix(flatpak): file dialogs and forwarded descriptors work in Flatpak apps (#3190)
* fix(flatpak): file dialogs and forwarded descriptors work in Flatpak apps

Flatpak apps opened from the desktop could not open files: the file
chooser's result went through a document store that cannot mount on
Android, and image loaders started with flatpak-spawn --forward-fd lost
their D-Bus descriptor because the app relaunches sandboxes and only
stdio survived.

- A session document store hands picked files and folders back in place
  instead of failing without a mount.
- The bwrap shim offers its inherited descriptors once over a private
  socket, and the native hook puts them back on their original numbers
  before the program starts.
- The native hook resolves /proc/<pid>/root paths to the other
  process's sandbox, so xdg-desktop-portal reads .flatpak-info and
  identifies the calling app.

* fix(flatpak): check documents against the app's view and harden fd forwarding

The document store hands a picked file back in place only when the
calling app's own sandbox can open it with the requested access, so
paths the app cannot see are refused instead of handed out broken.
/proc/<pid>/root lookups follow links inside that process's view,
duplicated root descriptors keep their mapping, and close_range drops
stale records. Forwarded descriptors survive targets at the fd limit,
truncated offers are ignored, and the shim refuses more descriptors
than one message can carry.

* fix(flatpak): match picked documents by file identity and keep O_NOFOLLOW on process roots

The document store accepts an in-place path only when the app's view
holds the same file (device and inode) as the picked descriptor, and
reads each process root once. A bare /proc/<pid>/root opened with
O_NOFOLLOW is no longer mapped, so it fails like the kernel's link.

* Keep a trailing-slash process root translated and track only directory roots
2026-11-25 03:03:03 -05:00
MaxsTechReview 19d8819137 fix(battlenet): drop the unused runtime drive and list its games under the runtime path (#3188)
* fix(battlenet): drop the unused runtime drive and list its games under the runtime path

* fix(battlenet): read product.db paths decoded and keep alias-saved folders

* fix(battlenet): keep drives for paths that climb out of the runtime

* fix(battlenet): keep a drive referenced with any separator spelling

* fix(battlenet): check decoded config values before dropping a drive
2026-11-24 23:29:32 -05:00
Kurt Himebauch 1b80b506cb Default gamescope cursor drawing to on (#3187) 2026-11-24 21:40:15 -05:00
4b289a4802 fix(battlenet): games installed inside the runtime stay listed after a native session (#3148)
* fix(battlenet): games installed inside the runtime stay listed after a native session

* test(battlenet): expect the shared folder for a lone Forever install

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-24 21:12:33 -05:00
MaxsTechReview 238ef76c5c fix(preload): apps that reload libudev no longer crash in the input wrappers (#3180)
fix(preload): keep libudev loaded while the input wrappers use it

Programs that close libudev and open it again crashed in the next wrapped
udev call: the wrappers kept function pointers into the unmapped copy.
Pin libudev with RTLD_NODELETE when it is opened so those pointers and
the stored handle stay valid.
2026-11-24 20:19:53 -05:00
Kurt Himebauch 906e66e3cf fix(library): added-games selection edge cases from #2818 review (#3177)
fix(library): saved exes skip store games that are updating
2026-11-24 19:26:44 -05:00
Kurt Himebauch c0d14f9632 fix(xbox): an application element with attributes on the next line still counts (#3175)
* fix(xbox): an application element with attributes on the next line still counts

* fix(xbox): repair the patch hunk for the pretty-printed manifest test
2026-11-24 19:26:04 -05:00
Kurt Himebauch 70bda85dd5 fix(desktop): the SteamOS panel layout replaces an older or Kubuntu-default panel (#3173)
* fix(desktop): a Kubuntu-default panel gets the SteamOS layout and launcher icon

* fix(desktop): lay out Plasma's stock panel with the SteamOS pins, once, over an older panel

* fix(desktop): keep Plasma's wide-screen cap and input-method panel in the SteamOS layout

* fix(desktop): stamp the panel layout only after the old panel is backed up, never over a backup
2026-11-24 19:25:59 -05:00
The412Banner 9e6f81540f feat(bionic): DroidDeck-Bionic compatibility tool (Wine on Android's libc, no proot) (#3037)
DroidDeck-Bionic: a Steam compatibility tool that runs the game itself on Android's libc (bionic) instead of glibc inside proot. Steam, the stores and the session stay on DroidDeck's Linux side; only the game process leaves proot.

- Listed in the Proton list only when Run without proot is on, in its own row. Its builds are pre-releases on Droid-Deck/DroidDeck-Proton (DroidDeck-Bionic-12.8-rNN, runtime built by .github/workflows/build-bionic-runtime.yml from tools/bionic-runtime); the app installs and updates them like the other extra tools and never makes one the default unless the user picks it.
- With proot on, a launch sent to a bionic tool goes to the newest DroidDeck-Proton (picks stay as set).
- ProtonExtras / ProtonMenu / ExperimentalProtons / droiddeck-proton-extra: bionic pre-releases checked and listed only without proot; updates carry the default and per-game picks over; deleting a tool never follows links out of it. ProtonDefault: picks left on an older bionic build move to the installed one.
- Components: FEX builds for bionic (bionic-stable on DroidDeck-Components); each tool is offered only the FEX builds that fit it.
- Session logs: the bionic game log and its graphics logs are part of Share logs.

Synced with main twice before the merge (latest sync fbed69ce on main 67b82ad9; Build APK and validation green); a local trial merge on main 3e1fc3e6 had no conflicts and the game-environment, Proton-extra and store-launch tests pass.
2026-11-24 23:39:23 +00:00
Kurt Himebauch 3e1fc3e60e fix(xbox): a bundle with resource packages installs from its application package (#3172)
* fix(xbox): a bundle with resource packages installs from its application package

* fix(xbox): repair the patch hunk for the hoist tests
2026-11-24 18:32:38 -05:00
MaxsTechReview 826853fff5 fix(desktop): package updates that set file capabilities finish without proot (#3151) 2026-11-24 18:25:05 -05:00
MaxsTechReview 9be131cf6d fix(native): a trailing slash after a program keeps the hook's exe name like the kernel (#3171) 2026-11-24 18:24:41 -05:00
Kurt Himebauchandmaxjivi05 5ed97915c7 fix(session): report the CPU cache sizes the x86 CPUID reports to Windows programs (#2705)
* fix(session): report the CPU cache sizes the x86 CPUID reports to Windows programs

* fix(session): clear the staged core caches without following links

* fix(session): stage CPU cache binds per session generation and per core

* fix(session): keep every start's staged CPU caches until the process ends

* fix(session): give every start its own CPU cache staging folder

* test(session): a delayed worker from a recreated service keeps its own cache folder

---------

Co-authored-by: maxjivi05 <maxjividen@gmail.com>
2026-11-24 18:18:14 -05:00
Kurt Himebauch d8654ae1be fix(retroarch): use the packaged assets, cores and core info paths (#2451)
* fix(retroarch): use the packaged assets, cores and core info paths

* fix(retroarch): migrate incomplete configs

* fix(retroarch): preserve configured core directories

* fix(retroarch): replace empty path settings in place

* fix(retroarch): keep installed core directory when repairing a blank libretro_directory
2026-11-24 18:15:35 -05:00
Kurt Himebauch 8f4744398d fix(ea): a failed touchup is retried and its output reaches the store log (#2505)
* fix(ea): a failed touchup is retried and its output reaches the store log

* fix(ea): bound the touchup output kept for the store log

The output goes to a temporary file and only its last 64 KiB are read back. The timeout test now checks the output is logged and the next launch retries.

* fix(ea): a touchup still runs when its output cannot be captured
2026-11-24 18:15:30 -05:00
The412BannerandKurt Himebauch 8f4cefd3bd fix(game-env): turn on FEX x87 FIP emulation for the SecuROM racing title that needs it (#3092)
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:22 -05:00
Kurt Himebauch 01dc415f10 fix(gog): check space for the extracted install before downloading an offline installer (#2419)
* fix(gog): bind every store root for installer extraction and log its error

* fix(gog): count the extracted size before downloading an offline installer

The installer fallback only checked free space for the download, so a
game that needs the download plus its extracted files failed after
every part was fetched, with innoextract's stream error. The failure
reason now drops innoextract's warnings and bug-report trailer.

* fix(gog): keep the internal store root visible to installer extraction

* fix(games): never give an added folder the internal store guest path

An added folder named Stores was bound at /root/Games/Stores, over the
internal store install root. legacyRoots, used by bindFolder and the
games-folder migration, now gives such a folder a suffixed guest path,
so guestBinds mounts every added root again, matching guestPath and the
session binds.

* fix(games): re-path saved folder binds that hold the internal store guest path

* test(games): verify extractor binds after migrating a saved internal-guest bind

* fix(gog): keep innoextract output in the log and leave the install failure message unchanged

* fix(gog): count known installer part sizes in the free-space check when some part has no size
2026-11-24 18:13:16 -05:00
Tushar GandheandKurt Himebauch af1fe6c61c fix(launcher): LT and RT keep the focus ring on the tab rail (#3039)
* fix(launcher): LT and RT keep the focus ring on the tab rail

A trigger step selected the tab like a tap on the rail, which also sent focus into the new page, and each page put it somewhere different. The step now shows the page and focuses its rail item, and for a second puts focus back on the rail if the page takes it, until another key is pressed. Dual screens, which have no rail on the main screen, keep focusing the page.

* fix(launcher): end the trigger step's rail hold when another navigation changes the page

A navigation that changed the selected page during the hold, such as opening a game from a link, was undone: the hold focused the stepped tab's rail item, and that focus switched the page back. The hold now stops as soon as the selection is no longer the one the step made.

* fix(launcher): end the trigger step's rail hold when another navigation opens a page

Opening the Components page does not change the selected tab, so a navigation there during the hold kept it running and the hold could pull focus from Components back to the rail. The hold now also tracks the page key: once the page its own step opened is showing, any other page ends the hold.

---------

Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:10 -05:00
The412BannerandKurt Himebauch 7bf75af8a1 fix(input): only an on-screen left mouse button stops screen taps from clicking (#3008)
Co-authored-by: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com>
2026-11-24 18:13:05 -05:00
112 changed files with 7380 additions and 277 deletions

No files matched your search

@@ -0,0 +1,35 @@
name: Build bionic runtime pack and DroidDeck-Bionic tool
on:
push:
paths:
- 'tools/bionic-runtime/**'
- 'tools/gamescope/patches/0117-wsi-cache-present-bypass-check.patch'
- 'tools/gamescope/patches/0119-wsi-default-images-under-limiter.patch'
- 'app/src/main/cpp/fakeinput_steam.cpp'
- 'tools/gpuload/**'
- '.github/workflows/build-bionic-runtime.yml'
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-24.04
timeout-minutes: 45
steps:
- uses: actions/checkout@v4
- name: Host tools
run: |
set -euo pipefail
sudo apt-get update -qq
sudo apt-get install -y -qq --no-install-recommends libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev \
libxcb1-dev libxcb-composite0-dev libglm-dev zstd
- name: Build
run: |
set -euo pipefail
export NDK="${ANDROID_NDK_LATEST_HOME:-${ANDROID_NDK_HOME:-$ANDROID_NDK_ROOT}}"
export BUILD_NUMBER=${{ github.run_number }}
tools/bionic-runtime/build.sh "$RUNNER_TEMP/bionic-runtime" "$PWD/out"
- uses: actions/upload-artifact@v4
with:
name: droiddeck-bionic-runtime-${{ github.sha }}
path: out/*
+155 -51
View File
@@ -58,6 +58,59 @@
#define EXPORT extern "C" __attribute__((visibility("default")))
struct SymbolSlot {
std::atomic<void *> fn{nullptr};
std::atomic<bool> resolved{false};
};
template <typename Fn> static Fn resolved_symbol(SymbolSlot &slot, void *handle, const char *name) {
if (!slot.resolved.load(std::memory_order_acquire)) {
slot.fn.store(dlsym(handle, name), std::memory_order_relaxed);
slot.resolved.store(true, std::memory_order_release);
}
return reinterpret_cast<Fn>(slot.fn.load(std::memory_order_relaxed));
}
enum class Next : size_t {
open,
openat,
close,
write,
ioctl,
poll,
ppoll,
select,
stat,
stat64,
fstat,
fstat64,
xstat,
xstat64,
fxstat,
fxstat64,
statx,
statfs,
fstatfs,
access,
faccessat,
opendir,
scandir,
inotify_add_watch,
count
};
static const char *const next_names[] = {"open", "openat", "close", "write", "ioctl", "poll", "ppoll", "select", "stat", "stat64", "fstat", "fstat64", "__xstat", "__xstat64", "__fxstat", "__fxstat64", "statx", "statfs", "fstatfs", "access", "faccessat", "opendir", "scandir", "inotify_add_watch"};
static_assert(sizeof(next_names) / sizeof(next_names[0]) == static_cast<size_t>(Next::count), "next_names");
static SymbolSlot next_slots[static_cast<size_t>(Next::count)];
template <typename Fn> static Fn next_symbol(Next which) {
return resolved_symbol<Fn>(next_slots[static_cast<size_t>(which)], RTLD_NEXT, next_names[static_cast<size_t>(which)]);
}
static void resolve_next_symbols() {
for (size_t i = 0; i < static_cast<size_t>(Next::count); i++) next_symbol<void *>(static_cast<Next>(i));
}
#ifdef __GLIBC__
typedef unsigned long ioctl_request_t;
#else
@@ -205,6 +258,11 @@ static void controller_fork_prepare();
static void controller_fork_parent();
static void controller_fork_child();
// bionic: libc's own start-up calls hooked functions (access) before environ is set. Settings read
// then would be empty and cached for good, so until environ exists hooks see defaults, uncached.
extern "C" char **environ;
static bool env_ready() { return environ != nullptr; }
struct FakeConfig {
const char *hook_dir;
const char *udev_data_dir;
@@ -218,6 +276,10 @@ struct FakeConfig {
// would throw a recursive-init error there, so the fields are filled without allocating, and a
// reentry on the initializing thread gets them while other threads wait for the fork handlers.
static FakeConfig &config() {
if (!env_ready()) {
static FakeConfig early = {"/data/data/com.termux/files/home/fake-input", nullptr, false, false, false};
return early;
}
static FakeConfig cfg;
static std::atomic<int> state{0};
static __thread bool initializing __attribute__((tls_model("initial-exec")));
@@ -433,6 +495,7 @@ void log(const char *message, ...) {
}
__attribute__((constructor)) static void library_init() {
resolve_next_symbols();
config();
controller_mutex();
controller_map();
@@ -587,7 +650,7 @@ get_fake_input_rdev(const char *event) {
__attribute__((visibility("hidden"))) static void load_ring_paths() {
std::lock_guard<std::recursive_mutex> guard(controller_mutex());
if (ring_paths_loaded)
if (ring_paths_loaded || !env_ready())
return;
const char *spec = getenv("FAKE_EVDEV_MEMFD_PATHS");
@@ -724,7 +787,7 @@ open_fake_input_ring(const char *event, int flags) {
return -1;
}
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
int fd = my_open(ring_path.c_str(), O_RDWR | (flags & (O_NONBLOCK | O_CLOEXEC)));
if (fd < 0)
@@ -807,12 +870,25 @@ __attribute__((visibility("hidden"))) static bool is_steam_client() {
__attribute__((visibility("hidden"))) static bool presents_steam_virtual() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *enabled = getenv("FAKE_EVDEV_STEAM_VIRTUAL");
known = enabled && atoi(enabled) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
// The bionic Proton layer's winebus has no udev bus, and its SDL bus skips 28de:11ff (Proton reads Steam's virtual
// pad through udev/evdev), so with FAKE_EVDEV_STEAM_PAD_AS_X360=1 other processes see that pad as a plain Xbox 360 pad.
__attribute__((visibility("hidden"))) static bool steam_pad_as_x360() {
static int known;
if (known == 0) {
if (!env_ready()) return false;
const char *v = getenv("FAKE_EVDEV_STEAM_PAD_AS_X360");
known = v && atoi(v) && !is_steam_client() ? 1 : -1;
}
return known == 1;
}
__attribute__((visibility("hidden"))) static bool
presents_xbox_triggers(const FakeController &fake) {
return fake.uinput || !is_steam_client();
@@ -978,7 +1054,7 @@ __attribute__((visibility("hidden"))) static void unpublish_uinput(UinputWriter
}
__attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
for (int node = UINPUT_EVENT_BASE; node < UINPUT_EVENT_LIMIT; node++) {
std::string path = uinput_ring_path(node);
int fd = my_open(path.c_str(), O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0644);
@@ -1005,7 +1081,7 @@ __attribute__((visibility("hidden"))) static int claim_uinput_node(int *fd_out)
}
__attribute__((visibility("hidden"))) static int publish_uinput(UinputWriter &w) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
int fd = -1;
int node = claim_uinput_node(&fd);
if (node < 0) return -1;
@@ -1391,6 +1467,7 @@ static std::unordered_map<int, std::shared_ptr<DeckHidraw>> &deck_map() {
static bool fake_deck_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0) enabled = getenv("FAKE_EVDEV_DECK") && atoi(getenv("FAKE_EVDEV_DECK")) ? 1 : 0;
return enabled == 1;
}
@@ -1398,6 +1475,7 @@ static bool fake_deck_enabled() {
__attribute__((visibility("hidden"))) static uint32_t session_pad_type() {
static int type = -1;
if (type < 0) {
if (!env_ready()) return PAD_TYPE_DECK;
const char *env = getenv("FAKE_EVDEV_PAD_TYPE");
type = env && !strcmp(env, "steamcontroller") ? PAD_TYPE_STEAM
: env && !strcmp(env, "xbox360") ? PAD_TYPE_XBOX
@@ -1416,7 +1494,7 @@ __attribute__((visibility("hidden"))) static const uint8_t *ring_blocks() {
std::lock_guard<std::mutex> guard(lock);
if ((mapped = block.load(std::memory_order_acquire))) return mapped;
tries.fetch_add(1, std::memory_order_relaxed);
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
std::string path = get_ring_path_for_slot(0);
int fd = path.empty() ? -1 : my_open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) return nullptr;
@@ -1470,6 +1548,7 @@ __attribute__((visibility("hidden"))) static uint64_t monotonic_us() {
static bool fake_triton_enabled() {
static int enabled = -1;
if (enabled < 0 && !env_ready()) return false;
if (enabled < 0)
enabled = fake_deck_enabled() && getenv("FAKE_EVDEV_TRITON") && atoi(getenv("FAKE_EVDEV_TRITON")) ? 1 : 0;
return enabled == 1;
@@ -1768,7 +1847,7 @@ __attribute__((visibility("hidden"))) static void *sony_report_thread(void *arg)
__attribute__((visibility("hidden"))) static int open_deck_hidraw(int flags, uint8_t sony = 0) {
const char *path = sony == 4 ? DS4_HIDRAW_PATH : sony == 5 ? DUALSENSE_HIDRAW_PATH : DECK_HIDRAW_PATH;
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
if (!process_reads_pads()) {
Logger::log("deck: %s refused: not the Steam client\n", path);
errno = ENOENT;
@@ -1977,7 +2056,7 @@ __attribute__((visibility("hidden"))) static void *triton_pad_thread(void *arg)
}
__attribute__((visibility("hidden"))) static int open_triton_hidraw(int flags, bool emulated) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
if (!process_reads_pads()) {
errno = ENOENT;
return -1;
@@ -2091,11 +2170,12 @@ static_assert(sizeof(TouchRingFile) <= TOUCH_RING_SIZE, "TouchRingFile layout");
__attribute__((visibility("hidden"))) static TouchRingFile *touch_ring() {
static TouchRingFile *ring = nullptr;
if (!env_ready()) return nullptr;
static std::once_flag once;
std::call_once(once, [] {
const char *path = getenv("FAKE_TOUCHCTL_RING");
if (!path || !*path || !fake_deck_enabled()) return;
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
int fd = my_open(path, O_RDWR | O_CLOEXEC);
if (fd < 0) {
Logger::log("touch: %s not openable (%s)\n", path, strerror(errno));
@@ -2312,7 +2392,8 @@ __attribute__((visibility("hidden"))) static int inject_uevent(const char *actio
const char *subsystem, const char *devname,
unsigned major, unsigned minor) {
using inject_fn = int (*)(const char *, const char *, const char *, const char *, unsigned, unsigned);
static auto inject = reinterpret_cast<inject_fn>(dlsym(RTLD_DEFAULT, "dd_udevmon_inject"));
static SymbolSlot inject_slot;
const auto inject = resolved_symbol<inject_fn>(inject_slot, RTLD_DEFAULT, "dd_udevmon_inject");
return inject ? inject(action, devpath, subsystem, devname, major, minor) : -1;
}
@@ -2434,6 +2515,7 @@ __attribute__((constructor)) static void start_touch_controller() {
static constexpr long SYSFS_FS_MAGIC = 0x62656572;
__attribute__((visibility("hidden"))) static const char *deck_listing_dir() {
if (!env_ready()) return nullptr;
static const char *dir = getenv("FAKE_DECK_SYSFS_LISTING");
return dir && *dir ? dir : nullptr;
}
@@ -2469,7 +2551,7 @@ __attribute__((visibility("hidden"))) static void note_deck_sysfs(const char *ho
}
EXPORT int fstatfs(int fd, struct statfs *buf) {
static auto real = reinterpret_cast<int (*)(int, struct statfs *)>(dlsym(RTLD_NEXT, "fstatfs"));
const auto real = next_symbol<int (*)(int, struct statfs *)>(Next::fstatfs);
int result = real(fd, buf);
if (fake_deck_enabled() && is_deck_sysfs_fd(fd)) {
note_deck_sysfs("fstatfs", result);
@@ -2479,7 +2561,7 @@ EXPORT int fstatfs(int fd, struct statfs *buf) {
}
EXPORT int statfs(const char *path, struct statfs *buf) {
static auto real = reinterpret_cast<int (*)(const char *, struct statfs *)>(dlsym(RTLD_NEXT, "statfs"));
const auto real = next_symbol<int (*)(const char *, struct statfs *)>(Next::statfs);
int result = real(path, buf);
if (fake_deck_enabled() && is_deck_sysfs_path(path)) {
note_deck_sysfs(path, result);
@@ -2528,7 +2610,7 @@ __attribute__((visibility("hidden"))) static int deck_imu_mode_change(const uint
}
__attribute__((visibility("hidden"))) static void publish_imu_mode(const DeckHidraw &deck, int mode) {
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
if (deck.mapping_size < FAKE_INPUT_RING_SIZE + DECK_IMU_BLOCK_SIZE) return;
std::string path = get_ring_path_for_slot(0);
int fd = path.empty() ? -1 : my_open(path.c_str(), O_WRONLY | O_CLOEXEC);
@@ -3037,7 +3119,7 @@ static int real_fstat(int fd, struct stat *buf);
__attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
int dirfd, const char *path, int flags, struct statx *buf) {
static auto real_openat = reinterpret_cast<decltype(&::openat)>(dlsym(RTLD_NEXT, "openat"));
const auto real_openat = next_symbol<decltype(&::openat)>(Next::openat);
int target;
if (!path || !*path) {
if (!(flags & AT_EMPTY_PATH)) return false;
@@ -3075,7 +3157,7 @@ __attribute__((visibility("hidden"))) static bool deck_mount_id_from_fdinfo(
}
EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct statx *buf) {
static auto real = reinterpret_cast<decltype(&::statx)>(dlsym(RTLD_NEXT, "statx"));
const auto real = next_symbol<decltype(&::statx)>(Next::statx);
int result = real(dirfd, path, flags, mask, buf);
int saved_errno = errno;
constexpr unsigned unique_mount_id = 0x4000;
@@ -3096,7 +3178,7 @@ EXPORT int statx(int dirfd, const char *path, int flags, unsigned mask, struct s
#endif
EXPORT DIR *opendir(const char *name) {
static auto real = reinterpret_cast<DIR *(*)(const char *)>(dlsym(RTLD_NEXT, "opendir"));
const auto real = next_symbol<DIR *(*)(const char *)>(Next::opendir);
DIR *dir = real(name);
if (!dir) {
note_sys_failure(AT_FDCWD, name);
@@ -3126,7 +3208,7 @@ EXPORT int open(const char *pathname, int flags, ...) {
va_end(va);
static auto my_open = reinterpret_cast<int (*)(const char *, int, ...)>(dlsym(RTLD_NEXT, "open"));
const auto my_open = next_symbol<int (*)(const char *, int, ...)>(Next::open);
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
@@ -3204,7 +3286,7 @@ EXPORT int openat(int dirfd, const char *pathname, int flags, ...) {
va_end(va);
static auto my_openat = reinterpret_cast<int (*)(int, const char *, int, ...)>(dlsym(RTLD_NEXT, "openat"));
const auto my_openat = next_symbol<int (*)(int, const char *, int, ...)>(Next::openat);
if (fake_uinput_enabled() && is_uinput_path(pathname)) return open_uinput(flags);
if (is_deck_hidraw_path(pathname)) return open_deck_hidraw(flags);
@@ -3363,10 +3445,10 @@ static int fake_stat_fd(int fd, S *buf, Real real) {
}
static int real_stat(const char *pathname, struct stat *statbuf) {
static auto fn = reinterpret_cast<int (*)(const char *, struct stat *)>(dlsym(RTLD_NEXT, "stat"));
const auto fn = next_symbol<int (*)(const char *, struct stat *)>(Next::stat);
if (fn) return fn(pathname, statbuf);
#ifdef _STAT_VER
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
const auto xfn = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
#endif
errno = ENOSYS;
@@ -3374,10 +3456,10 @@ static int real_stat(const char *pathname, struct stat *statbuf) {
}
static int real_fstat(int fd, struct stat *buf) {
static auto fn = reinterpret_cast<int (*)(int, struct stat *)>(dlsym(RTLD_NEXT, "fstat"));
const auto fn = next_symbol<int (*)(int, struct stat *)>(Next::fstat);
if (fn) return fn(fd, buf);
#ifdef _STAT_VER
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
const auto xfn = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
if (xfn) return xfn(_STAT_VER, fd, buf);
#endif
errno = ENOSYS;
@@ -3393,7 +3475,7 @@ EXPORT int fstat(int fd, struct stat *buf) {
}
EXPORT int access(const char *pathname, int mode) {
static auto my_access = reinterpret_cast<decltype(&::access)>(dlsym(RTLD_NEXT, "access"));
const auto my_access = next_symbol<decltype(&::access)>(Next::access);
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
@@ -3434,7 +3516,7 @@ EXPORT int access(const char *pathname, int mode) {
}
EXPORT int faccessat(int dirfd, const char *pathname, int mode, int flags) {
static auto my_faccessat = reinterpret_cast<decltype(&::faccessat)>(dlsym(RTLD_NEXT, "faccessat"));
const auto my_faccessat = next_symbol<decltype(&::faccessat)>(Next::faccessat);
if (fake_uinput_enabled() && is_uinput_path(pathname)) return 0;
if (is_deck_hidraw_path(pathname) && process_reads_pads()) return 0;
if ((is_triton_hidraw_path(pathname) || is_triton_pad_path(pathname) || sony_pad_path(pathname)) &&
@@ -3478,7 +3560,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **,
const struct dirent **)) {
static auto my_scandir = reinterpret_cast<decltype(&::scandir)>(dlsym(RTLD_NEXT, "scandir"));
const auto my_scandir = next_symbol<decltype(&::scandir)>(Next::scandir);
if (dirp) {
if (!strcmp(dirp, "/dev/input")) {
@@ -3492,7 +3574,7 @@ EXPORT int scandir(const char *dirp, struct dirent ***namelist,
}
EXPORT int inotify_add_watch(int fd, const char *pathname, uint32_t mask) {
static auto my_inotify_add_watch = reinterpret_cast<decltype(&::inotify_add_watch)>(dlsym(RTLD_NEXT, "inotify_add_watch"));
const auto my_inotify_add_watch = next_symbol<decltype(&::inotify_add_watch)>(Next::inotify_add_watch);
char *fake_path = nullptr;
if (pathname) {
@@ -3631,7 +3713,7 @@ static bool wait_snapshot(std::shared_ptr<FakeController> fake,
static int forward_ioctl(int fd, ioctl_request_t op, void *argp) {
using ioctl_fn = int (*)(int, ioctl_request_t, ...);
static const auto next = reinterpret_cast<ioctl_fn>(dlsym(RTLD_NEXT, "ioctl"));
const auto next = next_symbol<ioctl_fn>(Next::ioctl);
return next ? next(fd, op, argp) : static_cast<int>(syscall(SYS_ioctl, fd, op, argp));
}
@@ -3689,6 +3771,10 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
id.bustype = 0x03;
if (made) {
id = made->id;
if (steam_pad_as_x360() && id.vendor == STEAM_VIRTUAL_VENDOR_ID && id.product == STEAM_VIRTUAL_PRODUCT_ID) {
id.vendor = X360_VENDOR_ID;
id.product = X360_PRODUCT_ID;
}
} else if (presents_steam_virtual()) {
id.vendor = STEAM_VIRTUAL_VENDOR_ID;
id.product = STEAM_VIRTUAL_PRODUCT_ID;
@@ -3866,7 +3952,7 @@ EXPORT int ioctl(int fd, ioctl_request_t op, ...) {
}
EXPORT int close(int fd) {
static auto my_close = reinterpret_cast<decltype(&::close)>(dlsym(RTLD_NEXT, "close"));
const auto my_close = next_symbol<decltype(&::close)>(Next::close);
if (!watched(fd)) return my_close(fd);
close_uinput(fd);
@@ -4054,7 +4140,7 @@ EXPORT ssize_t readv(int fd, const struct iovec *iov, int iovcnt) {
}
EXPORT ssize_t write(int fd, const void *buf, size_t count) {
static auto my_write = reinterpret_cast<decltype(&::write)>(dlsym(RTLD_NEXT, "write"));
const auto my_write = next_symbol<decltype(&::write)>(Next::write);
if (!watched(fd)) return my_write(fd, buf, count);
std::unique_lock<std::recursive_mutex> guard(controller_mutex());
@@ -4129,8 +4215,8 @@ EXPORT ssize_t writev(int fd, const struct iovec *iov, int iovcnt) {
static int poll_fake(struct pollfd *fds, nfds_t nfds, int timeout,
const sigset_t *sigmask) {
static auto my_poll = reinterpret_cast<decltype(&::poll)>(dlsym(RTLD_NEXT, "poll"));
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
const auto my_poll = next_symbol<decltype(&::poll)>(Next::poll);
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
nfds_t first = 0;
while (first < nfds && !watched(fds[first].fd)) first++;
@@ -4234,7 +4320,7 @@ EXPORT int poll(struct pollfd *fds, nfds_t nfds, int timeout) {
EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
const struct timespec *timeout, const sigset_t *sigmask) {
static auto my_ppoll = reinterpret_cast<decltype(&::ppoll)>(dlsym(RTLD_NEXT, "ppoll"));
const auto my_ppoll = next_symbol<decltype(&::ppoll)>(Next::ppoll);
if (timeout && (timeout->tv_sec < 0 || timeout->tv_nsec < 0 || timeout->tv_nsec >= 1000000000L)) {
errno = EINVAL;
return -1;
@@ -4261,7 +4347,7 @@ EXPORT int ppoll(struct pollfd *fds, nfds_t nfds,
EXPORT int select(int nfds, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout) {
static auto my_select = reinterpret_cast<decltype(&::select)>(dlsym(RTLD_NEXT, "select"));
const auto my_select = next_symbol<decltype(&::select)>(Next::select);
fd_set original_readfds;
fd_set original_writefds;
@@ -4423,10 +4509,10 @@ EXPORT int openat64(int dirfd, const char *pathname, int flags, ...) {
}
static int real_stat64(const char *pathname, struct stat64 *statbuf) {
static auto fn = reinterpret_cast<int (*)(const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "stat64"));
const auto fn = next_symbol<int (*)(const char *, struct stat64 *)>(Next::stat64);
if (fn) return fn(pathname, statbuf);
#ifdef _STAT_VER
static auto xfn = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
const auto xfn = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
if (xfn) return xfn(_STAT_VER, pathname, statbuf);
#endif
errno = ENOSYS;
@@ -4434,10 +4520,10 @@ static int real_stat64(const char *pathname, struct stat64 *statbuf) {
}
static int real_fstat64(int fd, struct stat64 *buf) {
static auto fn = reinterpret_cast<int (*)(int, struct stat64 *)>(dlsym(RTLD_NEXT, "fstat64"));
const auto fn = next_symbol<int (*)(int, struct stat64 *)>(Next::fstat64);
if (fn) return fn(fd, buf);
#ifdef _STAT_VER
static auto xfn = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
const auto xfn = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
if (xfn) return xfn(_STAT_VER, fd, buf);
#endif
errno = ENOSYS;
@@ -4453,27 +4539,27 @@ EXPORT int fstat64(int fd, struct stat64 *buf) {
}
EXPORT int __xstat(int version, const char *pathname, struct stat *statbuf) {
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat *)>(dlsym(RTLD_NEXT, "__xstat"));
const auto real = next_symbol<int (*)(int, const char *, struct stat *)>(Next::xstat);
if (!real) return stat(pathname, statbuf);
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat *buf) { return real(version, path, buf); });
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat *buf) { return real(version, path, buf); });
}
EXPORT int __xstat64(int version, const char *pathname, struct stat64 *statbuf) {
static auto real = reinterpret_cast<int (*)(int, const char *, struct stat64 *)>(dlsym(RTLD_NEXT, "__xstat64"));
const auto real = next_symbol<int (*)(int, const char *, struct stat64 *)>(Next::xstat64);
if (!real) return stat64(pathname, statbuf);
return fake_stat_path(pathname, statbuf, [version](const char *path, struct stat64 *buf) { return real(version, path, buf); });
return fake_stat_path(pathname, statbuf, [version, real](const char *path, struct stat64 *buf) { return real(version, path, buf); });
}
EXPORT int __fxstat(int version, int fd, struct stat *buf) {
static auto real = reinterpret_cast<int (*)(int, int, struct stat *)>(dlsym(RTLD_NEXT, "__fxstat"));
const auto real = next_symbol<int (*)(int, int, struct stat *)>(Next::fxstat);
if (!real) return fstat(fd, buf);
return fake_stat_fd(fd, buf, [version](int f, struct stat *b) { return real(version, f, b); });
return fake_stat_fd(fd, buf, [version, real](int f, struct stat *b) { return real(version, f, b); });
}
EXPORT int __fxstat64(int version, int fd, struct stat64 *buf) {
static auto real = reinterpret_cast<int (*)(int, int, struct stat64 *)>(dlsym(RTLD_NEXT, "__fxstat64"));
const auto real = next_symbol<int (*)(int, int, struct stat64 *)>(Next::fxstat64);
if (!real) return fstat64(fd, buf);
return fake_stat_fd(fd, buf, [version](int f, struct stat64 *b) { return real(version, f, b); });
return fake_stat_fd(fd, buf, [version, real](int f, struct stat64 *b) { return real(version, f, b); });
}
#if defined(__x86_64__) || defined(__i386__)
@@ -4487,18 +4573,37 @@ static const char *const interposed_names[] = {
};
static dlsym_fn next_dlsym() {
static const dlsym_fn fn = [] {
static std::atomic<dlsym_fn> fn{nullptr};
static std::atomic<bool> resolved{false};
if (!resolved.load(std::memory_order_acquire)) {
#ifdef __x86_64__
const char *base = "GLIBC_2.2.5";
#else
const char *base = "GLIBC_2.0";
#endif
dlsym_fn found{};
for (const char *version : {base, "GLIBC_2.34"}) {
if (auto found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version))) return found;
if ((found = reinterpret_cast<dlsym_fn>(dlvsym(RTLD_NEXT, "dlsym", version)))) break;
}
return dlsym_fn{};
}();
return fn;
fn.store(found, std::memory_order_relaxed);
resolved.store(true, std::memory_order_release);
}
return fn.load(std::memory_order_relaxed);
}
static void *libc_handle() {
static std::atomic<void *> handle{nullptr};
static std::atomic<bool> resolved{false};
if (!resolved.load(std::memory_order_acquire)) {
handle.store(dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD), std::memory_order_relaxed);
resolved.store(true, std::memory_order_release);
}
return handle.load(std::memory_order_relaxed);
}
__attribute__((constructor)) static void resolve_dlsym_targets() {
next_dlsym();
libc_handle();
}
static void *global_dlsym(void *, const char *name) { return next_dlsym()(RTLD_DEFAULT, name); }
@@ -4516,8 +4621,7 @@ extern "C" __attribute__((visibility("hidden"), used)) void *fakeinput_dlsym_tar
dlsym_fn next = next_dlsym();
if (!next) return reinterpret_cast<void *>(missing_dlsym);
if (handle == RTLD_DEFAULT || handle == RTLD_NEXT || name == nullptr) return reinterpret_cast<void *>(next);
static void *const libc = dlopen(LIBC_SO, RTLD_LAZY | RTLD_NOLOAD);
if (handle != libc || !interposed(name)) return reinterpret_cast<void *>(next);
if (handle != libc_handle() || !interposed(name)) return reinterpret_cast<void *>(next);
return reinterpret_cast<void *>(global_dlsym);
}
@@ -190,7 +190,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
private var prootNoSeccomp by mutableStateOf(false)
private var prootFastPath by mutableStateOf(true)
private var nativeUserland by mutableStateOf(true)
private var cursorComposite by mutableStateOf(false)
private var cursorComposite by mutableStateOf(true)
private var guestHostname by mutableStateOf(SessionPrefs.DEFAULT_GUEST_HOSTNAME)
private var phantomWarning by mutableStateOf<String?>(null)
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
@@ -2170,6 +2170,7 @@ class FrontEndActivity : ComponentActivity(), com.droiddeck.launcher.ui.AgentPet
if (!triggerKeys.synthesizing && triggerKeys.nativeKey(event)) return true
val tabStep = com.droiddeck.launcher.ui.dualPageStep(event)
val tabs = com.droiddeck.launcher.ui.MainTabSteps.handler
if (tabStep == null && event.action == KeyEvent.ACTION_DOWN) com.droiddeck.launcher.ui.MainTabSteps.otherKeys++
if (tabStep != null && tabs != null) {
if (controllerHaptics) com.droiddeck.launcher.ui.ControllerHaptics.onKey(this, event)
if (event.action == KeyEvent.ACTION_DOWN && event.repeatCount == 0) tabs(tabStep)
@@ -156,7 +156,7 @@ internal class ProtonMenu(
fun refreshProtons() {
refreshExperimental()
protonRows = ProtonExtras.tools.map {
protonRows = ProtonExtras.offered(activity).map {
val all = ProtonExtras.installedAll(activity, it)
ProtonRow(it.id, it.name, all.lastOrNull(), ProtonExtras.queued(activity, it), all, ProtonExtras.update(activity, it))
}
@@ -5158,10 +5158,10 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
private var sessionTouchDown = false
private var screenTapsClick = true
private fun onScreenMouseButtonShown(): Boolean = listOfNotNull(
private fun onScreenLeftMouseButtonShown(): Boolean = listOfNotNull(
onScreenControls?.inputSurface, bottomInputControls?.inputSurface, unfoldedPanel?.inputSurface, unfoldedDeckSurface,
secondScreenPresentation?.controlsView, swappedInputSurface,
).any { it.isShown && inputProfile.showsMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
).any { it.isShown && inputProfile.showsLeftMouseButton(it.inputRole, it.shownElements, stockInputProfile) }
override fun onTouchEvent(event: MotionEvent): Boolean = inSurfaceSpace(event) { handleTouch(event) }
@@ -5197,7 +5197,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback, com.droidde
val snapshot = fingerTouchSnapshot(uiBlocking)
val route = com.droiddeck.launcher.input.TouchRouter.decide(snapshot)
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
screenTapsClick = !onScreenMouseButtonShown()
screenTapsClick = !onScreenLeftMouseButtonShown()
if (::touchpad.isInitialized) touchpad.clicks = screenTapsClick
if (::scrollTouch.isInitialized) scrollTouch.clicks = screenTapsClick
}
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.audio;
import android.os.Process;
import android.util.Log;
import com.droiddeck.launcher.core.CappedLogWriter;
import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.SessionPart;
import com.droiddeck.launcher.core.HostProcess;
@@ -16,6 +17,7 @@ public class DirectAudioRelayComponent extends SessionPart {
private final File socketPath;
private File logFile;
private volatile CappedLogWriter log;
private final File micFifoPath;
private volatile int pid = -1;
private final Object micLock = new Object();
@@ -77,24 +79,23 @@ public class DirectAudioRelayComponent extends SessionPart {
}
ArrayList<String> env = new ArrayList<>();
env.add("HOME=" + app().getFilesDir());
java.io.PrintWriter out = null;
CappedLogWriter out = null;
if (logFile != null) {
try {
out = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
out.println("== DirectAudio relay helper starting"
out = new CappedLogWriter(logFile, true);
out.line("== DirectAudio relay helper starting"
+ (withMic ? " with the microphone" : " (no microphone)"));
out.flush();
} catch (Exception e) {
Log.w(TAG, "could not open " + logFile, e);
}
}
final java.io.PrintWriter log = out;
final CappedLogWriter helperLog = out;
log = out;
pid = HostProcess.start(command.toString(), env.toArray(new String[0]),
app().getFilesDir(), null,
line -> {
Log.i(TAG, line);
if (helperLog == null || helperLog.line(line)) Log.i(TAG, line);
if (withMic) trackMic(line);
if (log != null) synchronized (log) { log.println(line); log.flush(); }
});
Log.i(TAG, "started pid=" + pid + " socket=" + socketPath
+ (withMic ? " mic=" + micFifoPath : " (no microphone)"));
@@ -141,6 +142,9 @@ public class DirectAudioRelayComponent extends SessionPart {
Process.killProcess(pid);
pid = -1;
}
CappedLogWriter current = log;
log = null;
if (current != null) current.close();
}
@Override
@@ -4,6 +4,7 @@ import android.content.Context;
import android.os.Process;
import android.util.Log;
import com.droiddeck.launcher.core.CappedLogWriter;
import com.droiddeck.launcher.core.FileUtils;
import com.droiddeck.launcher.core.SessionPart;
import com.droiddeck.launcher.core.HostProcess;
@@ -32,6 +33,7 @@ public class PulseAudioComponent extends SessionPart {
private final File workingDir;
private final File deviceControls;
private File logFile;
private CappedLogWriter log;
private final String micFifoPath;
private final HostLifecycle host = new HostLifecycle(Process::killProcess);
@@ -191,7 +193,7 @@ public class PulseAudioComponent extends SessionPart {
+ " --system=false --disable-shm=true --fail=false"
+ " -n --file=default.pa --daemonize=false --use-pid-file=false --exit-idle-time=-1"
+ " --log-level=info";
final java.io.PrintWriter out = openLog();
final CappedLogWriter out = openLog();
if (!host.launch(generation, () -> HostProcess.start(command, env.toArray(new String[0]), workingDir, status -> {
if (host.exited(generation)) {
Log.w(TAG, "audio host exited with status " + status + "; restarting");
@@ -199,8 +201,7 @@ public class PulseAudioComponent extends SessionPart {
}
},
line -> {
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
if (out == null || out.line(line)) Log.i(TAG, line);
}))) return;
long token = host.token();
Thread guard = new Thread(() -> ensureClientSink(out, token), "pulse-sink-guard");
@@ -208,7 +209,7 @@ public class PulseAudioComponent extends SessionPart {
guard.start();
}
private void ensureClientSink(java.io.PrintWriter out, long token) {
private void ensureClientSink(CappedLogWriter out, long token) {
try {
// Nothing that may block (a sink whose AAudio open hangs: a Galaxy S24 FE (US) hung the
// daemon's start-up loading one from default.pa) is loaded by the daemon itself; the
@@ -253,17 +254,17 @@ public class PulseAudioComponent extends SessionPart {
Log.w(TAG, line);
}
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
if (out != null) out.line(line);
} catch (Throwable t) {
Log.w(TAG, "ensureClientSink failed", t);
}
}
/** A timestamped line in the session's audio log. */
private void note(java.io.PrintWriter out, String what) {
private void note(CappedLogWriter out, String what) {
String line = "== " + new java.text.SimpleDateFormat("HH:mm:ss.SSS", java.util.Locale.US).format(new java.util.Date()) + " " + what;
Log.i(TAG, line);
if (out != null) synchronized (out) { out.println(line); out.flush(); }
if (out != null) out.line(line);
}
private String pactlFor(long token, String... args) {
@@ -330,6 +331,7 @@ public class PulseAudioComponent extends SessionPart {
@Override
public void stop() {
host.stop();
closeLog();
}
public boolean setSinkSuspended(boolean suspended) {
@@ -380,19 +382,24 @@ public class PulseAudioComponent extends SessionPart {
}
}
private java.io.PrintWriter openLog() {
private synchronized CappedLogWriter openLog() {
closeLog();
if (logFile == null) return null;
try {
java.io.PrintWriter w = new java.io.PrintWriter(new java.io.FileWriter(logFile, true));
w.println("== PulseAudio daemon starting" + (micFifoPath != null ? " with a microphone source" : ""));
w.flush();
return w;
log = new CappedLogWriter(logFile, true);
log.line("== PulseAudio daemon starting" + (micFifoPath != null ? " with a microphone source" : ""));
return log;
} catch (Exception e) {
Log.w(TAG, "could not open " + logFile, e);
return null;
}
}
private synchronized void closeLog() {
if (log != null) log.close();
log = null;
}
private void copyFromLibraryDir() {
String[] libs = {"libltdl.so", "libpulseaudio.so", "libpulse.so",
"libpulsecommon-13.0.so", "libpulsecore-13.0.so", "libsndfile.so", "libffi.so"};
@@ -0,0 +1,59 @@
package com.droiddeck.launcher.core
import java.io.BufferedWriter
import java.io.Closeable
import java.io.File
import java.io.FileOutputStream
import java.io.OutputStreamWriter
class CappedLogWriter @JvmOverloads constructor(
private val file: File,
append: Boolean,
private val limitBytes: Long = SESSION_LOG_LIMIT_BYTES,
private val tailLines: Int = TAIL_LINES,
) : Closeable {
private val out = BufferedWriter(OutputStreamWriter(FileOutputStream(file, append), Charsets.UTF_8))
private val tail = ArrayDeque<String>()
private var dropped = 0L
private var closed = false
@Synchronized
fun line(text: String): Boolean {
if (closed) return false
if (dropped == 0L && file.length() + text.toByteArray(Charsets.UTF_8).size + 1 <= limitBytes) {
runCatching { out.write(text); out.newLine(); out.flush() }
return true
}
if (dropped == 0L) {
runCatching {
out.write("== this log reached its ${limitBytes / (1024 * 1024)} MB limit; later lines are dropped and only the last $tailLines are kept at the end")
out.newLine()
out.flush()
}
}
dropped++
tail.addLast(text)
if (tail.size > tailLines) tail.removeFirst()
return false
}
@Synchronized
override fun close() {
if (closed) return
closed = true
runCatching {
if (dropped > 0) {
out.write("== ${dropped - tail.size} lines dropped after the limit; the last ${tail.size} follow")
out.newLine()
tail.forEach { out.write(it); out.newLine() }
}
out.flush()
}
runCatching { out.close() }
}
companion object {
const val SESSION_LOG_LIMIT_BYTES = 64L * 1024 * 1024
const val TAIL_LINES = 400
}
}
@@ -3,7 +3,6 @@ package com.droiddeck.launcher.core
import android.content.Context
import android.os.Process
import android.util.Log
import java.io.BufferedWriter
import java.io.File
import java.io.FileOutputStream
import java.nio.file.Files
@@ -14,7 +13,7 @@ object SessionLogCapture {
private const val TAG = "SessionLogCapture"
private var pid = -1
private var writer: BufferedWriter? = null
private var writer: CappedLogWriter? = null
private var target: File? = null
private var syncer: Thread? = null
@@ -22,26 +21,20 @@ object SessionLogCapture {
fun start(target: File, sinceMillis: Long) {
stop()
try {
val out = target.bufferedWriter()
out.write("The app's own log for this session (logcat, this process only).\n")
out.write("Lines the app wrote before the session folder existed are in logcat only.\n\n")
out.flush()
val out = CappedLogWriter(target, false)
out.line("The app's own log for this session (logcat, this process only).")
out.line("Lines the app wrote before the session folder existed are in logcat only.")
out.line("")
writer = out
this.target = target
pid = HostProcess.start(
command(Process.myPid(), sinceMillis),
null, target.parentFile, null,
) { line ->
synchronized(this) {
try {
writer?.apply { write(line); newLine(); flush() }
} catch (e: Exception) {
}
}
synchronized(this) { writer?.line(line) }
}
if (pid == -1) {
out.write("logcat could not be started; this ROM may not hand an app its own entries.\n")
out.flush()
out.line("logcat could not be started; this ROM may not hand an app its own entries.")
}
target.parentFile?.let { syncer = startSyncing(it) }
Log.i(TAG, "app log -> $target (logcat pid $pid)")
@@ -81,10 +74,7 @@ object SessionLogCapture {
}
pid = -1
}
try {
writer?.close()
} catch (e: Exception) {
}
writer?.close()
writer = null
}
@@ -239,6 +239,7 @@ object AddedGames {
for (entry in AddedExes.list(context)) {
val folder = File(entry.folder)
if (folder.path in removed || !folder.isDirectory) continue
if (StoreGameSidecar.read(folder)?.isInstalled == false) continue
scanGame(context, folder, out, single = entry, reuse = true)
}
for (folder in libraryDepotInstalls(context)) if (folder.path !in removed) scanGame(context, folder, out, reuse = true)
@@ -337,9 +338,10 @@ object AddedGames {
val owner = ownerFolder(app, exe)
if (owner != null && owner.path !in SessionPrefs.removedAddedGames(app)) {
single(app, owner.path)?.takeIf { canonical(it.exe) == path }?.let {
if (guestPath(app, it.exe) != null) {
SessionPrefs.setAddedGameExe(app, owner.path, it.exe.path)
AddedExes.put(app, AddedExes.Entry(owner.path, it.exe.path))
val keep = listOf(it.exe, exe).firstOrNull { f -> guestPath(app, f) != null }
if (keep != null) {
SessionPrefs.setAddedGameExe(app, owner.path, keep.path)
AddedExes.put(app, AddedExes.Entry(owner.path, keep.path))
}
return AddResult.Existing(it)
}
@@ -13,6 +13,7 @@ object GamesFolderMigration {
@Synchronized
fun run(context: Context) {
repathInternalGuest(context)
val dirs = SessionPrefs.addedGamesDirs(context)
if (dirs.isEmpty()) return
val roots = legacyRoots(SessionPrefs.gameFolderBinds(context).map { it.first } + dirs)
@@ -58,12 +59,30 @@ object GamesFolderMigration {
SessionPrefs.setGamesFoldersMigrated(context)
}
private fun repathInternalGuest(context: Context) {
val binds = SessionPrefs.gameFolderBinds(context)
if (binds.none { it.second == StoreInstallRoot.INTERNAL_GUEST }) return
val hosts = binds.map { it.first }
val roots = legacyRoots(hosts).associateBy { it.host.path }
val taken = binds.map { it.second }.filter { it != StoreInstallRoot.INTERNAL_GUEST }.toMutableSet()
SessionPrefs.setGameFolderBinds(context, binds.map { (host, guest) ->
if (guest != StoreInstallRoot.INTERNAL_GUEST) return@map host to guest
val base = roots.getValue(host).guest
var next = base
var n = 2
while (next in taken) next = "$base-${n++}"
taken.add(next)
host to next
})
}
internal fun legacyRoots(paths: List<String>): List<AddedGames.Root> {
val hosts = paths.distinct().map { File(it) }
val names = hosts.groupingBy { it.name.lowercase() }.eachCount()
return hosts.map { host ->
val name = host.name.ifEmpty { "games" }
val guestName = if ((names[name.lowercase()] ?: 0) > 1) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
val clash = (names[name.lowercase()] ?: 0) > 1 || "${AddedGames.GUEST_DIR}/$name" == StoreInstallRoot.INTERNAL_GUEST
val guestName = if (clash) name + "-" + "%08x".format(CRC32().apply { update(host.path.toByteArray()) }.value).take(4) else name
AddedGames.Root(host, "${AddedGames.GUEST_DIR}/$guestName")
}
}
@@ -53,14 +53,14 @@ data class InputProfile(
fun elementClickAction(role: InputRole, element: InputSurfaceElement): InputAction = clicks[role]?.get(element.id)
?: defaultElementClick(element, elementAction(role, element.id, element.control)) { action(role, it) }
fun showsMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
fun showsLeftMouseButton(role: InputRole, shown: List<InputSurfaceElement>, stock: InputProfile): Boolean = shown.any { element ->
val action = elementAction(role, element.id, element.control).takeIf {
elements[role]?.get(element.id) != stock.elements[role]?.get(element.id) || it != stock.elementAction(role, element.id, element.control)
}
val click = elementClickAction(role, element).takeIf {
clicks[role]?.get(element.id) != stock.clicks[role]?.get(element.id) || it != stock.elementClickAction(role, element)
}
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.validFor(element.control) }
listOfNotNull(action, click).any { it is InputAction.MouseButton && it.code == PointerGestures.BTN_LEFT }
}
companion object {
@@ -207,7 +207,8 @@ object BattleNet {
val taken = HashSet<File>()
fun options(title: Title, folder: File) = listOfNotNull(folder, title.flavor?.let { File(folder, it) }?.takeIf { it.isDirectory })
for ((code, game) in games) {
val keep = saved[code]?.let(::File)?.takeIf { it in options(game.first, game.second) && it !in taken } ?: continue
val want = saved[code]?.let { runCatching { File(it).canonicalFile }.getOrNull() } ?: continue
val keep = options(game.first, game.second).firstOrNull { runCatching { it.canonicalFile }.getOrNull() == want }?.takeIf { it !in taken } ?: continue
out[code] = keep
taken.add(keep)
}
@@ -244,6 +245,14 @@ object BattleNet {
"/" + rootfs.relativize(resolved).joinToString("/")
}
}.trimEnd('/')
if (mapped?.startsWith("/") == true) {
val rootfs = LinuxRuntime.rootDir(context)
runCatching {
val home = rootfs.canonicalFile.toPath()
val host = File("$target/$relative").canonicalFile.toPath()
if (host.startsWith(home)) File(rootfs, home.relativize(host).toString()) else null
}.getOrNull()?.let { return it }
}
return com.droiddeck.launcher.frontend.AddedGames.hostPath(context, "$target/$relative")
}
@@ -88,8 +88,8 @@ object ComponentUpdater {
logLines(context).mapNotNull { STAMP.find(it)?.groupValues?.get(1) }.maxOrNull() ?: "0"
private fun lineOf(context: Context, state: JSONObject, p: ComponentsManager.Proton, comp: String): ComponentUpdates.Line? {
if (!ComponentUpdates.follows(p) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.line("fex", false)
if (!ComponentUpdates.autoFollows(p, comp) || !ComponentsManager.supports(p, comp)) return null
if (comp == "fex") return ComponentUpdates.fexLine(p)
val key = "${p.id}|${p.version}"
val flavors = state.obj("flavors").obj(key)
val arm64ec = if (flavors.has(comp)) flavors.optBoolean(comp) else ComponentsManager.arm64ec(context, p, comp)?.also { flavors.put(comp, it) }
@@ -13,7 +13,7 @@ object ComponentUpdates {
const val BOOTED_SECONDS = 60L
const val FAILED_BOOTS_BEFORE_ROLLBACK = 2
data class Line(val key: String, val comp: String, val prefix: String)
data class Line(val key: String, val comp: String, val prefix: String, val release: String = ComponentsManager.DD_NIGHTLY)
val LINES = listOf(
Line("dxvk", "dxvk", "DD-dxvk-"),
@@ -21,12 +21,19 @@ object ComponentUpdates {
Line("vkd3d", "vkd3d", "DD-vkd3d-proton-"),
Line("vkd3d-arm64ec", "vkd3d", "DD-vkd3d-proton-arm64ec-"),
Line("fex", "fex", "DD-FEXCore-"),
Line("fex-bionic", "fex", "FEXCore-", ComponentsManager.DD_BIONIC),
)
private val OWN_PREFIX = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }.prefix
fun follows(p: ComponentsManager.Proton): Boolean = !p.valve && p.dir.name.startsWith(OWN_PREFIX)
fun autoFollows(p: ComponentsManager.Proton, comp: String): Boolean =
follows(p) || (comp == "fex" && !p.valve && ComponentsManager.bionicTool(p.dir.name))
fun fexLine(p: ComponentsManager.Proton): Line =
if (ComponentsManager.bionicTool(p.dir.name)) LINES.first { it.release == ComponentsManager.DD_BIONIC } else line("fex", false)
fun ownId(protonId: String): Boolean = protonId.startsWith(ComponentsManager.safeName(OWN_PREFIX))
fun strays(
@@ -34,8 +41,8 @@ object ComponentUpdates {
choices: Map<String, Map<String, ComponentsManager.Choice>>,
placed: Set<String>,
): List<Pair<ComponentsManager.Proton, String>> =
protons.filterNot(::follows).flatMap { p ->
choices[p.id].orEmpty().filter { (_, c) -> !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
protons.flatMap { p ->
choices[p.id].orEmpty().filter { (comp, c) -> !autoFollows(p, comp) && !c.auto && c.protonVersion == p.version && c.file in placed }.keys.map { p to it }
}
fun unseen(
@@ -53,13 +60,14 @@ object ComponentUpdates {
fun pick(items: List<ComponentsManager.CatalogItem>, line: Line, bad: Set<String>): ComponentsManager.CatalogItem? {
val newestBad = bad.filter { belongs(it, line) }.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a, b) }
return items.filter { it.release == ComponentsManager.DD_NIGHTLY && it.comp == line.comp && belongs(it.file, line) }
return items.filter { it.release == line.release && it.comp == line.comp && belongs(it.file, line) }
.filter { newestBad == null || ProtonExtras.compareVersions(it.file, newestBad) > 0 }
.maxWithOrNull { a, b -> ProtonExtras.compareVersions(a.file, b.file) }
}
fun belongs(file: String, line: Line): Boolean =
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true
file.startsWith(line.prefix) && file.removePrefix(line.prefix).firstOrNull()?.isDigit() == true &&
(line.comp != "fex" || ComponentsManager.bionicFex(file) == (line.release == ComponentsManager.DD_BIONIC))
fun arm64ec(pe: ByteArray): Boolean? = runCatching {
val b = ByteBuffer.wrap(pe).order(ByteOrder.LITTLE_ENDIAN)
@@ -161,7 +169,7 @@ object ComponentUpdates {
fun stale(line: Line?, owned: Set<String>, stored: List<String>, keep: Set<String>, current: String, bad: Set<String> = emptySet()): List<String> {
val ranked = line?.takeIf { belongs(current, it) }
fun newer(file: String) = ranked != null && belongs(file, ranked) && ProtonExtras.compareVersions(file, current) > 0
return (owned + stored.filter { ranked != null && belongs(it, ranked) })
return (owned + stored.filter { ranked != null && ranked.release == ComponentsManager.DD_NIGHTLY && belongs(it, ranked) })
.filter { it !in keep && ((it in bad && it in owned) || !newer(it)) }.distinct()
}
}
@@ -29,6 +29,7 @@ object ComponentsManager {
private const val NIGHTLIES = "The412Banner/Nightlies"
private const val DD_COMPONENTS = "Droid-Deck/DroidDeck-Components"
internal const val DD_NIGHTLY = "linux-nightly"
internal const val DD_BIONIC = "bionic-stable"
private val RELEASES = linkedMapOf(
"FexCore-Linux" to "fex",
"Dxvk-Linux" to "dxvk",
@@ -37,9 +38,9 @@ object ComponentsManager {
"Vkd3d-proton-Linux" to "vkd3d",
)
private val NIGHTLY_PREFIXES = linkedMapOf("DD-dxvk-" to "dxvk", "DD-vkd3d-proton-" to "vkd3d", "DD-FEXCore-" to "fex")
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY)
private val SOURCES = RELEASES.keys.map { NIGHTLIES to it } + (DD_COMPONENTS to DD_NIGHTLY) + (DD_COMPONENTS to DD_BIONIC)
private val DOWNLOAD_REPOS = listOf(NIGHTLIES, DD_COMPONENTS)
private val TYPES = mapOf("FEXCore-Linux" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPES = mapOf("FEXCore-Linux" to "fex", "FEXCore-Bionic" to "fex", "DXVK-Linux" to "dxvk", "VKD3D-Linux" to "vkd3d")
private val TYPE_OF = mapOf("fex" to "FEXCore-Linux", "dxvk" to "DXVK-Linux", "vkd3d" to "VKD3D-Linux")
val COMPONENTS = listOf("fex", "dxvk", "vkd3d")
val LABEL = mapOf("fex" to "FEX", "dxvk" to "DXVK", "vkd3d" to "VKD3D-Proton")
@@ -201,8 +202,34 @@ object ComponentsManager {
COMPONENTS.mapNotNull { comp -> profile.optString(comp).takeIf(String::isNotEmpty)?.let { comp to it } }.toMap()
}
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) =
fun setGameComponent(context: Context, scope: String, comp: String, file: String?) {
setGameComponent(context, scope, comp, file) { runtimeManaged(context, it) }
if (comp == "fex" && file != null) fetchFexTwin(context, safeName(file))
}
// Twin downloads in flight: one worker per name, so two profile changes cannot share one partial download.
private val twinDownloads = HashSet<String>()
private fun fetchFexTwin(context: Context, file: String) {
val twin = fexTwin(file) ?: return
if (protons(context).all { fexFits(it.dir.name, file) }) return
synchronized(lock) { if (isStored(context, twin) || !twinDownloads.add(twin)) return }
val app = context.applicationContext
Thread({
try {
runCatching {
val item = catalogItem(app, twin, if (bionicFex(twin)) DD_BIONIC else "FexCore-Linux")
if (item == null) Log.i(TAG, "$twin is not listed")
else {
download(app, item) {}
republish(app)
}
}.onFailure { Log.w(TAG, "download $twin", it) }
} finally {
synchronized(lock) { twinDownloads.remove(twin) }
}
}, "fex-twin").start()
}
internal fun setGameComponent(context: Context, scope: String, comp: String, file: String?, managed: (String) -> Boolean) = synchronized(lock) {
require(scope.matches(Regex("[1-9][0-9]{0,9}")) && scope.toLong() <= 4294967295L)
@@ -413,7 +440,7 @@ object ComponentsManager {
}
}
require(File(staged, "files").isDirectory) { "${wcp.name} has no files/" }
if (comp == "fex") FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
if (comp == "fex" && !bionicTool(dir.name)) FEX_FILES.filter { it.endsWith(".so") && !File(staged, it).isFile }.forEach { File(dir, it).delete() }
COMP_DIR[comp]?.let { compDir ->
for (arch in PE_ARCHES) {
val target = File(dir, "$compDir/$arch")
@@ -603,7 +630,9 @@ object ComponentsManager {
File(base, "files").walkTopDown().filter { it.isFile }.map { it.relativeTo(base).invariantSeparatorsPath }
.filter { owned(comp, it) }.associateWith { File(base, it) }
}
for (rel in managed(comp) - files.keys) {
// A bionic tool never loses a FEX file: its launch.sh would put the whole bundled FEX back.
val removed = if (comp == "fex" && bionicTool(p.dir.name)) emptySet() else managed(comp) - files.keys
for (rel in removed) {
lines.append(scope).append('\t').append(p.dir.name).append('\t').append(p.version).append('\t').append(comp)
.append('\t').append(rel).append("\t-\t-\n")
}
@@ -620,7 +649,8 @@ object ComponentsManager {
val version = safeName(file.removePrefix("original "))
"original-${p.id}-$version-$comp" to File(originalsDir(context), "${p.id}/$version/$comp.wcp")
} else {
safeName(file.removeSuffix(".wcp")) to File(packagesDir(context), file)
val fit = (if (comp == "fex") launchFex(p.dir.name, file) { File(packagesDir(context), it).isFile } else file) ?: return null
safeName(fit.removeSuffix(".wcp")) to File(packagesDir(context), fit)
}.takeIf { it.second.isFile }
}
@@ -651,12 +681,14 @@ object ComponentsManager {
for (scope in profiles.keys()) {
val profile = profiles.optJSONObject(scope) ?: continue
for (comp in COMPONENTS) {
val file = profile.optString(comp)
if (file.isEmpty()) continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
val key = safeName(file.removeSuffix(".wcp"))
for (p in all) append(scope, p, comp, key, wcp)
val chosen = profile.optString(comp)
if (chosen.isEmpty()) continue
for (p in all) {
val file = (if (comp == "fex") launchFex(p.dir.name, chosen) { File(packagesDir(context), it).isFile } else chosen) ?: continue
val wcp = File(packagesDir(context), file)
if (!wcp.isFile) continue
append(scope, p, comp, safeName(file.removeSuffix(".wcp")), wcp)
}
}
}
return PreparedLaunchState(lines.toString(), keep)
@@ -677,6 +709,7 @@ object ComponentsManager {
val wcp = File(packagesDir(context), safeName(file))
val info = packageInfo(context, wcp)
requireSelectable(context, info.comp)
requireFits(p, info)
val state = loadState(context)
if (inUse(context, p)) {
state.sub("queued").sub(p.id).put(info.comp, JSONObject().put("kind", "package").put("file", wcp.name).put("label", info.version)
@@ -690,7 +723,11 @@ object ComponentsManager {
context.getString(R.string.cmgr_swap_done, LABEL[info.comp], info.version, p.name)
}
private fun requireFits(p: Proton, info: Package) =
check(info.comp != "fex" || fexFits(p.dir.name, info.file)) { "${info.file} is not a FEX build for ${p.name}" }
private fun applyPackage(context: Context, p: Proton, info: Package, wcp: File, state: JSONObject, auto: Boolean = false) {
requireFits(p, info)
ensureOriginal(context, p, info.comp, state)
val hashes = installFiles(context, p.dir, info.comp, wcp)
state.sub("active").sub(p.id).put(info.comp, JSONObject()
@@ -803,6 +840,18 @@ object ComponentsManager {
internal fun liveOnAny(key: String, entry: JSONObject, installs: List<Proton>?): Boolean =
installs?.any { liveSelection(key, entry, it) } == true
// An installed tool that launches with `name` as the stored twin of a game's FEX choice (a Linux choice on
// DroidDeck-Bionic, a -bionic one on another Proton): deleting the twin would drop that choice for that tool.
internal fun twinUser(state: JSONObject, installed: List<Proton>, name: String): Proton? {
val profiles = state.optJSONObject("profiles") ?: return null
for (scope in profiles.keys()) {
val chosen = profiles.optJSONObject(scope)?.optString("fex")?.takeIf { it.isNotEmpty() } ?: continue
if (fexTwin(chosen) != name) continue
installed.firstOrNull { !fexFits(it.dir.name, chosen) }?.let { return it }
}
return null
}
internal fun packagesInUse(state: JSONObject, installed: List<Proton>): Set<String> {
val byId = installed.groupBy { it.id }
val names = HashSet<String>()
@@ -819,7 +868,11 @@ object ComponentsManager {
val profiles = state.optJSONObject("profiles")
for (scope in profiles?.keys() ?: emptyList<String>().iterator()) {
val profile = profiles?.optJSONObject(scope) ?: continue
COMPONENTS.forEach { comp -> profile.optString(comp).takeIf { it.isNotEmpty() }?.let(names::add) }
COMPONENTS.forEach { comp ->
val file = profile.optString(comp).takeIf { it.isNotEmpty() } ?: return@forEach
names.add(file)
if (comp == "fex" && installed.any { !fexFits(it.dir.name, file) }) fexTwin(file)?.let(names::add)
}
}
return names
}
@@ -890,6 +943,7 @@ object ComponentsManager {
val queued = state.sub("queued").sub(target.id)
var changed = false
wanted.forEach { (comp, entry) ->
if (comp == "fex" && !fexFits(target.dir.name, entry.optString("file"))) return@forEach
if (active?.has(comp) != true && !queued.has(comp)) {
queued.put(comp, entry)
changed = true
@@ -970,6 +1024,8 @@ object ComponentsManager {
fun deletePackage(context: Context, file: String): String = synchronized(lock) {
val name = safeName(file)
val state = loadState(context)
val twinTool = twinUser(state, protons(context), name)
check(twinTool == null) { context.getString(R.string.cmgr_package_in_use, name, twinTool?.name ?: "") }
val installed = protons(context).groupBy { it.id }
var changed = false
for (key in listOf("queued", "active")) {
@@ -1066,8 +1122,11 @@ object ComponentsManager {
return Catalog(items, o.optLong("fetchedAt"))
}
internal fun assetComp(release: String, name: String): String? =
RELEASES[release] ?: if (release == DD_NIGHTLY) NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value else null
internal fun assetComp(release: String, name: String): String? = RELEASES[release] ?: when (release) {
DD_NIGHTLY -> NIGHTLY_PREFIXES.entries.firstOrNull { name.startsWith(it.key) }?.value
DD_BIONIC -> "fex"
else -> null
}
internal val CATALOG_ORDER: Comparator<CatalogItem> =
compareBy<CatalogItem> { it.comp }.thenBy { it.release == DD_NIGHTLY }.then(newestFirst { it.file })
@@ -1155,6 +1214,25 @@ object ComponentsManager {
return runCatching { readWcpEntry(original, rel) }.getOrNull()
}
// DroidDeck-Bionic loads only Android builds of FEX's unix libraries; other Protons only glibc builds.
internal fun bionicTool(dirName: String?): Boolean = dirName?.startsWith("DroidDeck-Bionic") == true
internal fun bionicFex(file: String): Boolean = file.endsWith("-bionic.wcp", ignoreCase = true)
internal fun fexFits(toolDir: String?, file: String): Boolean = bionicTool(toolDir) == bionicFex(file)
internal fun fexTwin(file: String): String? = when {
file.endsWith("-linux.wcp", ignoreCase = true) -> file.dropLast("-linux.wcp".length) + "-bionic.wcp"
file.endsWith("-bionic.wcp", ignoreCase = true) -> file.dropLast("-bionic.wcp".length) + "-linux.wcp"
else -> null
}
internal fun launchFex(toolDir: String, file: String, stored: (String) -> Boolean): String? =
if (fexFits(toolDir, file)) file else fexTwin(file)?.takeIf(stored)
internal fun <T> forTool(comp: String, toolDir: String?, items: List<T>, selected: String? = null, file: (T) -> String): List<T> =
if (comp != "fex") items else items.filter { file(it) == selected || fexFits(toolDir, file(it)) }
fun supports(p: Proton, comp: String): Boolean =
if (comp == "fex") File(p.dir, FEX_FILES.first()).isFile else File(p.dir, "${COMP_DIR.getValue(comp)}/aarch64-windows").isDirectory
@@ -0,0 +1,52 @@
package com.droiddeck.launcher.session
import android.util.Log
import com.droiddeck.launcher.stores.StoreInstalls
import java.io.File
object CpuCacheSysfs {
private const val TAG = "SessionService"
private val FEX_CPUID_SIZE_KB = mapOf(1 to 32, 2 to 512, 3 to 8192)
private val PROCESS = java.util.UUID.randomUUID().toString()
private val STARTS = java.util.concurrent.atomic.AtomicInteger()
fun binds(root: File, start: Int = STARTS.incrementAndGet(), host: File = File("/sys/devices/system/cpu"), process: String = PROCESS): List<String> = try {
root.listFiles()?.forEach { old -> if (old.name != process) StoreInstalls.deleteTree(old) }
val dir = File(root, "$process/$start")
StoreInstalls.deleteTree(dir)
val cpus = host.list { _, name -> name.matches(Regex("cpu\\d+")) }?.sorted().orEmpty()
val binds = cpus.mapNotNull { cpu ->
val staged = try {
stage(File(host, "$cpu/cache"), File(dir, cpu))
} catch (e: Exception) {
Log.w(TAG, "cpu cache: could not stage $cpu: $e")
false
}
if (staged) File(dir, cpu).path + ":" + File(host, "$cpu/cache").path else null
}
Log.i(TAG, "cpu cache: ${binds.size} of ${cpus.size} cores report the sizes the x86 CPUID reports")
binds
} catch (e: Exception) {
Log.w(TAG, "cpu cache: could not stage the core caches: $e")
emptyList()
}
private fun stage(cache: File, out: File): Boolean {
val indexes = cache.listFiles { f -> f.isDirectory && f.name.matches(Regex("index\\d+")) } ?: return false
var staged = false
for (index in indexes) {
val target = File(out, index.name).apply { mkdirs() }
val kb = runCatching { File(index, "level").readText().trim().toInt() }.getOrNull()?.let { FEX_CPUID_SIZE_KB[it] }
val files = index.listFiles { f -> f.isFile } ?: throw java.io.IOException("cannot list $index")
for (f in files) {
if (kb != null && f.name == "size") continue
File(target, f.name).writeText(f.readText())
}
if (kb == null) continue
File(target, "size").writeText("${kb}K\n")
staged = true
}
return staged
}
}
@@ -937,7 +937,7 @@ internal object EnhancedSessionLogShare {
val value = entry.lowercase(Locale.US)
if (value.startsWith("battlenet/") || value.startsWith("stores/") || value.startsWith("tools/") || value.startsWith("rpcs3/") ||
value.contains("droiddeck-esync/") || GAME_LOG.matches(value.substringAfterLast('/')) ||
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug").any(value::contains)) return Category.GAMES
listOf("proton", "wine", "dxvk", "vkd3d", "battle.net", "game-debug", "bionic").any(value::contains)) return Category.GAMES
if (listOf("wayland", "gamescope", "xwayland", "vulkan", "gpu", "mesa", "egl", "glx", "drm", "compositor", "frame-trace").any(value::contains)) return Category.GRAPHICS
return Category.SESSION
}
@@ -948,7 +948,7 @@ internal object EnhancedSessionLogShare {
"droiddeck", "droiddeck-esync", "session.log", "app.log", "wayland.log", "audio.log",
"device.txt", "network.txt", "events.jsonl", "memory.csv", "capture.json", "crash.log",
"frame-trace.log", "process-trace.log", "game-lifecycle.log", "launches.log", "tools.tsv", "wanted.tsv", "prefixes.json",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt",
"battlenet.log", "spawned.log", "flatpak-install.log", "cef_log.txt", "cef_log.previous.txt", "droiddeck-bionic.log",
"console_log.txt", "webhelper_js.txt", "controller_support.txt", "systemperfmanager.txt",
"rpcs3", "RPCS3.log",
)
@@ -74,10 +74,16 @@ object ExperimentalProtons {
return PREFIX + base + (tag?.let { "-$it" } ?: "")
}
/** DroidDeck-Bionic test builds are prereleases of the same repository and have their own row in the Proton list. */
internal fun listed(assets: List<ProtonExtras.Asset>): List<ProtonExtras.Asset> {
val bionic = ProtonExtras.tools.first { it.id == ProtonExtras.BIONIC }
return assets.filterNot { bionic.assetPattern.containsMatchIn(it.name) }
}
fun refresh(context: Context): List<Release>? {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val fetched = ProtonExtras.releasesForRemoval(tool) ?: return null
val assets = ProtonExtras.assets(tool, fetched.releases, prerelease = true)
val assets = listed(ProtonExtras.assets(tool, fetched.releases, prerelease = true))
val rows = assets.map { Release(it.tag, it.name, it.url, it.sha512, it.size, it.releaseName) }.distinctBy { it.tag }
if (!SessionState.running) {
reconcile(context, fetched)
@@ -14,7 +14,8 @@ object ProtonDefault {
data class Tool(val name: String, val display: String, val dir: String, val valve: Boolean)
data class Request(val seq: Long, val valve: Boolean, val dir: String)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>)
data class State(val default: String?, val applied: Long, val live: Boolean, val pending: String?, val tools: List<Tool>,
val source: String? = null)
data class GameChoice(val valve: Boolean, val dir: String)
enum class Outcome { LIVE, NEXT_START, NOT_RUNNABLE }
@@ -34,6 +35,7 @@ object ProtonDefault {
Tool(t.optString("name"), t.optString("display"), t.optString("dir"), t.optBoolean("valve"))
}?.takeIf { it.name.isNotEmpty() }
},
source = o.optString("source").ifEmpty { null },
)
}
@@ -99,7 +101,13 @@ object ProtonDefault {
if (!runnable(state, proton)) return Outcome.NOT_RUNNABLE
val d = dir(context)
val seq = nextSeq(System.currentTimeMillis(), state, parseRequest(read(File(d, "request.json"))))
val body = JSONObject().put("seq", seq).put("valve", proton.valve).put("dir", proton.dir.name).toString(1) + "\n"
writeRequest(d, Request(seq, proton.valve, proton.dir.name))
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
private fun writeRequest(d: File, request: Request) {
val body = JSONObject().put("seq", request.seq).put("valve", request.valve).put("dir", request.dir).toString(1) + "\n"
val staged = File(d, "request.json.staged")
try {
d.mkdirs()
@@ -110,8 +118,45 @@ object ProtonDefault {
Log.w(TAG, "could not write the Proton request", e)
throw e
}
val tool = state.tools.firstOrNull { it.valve == proton.valve && it.dir == proton.dir.name }
return if (SessionState.running && state.live && (tool == null || state.pending != tool.name)) Outcome.LIVE else Outcome.NEXT_START
}
// The default that names a tool an update replaces moves to the new one, as the per-game picks do: otherwise the guest
// no longer finds it and falls back to DroidDeck-Proton.
internal fun movedDefault(state: State, request: Request?, from: Set<String>, to: String, now: Long): Request? {
val (valve, dir) = chosen(state, request) ?: return null
if (valve || dir !in from) return null
return Request(nextSeq(now, state, request), false, to)
}
@Synchronized
fun moveDefault(context: Context, from: Set<String>, to: String) {
val d = dir(context)
val moved = movedDefault(state(context), parseRequest(read(File(d, "request.json"))), from, to, System.currentTimeMillis()) ?: return
writeRequest(d, moved)
}
// DroidDeck-Bionic keeps one build. A default naming another one moves to the installed build: an app from before
// updates carried the default over left it, or the guest fell back to its own tool when that build was gone (the
// request the app last wrote still names it).
internal fun bionicDefault(state: State, request: Request?, prefix: String, newest: String, now: Long): Request? {
val current = chosen(state, request)
val stale = when {
current != null && !current.first && current.second.startsWith(prefix) -> current.second
state.source == "fallback" && request != null && !request.valve && request.dir.startsWith(prefix) -> request.dir
else -> return null
}
return if (stale == newest) null else Request(nextSeq(now, state, request), false, newest)
}
/** The default and the per-game picks that name a DroidDeck-Bionic build other than [newest] move to it. */
@Synchronized
fun keepBionicCurrent(context: Context, prefix: String, newest: String) {
val d = dir(context)
bionicDefault(state(context), parseRequest(read(File(d, "request.json"))), prefix, newest, System.currentTimeMillis())
?.let { writeRequest(d, it) }
val games = parseGames(read(File(d, GAMES)))
val stale = games.values.filterNotNull().filter { !it.valve && it.dir.startsWith(prefix) && it.dir != newest }.map { it.dir }.toSet()
if (stale.isNotEmpty()) movedGames(games, stale, newest)?.let { writeGames(d, it) }
}
internal fun movedGames(choices: Map<String, GameChoice?>, from: Set<String>, to: String): Map<String, GameChoice?>? {
@@ -8,6 +8,7 @@ import android.util.Log
import com.droiddeck.launcher.core.Downloader
import com.droiddeck.launcher.core.FileUtils
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.runtime.NativeGuest
import java.io.File
import java.util.Locale
import org.json.JSONArray
@@ -32,20 +33,27 @@ object ProtonExtras {
@Volatile
private var replacing = false
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex)
class Tool(val id: String, val name: String, val prefix: String, val repo: String, val assetPattern: Regex,
val prereleases: Boolean = false)
internal data class Asset(val tag: String, val name: String, val url: String, val sha512: String?, val size: Long,
val sha256: String? = null, val releaseName: String = tag)
internal data class ReleaseFetch(val releases: JSONArray, val complete: Boolean)
const val OWN = "droiddeck"
const val BIONIC = "bionic"
val tools = listOf(
Tool("ge", "GE-Proton", "GE-Proton", "GloriousEggroll/proton-ge-custom", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("cachyos", "proton-cachyos", "proton-cachyos", "CachyOS/proton-cachyos", Regex("arm64\\.tar\\.(gz|xz)$")),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("aarch64\\.tar\\.(gz|xz)$")),
Tool("droiddeck", "DroidDeck-Proton", "DroidDeck-Proton", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Proton-.*aarch64\\.tar\\.(gz|xz)$")),
// Bionic (Android libc) Proton started outside the Linux userland; test builds are prereleases. No-proot only.
Tool(BIONIC, "DroidDeck-Bionic", "DroidDeck-Bionic", "Droid-Deck/DroidDeck-Proton", Regex("^DroidDeck-Bionic-.*aarch64\\.tar\\.(gz|xz)$"), prereleases = true),
)
/** The sources offered on this device: DroidDeck-Bionic only with Run without proot on. */
fun offered(context: Context): List<Tool> = tools.filter { it.id != BIONIC || NativeGuest.enabled(context) }
private fun home(context: Context) = File(LinuxRuntime.rootDir(context), "root")
private fun requests(context: Context) = File(home(context), ".dd-proton-extra")
private fun toolsDir(context: Context) = File(home(context), ".local/share/Steam/compatibilitytools.d")
@@ -120,10 +128,11 @@ object ProtonExtras {
private var lastAttempt = 0L
fun checkLatest(context: Context, force: Boolean = false, now: Long = System.currentTimeMillis()): Boolean {
keepBionicCurrent(context)
synchronized(checkLock) {
val file = latestFile(context)
val cache = readJson(file)
val due = tools.filter { tool ->
val due = offered(context).filter { tool ->
val at = cache.optJSONObject(tool.id)?.optLong("at", 0L) ?: 0L
force || (now - at) !in 0 until CHECK_EVERY_MS
}
@@ -173,15 +182,32 @@ object ProtonExtras {
fun remove(context: Context, tool: Tool, dir: String? = null) {
val name = if (dir != null) dir.takeIf { it in installedAll(context, tool) } ?: return else installed(context, tool) ?: return
if (File(toolsDir(context), name).deleteRecursively()) ComponentsManager.forgetProton(context, name)
if (deleteTool(context, name)) ComponentsManager.forgetProton(context, name)
}
// A tool folder can hold links that point out of it (a prefix template's dosdevices/z: -> /), and
// File.deleteRecursively() follows links into directories: remove each link itself, never what it points to.
private fun deleteTool(context: Context, name: String): Boolean {
val dir = File(toolsDir(context), name)
FileUtils.delete(dir)
return !dir.exists() && !java.nio.file.Files.isSymbolicLink(dir.toPath())
}
fun removeOlder(context: Context, tool: Tool) {
installedAll(context, tool).dropLast(1).forEach {
if (File(toolsDir(context), it).deleteRecursively()) ComponentsManager.forgetProton(context, it)
if (deleteTool(context, it)) ComponentsManager.forgetProton(context, it)
}
}
// DroidDeck-Bionic: the default and the game picks name the installed build, also when they were left on one an
// older app deleted without moving them.
private fun keepBionicCurrent(context: Context) {
if (SessionState.running) return
val tool = tools.firstOrNull { it.id == BIONIC } ?: return
val newest = installedAll(context, tool).lastOrNull() ?: return
runCatching { ProtonDefault.keepBionicCurrent(context, tool.prefix, newest) }.onFailure { Log.w(TAG, "bionic default and picks", it) }
}
private fun replaceOlder(context: Context, tool: Tool) {
val all = installedAll(context, tool)
val newest = all.lastOrNull() ?: return
@@ -194,7 +220,9 @@ object ProtonExtras {
if (runCatching { ComponentsManager.carryOver(context, old, newest) }.onFailure { Log.w(TAG, "components of $old", it) }.isFailure) continue
if (runCatching { keepUserSettings(context, old, newest) }.onFailure { Log.w(TAG, "user settings of $old", it) }.isFailure) continue
if (runCatching { ProtonDefault.moveGames(context, setOf(old), newest) }.onFailure { Log.w(TAG, "per-game picks of $old", it) }.isFailure) continue
if (File(toolsDir(context), old).deleteRecursively()) ComponentsManager.forgetProton(context, old)
// DroidDeck-Bionic only: the guest finds no default for a deleted Bionic build and falls back to DroidDeck-Proton
if (tool.id == BIONIC && runCatching { ProtonDefault.moveDefault(context, setOf(old), newest) }.onFailure { Log.w(TAG, "default pick of $old", it) }.isFailure) continue
if (deleteTool(context, old)) ComponentsManager.forgetProton(context, old)
else Log.w(TAG, "could not remove $old")
}
} finally {
@@ -342,7 +370,7 @@ object ProtonExtras {
archive.delete()
unqueue(context, tool)
record(context, tool, placed, asset.tag)
if (tool.id == OWN) replaceOlder(context, tool)
if (tool.id == OWN || tool.id == BIONIC) replaceOlder(context, tool)
if (EsyncPacks.enabled(context)) {
onProgress(context.getString(R.string.esync_fetching), -1)
try {
@@ -427,7 +455,7 @@ object ProtonExtras {
internal fun pickAsset(tool: Tool, array: JSONArray): Asset? {
val candidates = (0 until array.length()).asSequence()
.mapNotNull { array.optJSONObject(it) }
.filter { !it.optBoolean("draft", false) && !it.optBoolean("prerelease", false) }
.filter { !it.optBoolean("draft", false) && (tool.prereleases || !it.optBoolean("prerelease", false)) }
return candidates.firstNotNullOfOrNull { assetOf(tool, it) }
}
@@ -143,6 +143,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-proton-extra" to "usr/local/bin/droiddeck-proton-extra",
"usr/local/bin/droiddeck-netmanager" to "usr/local/bin/droiddeck-netmanager",
"usr/local/bin/droiddeck-login1" to "usr/local/bin/droiddeck-login1",
"usr/local/bin/droiddeck-documents" to "usr/local/bin/droiddeck-documents",
"usr/local/bin/droiddeck-steam-launch" to "usr/local/bin/droiddeck-steam-launch",
"usr/local/bin/droiddeck-desktop-games" to "usr/local/bin/droiddeck-desktop-games",
"usr/local/bin/droiddeck-desktop-programs" to "usr/local/bin/droiddeck-desktop-programs",
@@ -154,6 +155,7 @@ object SessionFiles {
"usr/local/bin/droiddeck-emulators" to "usr/local/bin/droiddeck-emulators",
"usr/local/bin/droiddeck-snap-run" to "usr/local/bin/droiddeck-snap-run",
"usr/local/bin/droiddeck-snap-confine" to "usr/local/bin/droiddeck-snap-confine",
"usr/local/bin/droiddeck-diversion-stub" to "usr/local/bin/droiddeck-diversion-stub",
"usr/local/bin/droiddeck-snapctl" to "usr/local/bin/droiddeck-snapctl",
"usr/local/bin/droiddeck-systemd-run" to "usr/local/bin/systemd-run",
"usr/local/bin/droiddeck-snap-cli" to "usr/local/bin/snap",
@@ -1042,7 +1042,7 @@ object SessionPrefs {
prefs(context).edit().putBoolean("prootFastPath", on).apply()
}
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", false)
fun cursorComposite(context: Context): Boolean = prefs(context).getBoolean("cursorComposite", true)
fun setCursorComposite(context: Context, on: Boolean) {
prefs(context).edit().putBoolean("cursorComposite", on).apply()
@@ -1033,6 +1033,9 @@ class SessionService : Service() {
)
(if (bridge || venus) null else LinuxVulkanDriver.resolveIcdPath(this, linuxDriverId))
?.let { guest.add(LinuxVulkanDriver.ENV + "=" + it) }
// DroidDeck-Bionic games load an Android driver build; this is the one the display uses, for a runtime driver
// that has none.
guest.add("DROIDDECK_DISPLAY_DRIVER=" + com.droiddeck.launcher.gpu.TurnipDriver(this).effectiveId())
if (!com.droiddeck.launcher.core.DeviceSupport.adreno() && lastXwaylandCrashed()) {
guest.add("XWAYLAND_NO_GLAMOR=1")
Log.w(TAG, "xwayland: the last session's Xwayland crashed; glamor off for this one (XWAYLAND_NO_GLAMOR=1)")
@@ -1264,6 +1267,7 @@ class SessionService : Service() {
components.add(hwmon)
binds.add(hwmon.dir.path + ":/sys/class/hwmon")
}
binds.addAll(CpuCacheSysfs.binds(File(filesDir, "session/sys/cpu-cache")))
val cpuStat = CpuStatComponent(File(filesDir, "session/proc-stat"))
if (cpuStat.prepare()) {
cpuStat.attach(this)
@@ -3,8 +3,10 @@ package com.droiddeck.launcher.stores
import android.content.Context
import android.os.StatFs
import android.os.storage.StorageManager
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SecondaryLibrary
import com.droiddeck.launcher.session.SessionPrefs
import java.io.File
import java.util.zip.CRC32
@@ -12,6 +14,7 @@ import java.util.zip.CRC32
object StoreInstallRoot {
const val SPACE_UNKNOWN = -1L
private const val INTERNAL = "root/Games/Stores"
const val INTERNAL_GUEST = "/$INTERNAL"
private const val ON_VOLUME = "Games"
const val GUEST_EXTERNAL = "/mnt/droiddeck-stores"
@@ -179,6 +182,24 @@ object StoreInstallRoot {
fun externalBindSpecsForXodus(context: Context): List<String> =
externalBindSpecs(externalRootsForXodus(context), LinuxRuntime.rootDir(context))
fun guestBinds(context: Context): List<String> {
val out = ArrayList<String>(externalBindSpecs(context))
val root = LinuxRuntime.rootDir(context)
GameStorage.effective(context)?.takeIf { File(it.path).isDirectory }?.let { library ->
val content = SecondaryLibrary.contentPath(File(library.path)).path
for (guest in SecondaryLibrary.CARD_GUESTS) {
File(root, guest.removePrefix("/")).mkdirs()
out += "$content:$guest"
}
}
for (folder in AddedGames.roots(context)) {
if (!folder.host.isDirectory || !folder.host.canRead()) continue
File(root, folder.guest.removePrefix("/")).mkdirs()
out += folder.host.path + ":" + folder.guest
}
return out
}
internal fun externalBindSpecs(roots: List<Pair<File, String>>, guestRoot: File): List<String> =
roots.mapNotNull { (host, guest) ->
if (!host.isDirectory || !host.canRead()) return@mapNotNull null
@@ -12,8 +12,11 @@ object StoreLaunch {
const val EPIC_CODE = ".droiddeck-epic-code"
const val EPIC_ARGS = ".droiddeck-epic-args"
const val UBISOFT_LAUNCH = ".droiddeck-ubisoft.json"
private const val UBISOFT_SERVICE = "Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
/** DroidDeck-Bionic's Wine has Android's root on Z:; that tool sets this to the guest's root as its Wine names it. */
const val GUEST_ROOT = "DROIDDECK_GUEST_ROOT"
private const val ROOT_VAR = "DD_R"
private const val UBISOFT_SERVICE = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe"
const val EPIC_PARENT = "%$ROOT_VAR%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe"
/** Per-game environment switch: 1 starts any Epic game under [EPIC_PARENT], 0 never does. */
const val EPIC_PARENT_SWITCH = "DD_EPIC_PARENT"
/** Epic app names whose launchers treat the game as unowned unless a process named EpicGamesLauncher.exe started it. */
@@ -47,6 +50,10 @@ object StoreLaunch {
for ((k, v) in sidecar.env) if (ENV_NAME.matches(k)) lines += "set \"$k=${v.replace("\"", "")}\""
val args = sidecar.args.joinToString(" ") { if (sidecar.store == Store.ROCKSTAR) batchArg(it) else quoteArg(it) }
val run = "\"%~dp0$exe\"" + (if (args.isNotEmpty()) " $args" else "")
if (sidecar.store == Store.EPIC || sidecar.store == Store.UBISOFT) {
lines += "set \"$ROOT_VAR=Z:\""
lines += "if defined $GUEST_ROOT set \"$ROOT_VAR=%$GUEST_ROOT%\""
}
if (sidecar.store == Store.EPIC) {
lines += "set \"$PARENT_VAR=${if (sidecar.id in EPIC_PARENT_TITLES) "1" else ""}\""
lines += "if \"%$EPIC_PARENT_SWITCH%\"==\"1\" set \"$PARENT_VAR=1\""
@@ -137,7 +144,6 @@ object StoreLaunch {
if (sidecar.store !in listOf(Store.UBISOFT, Store.ROCKSTAR) || !sidecar.isInstalled) return sidecar
if (sidecar.store == Store.ROCKSTAR && java.nio.file.Files.isSymbolicLink(File(folder, LAUNCHER).toPath())) return sidecar.copy(launcher = null)
val wrongExe = !sidecar.exeFile(folder).isFile || sidecar.exe.contains("installer", ignoreCase = true) || sidecar.exe.contains("autorun", ignoreCase = true)
if (sidecar.store == Store.UBISOFT && sidecar.launcher == LAUNCHER && !wrongExe) return sidecar
val metadataExe = if (sidecar.store == Store.ROCKSTAR) com.droiddeck.launcher.stores.rockstar.RockstarMetadata.find(folder)?.exe
?.takeIf { File(folder, it).isFile && File(folder, it).canonicalPath.startsWith(folder.canonicalPath + File.separator) } else null
val exe = metadataExe ?: if (wrongExe) StoreExe.pick(folder, null, sidecar.title).ifEmpty { sidecar.exe } else sidecar.exe
@@ -7,9 +7,7 @@ import com.droiddeck.launcher.R
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.BattleNet
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.runtime.LinuxRuntime
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SecondaryLibrary
import com.droiddeck.launcher.stores.CatalogItem
import com.droiddeck.launcher.stores.InstalledStoreGame
import com.droiddeck.launcher.stores.Store
@@ -75,22 +73,10 @@ object BattleNetInstall {
}
internal fun binds(context: Context): List<String> {
val out = ArrayList<String>(StoreInstallRoot.externalBindSpecs(context))
val root = LinuxRuntime.rootDir(context)
GameStorage.effective(context)?.let { library ->
if (!File(library.path).isDirectory) throw IllegalStateException(context.getString(R.string.game_sync_err_game_storage))
val content = SecondaryLibrary.contentPath(File(library.path)).path
for (guest in SecondaryLibrary.CARD_GUESTS) {
File(root, guest.removePrefix("/")).mkdirs()
out += "$content:$guest"
}
}
for (folder in AddedGames.roots(context)) {
if (!folder.host.isDirectory || !folder.host.canRead()) continue
File(root, folder.guest.removePrefix("/")).mkdirs()
out += folder.host.path + ":" + folder.guest
}
return out
return StoreInstallRoot.guestBinds(context)
}
internal fun run(context: Context, args: List<String>, cancelled: AtomicBoolean?, onLine: (String) -> Unit): Int =
@@ -4,7 +4,6 @@ import android.content.Context;
import android.util.Log;
import com.droiddeck.launcher.frontend.AddedGames;
import com.droiddeck.launcher.runtime.GuestCommand;
import com.droiddeck.launcher.stores.StoreLanguage;
import com.droiddeck.launcher.stores.StoreLog;
import com.droiddeck.launcher.stores.download.StoreDownloadTier;
@@ -271,11 +270,10 @@ public final class GogDownloadManager {
long planned = 0;
boolean sized = true;
for (InstallerPart part : parts) { planned += part.size; if (part.size <= 0) sized = false; }
if (sized) {
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(planned, usable)) {
throw new InstallException("Not enough free space: need " + formatBytes(planned) + ", only " + formatBytes(usable) + " free");
}
long needed = installerBytesNeeded(knownPartBytes(parts), GogLibrary.INSTANCE.sizeOf(ctx, game.gameId));
long usable = com.droiddeck.launcher.stores.StoreInstallRoot.availableBytes(installPath);
if (com.droiddeck.launcher.stores.StoreInstallRoot.insufficientSpace(needed, usable)) {
throw new InstallException("Not enough free space: need " + formatBytes(needed) + ", only " + formatBytes(usable) + " free");
}
long total = 0;
for (InstallerPart part : parts) {
@@ -327,10 +325,7 @@ public final class GogDownloadManager {
cb.onProgress("Extracting installer…", 95);
int rc;
try {
rc = GuestCommand.INSTANCE.run(ctx, Arrays.asList(
"/usr/local/bin/droiddeck-innoextract", "--gog", "--silent",
"-d", guestDir, guestSetup),
false, "gog-innoextract", null, null, false, cancelled, null,
rc = GogInnoextract.extract(ctx, guestSetup, guestDir, "gog-innoextract", cancelled,
line -> { cb.onLog("gog innoextract: " + line); return kotlin.Unit.INSTANCE; });
} catch (Exception e) {
throw new InstallException("The installer could not be extracted: " + e.getClass().getSimpleName());
@@ -339,6 +334,16 @@ public final class GogDownloadManager {
if (rc != 0) throw new InstallException("The installer could not be extracted (innoextract exit " + rc + ")");
}
static long knownPartBytes(List<InstallerPart> parts) {
long known = 0;
for (InstallerPart part : parts) if (part.size > 0) known += part.size;
return known;
}
static long installerBytesNeeded(long downloadBytes, long installedBytes) {
return Math.max(0, downloadBytes) + Math.max(0, installedBytes);
}
static final class InstallerPart {
final String url;
final String filename;
@@ -0,0 +1,17 @@
package com.droiddeck.launcher.stores.gog
import android.content.Context
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.util.concurrent.atomic.AtomicBoolean
internal object GogInnoextract {
private const val PROGRAM = "/usr/local/bin/droiddeck-innoextract"
@JvmStatic
fun extract(context: Context, setup: String, target: String, logName: String, cancelled: AtomicBoolean, onLine: (String) -> Unit): Int =
GuestCommand.run(context, argv(setup, target), logName = logName,
extraBinds = StoreInstallRoot.guestBinds(context), cancelled = cancelled, onLine = onLine)
internal fun argv(setup: String, target: String): List<String> = listOf(PROGRAM, "--gog", "--silent", "-d", target, setup)
}
@@ -3,11 +3,9 @@ package com.droiddeck.launcher.stores.gog
import android.content.Context
import com.droiddeck.launcher.agent.AgentGuest
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.runtime.GuestCommand
import com.droiddeck.launcher.session.SessionService
import com.droiddeck.launcher.session.SessionState
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import com.droiddeck.launcher.stores.download.DownloadQueue
import com.droiddeck.launcher.stores.download.DownloadStage
import org.json.JSONArray
@@ -71,8 +69,7 @@ internal object GogOffline {
val source = AddedGames.guestPath(context, installer) ?: error("The GOG installer is not visible to Linux")
val target = AddedGames.guestPath(context, extracted) ?: error("The GOG staging folder is not visible to Linux")
handle.stage(DownloadStage.INSTALL, "Extracting the full offline installer")
val rc = GuestCommand.run(context, listOf("/usr/local/bin/droiddeck-innoextract", "--gog", "--silent", "-d", target, source),
extraBinds = StoreInstallRoot.externalBindSpecs(context), cancelled = stop, logName = "gog-refresh", onLine = handle::log)
val rc = GogInnoextract.extract(context, source, target, "gog-refresh", stop, handle::log)
if (stop.get()) return
check(rc == 0) { "GOG installer extraction failed (exit $rc)" }
applyRefresh(proposal, extracted, handle, stop)
@@ -526,11 +526,11 @@ fun ComponentsPage(
val availableTitle: @Composable (String) -> String = { l ->
when (l) {
PROTON_TAB -> stringResource(R.string.comp_available_count, protons.rows.count(ProtonRow::available))
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot).size)
else -> stringResource(R.string.comp_nightlies_count, availableRows(l, catalog, snapshot, view?.proton?.dir?.name).size)
}
}
val followed = view?.proton?.let(ComponentUpdates::follows) == true
val moded: (String) -> Boolean = { followed && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val followed: (String) -> Boolean = { l -> view?.proton?.let { ComponentUpdates.autoFollows(it, l) } == true }
val moded: (String) -> Boolean = { followed(it) && it in compModes && it !in compAutoHeld && !ComponentsManager.runtimeManaged(it, gpu.systemPowerVr) }
val automatic: (String) -> Boolean = { moded(it) && compModes[it] == ComponentUpdates.AUTO }
val installedRows: @Composable ColumnScope.(String, Boolean) -> Unit = { l, right ->
when (l) {
@@ -614,7 +614,7 @@ fun ComponentsPage(
}
}
else -> {
val available = availableRows(l, catalog, snapshot)
val available = availableRows(l, catalog, snapshot, view?.proton?.dir?.name)
if (available.isEmpty()) EmptyLine(if (catalogAt == 0L) stringResource(R.string.comp_refresh_to_list) else stringResource(R.string.comp_nothing_new))
for ((stable, nightly) in available) {
val d = if (nightly != null && nightlyPicked[stable.file] == true) nightly else stable
@@ -974,18 +974,18 @@ private fun installedFor(l: String, view: ComponentsManager.ProtonView?, snapsho
o.label.substringAfterLast(" · ", "").ifEmpty { o.label }.let { if (isCurrent) stringResource(R.string.comp_this_build, it) else stringResource(R.string.comp_earlier_build, it) },
"ORIGINAL", activeIsOriginal && isCurrent, !isCurrent, null, o.protonVersion,
)
} + (snapshot?.packages ?: emptyList()).filter { it.comp == l }.map { s ->
} + ComponentsManager.forTool(l, view.proton.dir.name, (snapshot?.packages ?: emptyList()).filter { it.comp == l }, st.activeFile) { it.file }.map { s ->
InstalledItem(s.version, stringResource(R.string.common_size_mb, s.size / 1048576.0), "STORED", !runtimeManaged && s.file == st.activeFile, true, s.file, null)
}
}
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<CatalogItem> {
private fun availableFor(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<CatalogItem> {
val stored = (snapshot?.packages ?: emptyList()).map { it.file }.toSet()
return catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }
return ComponentsManager.forTool(l, toolDir, catalog.filter { it.comp == l && ComponentsManager.safeName(it.file) !in stored }) { it.file }
}
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot)
private fun availableRows(l: String, catalog: List<CatalogItem>, snapshot: Snapshot?, toolDir: String?): List<Pair<CatalogItem, CatalogItem?>> {
val available = availableFor(l, catalog, snapshot, toolDir)
val pairs = ComponentsManager.nightlyPairs(available)
val paired = pairs.values.toSet()
return available.filter { it !in paired }.map { it to pairs[it] }
@@ -1201,7 +1201,7 @@ private fun GameComponentOverrides(
}
GamePackageRow(
comp = "fex",
packages = packages,
packages = ComponentsManager.forTool("fex", protonChoice?.dir ?: generalProton?.dir?.name, packages, componentChoices["fex"]) { it.file },
selectedFile = componentChoices["fex"],
open = componentMenu == "fex",
busy = busy,
@@ -58,6 +58,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.withFrameNanos
import kotlinx.coroutines.launch
import kotlinx.coroutines.flow.first
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
@@ -764,12 +765,31 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
focusManager.clearFocus(force = true)
onRailSelect(key)
}, a)
val stepScope = androidx.compose.runtime.rememberCoroutineScope()
val pageKeyNow = androidx.compose.runtime.rememberUpdatedState(s.pageKey)
var railHold by remember { mutableStateOf<kotlinx.coroutines.Job?>(null) }
val tabStep = androidx.compose.runtime.rememberUpdatedState { step: Int ->
if (!processSettingsPageVisible) {
val keys = navigationKeys(s)
keys.getOrNull(keys.indexOf(railSelectionNow.value) + step)?.let { key ->
PageSwipe.direction = step
onRailSelect(key)
if (s.dualScreen) { onRailSelect(key); return@let }
showRailPage(key, false)
if (inputModeManager.inputMode != InputMode.Keyboard) inputModeManager.requestInputMode(InputMode.Keyboard)
val since = MainTabSteps.otherKeys
val owner = selected
val ownPage = if (key == "components") "components" else null
railHold?.cancel()
// Pages focus their own first control as they appear; the ring stays on the rail until another key moves it.
railHold = stepScope.launch {
var pageShown = false
repeat(RAIL_HOLD_FRAMES) {
withFrameNanos { }
if (MainTabSteps.otherKeys != since || selected != owner) return@launch
if (pageKeyNow.value == ownPage) pageShown = true else if (pageShown) return@launch
if (frontFocus.focusedRail != key) runCatching { frontFocus.railFor(key).requestFocus() }
}
}
}
}
}
@@ -900,4 +920,7 @@ internal object ChildProcessSetup {
internal object MainTabSteps {
@Volatile var handler: ((Int) -> Unit)? = null
@Volatile var otherKeys = 0
}
private const val RAIL_HOLD_FRAMES = 60
@@ -1787,12 +1787,15 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
chipModifier = track("cmp-proton"),
onPick = { id -> a.onGameProton(gameProfile.appId, id) },
)
val gameTool = snap.protons.firstOrNull { it.proton.id == gameProfile.protonId }?.proton?.dir?.name
for (comp in ComponentsManager.COMPONENTS) {
val value = gameProfile.components.getValue(comp)
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val options: List<Pair<String?, String>> =
listOf(null to stringResource(R.string.comp_game_use_general)) +
if (managedDxvk) emptyList() else snap.packages.filter { it.comp == comp }.map { it.file to it.version }
if (managedDxvk) emptyList() else ComponentsManager.forTool(
comp, gameTool, snap.packages.filter { it.comp == comp }, gameProfile.componentFiles[comp],
) { it.file }.map { it.file to it.version }
DrawerStackedChoice(
host = host,
key = "game-cmp-$comp",
@@ -1875,7 +1878,7 @@ private fun ComponentsDrawerPage(host: MenuHost, a: DrawerActions, track: (Strin
val managedDxvk = ComponentsManager.runtimeManaged(comp, a.systemPowerVr)
val originals = view.originals.filter { it.comp == comp }
val options = originals.map { "orig:${it.protonVersion}" to (if (it.protonVersion == build) originalLabel else stringResource(R.string.comp_original, it.protonVersion)) } +
snap.packages.filter { it.comp == comp }.map { it.file to it.version }
ComponentsManager.forTool(comp, p.dir.name, snap.packages.filter { it.comp == comp }, st.activeFile) { it.file }.map { it.file to it.version }
if (options.isEmpty() && !managedDxvk) continue
val current = st.activeFile ?: "orig:$build"
val shown = options.firstOrNull { it.first == current }?.second
+1 -1
View File
@@ -672,7 +672,7 @@
<string name="perf_fastpath_needs_seccomp">Needs proot\'s seccomp filter.</string>
<string name="perf_fastpath_hint">Faster file lookups and less stutter. Turn off if a program can\'t find its files.</string>
<string name="perf_cursor_composite">Draw the cursor inside gamescope</string>
<string name="perf_cursor_composite_hint">Gamescope paints the pointer itself instead of handing it to Android. Turn on for a controller-driven cursor. Off is faster on a phone. Applies next session.</string>
<string name="perf_cursor_composite_hint">Gamescope paints the pointer itself instead of handing it to Android. Applies next session.</string>
<string name="perf_identity">Session identity</string>
<string name="perf_hostname">Host name</string>
<string name="perf_hostname_hint">The name Steam sees for this device. Blank restores %1$s.</string>
@@ -0,0 +1,79 @@
package com.droiddeck.launcher.core
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class CappedLogWriterTest {
@get:Rule val folder = TemporaryFolder()
@Test fun aLogUnderTheLimitIsWrittenAsIs() {
val file = folder.newFile("app.log")
CappedLogWriter(file, false, 1024, 3).use { log ->
assertTrue(log.line("first"))
assertTrue(log.line("second"))
}
assertEquals(listOf("first", "second"), file.readLines())
}
@Test fun aReconnectStormStopsAtTheLimitAndKeepsTheLastLines() {
val file = folder.newFile("audio.log")
val limit = 4096L
val log = CappedLogWriter(file, true, limit, 3)
var written = 0
for (n in 0 until 10_000) {
if (log.line("I: [linker64] client.c: Created $n \"Native client (UNIX socket client)\"")) written++
}
val capped = file.length()
assertTrue("file grew to $capped bytes", capped <= limit + 200)
assertFalse(log.line("after the limit"))
log.close()
val lines = file.readLines()
assertEquals(written, lines.count { it.startsWith("I: [linker64] client.c: Created ") } - 2)
assertTrue(lines.any { it.startsWith("== this log reached its") })
assertEquals("== ${10_000 + 1 - written - 3} lines dropped after the limit; the last 3 follow", lines[lines.size - 4])
assertEquals(
listOf(
"I: [linker64] client.c: Created 9998 \"Native client (UNIX socket client)\"",
"I: [linker64] client.c: Created 9999 \"Native client (UNIX socket client)\"",
"after the limit",
),
lines.takeLast(3),
)
assertTrue(file.length() < limit + 1024)
}
@Test fun twoWritersOnOneFileShareItsLimit() {
val file = folder.newFile("audio.log")
val daemon = CappedLogWriter(file, true, 2048, 2)
val relay = CappedLogWriter(file, true, 2048, 2)
repeat(2_000) { daemon.line("I: [linker64] protocol-native.c: Connection died.") }
assertFalse(relay.line("DA-Relay: mic enabled=1"))
assertTrue(file.length() <= 2048 + 200)
daemon.close()
relay.close()
assertEquals("DA-Relay: mic enabled=1", file.readLines().last())
}
@Test fun appendKeepsWhatTheFileHeldAndOverwriteStartsFresh() {
val file = folder.newFile("audio.log")
file.writeText("== PulseAudio daemon starting\n")
CappedLogWriter(file, true, 1024, 2).use { it.line("restarted") }
assertEquals(listOf("== PulseAudio daemon starting", "restarted"), file.readLines())
CappedLogWriter(file, false, 1024, 2).use { it.line("new session") }
assertEquals(listOf("new session"), file.readLines())
}
@Test fun linesAfterCloseAreIgnored() {
val file = folder.newFile("app.log")
val log = CappedLogWriter(file, false, 1024, 2)
log.line("kept")
log.close()
assertFalse(log.line("late"))
log.close()
assertEquals(listOf("kept"), file.readLines())
}
}
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.assumeFilePermissionsEnforced
import android.os.Environment
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
@@ -461,6 +462,15 @@ class AddedExesTest {
assertEquals("$clash-2", guests.last())
}
@Test fun aFolderNamedStoresIsNotBoundOverTheInternalStoreRoot() {
noGamesFolders()
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(File(this, "One/One.exe")) }
val result = AddedGames.addFolder(app, stores)
val guest = SessionPrefs.gameFolderBinds(app).single().second
assertTrue(guest != StoreInstallRoot.INTERNAL_GUEST && guest.startsWith("${AddedGames.GUEST_DIR}/Stores-"))
assertEquals("$guest/One/One.exe", result.added.single().guestExe)
}
@Test fun aRemovedSingleExeGameStaysOffUntilPickedAgain() {
noGamesFolders()
val pick = onStorage("Download/Celeste/Celeste.exe")
@@ -137,4 +137,30 @@ class AddedGamesStoreScanTest {
val game = AddedGames.scan(app).single { it.folder.absolutePath == folder.absolutePath }
assertEquals("/root/Games/Stores/GOG/Witcher Game", game.guestDir)
}
@Test fun aStoreGameThatIsUpdatingIsNotListedThroughItsSavedExe() {
val folder = install(Store.GOG, "upd", "Updating GOG", "Binaries/Game.exe", launcher = true)
val own = File(folder, "Binaries/Game.exe")
assertTrue(AddedGames.addExe(app, own) is AddedGames.AddResult.Existing)
assertTrue(AddedGames.scan(app).any { it.folder.absolutePath == folder.absolutePath })
StoreGameSidecar.read(folder)!!.copy(state = StoreGameSidecar.STATE_UPDATING).write(folder)
assertTrue(AddedGames.scan(app).none { it.folder.absolutePath == folder.absolutePath })
}
@Test fun reselectingTheMappedExeReplacesAnUnmappedAliasOfIt() {
val folder = install(Store.EPIC, "alias", "Alias Epic", "Binaries/Game.exe", launcher = true)
val own = File(folder, "Binaries/Game.exe")
val alias = File(java.nio.file.Files.createTempDirectory("alias").toFile(), "bin")
try {
java.nio.file.Files.createSymbolicLink(alias.toPath(), File(folder, "Binaries").toPath())
} catch (e: Exception) {
org.junit.Assume.assumeNoException(e)
}
val aliased = File(alias, "Game.exe")
assertNull(AddedGames.guestPath(app, aliased))
SessionPrefs.setAddedGameExe(app, folder.path, aliased.path)
assertTrue(AddedGames.addExe(app, own) is AddedGames.AddResult.Existing)
assertEquals(own.path, SessionPrefs.addedGameExe(app, folder.path))
assertEquals(own.path, AddedExes.list(app).single { it.folder == folder.path }.exe)
}
}
@@ -3,6 +3,7 @@ package com.droiddeck.launcher.frontend
import com.droiddeck.launcher.session.GameStorage
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreGameSidecar
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
@@ -182,6 +183,41 @@ class GamesFolderMigrationTest {
assertEquals(listOf(pc.path to AddedGames.GUEST_DIR + "/PC"), binds)
}
@Test fun aMigratedFolderNamedStoresDoesNotTakeTheInternalStoreGuest() {
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(this, "One/One.exe") }
val pc = tmp.newFolder("PC").apply { exe(this, "Two/Two.exe") }
SessionPrefs.setAddedGamesDirs(app, listOf(stores.path, pc.path))
GamesFolderMigration.run(app)
val binds = SessionPrefs.gameFolderBinds(app).toMap()
assertTrue(binds.getValue(stores.path) != StoreInstallRoot.INTERNAL_GUEST)
assertEquals(AddedGames.GUEST_DIR + "/PC", binds.getValue(pc.path))
val games = AddedGames.scan(app).associateBy { it.name }
assertEquals(binds.getValue(stores.path) + "/One/One.exe", games.getValue("One").guestExe)
}
@Test fun aSavedBindAtTheInternalStoreGuestIsRepathed() {
val stores = File(tmp.newFolder("card"), "Stores").apply { exe(this, "One/One.exe") }
val pc = tmp.newFolder("PC").apply { exe(this, "Two/Two.exe") }
SessionPrefs.setGameFolderBinds(
app,
listOf(stores.path to StoreInstallRoot.INTERNAL_GUEST, pc.path to AddedGames.GUEST_DIR + "/PC"),
)
GamesFolderMigration.run(app)
val binds = SessionPrefs.gameFolderBinds(app).toMap()
assertTrue(binds.getValue(stores.path) != StoreInstallRoot.INTERNAL_GUEST)
assertTrue(binds.getValue(stores.path).startsWith("${AddedGames.GUEST_DIR}/Stores-"))
assertEquals(AddedGames.GUEST_DIR + "/PC", binds.getValue(pc.path))
assertTrue(binds.values.none { it == StoreInstallRoot.INTERNAL_GUEST })
assertEquals(binds.getValue(stores.path) + "/One/One.exe", AddedGames.guestPath(app, File(stores, "One/One.exe")))
val installer = File(stores, "GOG/Game/setup_1.exe").apply { parentFile?.mkdirs(); writeText("MZ") }
val guestInstaller = AddedGames.guestPath(app, installer)!!
val extractorBinds = StoreInstallRoot.guestBinds(app).map { it.substringBeforeLast(':') to it.substringAfterLast(':') }
val covering = extractorBinds.filter { (_, mount) -> guestInstaller.startsWith("$mount/") }.maxByOrNull { it.second.length }!!
assertEquals(installer.canonicalFile, File(covering.first + guestInstaller.removePrefix(covering.second)).canonicalFile)
val internalInstaller = "${StoreInstallRoot.INTERNAL_GUEST}/GOG/Game/setup_1.exe"
assertTrue(extractorBinds.none { (_, mount) -> internalInstaller == mount || internalInstaller.startsWith("$mount/") })
}
@Test fun twoFoldersOfOneNameKeepTheirOwnGuestPaths() {
val a = File(tmp.newFolder("a"), "Games").apply { mkdirs() }
val b = File(tmp.newFolder("b"), "Games").apply { mkdirs() }
@@ -694,22 +694,22 @@ class InputLibraryTest {
for (desktop in listOf(false, true)) for (panel in listOf(null, InputStockLayouts.TRACKPAD) + DeckPanel.entries.map { it.bindings }) {
val shown = library.panelLayout(desktop, panel)!!.elements
assertTrue(shown.isNotEmpty())
assertFalse(library.compileActive(desktop, panel).showsMouseButton(InputRole.SECONDARY, shown, library.compileStock(desktop, panel)))
assertFalse(library.compileActive(desktop, panel).showsLeftMouseButton(InputRole.SECONDARY, shown, library.compileStock(desktop, panel)))
}
}
@Test fun userBoundSecondScreenMouseButtonIsDetected() {
@Test fun userBoundSecondScreenLeftMouseButtonIsDetected() {
val stock = InputLibraries.read(context)
val grips = DeckPanel.GRIPS.bindings
val button = stock.panelLayout(false, grips)!!.elements.first { it.control.dimensions == 1 }
val bound = stock.withPreset(stock.preset(grips).copy(elements = mapOf(button.id to InputAction.MouseButton(272))))
for (desktop in listOf(false, true)) {
assertTrue(bound.compileActive(desktop, grips).showsMouseButton(InputRole.SECONDARY, listOf(button), bound.compileStock(desktop, grips)))
assertFalse(bound.compileActive(desktop, grips).showsMouseButton(InputRole.PRIMARY, listOf(button), bound.compileStock(desktop, grips)))
assertTrue(bound.compileActive(desktop, grips).showsLeftMouseButton(InputRole.SECONDARY, listOf(button), bound.compileStock(desktop, grips)))
assertFalse(bound.compileActive(desktop, grips).showsLeftMouseButton(InputRole.PRIMARY, listOf(button), bound.compileStock(desktop, grips)))
}
val pad = stock.panelLayout(true, InputStockLayouts.TRACKPAD)!!.elements.single()
val rebound = stock.withPreset(stock.preset(InputStockLayouts.TRACKPAD).let { it.copy(clicks = it.clicks + (pad.id to InputAction.MouseButton(273))) })
assertTrue(rebound.compileActive(true).showsMouseButton(InputRole.SECONDARY, listOf(pad), rebound.compileStock(true)))
assertFalse(rebound.compileActive(true).showsLeftMouseButton(InputRole.SECONDARY, listOf(pad), rebound.compileStock(true)))
}
@Test fun copiedStockPanelsKeepTapsClickingUntilAMouseButtonIsAdded() {
@@ -720,13 +720,13 @@ class InputLibraryTest {
val layout = copied.activeLayout(desktop, InputRole.SECONDARY)!!
assertNotEquals(source.id, layout.id)
assertEquals(source.id, layout.origin)
assertFalse(copied.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, copied.compileStock(desktop)))
assertFalse(copied.compileActive(desktop).showsLeftMouseButton(InputRole.SECONDARY, layout.elements, copied.compileStock(desktop)))
val added = InputSurfaceElement(InputControl.A, .4f, .4f, .1f, .1f, id = "custom:added")
val grown = copied.withLayout(layout.copy(elements = layout.elements + added))
val bindings = grown.activePart(desktop, InputRole.SECONDARY).bindings
val bound = grown.withPreset(grown.preset(bindings).let { it.copy(elements = it.elements + (added.id to InputAction.MouseButton(272))) })
assertTrue(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements + added, bound.compileStock(desktop)))
assertFalse(bound.compileActive(desktop).showsMouseButton(InputRole.SECONDARY, layout.elements, bound.compileStock(desktop)))
assertTrue(bound.compileActive(desktop).showsLeftMouseButton(InputRole.SECONDARY, layout.elements + added, bound.compileStock(desktop)))
assertFalse(bound.compileActive(desktop).showsLeftMouseButton(InputRole.SECONDARY, layout.elements, bound.compileStock(desktop)))
}
}
}
@@ -15,57 +15,73 @@ class OnScreenMouseButtonTest {
private fun profile(vararg elements: Pair<String, InputAction>, clicks: Map<String, InputAction> = emptyMap(), base: InputProfile = game) =
base.copy(elements = mapOf(InputRole.PRIMARY to elements.toMap()), clicks = mapOf(InputRole.PRIMARY to clicks))
@Test fun shownButtonBoundToAMouseButtonIsDetected() {
listOf(272, 273, 274).forEach { code ->
assertTrue(profile(button.id to InputAction.MouseButton(code)).showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
@Test fun shownButtonBoundToTheLeftMouseButtonIsDetected() {
assertTrue(profile(button.id to InputAction.MouseButton(272)).showsLeftMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
}
@Test fun rightOrMiddleMouseButtonAloneKeepsTapsClicking() {
listOf(273, 274, 275, 276).forEach { code ->
assertFalse(profile(button.id to InputAction.MouseButton(code)).showsLeftMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
val stickClick = profile(stick.id to InputAction.Native(), clicks = mapOf(stick.id to InputAction.MouseButton(code)))
assertFalse(stickClick.showsLeftMouseButton(InputRole.PRIMARY, listOf(stick), game))
assertFalse(game.withBinding(InputRole.PRIMARY, InputControl.A, InputAction.MouseButton(code)).showsLeftMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
}
}
@Test fun rightButtonNextToALeftButtonStillStopsTapClicks() {
val right = InputSurfaceElement(InputControl.B, .7f, .6f, .1f, .1f, id = "custom:right")
val both = profile(button.id to InputAction.MouseButton(272), right.id to InputAction.MouseButton(273))
assertTrue(both.showsLeftMouseButton(InputRole.PRIMARY, listOf(button, right), game))
assertFalse(both.showsLeftMouseButton(InputRole.PRIMARY, listOf(right), game))
}
@Test fun stickClickBoundToAMouseButtonIsDetected() {
val profile = profile(stick.id to InputAction.Native(), clicks = mapOf(stick.id to InputAction.MouseButton(272)))
assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick), game))
assertTrue(profile.showsLeftMouseButton(InputRole.PRIMARY, listOf(stick), game))
}
@Test fun legacyButtonUsesItsRoleBinding() {
val profile = game.withBinding(InputRole.PRIMARY, InputControl.A, InputAction.MouseButton(272))
assertTrue(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
assertFalse(profile.showsMouseButton(InputRole.SECONDARY, listOf(legacyA), game))
assertTrue(profile.showsLeftMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
assertFalse(profile.showsLeftMouseButton(InputRole.SECONDARY, listOf(legacyA), game))
}
@Test fun stockDesktopOverlayKeepsTapsClicking() {
assertFalse(desktop.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
assertFalse(desktop.showsLeftMouseButton(InputRole.PRIMARY, overlay, desktop))
}
@Test fun userBoundMouseButtonInDesktopIsDetected() {
val rebound = desktop.withBinding(InputRole.PRIMARY, InputControl.X, InputAction.MouseButton(272))
assertTrue(rebound.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
val stickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(274))
assertTrue(stickClick.showsMouseButton(InputRole.PRIMARY, overlay, desktop))
assertTrue(profile(button.id to InputAction.MouseButton(272), base = desktop).showsMouseButton(InputRole.PRIMARY, overlay + button, desktop))
assertTrue(rebound.showsLeftMouseButton(InputRole.PRIMARY, overlay, desktop))
val stickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(272))
assertTrue(stickClick.showsLeftMouseButton(InputRole.PRIMARY, overlay, desktop))
val middleStickClick = desktop.withBinding(InputRole.PRIMARY, InputControl.L3, InputAction.MouseButton(274))
assertFalse(middleStickClick.showsLeftMouseButton(InputRole.PRIMARY, overlay, desktop))
assertTrue(profile(button.id to InputAction.MouseButton(272), base = desktop).showsLeftMouseButton(InputRole.PRIMARY, overlay + button, desktop))
}
@Test fun desktopBindingsOnAGameBaseProfileAreUserPicked() {
val copied = desktop.copy(id = "custom")
assertTrue(copied.showsMouseButton(InputRole.PRIMARY, overlay, game))
assertTrue(copied.showsLeftMouseButton(InputRole.PRIMARY, overlay, game))
}
@Test fun layoutWithoutAMouseButtonKeepsTapsClicking() {
val profile = profile(button.id to InputAction.Keys(listOf(57)), stick.id to InputAction.Pointer())
assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
assertFalse(game.showsMouseButton(InputRole.PRIMARY, listOf(legacyA, stick) + overlay, game))
assertFalse(profile.showsLeftMouseButton(InputRole.PRIMARY, listOf(stick, button), game))
assertFalse(game.showsLeftMouseButton(InputRole.PRIMARY, listOf(legacyA, stick) + overlay, game))
}
@Test fun hiddenMouseButtonDoesNotCount() {
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, listOf(stick), game))
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsMouseButton(InputRole.PRIMARY, emptyList(), game))
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsLeftMouseButton(InputRole.PRIMARY, listOf(stick), game))
assertFalse(profile(button.id to InputAction.MouseButton(272)).showsLeftMouseButton(InputRole.PRIMARY, emptyList(), game))
}
@Test fun physicalMouseBindingsDoNotCount() {
val profile = game.withBinding(InputRole.PHYSICAL, InputControl.A, InputAction.MouseButton(272))
assertFalse(profile.showsMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
assertFalse(profile.showsLeftMouseButton(InputRole.PRIMARY, listOf(legacyA), game))
}
@Test fun invalidMouseCodeDoesNotCount() {
assertFalse(profile(button.id to InputAction.MouseButton(1)).showsMouseButton(InputRole.PRIMARY, listOf(button), game))
assertFalse(profile(button.id to InputAction.MouseButton(1)).showsLeftMouseButton(InputRole.PRIMARY, listOf(button), game))
}
}
@@ -216,6 +216,41 @@ class BattleNetTest {
assertNull(BattleNet.hostFolder(context, "G:\\etc\\passwd"))
}
@Test fun aDriveAtTheAppDataFolderHoldingTheRuntimeListsTheGamesInside() {
val root = LinuxRuntime.rootDir(context)
val data = context.filesDir.parentFile!!
val pfx = File(BattleNet.prefix(context), "pfx")
val devices = File(pfx, "dosdevices").apply { mkdirs() }
java.nio.file.Files.createSymbolicLink(File(devices, "d:").toPath(), data.absoluteFile.toPath())
java.nio.file.Files.createSymbolicLink(File(devices, "e:").toPath(), java.nio.file.Paths.get("/root/Games/Card"))
val wow = File(root, "root/Games/Stores/Battle.net/World of Warcraft").apply { mkdirs() }
File(wow, "_forever_").mkdirs()
val drive = "D:/" + data.absoluteFile.toPath().relativize(wow.absoluteFile.toPath()).joinToString("/")
File(pfx, "drive_c/ProgramData/Battle.net/Agent").mkdirs()
File(pfx, "drive_c/ProgramData/Battle.net/Agent/product.db").writeBytes(message(
field(1, message(field(1, "wowf"), field(2, "wowf"), field(3, message(field(1, drive))))),
))
assertEquals(wow, BattleNet.hostFolder(context, drive))
assertEquals(wow, BattleNet.games(context).single().folder)
assertEquals(File(root, "root/Games/Card/Battle.net/X"), BattleNet.hostFolder(context, "E:\\Battle.net\\X"))
assertNull(BattleNet.hostFolder(context, "D:\\..\\etc"))
}
@Test fun aDriveAtAnAliasOfTheAppDataFolderListsTheGameUnderTheRuntimePath() {
val root = LinuxRuntime.rootDir(context)
val data = context.filesDir.parentFile!!
val alias = File(data.parentFile, "alias-" + data.name)
java.nio.file.Files.createSymbolicLink(alias.toPath(), data.absoluteFile.toPath())
try {
val devices = File(BattleNet.prefix(context), "pfx/dosdevices").apply { mkdirs() }
java.nio.file.Files.createSymbolicLink(File(devices, "d:").toPath(), alias.absoluteFile.toPath())
val game = File(root, "root/Games/Stores/Battle.net/StarCraft").apply { mkdirs() }
val drive = "D:\\" + data.absoluteFile.toPath().relativize(game.absoluteFile.toPath()).joinToString("\\")
assertEquals(game.path, BattleNet.hostFolder(context, drive)?.path)
} finally {
java.nio.file.Files.delete(alias.toPath())
}
}
@Test fun wowForeverIsListedBesideRetailInTheSharedWorldOfWarcraftFolder() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
@@ -274,6 +309,21 @@ class BattleNetTest {
assertEquals(mapOf("WoWF" to root), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to "/elsewhere")))
}
@Test fun aFolderSavedThroughAnAliasOfTheAppDataFolderIsKept() {
val data = context.filesDir.parentFile!!
val root = File(context.filesDir, "World of Warcraft").apply { mkdirs() }
val foreverDir = File(root, "_forever_").apply { mkdirs() }
val forever = BattleNet.title("wow_forever")!!
val alias = File(data.parentFile, "alias-" + data.name)
java.nio.file.Files.createSymbolicLink(alias.toPath(), data.absoluteFile.toPath())
try {
val saved = File(alias, data.absoluteFile.toPath().relativize(foreverDir.absoluteFile.toPath()).toString()).path
assertEquals(mapOf("WoWF" to foreverDir), BattleNet.ownFolders(mapOf("WoWF" to (forever to root)), mapOf("WoWF" to saved)))
} finally {
java.nio.file.Files.delete(alias.toPath())
}
}
@Test fun theListedFolderIsRememberedAcrossScans() {
val pfx = File(BattleNet.prefix(context), "pfx").apply { mkdirs() }
val wow = File(pfx, "drive_c/Program Files (x86)/World of Warcraft").apply { mkdirs() }
@@ -61,9 +61,11 @@ class BwrapSpawnerTest {
"DDNATV_ROOT" to rootfs, "DDNATV_BINDS" to "/dev:/dev", "HOME" to "/root",
"SPA_PLUGIN_DIR" to "/usr/local/lib/droiddeck-pipewire/lib/spa-0.2",
"LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so:$rootfs/usr/local/lib/libddsession.so:$rootfs/usr/lib/libddnatv-hook.so",
"DROIDDECK_FDS" to "droiddeck-fds-1",
)
BwrapSpawner.withoutRootfsSettings(env, rootfs)
assertEquals(mapOf("HOME" to "/root", "LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so"), env)
assertEquals(mapOf("HOME" to "/root", "LD_PRELOAD" to "/run/droiddeck-preload/libddsession.so",
"DROIDDECK_FDS" to "droiddeck-fds-1"), env)
val onlySession = mutableMapOf("LD_PRELOAD" to "$rootfs/usr/lib/libddnatv-hook.so")
BwrapSpawner.withoutRootfsSettings(onlySession, rootfs)
assertTrue(onlySession.isEmpty())
@@ -0,0 +1,139 @@
package com.droiddeck.launcher.session
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class ComponentsBionicFexTest {
private val bionicTool = "DroidDeck-Bionic-12.8-r24"
private val ownTool = "DroidDeck-Proton-11-12.8"
private fun proton(dir: String, valve: Boolean = false) =
ComponentsManager.Proton(dir, dir, File("/steam/compatibilitytools.d/$dir"), "/p/$dir", "$dir-1", valve)
private fun item(file: String, release: String) = ComponentsManager.CatalogItem(file, "fex", release, "", 1, "")
@Test fun onlyBionicNamedPackagesFitDroidDeckBionic() {
assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-bionic.wcp"))
assertTrue(ComponentsManager.bionicFex("FEXCore-2611.1-PPA-BIONIC.WCP"))
assertFalse(ComponentsManager.bionicFex("FEXCore-2611.1-linux.wcp"))
assertFalse(ComponentsManager.bionicFex("DD-FEXCore-2611+51-nightly.wcp"))
assertFalse(ComponentsManager.bionicFex("bionic-FEXCore-2611.wcp"))
assertTrue(ComponentsManager.bionicTool(bionicTool))
assertFalse(ComponentsManager.bionicTool(ownTool))
assertFalse(ComponentsManager.bionicTool("GE-Proton10-25"))
assertFalse(ComponentsManager.bionicTool(null))
assertTrue(ComponentsManager.fexFits(bionicTool, "FEXCore-2611-bionic.wcp"))
assertFalse(ComponentsManager.fexFits(bionicTool, "FEXCore-2611-linux.wcp"))
assertFalse(ComponentsManager.fexFits(bionicTool, "DD-FEXCore-2611+51-nightly.wcp"))
assertTrue(ComponentsManager.fexFits(ownTool, "DD-FEXCore-2611+51-nightly.wcp"))
assertTrue(ComponentsManager.fexFits(ownTool, "FEXCore-2611-linux.wcp"))
assertFalse(ComponentsManager.fexFits(ownTool, "FEXCore-2611-bionic.wcp"))
assertFalse(ComponentsManager.fexFits(null, "FEXCore-2611-bionic.wcp"))
}
@Test fun aTwinSwapsTheLinuxAndBionicEnding() {
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.fexTwin("FEXCore-2611.1-linux.wcp"))
assertEquals("FEXCore-2611.1-linux.wcp", ComponentsManager.fexTwin("FEXCore-2611.1-bionic.wcp"))
assertEquals("FEXCore-2611-PPA-bionic.wcp", ComponentsManager.fexTwin("FEXCore-2611-PPA-linux.wcp"))
assertNull(ComponentsManager.fexTwin("DD-FEXCore-2611+51-nightly.wcp"))
assertNull(ComponentsManager.fexTwin("my-fex.wcp"))
}
@Test fun aLaunchTakesTheChoiceOrItsStoredTwinForEachFlavor() {
val stored = setOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "FEXCore-2610-linux.wcp")
val has: (String) -> Boolean = { it in stored }
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.launchFex(bionicTool, "FEXCore-2611.1-linux.wcp", has))
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentsManager.launchFex(bionicTool, "FEXCore-2611.1-bionic.wcp", has))
assertEquals("FEXCore-2611.1-linux.wcp", ComponentsManager.launchFex(ownTool, "FEXCore-2611.1-bionic.wcp", has))
assertEquals("FEXCore-2610-linux.wcp", ComponentsManager.launchFex(ownTool, "FEXCore-2610-linux.wcp", has))
assertEquals("DD-FEXCore-2611+51-nightly.wcp", ComponentsManager.launchFex(ownTool, "DD-FEXCore-2611+51-nightly.wcp", has))
assertNull(ComponentsManager.launchFex(bionicTool, "FEXCore-2610-linux.wcp", has))
assertNull(ComponentsManager.launchFex(bionicTool, "DD-FEXCore-2611+51-nightly.wcp", has))
}
@Test fun fexListsShowTheProtonsFlavorAndTheCurrentChoice() {
val files = listOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "DD-FEXCore-2611+51-nightly.wcp", "FEXCore-2610-bionic.wcp")
assertEquals(listOf("FEXCore-2611.1-bionic.wcp", "FEXCore-2610-bionic.wcp"), ComponentsManager.forTool("fex", bionicTool, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "DD-FEXCore-2611+51-nightly.wcp"), ComponentsManager.forTool("fex", ownTool, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "DD-FEXCore-2611+51-nightly.wcp"), ComponentsManager.forTool("fex", null, files) { it })
assertEquals(listOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp", "FEXCore-2610-bionic.wcp"),
ComponentsManager.forTool("fex", bionicTool, files, selected = "FEXCore-2611.1-linux.wcp") { it })
assertEquals(files, ComponentsManager.forTool("dxvk", bionicTool, files) { it })
}
@Test fun bionicStableAssetsAreFex() {
assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_BIONIC, "FEXCore-2611.1-bionic.wcp"))
assertEquals("fex", ComponentsManager.assetComp(ComponentsManager.DD_BIONIC, "FEXCore-2610-PPA-bionic.wcp"))
assertEquals("fex", ComponentsManager.assetComp("FexCore-Linux", "FEXCore-2611.1-linux.wcp"))
}
@Test fun aGameFexChoiceKeepsItsTwinInUseWhileTheOtherFlavorIsInstalled() {
val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp")))
assertEquals(setOf("FEXCore-2611.1-linux.wcp"), ComponentsManager.packagesInUse(state, listOf(proton(ownTool))))
assertEquals(setOf("FEXCore-2611.1-linux.wcp", "FEXCore-2611.1-bionic.wcp"),
ComponentsManager.packagesInUse(state, listOf(proton(ownTool), proton(bionicTool))))
}
@Test fun aTwinAGameChoiceStillNeedsCannotBeDeletedAsUnused() {
val state = JSONObject().put("profiles", JSONObject().put("42", JSONObject().put("fex", "FEXCore-2611.1-linux.wcp")))
assertEquals(bionicTool, ComponentsManager.twinUser(state, listOf(proton(ownTool), proton(bionicTool)), "FEXCore-2611.1-bionic.wcp")?.dir?.name)
assertEquals(null, ComponentsManager.twinUser(state, listOf(proton(ownTool)), "FEXCore-2611.1-bionic.wcp"))
assertEquals(null, ComponentsManager.twinUser(state, listOf(proton(ownTool), proton(bionicTool)), "FEXCore-2610-bionic.wcp"))
assertEquals(null, ComponentsManager.twinUser(JSONObject(), listOf(proton(bionicTool)), "FEXCore-2611.1-bionic.wcp"))
}
@Test fun droidDeckBionicFollowsTheNewestBionicFexAndNothingElse() {
val bionic = proton(bionicTool)
val own = proton(ownTool)
assertTrue(ComponentUpdates.autoFollows(bionic, "fex"))
assertFalse(ComponentUpdates.autoFollows(bionic, "dxvk"))
assertFalse(ComponentUpdates.autoFollows(bionic, "vkd3d"))
assertFalse(ComponentUpdates.autoFollows(proton(bionicTool, valve = true), "fex"))
assertFalse(ComponentUpdates.follows(bionic))
assertTrue(ComponentUpdates.autoFollows(own, "dxvk"))
assertFalse(ComponentUpdates.autoFollows(proton("GE-Proton10-25"), "fex"))
assertEquals("fex-bionic", ComponentUpdates.fexLine(bionic).key)
assertEquals("fex", ComponentUpdates.fexLine(own).key)
assertEquals("fex", ComponentUpdates.line("fex", false).key)
val catalog = listOf(
item("DD-FEXCore-2611+51-nightly.wcp", ComponentsManager.DD_NIGHTLY),
item("DD-FEXCore-2611+52-bionic.wcp", ComponentsManager.DD_NIGHTLY),
item("FEXCore-2611.1-linux.wcp", "FexCore-Linux"),
item("FEXCore-2610-bionic.wcp", ComponentsManager.DD_BIONIC),
item("FEXCore-2611-PPA-bionic.wcp", ComponentsManager.DD_BIONIC),
item("FEXCore-2611.1-bionic.wcp", ComponentsManager.DD_BIONIC),
)
assertEquals("FEXCore-2611.1-bionic.wcp", ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(bionic), emptySet())?.file)
assertNull(ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(bionic), setOf("FEXCore-2611.1-bionic.wcp")))
assertEquals("DD-FEXCore-2611+51-nightly.wcp", ComponentUpdates.pick(catalog, ComponentUpdates.fexLine(own), emptySet())?.file)
}
@Test fun pruningTheBionicLineKeepsBionicPackagesTheUserDownloaded() {
val line = ComponentUpdates.fexLine(proton(bionicTool))
val current = "FEXCore-2611.1-bionic.wcp"
val stored = listOf("FEXCore-2610-bionic.wcp", "FEXCore-2611-PPA-bionic.wcp", current, "FEXCore-2610-linux.wcp")
assertEquals(listOf("FEXCore-2610-bionic.wcp"),
ComponentUpdates.stale(line, setOf("FEXCore-2610-bionic.wcp", current), stored, setOf(current), current))
}
@Test fun aBionicProtonsOwnFexChoiceIsNotHandedBack() {
val bionic = proton(bionicTool)
val choices = mapOf(bionic.id to mapOf(
"fex" to ComponentsManager.Choice("FEXCore-2611.1-bionic.wcp", false, bionic.version),
"dxvk" to ComponentsManager.Choice("DD-dxvk-3.1.1+190-nightly.wcp", false, bionic.version),
))
assertEquals(listOf(bionic to "dxvk"),
ComponentUpdates.strays(listOf(bionic), choices, setOf("FEXCore-2611.1-bionic.wcp", "DD-dxvk-3.1.1+190-nightly.wcp")))
}
}
@@ -8,6 +8,7 @@ import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
@@ -23,6 +24,7 @@ class ComponentsRepublishTest {
private val fex = "FEXCore-2610-d2rfix28-linux.wcp"
private val scope = "2596113170"
private val dll = "files/lib/wine/aarch64-windows/libwow64fex.dll"
private val so = "files/lib/wine/aarch64-unix/libwow64fex.so"
private lateinit var context: Context
@Before fun setUp() {
@@ -48,6 +50,61 @@ class ComponentsRepublishTest {
assertEquals(fex, ComponentsManager.gameComponents(context, scope)["fex"])
}
@Test fun aGlibcGameFexChoiceWithoutItsTwinLeavesDroidDeckBionicOnItsOwnFex() {
proton("DroidDeck-Proton 11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r6", "DroidDeck-Bionic-12.8-r6")
packageFile()
ComponentsManager.setGameComponent(context, scope, "fex", fex) { false }
assertEquals(setOf("DroidDeck-Proton 11-12.8"), scopedTools())
val bionic = rows().filter { it[1] == "DroidDeck-Bionic-12.8-r6" && it[3] == "fex" }
assertTrue(bionic.isNotEmpty())
assertTrue(bionic.all { it[0] == "*" && "/store/original-DroidDeck-Bionic-12.8-r6-" in it[6] })
}
@Test fun aGameFexChoiceReachesEachProtonAsTheBuildOfItsFlavor() {
proton("DroidDeck-Proton-11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r24", "DroidDeck-Bionic-12.8-r24")
val linux = "FEXCore-2611.1-linux.wcp"
val bionic = "FEXCore-2611.1-bionic.wcp"
packageFile(linux, "FEXCore-Linux", "glibc wow64")
packageFile(bionic, "FEXCore-Bionic", "android wow64")
for (choice in listOf(linux, bionic)) {
ComponentsManager.setGameComponent(context, scope, "fex", choice) { false }
val scoped = rows().filter { it[0] == scope && it[3] == "fex" }
val own = scoped.single { it[1] == "DroidDeck-Proton-11-12.8" && it[4] == dll }
val android = scoped.single { it[1] == "DroidDeck-Bionic-12.8-r24" && it[4] == dll }
assertEquals("glibc wow64", File(LinuxRuntime.rootDir(context), own[6].removePrefix("/")).readText())
assertEquals("android wow64", File(LinuxRuntime.rootDir(context), android[6].removePrefix("/")).readText())
assertTrue(scoped.any { it[1] == "DroidDeck-Proton-11-12.8" && it[6] == "-" })
assertTrue(scoped.none { it[1] == "DroidDeck-Bionic-12.8-r24" && it[6] == "-" })
assertEquals(choice, ComponentsManager.gameComponents(context, scope)["fex"])
}
}
@Test fun aProtonsFexIsOnlyEverSwappedToABuildOfItsFlavor() {
proton("DroidDeck-Proton-11-12.8", "DroidDeck-Proton-11-12.8")
proton("DroidDeck-Bionic-12.8-r24", "DroidDeck-Bionic-12.8-r24")
val linux = "FEXCore-2611.1-linux.wcp"
val bionic = "FEXCore-2611.1-bionic.wcp"
packageFile(linux, "FEXCore-Linux", "glibc wow64")
packageFile(bionic, "FEXCore-Bionic", "android wow64")
val bionicDll = File(protonDir("DroidDeck-Bionic-12.8-r24"), dll)
val ownDll = File(protonDir("DroidDeck-Proton-11-12.8"), dll)
assertThrows(IllegalStateException::class.java) { ComponentsManager.swap(context, "DroidDeck-Bionic-12.8-r24", linux) }
assertThrows(IllegalStateException::class.java) { ComponentsManager.swap(context, "DroidDeck-Proton-11-12.8", bionic) }
assertEquals("bundled FEX DroidDeck-Bionic-12.8-r24", bionicDll.readText())
assertEquals("bundled FEX DroidDeck-Proton-11-12.8", ownDll.readText())
ComponentsManager.swap(context, "DroidDeck-Bionic-12.8-r24", bionic)
ComponentsManager.swap(context, "DroidDeck-Proton-11-12.8", linux)
assertEquals("android wow64", bionicDll.readText())
assertEquals("glibc wow64", ownDll.readText())
assertTrue(File(protonDir("DroidDeck-Bionic-12.8-r24"), so).isFile)
assertTrue(rows().none { it[1] == "DroidDeck-Bionic-12.8-r24" && it[3] == "fex" && it[6] == "-" })
}
@Test fun nothingIsRewrittenWhileTheToolsAreUnchanged() {
proton("DroidDeck-Proton 11-11.8", "DroidDeck-Proton-11-11.8")
packageFile()
@@ -117,18 +174,21 @@ class ComponentsRepublishTest {
private fun launchState() = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-components/desired.tsv")
private fun protonDir(name: String) = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
private fun proton(name: String, version: String) {
val dir = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/steamapps/common/$name")
val dir = protonDir(name)
File(dir, "files/lib/wine").mkdirs()
File(dir, "proton").writeText("#!/bin/sh\n")
File(dir, "version").writeText("1 $version\n")
File(dir, dll).apply { parentFile!!.mkdirs(); writeText("bundled FEX $version") }
File(dir, so).apply { parentFile!!.mkdirs(); writeText("bundled unix FEX $version") }
}
private fun packageFile() {
val out = File(context.filesDir, "components/packages/$fex").apply { parentFile!!.mkdirs() }
val profile = JSONObject().put("type", "FEXCore-Linux").put("versionName", "2610-d2rfix28").toString().toByteArray()
val body = "d2rfix28 wow64".toByteArray()
private fun packageFile(name: String = fex, type: String = "FEXCore-Linux", text: String = "d2rfix28 wow64") {
val out = File(context.filesDir, "components/packages/$name").apply { parentFile!!.mkdirs() }
val profile = JSONObject().put("type", type).put("versionName", name.removeSuffix(".wcp")).toString().toByteArray()
val body = text.toByteArray()
TarArchiveOutputStream(ZstdOutputStream(out.outputStream())).use { tar ->
tar.putArchiveEntry(TarArchiveEntry("profile.json").apply { size = profile.size.toLong() })
tar.write(profile)
@@ -0,0 +1,191 @@
package com.droiddeck.launcher.session
import java.io.File
import java.nio.file.Files
import java.nio.file.LinkOption
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeFalse
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28], manifest = Config.NONE)
class CpuCacheSysfsTest {
@get:Rule val tmp = TemporaryFolder()
private fun cache(host: File, cpu: Int, vararg levels: Pair<Int, String?>) {
levels.forEachIndexed { i, (level, size) ->
val index = File(host, "cpu$cpu/cache/index$i").apply { mkdirs() }
File(index, "level").writeText("$level\n")
File(index, "type").writeText(if (level == 1) "Data\n" else "Unified\n")
File(index, "shared_cpu_list").writeText("$cpu\n")
if (size != null) File(index, "size").writeText(size)
}
}
@Test fun everyLevelReportsTheSizeTheEmulatedCpuidReports() {
val host = tmp.newFolder("host")
cache(host, 0, 1 to null, 2 to null, 3 to null)
val root = tmp.newFolder("out")
val out = File(root, "p/1")
val binds = CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals(listOf(File(out, "cpu0").path + ":" + File(host, "cpu0/cache").path), binds)
assertEquals("32K\n", File(out, "cpu0/index0/size").readText())
assertEquals("512K\n", File(out, "cpu0/index1/size").readText())
assertEquals("8192K\n", File(out, "cpu0/index2/size").readText())
assertEquals("2\n", File(out, "cpu0/index1/level").readText())
assertEquals("Unified\n", File(out, "cpu0/index1/type").readText())
}
@Test fun aKernelSizeThatDisagreesWithTheEmulatedCpuidIsReplaced() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to "12288K\n")
val root = tmp.newFolder("out")
val out = File(root, "p/1")
CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals("512K\n", File(out, "cpu0/index0/size").readText())
assertEquals("12288K\n", File(host, "cpu0/cache/index0/size").readText())
}
@Test fun everyCoreIsBoundAndACoreWithoutCacheInfoIsLeftAlone() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
cache(host, 1, 2 to null)
File(host, "cpu2").mkdirs()
File(host, "cpufreq").mkdirs()
val root = tmp.newFolder("out")
val out = File(root, "p/1")
val binds = CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals(2, binds.size)
assertFalse(File(out, "cpu2").exists())
assertTrue(binds.none { it.contains("cpufreq") })
}
@Test fun aLevelOutsideTheEmulatedCpuidIsNotGivenASize() {
val host = tmp.newFolder("host")
cache(host, 0, 4 to null)
val root = tmp.newFolder("out")
val out = File(root, "p/1")
assertEquals(emptyList<String>(), CpuCacheSysfs.binds(root, 1, host, "p"))
assertFalse(File(out, "cpu0/index0/size").exists())
}
@Test fun stalePreviousSessionFilesAreRemoved() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
val out = File(root, "p/1")
File(out, "cpu7/index0").mkdirs()
CpuCacheSysfs.binds(root, 1, host, "p")
assertFalse(File(out, "cpu7").exists())
}
@Test fun aLinkLeftInTheStagedFolderIsRemovedWithoutTouchingItsTarget() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val kept = tmp.newFolder("kept")
File(kept, "file").writeText("x")
val root = tmp.newFolder("out")
val out = File(root, "p/1")
File(out, "cpu0").mkdirs()
Files.createSymbolicLink(File(out, "cpu0/link").toPath(), kept.toPath())
CpuCacheSysfs.binds(root, 1, host, "p")
assertFalse(Files.exists(File(out, "cpu0/link").toPath(), LinkOption.NOFOLLOW_LINKS))
assertEquals("x", File(kept, "file").readText())
}
@Test fun anUnreadableHostLeavesNoBinds() {
assertEquals(emptyList<String>(), CpuCacheSysfs.binds(tmp.newFolder("out"), 1, File(tmp.root, "missing"), "p"))
}
@Test fun earlierProcessesAndTheFlatLayoutAreRemoved() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
listOf("cpu0", "7", "old/1").forEach { File(root, "$it/cpu0/index0").mkdirs() }
val binds = CpuCacheSysfs.binds(root, 3, host, "p")
assertEquals(listOf(File(root, "p/3/cpu0").path + ":" + File(host, "cpu0/cache").path), binds)
assertEquals(listOf("p"), root.list()!!.toList())
}
@Test fun aDelayedEarlierStartKeepsTheNewerStartsSources() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
CpuCacheSysfs.binds(root, 2, host, "p")
CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals("512K\n", File(root, "p/2/cpu0/index0/size").readText())
assertEquals("512K\n", File(root, "p/1/cpu0/index0/size").readText())
}
@Test fun aNewerStartKeepsTheEarlierStartsSources() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
CpuCacheSysfs.binds(root, 1, host, "p")
CpuCacheSysfs.binds(root, 2, host, "p")
assertEquals("512K\n", File(root, "p/1/cpu0/index0/size").readText())
assertEquals("512K\n", File(root, "p/2/cpu0/index0/size").readText())
}
@Test fun startsInOneProcessNeverShareAStagingFolder() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
val first = CpuCacheSysfs.binds(root, host = host, process = "p").single().substringBefore(':')
val second = CpuCacheSysfs.binds(root, host = host, process = "p").single().substringBefore(':')
assertTrue(first != second)
assertEquals("512K\n", File(first, "index0/size").readText())
assertEquals("512K\n", File(second, "index0/size").readText())
}
@Test fun aDelayedWorkerFromARecreatedServiceKeepsItsOwnFolder() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
val root = tmp.newFolder("out")
val ready = java.util.concurrent.CountDownLatch(2)
val pool = java.util.concurrent.Executors.newFixedThreadPool(2)
try {
val starts = List(2) {
pool.submit<String> {
ready.countDown()
ready.await()
CpuCacheSysfs.binds(root, host = host, process = "p").single().substringBefore(':')
}
}.map { it.get(10, java.util.concurrent.TimeUnit.SECONDS) }
assertEquals(2, starts.toSet().size)
starts.forEach { assertEquals("512K\n", File(it, "index0/size").readText()) }
} finally {
pool.shutdownNow()
}
}
@Test fun aCoreWhoseMetadataCannotBeCopiedIsSkippedAndTheOthersStayBound() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to null)
cache(host, 1, 2 to null, 4 to "1024K\n")
val locked = File(host, "cpu1/cache/index1/size")
locked.setReadable(false)
assumeFalse(locked.canRead())
val root = tmp.newFolder("out")
val binds = CpuCacheSysfs.binds(root, 1, host, "p")
assertEquals(listOf(File(root, "p/1/cpu0").path + ":" + File(host, "cpu0/cache").path), binds)
}
@Test fun anUnreadableKernelSizeForAnEmulatedLevelIsStillReplaced() {
val host = tmp.newFolder("host")
cache(host, 0, 2 to "12288K\n")
val locked = File(host, "cpu0/cache/index0/size")
locked.setReadable(false)
assumeFalse(locked.canRead())
val root = tmp.newFolder("out")
assertEquals(1, CpuCacheSysfs.binds(root, 1, host, "p").size)
assertEquals("512K\n", File(root, "p/1/cpu0/index0/size").readText())
}
}
@@ -98,6 +98,22 @@ class EnhancedSessionLogShareTest {
SessionLogShare.clear(app)
}
@Test fun aBionicGameLogIsSharedWithTheGamesUnderItsName() {
val session = tmp.newFolder("2026-11-22-09-steam")
session.resolve("session.log").writeText("startup ok\n")
val launch = session.resolve("games/2026-11-22-201105-bionic-341940").apply { mkdirs() }
launch.resolve("droiddeck-bionic.log").writeText("20:11:05 waitforexitandrun Hatred.exe\n")
val games = EnhancedSessionLogShare.create(app, session).single { it.name.endsWith("-games.zip") }
ZipFile(games).use { archive ->
val entry = archive.getEntry("${session.name}/games/2026-11-22-201105-bionic-341940/droiddeck-bionic.log")
assertTrue(entry != null)
assertEquals("20:11:05 waitforexitandrun Hatred.exe\n", archive.getInputStream(entry).bufferedReader().readText())
}
SessionLogShare.clear(app)
}
@Test fun oversizedFilesKeepBoundedBeginningAndTailAndDeclareTruncation() {
val session = tmp.newFolder("2026-11-04-02-game")
session.resolve("steam-7.log").writeText("begin\n" + "middle\n".repeat(100) + "tail\n")
@@ -68,6 +68,19 @@ class ExperimentalProtonsTest {
assertEquals(listOf("pre"), ProtonExtras.assets(tool, releases, true).map { it.tag })
}
@Test
fun bionicBuildsKeepTheirOwnRow() {
val tool = ProtonExtras.tools.first { it.id == ProtonExtras.OWN }
val releases = JSONArray("""
[{"tag_name":"DroidDeck-Proton-11-12.8","prerelease":false,"published_at":"2026-11-14T00:00:00Z","assets":[{"name":"DroidDeck-Proton-11-12.8-aarch64.tar.gz","browser_download_url":"https://example/stable"}]},
{"tag_name":"DroidDeck-Bionic-12.8-r37","prerelease":true,"published_at":"2026-11-19T00:00:00Z","assets":[{"name":"DroidDeck-Bionic-12.8-r37-aarch64.tar.xz","browser_download_url":"https://example/bionic"}]},
{"tag_name":"DroidDeck-Proton-11-12.9-test1","prerelease":true,"published_at":"2026-11-19T01:00:00Z","assets":[{"name":"DroidDeck-Proton-11-12.9-test1-aarch64.tar.xz","browser_download_url":"https://example/test"}]}]
""".trimIndent())
val assets = ProtonExtras.assets(tool, releases, true)
assertEquals(listOf("DroidDeck-Bionic-12.8-r37", "DroidDeck-Proton-11-12.9-test1"), assets.map { it.tag })
assertEquals(listOf("DroidDeck-Proton-11-12.9-test1"), ExperimentalProtons.listed(assets).map { it.tag })
}
@Test
fun markerRoundTripKeepsReleaseTag() {
val dir = File(com.droiddeck.launcher.runtime.LinuxRuntime.rootDir(activity), "root/.local/share/Steam/compatibilitytools.d/Experimental-pre").apply { mkdirs() }
@@ -127,4 +127,90 @@ class ProtonDefaultTest {
assertTrue(games.containsKey("43"))
assertNull(games["43"])
}
@Test
fun anUpdateMovesTheDefaultThatNamesTheReplacedTool() {
val bionic = """
{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7, "live": false,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false},
{"name": "DroidDeck-Proton-11-12.8", "display": "DD", "dir": "DroidDeck-Proton 11-12.8", "valve": false}]}
""".trimIndent()
val parsed = ProtonDefault.parseState(bionic)
val from = setOf("DroidDeck-Bionic-12.8-r30")
// applied default, no request yet
assertEquals(ProtonDefault.Request(100, false, "DroidDeck-Bionic-12.8-r31"),
ProtonDefault.movedDefault(parsed, null, from, "DroidDeck-Bionic-12.8-r31", 100))
// a pending request for the replaced tool wins over the applied default and the new seq is above both
assertEquals(ProtonDefault.Request(51, false, "DroidDeck-Bionic-12.8-r31"),
ProtonDefault.movedDefault(parsed, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r30"), from, "DroidDeck-Bionic-12.8-r31", 3))
// a default on another tool stays as it is
assertNull(ProtonDefault.movedDefault(parsed, ProtonDefault.Request(50, false, "DroidDeck-Proton 11-12.8"), from, "DroidDeck-Bionic-12.8-r31", 100))
assertNull(ProtonDefault.movedDefault(ProtonDefault.parseState(state), null, from, "DroidDeck-Bionic-12.8-r31", 100))
// an applied request (seq not above "applied") no longer decides: the applied default does
assertEquals("DroidDeck-Bionic-12.8-r31",
ProtonDefault.movedDefault(parsed, ProtonDefault.Request(7, false, "DroidDeck-Proton 11-12.8"), from, "DroidDeck-Bionic-12.8-r31", 1)?.dir)
}
@Test
fun aBionicDefaultOnAnotherBuildMovesToTheInstalledOne() {
val r37 = "DroidDeck-Bionic-12.8-r37"
val applied = ProtonDefault.parseState("""{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false},
{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
// the applied default is an older build
assertEquals(ProtonDefault.Request(100, false, r37), ProtonDefault.bionicDefault(applied, null, "DroidDeck-Bionic", r37, 100))
// the guest fell back to its own tool because the requested build was gone: the request still names it
val fallback = ProtonDefault.parseState("""{"default": "droiddeck-proton-arm64", "applied": 50, "source": "fallback",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
assertEquals(ProtonDefault.Request(51, false, r37),
ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r24"), "DroidDeck-Bionic", r37, 3))
// already the installed build, another tool, or a fallback the request did not cause: left as it is
assertNull(ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, r37), "DroidDeck-Bionic", r37, 3))
assertNull(ProtonDefault.bionicDefault(fallback, ProtonDefault.Request(50, false, "DroidDeck-Proton 11-12.8"), "DroidDeck-Bionic", r37, 3))
assertNull(ProtonDefault.bionicDefault(ProtonDefault.parseState(state), null, "DroidDeck-Bionic", r37, 100))
val steam = ProtonDefault.parseState("""{"default": "droiddeck-proton-arm64", "applied": 50, "source": "steam",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
assertNull(ProtonDefault.bionicDefault(steam, ProtonDefault.Request(50, false, "DroidDeck-Bionic-12.8-r24"), "DroidDeck-Bionic", r37, 3))
}
@Test
fun keepingBionicCurrentRewritesTheDefaultAndThePicks() {
val context = RuntimeEnvironment.getApplication()
val d = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").apply { deleteRecursively(); mkdirs() }
File(d, "state.json").writeText("""{"default": "droiddeck-proton-arm64", "applied": 9, "source": "fallback",
"tools": [{"name": "droiddeck-proton-arm64", "display": "Proton ARM64", "dir": "Proton Experimental (ARM64)", "valve": true}]}""")
File(d, "request.json").writeText("""{"seq": 9, "valve": false, "dir": "DroidDeck-Bionic-12.8-r24"}""")
ProtonDefault.requestGame(context, "42", proton("DroidDeck-Bionic-12.8-r29", false))
ProtonDefault.requestGame(context, "43", proton("DroidDeck-Proton 11-12.8", false))
ProtonDefault.requestGame(context, "44", null)
ProtonDefault.keepBionicCurrent(context, "DroidDeck-Bionic", "DroidDeck-Bionic-12.8-r37")
val request = ProtonDefault.parseRequest(File(d, "request.json").readText())
assertEquals("DroidDeck-Bionic-12.8-r37", request?.dir)
assertTrue(request!!.seq > 9)
val games = ProtonDefault.parseGames(File(d, "games.json").readText())
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Bionic-12.8-r37"), games["42"])
assertEquals(ProtonDefault.GameChoice(false, "DroidDeck-Proton 11-12.8"), games["43"])
assertTrue(games.containsKey("44"))
assertNull(games["44"])
val before = File(d, "request.json").readText() + File(d, "games.json").readText()
ProtonDefault.keepBionicCurrent(context, "DroidDeck-Bionic", "DroidDeck-Bionic-12.8-r37")
assertEquals(before, File(d, "request.json").readText() + File(d, "games.json").readText())
}
@Test
fun moveDefaultRewritesTheRequestFile() {
val context = RuntimeEnvironment.getApplication()
val d = File(LinuxRuntime.rootDir(context), "root/.local/share/droiddeck-compat").apply { mkdirs() }
File(d, "state.json").writeText("""{"default": "DroidDeck-Bionic-12.8-r30-Proton", "applied": 7,
"tools": [{"name": "DroidDeck-Bionic-12.8-r30-Proton", "display": "r30", "dir": "DroidDeck-Bionic-12.8-r30", "valve": false}]}""")
File(d, "request.json").delete()
ProtonDefault.moveDefault(context, setOf("DroidDeck-Bionic-12.8-r30"), "DroidDeck-Bionic-12.8-r31")
val written = ProtonDefault.parseRequest(File(d, "request.json").readText())
assertEquals("DroidDeck-Bionic-12.8-r31", written?.dir)
assertFalse(written!!.valve)
assertTrue(written.seq > 7)
val before = File(d, "request.json").readText()
ProtonDefault.moveDefault(context, setOf("DroidDeck-Bionic-12.8-r29"), "DroidDeck-Bionic-12.8-r31")
assertEquals(before, File(d, "request.json").readText())
}
}
@@ -77,8 +77,8 @@ class ProtonExtrasTest {
}
@Test
fun theThreeSourcesInOrder() {
assertEquals(listOf("ge", "cachyos", "droiddeck"), ProtonExtras.tools.map { it.id })
fun theSourcesInOrder() {
assertEquals(listOf("ge", "cachyos", "droiddeck", "bionic"), ProtonExtras.tools.map { it.id })
val droiddeck = tool("droiddeck")
assertEquals("DroidDeck-Proton", droiddeck.name)
assertEquals("DroidDeck-Proton", droiddeck.prefix)
@@ -90,6 +90,29 @@ class ProtonExtrasTest {
assertFalse(tool("cachyos").assetPattern.containsMatchIn("proton-cachyos-11.0-20261005-slr-x86_64.tar.xz"))
}
@Test
fun bionicAndDroidDeckProtonShareTheReleasesButNotTheirArchives() {
val bionic = tool("bionic")
assertEquals("DroidDeck-Bionic", bionic.prefix)
assertEquals("Droid-Deck/DroidDeck-Proton", bionic.repo)
assertTrue(bionic.assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"))
assertFalse(bionic.assetPattern.containsMatchIn("DroidDeck-Proton-11-12.8-aarch64.tar.gz"))
assertFalse(bionic.assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"))
assertFalse(tool("droiddeck").assetPattern.containsMatchIn("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"))
}
@Test
fun bionicTakesItsPrereleaseAndDroidDeckProtonSkipsIt() {
val releases = JSONArray()
.put(release("DroidDeck-Bionic-12.8-r3", asset("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"),
asset("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz"), prerelease = true))
.put(droiddeckRelease("11-12.8"))
val bionic = ProtonExtras.pickAsset(tool("bionic"), releases)!!
assertEquals("DroidDeck-Bionic-12.8-r3-aarch64.tar.xz", bionic.name)
assertTrue(bionic.sha512!!.endsWith("DroidDeck-Bionic-12.8-r3-aarch64.sha512sum"))
assertEquals("DroidDeck-Proton-11-12.8-aarch64.tar.gz", ProtonExtras.pickAsset(tool("droiddeck"), releases)!!.name)
}
@Test
fun theTarballAndItsSha512FileArePicked() {
val picked = ProtonExtras.pickAsset(tool("droiddeck"), JSONArray().put(droiddeckRelease("11-7.5")))!!
@@ -206,6 +229,22 @@ class ProtonExtrasTest {
assertNull(ProtonExtras.update(context, tool("droiddeck")))
}
@Test
fun removingDeletesLinksButNeverWhatTheyPointTo() {
val context = RuntimeEnvironment.getApplication()
val tools = File(LinuxRuntime.rootDir(context), "root/.local/share/Steam/compatibilitytools.d")
val outside = temp.newFolder("outside").apply { File(this, "keep.txt").writeText("x") }
for (name in listOf("DroidDeck-Bionic-12.8-r3", "DroidDeck-Bionic-12.8-r5")) {
val dosdevices = File(installTool(tools, name), "files/default_pfx/dosdevices").apply { mkdirs() }
java.nio.file.Files.createSymbolicLink(File(dosdevices, "z:").toPath(), outside.toPath())
}
ProtonExtras.removeOlder(context, tool("bionic"))
ProtonExtras.remove(context, tool("bionic"), "DroidDeck-Bionic-12.8-r5")
assertFalse(File(tools, "DroidDeck-Bionic-12.8-r3").exists())
assertFalse(File(tools, "DroidDeck-Bionic-12.8-r5").exists())
assertTrue(File(outside, "keep.txt").isFile)
}
@Test
fun removingDeletesOneBuildOrEveryOlderOne() {
val context = RuntimeEnvironment.getApplication()
@@ -168,8 +168,8 @@ class StoreGameSidecarTest {
"if \"%DD_EPIC_PARENT%\"==\"1\" set \"DD_P=1\"",
"if \"%DD_EPIC_PARENT%\"==\"0\" set \"DD_P=\"",
"if defined DD_P set \"SteamAppId=\"",
"if defined DD_P if not exist \"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\" set \"DD_P=\"",
"if defined DD_P set DD_P=\"Z:\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\"",
"if defined DD_P if not exist \"%DD_R%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\" set \"DD_P=\"",
"if defined DD_P set DD_P=\"%DD_R%\\usr\\local\\lib\\droiddeck-epic\\EpicGamesLauncher.exe\"",
)
@Test fun epicTitlesThatCheckTheirParentStartUnderTheStandIn() {
@@ -0,0 +1,93 @@
package com.droiddeck.launcher.stores.gog
import com.droiddeck.launcher.frontend.AddedGames
import com.droiddeck.launcher.session.SecondaryLibrary
import com.droiddeck.launcher.session.SessionPrefs
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [33])
class GogInnoextractTest {
private val app get() = RuntimeEnvironment.getApplication()
@Before @After fun resetStorage() {
SessionPrefs.setDefaultStorageFolder(app, "", "")
SessionPrefs.setGameStorage(app, SessionPrefs.GAME_STORAGE_OFF, "")
}
private fun installer(folder: File, names: List<String>) = names.map { File(folder, it).apply { parentFile?.mkdirs(); writeText("MZ") } }
private fun hostOf(guest: String, binds: List<String>): File? = binds
.map { it.substringBeforeLast(':') to it.substringAfterLast(':') }
.filter { (_, mount) -> guest == mount || guest.startsWith("$mount/") }
.maxByOrNull { it.second.length }
?.let { (host, mount) -> File(host + guest.removePrefix(mount)) }
private fun assertExtractorSeesEveryPart(folder: File, parts: List<String>) {
val files = installer(folder, parts)
val guestDir = AddedGames.guestPath(app, folder)
assertNotNull(guestDir)
val argv = GogInnoextract.argv("$guestDir/${parts.first()}", guestDir!!)
assertEquals("$guestDir/${parts.first()}", argv.last())
assertEquals(guestDir, argv[argv.indexOf("-d") + 1])
assertTrue(argv.contains("--gog"))
val binds = StoreInstallRoot.guestBinds(app)
assertEquals(folder.canonicalFile, hostOf(guestDir, binds)?.canonicalFile)
for (file in files) assertEquals(file.canonicalFile, hostOf("$guestDir/${file.name}", binds)?.canonicalFile)
assertNull(hostOf("$guestDir/${parts.first()}", emptyList()))
}
@Test fun singleFileAndMultiPartInstallersOnAChosenFolderAreVisibleToTheExtractor() {
val drive = File(app.filesDir, "usb/SSD").apply { mkdirs() }
SessionPrefs.setDefaultStorageFolder(app, drive.path, "SSD")
val single = File(drive, "Games/GOG/Single")
assertTrue(AddedGames.guestPath(app, single)!!.startsWith(StoreInstallRoot.GUEST_EXTERNAL + "/"))
assertExtractorSeesEveryPart(single, listOf("setup_1207658930.exe"))
assertExtractorSeesEveryPart(File(drive, "Games/GOG/Multi Part"), listOf("setup_1207658931.exe", "setup_1207658931-1.bin", "setup_1207658931-2.bin"))
}
@Test fun installersOnTheGameStorageCardAreVisibleToTheExtractor() {
val card = File(app.filesDir, "card/steam").apply { mkdirs() }
SessionPrefs.setGameStorage(app, card.path, "Card")
val folder = File(card, "Games/GOG/Multi Part")
assertTrue(SecondaryLibrary.CARD_GUESTS.any { AddedGames.guestPath(app, folder)!!.startsWith("$it/") })
assertExtractorSeesEveryPart(folder, listOf("setup_1207658932.exe", "setup_1207658932-1.bin"))
}
@Test fun anUnpluggedGameStorageCardDoesNotStopAnInternalExtraction() {
SessionPrefs.setGameStorage(app, File(app.filesDir, "unplugged/steam").path, "Card")
val folder = File(StoreInstallRoot.internalRoot(app), "GOG/Internal")
installer(folder, listOf("setup_1207658933.exe"))
val binds = StoreInstallRoot.guestBinds(app)
assertTrue(binds.none { bind -> SecondaryLibrary.CARD_GUESTS.any { bind.endsWith(":$it") } })
assertTrue(AddedGames.guestPath(app, folder)!!.startsWith("/root/Games/Stores/GOG/"))
}
@Test fun anAddedFolderNamedStoresIsMountedWithoutHidingTheInternalInstallRoot() {
val drive = File(app.filesDir, "usb/Stores").apply { mkdirs() }
AddedGames.bindFolder(app, drive)
val guest = AddedGames.guestPath(app, drive)!!
assertTrue(guest != StoreInstallRoot.INTERNAL_GUEST && !guest.startsWith(StoreInstallRoot.INTERNAL_GUEST + "/"))
SessionPrefs.setDefaultStorageFolder(app, drive.path, "Stores")
val chosen = File(drive, "Games/GOG/Chosen")
assertTrue(AddedGames.guestPath(app, chosen)!!.startsWith("$guest/"))
assertExtractorSeesEveryPart(chosen, listOf("setup_1207658934.exe", "setup_1207658934-1.bin"))
val internal = File(StoreInstallRoot.internalRoot(app), "GOG/Internal")
installer(internal, listOf("setup_1207658935.exe"))
val internalGuest = AddedGames.guestPath(app, internal)!!
assertTrue(internalGuest.startsWith(StoreInstallRoot.INTERNAL_GUEST + "/GOG/"))
assertNull(hostOf("$internalGuest/setup_1207658935.exe", StoreInstallRoot.guestBinds(app)))
}
}
@@ -1,10 +1,12 @@
package com.droiddeck.launcher.stores.gog
import com.droiddeck.launcher.stores.StoreInstallRoot
import java.io.File
import java.io.IOException
import java.nio.file.Files
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -83,6 +85,42 @@ class GogInstallerPartsTest {
}
}
private val gib = 1024L * 1024 * 1024
@Test fun anInstallerThatFitsOnlyBeforeExtractionIsRefusedBeforeItDownloads() {
val download = 1_048_576L + 17 * (7 * gib / 2)
val installed = 699 * gib / 10
val free = 944 * gib / 10
assertFalse(StoreInstallRoot.insufficientSpace(download, free))
val needed = GogDownloadManager.installerBytesNeeded(download, installed)
assertEquals(download + installed, needed)
assertTrue(StoreInstallRoot.insufficientSpace(needed, free))
}
@Test fun anInstallerThatFitsWithItsExtractedFilesIsAllowed() {
val download = 1_048_576L + 3_786_407_936L
assertFalse(StoreInstallRoot.insufficientSpace(GogDownloadManager.installerBytesNeeded(download, 6 * gib), 944 * gib / 10))
}
@Test fun anUnknownInstalledSizeKeepsTheDownloadOnlyCheck() {
val download = 1_048_576L + 3_786_407_936L
assertEquals(download, GogDownloadManager.installerBytesNeeded(download, 0L))
assertEquals(download, GogDownloadManager.installerBytesNeeded(download, -1L))
assertEquals(5 * gib, GogDownloadManager.installerBytesNeeded(0L, 5 * gib))
assertEquals(0L, GogDownloadManager.installerBytesNeeded(0L, -1L))
}
@Test fun aPartWithoutASizeStillCountsTheKnownBytesOfTheOthers() {
val parts = listOf(
GogDownloadManager.InstallerPart("u0", "setup.exe", 0L),
GogDownloadManager.InstallerPart("u1", "setup-1.bin", 60 * gib),
)
val needed = GogDownloadManager.installerBytesNeeded(GogDownloadManager.knownPartBytes(parts), 70 * gib)
assertEquals(130 * gib, needed)
assertTrue(StoreInstallRoot.insufficientSpace(needed, 95 * gib))
assertEquals(0L, GogDownloadManager.knownPartBytes(emptyList()))
}
@Test fun anotherPlatformOrNoDownloadsAddsNothing() {
assertEquals(0, GogDownloadManager.installerParts(downloads("""{"installers":[{"os":"linux","manualUrl":"https://example.invalid/x"}]}"""), "1").size)
assertEquals(0, GogDownloadManager.installerParts(downloads("{}"), "1").size)
@@ -105,11 +105,28 @@ class UbisoftTest {
val text = StoreLaunch.launcherText(StoreGameSidecar(Store.UBISOFT, "space-sc", "Splinter Cell", "system/SplinterCell.exe"))
val lines = text.trimEnd().split("\r\n")
assertTrue(lines.contains("if not exist \"%~dp0.droiddeck-ubisoft.json\" goto direct"))
assertTrue(lines.contains("\"Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" \"%~dp0.droiddeck-ubisoft.json\""))
val service = lines.indexOf("\"%DD_R%\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" \"%~dp0.droiddeck-ubisoft.json\"")
assertTrue(service in 0 until lines.indexOf(":direct"))
assertTrue(lines.indexOf("set \"DD_R=Z:\"") in 0 until lines.indexOf("if defined DROIDDECK_GUEST_ROOT set \"DD_R=%DROIDDECK_GUEST_ROOT%\""))
assertTrue(lines.indexOf("if defined DROIDDECK_GUEST_ROOT set \"DD_R=%DROIDDECK_GUEST_ROOT%\"") < service)
assertEquals("\"%~dp0system\\SplinterCell.exe\"", lines.last())
assertTrue(lines.indexOf(":direct") < lines.lastIndex)
}
@Test fun anInstalledGamesOlderLauncherIsRewritten() {
val folder = java.nio.file.Files.createTempDirectory("ubisoft-adopt").toFile()
try {
File(folder, "system").mkdirs()
File(folder, "system/SplinterCell.exe").writeText("exe")
val sidecar = StoreGameSidecar(Store.UBISOFT, "space-sc", "Splinter Cell", "system/SplinterCell.exe", launcher = StoreLaunch.LAUNCHER)
File(folder, StoreLaunch.LAUNCHER).writeText("@echo off\r\nif not exist \"Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe\" goto direct\r\n")
StoreLaunch.adopt(folder, sidecar)
assertEquals(StoreLaunch.launcherText(sidecar), File(folder, StoreLaunch.LAUNCHER).readText())
} finally {
folder.deleteRecursively()
}
}
@Test fun activationPayloadsSurviveTheHexHop() {
val bytes = byteArrayOf(0, 1, 0x7f, -1, -128, 42)
assertEquals("00017fff802a", UbisoftActivation.hex(bytes))
+45
View File
@@ -0,0 +1,45 @@
DroidDeck bionic runtime pack: sources, credits and licences
Built by DroidDeck's CI with tools/bionic-runtime/build.sh (GPL-3.0, like DroidDeck). Exact pins and the
sha256 of every file are in MANIFEST.txt.
Built from source in this pack:
- layer/libVkLayer_FROG_gamescope_wsi_aarch64.so: gamescope's Vulkan WSI layer (Valve Corporation, BSD-2-Clause,
https://github.com/ValveSoftware/gamescope) at the pinned tag with DroidDeck's patches 0117 and 0119
(tools/gamescope/patches), using vkroots by Joshua Ashton (vkroots.h: Apache-2.0 OR MIT,
https://github.com/Joshua-Ashton/vkroots) and the Khronos Vulkan-Headers (Apache-2.0 / MIT).
- preload/libfakeinput.so: DroidDeck's app/src/main/cpp/fakeinput_steam.cpp, taken from WinNative by maxjivi05
(GPL-3.0, https://github.com/WinNative-Emu/WinNative), mmap ring controller input by ribbit384 (WinNative #345).
- preload/libnotag.so, bin/gstag: DroidDeck (GPL-3.0).
- layer/libVkLayer_droiddeck_gpuload.so: DroidDeck's HUD GPU-load Vulkan layer (tools/gpuload, GPL-3.0), built for the
bionic userland.
Taken unchanged from The412Banner's Bannerlator (GPL-3.0, https://github.com/The412Banner/Bannerlator):
- lib/: Android builds of open-source libraries from Bannerlator's base imagefs
(https://github.com/The412Banner/winlator-contents, release base-assets-v1), among them X.Org libX11/libXext/...
and libxcb (MIT/X11), Wayland (MIT), SDL2 (zlib), GStreamer and its plugins, GLib, PulseAudio, GnuTLS, libsndfile,
alsa-lib, libiconv (LGPL-2.1 or later), FreeType (FTL or GPL-2.0), Fontconfig (MIT), libxml2 (MIT), libffi (MIT),
PCRE2 (BSD-3-Clause), zlib (zlib), and FFmpeg 8 libraries (LGPL-2.1 or later) from Bannerlator's ffmpeg8.tzst.
share/X11 and etc/ (fonts, tls) come from the same imagefs.
From The412Banner/Banners-Turnip (https://github.com/The412Banner/Banners-Turnip, release
fastgl-x11egl-mesa-d8cfbe8-r1):
- egl/: Mesa (MIT, https://gitlab.freedesktop.org/mesa/mesa) EGL, GLX and Gallium with Zink at Mesa main d8cfbe82766,
built for the bionic userland with the x11 and wayland platforms (branch fix/fastgl-zink-readback, the
exp/egl-x11-platform recipe that builds Bannerlator's Fast OpenGL set), with libwayland-client (MIT) and libarchive
(BSD-2-Clause); egl/x11egl.json records the build. Newer Mesa brings Zink's kopper front-buffer readback fixes by
Mike Blumenkrantz.
From The412Banner/bionic-vulkan-wrapper (https://github.com/The412Banner/bionic-vulkan-wrapper, release
wayland-adapter-placed-export-r1):
- adapter/libvulkan_wrapper.so: the Wayland adapter Bannerlator ships (branch banner/wayland-wsi-bgra-native) plus
placed-mapping fixes for 32-bit OpenGL / WineD3D (branch banner/wayland-wsi-placed-export), a Mesa tree (MIT) in
the line of Pipetto-crypto's wrapper and leegao's bionic Vulkan wrapper. adapter/adapter.json records the build.
Taken unchanged from DroidDeck-Proton (https://github.com/Droid-Deck/DroidDeck-Proton, release DroidDeck-Proton-11-12.8):
- d7vk/ddraw.dll: D7VK by WinterSnowfall (zlib, https://github.com/WinterSnowfall/d7vk, commit 06656b9e), Direct3D 7
and older on Vulkan, based on DXVK by Philip Rebohle and contributors (zlib, https://github.com/doitsujin/dxvk);
32-bit build from DroidDeck-Proton's CI.
Not in this pack: the bionic DroidDeck-Proton layer (The412Banner/proton-wine releases), GPU drivers, DXVK/VKD3D
and FEX (DroidDeck components).
@@ -0,0 +1,14 @@
{
"file_format_version" : "1.0.0",
"layer" : {
"name": "VK_LAYER_FROG_gamescope_wsi_aarch64",
"type": "GLOBAL",
"api_version": "1.3.221",
"library_path": "./libVkLayer_FROG_gamescope_wsi_aarch64.so",
"implementation_version": "1",
"description": "Gamescope WSI (XWayland Bypass) Layer (aarch64), bionic build",
"functions": { "vkNegotiateLoaderLayerInterfaceVersion": "vkNegotiateLoaderLayerInterfaceVersion" },
"enable_environment": { "ENABLE_GAMESCOPE_WSI": "1" },
"disable_environment": { "DISABLE_GAMESCOPE_WSI": "1" }
}
}
+9
View File
@@ -0,0 +1,9 @@
// glibc's program_invocation_name is __progname in Android's libc (exported, set from argv[0]).
#pragma once
#ifdef __cplusplus
extern "C" char *__progname;
#else
extern char *__progname;
#endif
#define program_invocation_name __progname
#define program_invocation_short_name __progname
+272
View File
@@ -0,0 +1,272 @@
#!/usr/bin/env bash
# Builds DroidDeck's bionic runtime pack: the Android-side (bionic libc) pieces a bionic DroidDeck-Proton layer
# needs inside DroidDeck's gamescope session. The Proton layer itself comes from The412Banner/proton-wine releases;
# GPU drivers, DXVK/VKD3D and FEX stay app options. Binaries target Android 11+ (API 30: the fake-input
# library hooks statx).
#
# usage: NDK=<Android NDK root> tools/bionic-runtime/build.sh <work dir> <out dir>
# host needs: curl git tar zstd python3, wayland-scanner, and the X11/xcb/wayland/glm headers
# (Debian/Ubuntu: libwayland-bin libwayland-dev libx11-dev libx11-xcb-dev libxcb1-dev libxcb-composite0-dev libglm-dev)
set -euo pipefail
HERE=$(cd "$(dirname "$0")" && pwd)
ROOT=$(cd "$HERE/../.." && pwd)
WORK=${1:?usage: build.sh <work dir> <out dir>}
OUT=${2:?usage: build.sh <work dir> <out dir>}
: "${NDK:?set NDK to the Android NDK root}"
API=30
# Pinned inputs (bump together with their sha256).
IMAGEFS_URL=https://github.com/The412Banner/winlator-contents/releases/download/base-assets-v1/imagefs.tar.zst
IMAGEFS_SHA256=7838756e6a05c91afff68f4bf12aa2780f815877753f8dd354e203e99b9caf8a # same pin as Bannerlator app/build.gradle
BL_COMMIT=410c969dfe37ed0c687d6a5ee3327ea21a53e0f8 # The412Banner/Bannerlator
BL_ASSETS=https://raw.githubusercontent.com/The412Banner/Bannerlator/$BL_COMMIT/app/src/main/assets
# The Wayland adapter: Bannerlator's (bionic-vulkan-wrapper banner/wayland-wsi-bgra-native f970b6c) plus the placed-
# mapping fixes 32-bit OpenGL / WineD3D need (branch banner/wayland-wsi-placed-export), from that repository's release.
ADAPTER_URL=https://github.com/The412Banner/bionic-vulkan-wrapper/releases/download/wayland-adapter-placed-export-r1
ADAPTER_SHA256=653791c2c2ea904a5122909f01d26689553e91cc4dc7a981478c1303adc96ea5 # libvulkan_wrapper.so
ADAPTER_JSON_SHA256=5448fd64f15fa13ca3c805967c2b4788eb5f86d29a2d2755e15498130cdef9b3
# OpenGL: the Fast OpenGL Mesa set (EGL + GLX + Zink) rebuilt from Mesa main d8cfbe82766 for Zink's kopper readback
# fixes (Banners-Turnip fix/fastgl-zink-readback e07e94d0, run 44232301491); Bannerlator's copy is the 7cda7850 build.
FASTGL_URL=https://github.com/The412Banner/Banners-Turnip/releases/download/fastgl-x11egl-mesa-d8cfbe8-r1
FFMPEG8_SHA256=34ca9076b6b69bc96ee0d53fcb7b9d0d8df869b9f1255dd686bf89cc590b1b08 # ffmpeg8.tzst
GAMESCOPE_TAG=3.16.29
GAMESCOPE_COMMIT=8f212644c46460549035971ab914421180f61a7c
GAMESCOPE_PATCHES="0117-wsi-cache-present-bypass-check.patch 0119-wsi-default-images-under-limiter.patch"
VULKAN_HEADERS_TAG=v1.4.341
# The bionic DroidDeck-Proton layer the pack is made for: linked against (libwayland-client) and checked against, not packed.
# Layer v16 (067c719d) plus the ARM64EC code-map fix for 39-bit hosts (d4c9ffa7, run 44291095238).
LAYER_URL=https://github.com/The412Banner/proton-wine/releases/download/build-bionic-layers-20261118-v16-unwind/DroidDeck-Proton-11.0-12.8-arm64ec.wcp
LAYER_SHA256=3cc74b877bc8707d75aa2cc22e335373b6a6c0b6b1937c7b3c2cd98e55de2e89 # proton-wine d48e30a1 (a188791d + fecf7376 on d4c9ffa7)
LAYER_VERSION=12.8
# Packed into the DroidDeck-Bionic tool next to the layer: FEX with Android-built unix libraries, and default
# DXVK / VKD3D-Proton (DroidDeck components can swap these in files/lib/wine/{dxvk,vkd3d-proton} later).
FEX_URL=https://github.com/The412Banner/Nightlies/releases/download/FEXCore-2611.1/FEXCore-2611.1-unix.wcp
FEX_SHA256=caca997e5e077feb5d9b7cf0f2c680cd93b442278903e3f3e7b1bd9cd544770c
DXVK_URL=https://github.com/The412Banner/Nightlies/releases/download/Dxvk-gplasync-Linux/dxvk-gplasync-2.4.1-1-pre-reg-linux.wcp
DXVK_SHA256=379b5dcde331de45a5f0ac7775d2c657c9c1510616afb9143ab8cdfbfa8e5342
# VKD3D-Proton from DroidDeck-Components' stable release: the linux-nightly files are replaced as nightlies land.
VKD3D_URL=https://github.com/Droid-Deck/DroidDeck-Components/releases/download/linux-stable/DD-vkd3d-proton-arm64ec-3.1.wcp
VKD3D_SHA256=bd458d8adb08631d7d5da93c51ad02ce224178127d3408ca693b2947bf85bdd0
# D7VK's 32-bit ddraw.dll (PROTON_USE_D7VK): the same file DroidDeck-Proton 11-12.8 ships, built there from
# WinterSnowfall/d7vk; only that file is taken out of the release archive.
D7VK_FROM=https://github.com/Droid-Deck/DroidDeck-Proton/releases/download/DroidDeck-Proton-11-12.8/DroidDeck-Proton-11-12.8-aarch64.tar.gz
D7VK_MEMBER="DroidDeck-Proton 11-12.8/files/lib/wine/d7vk/i386-windows/ddraw.dll"
D7VK_SHA256=aaf28d3dee147fd359d14bb08228f9d21335fb5fec334415e396353a967574aa
D7VK_COMMIT=06656b9e94bf275854e3d83d6426517253937738
case "$(uname -s):$(uname -m)" in
Linux:x86_64) NDK_HOST=linux-x86_64 ;;
Linux:aarch64|Linux:arm64) NDK_HOST=linux-aarch64 ;;
Darwin:arm64) NDK_HOST=darwin-arm64 ;;
Darwin:x86_64) NDK_HOST=darwin-x86_64 ;;
*) echo "unsupported host $(uname -s):$(uname -m)" >&2; exit 1 ;;
esac
TC="$NDK/toolchains/llvm/prebuilt/$NDK_HOST/bin"
[[ -d "$TC" ]] || TC="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin"
CC="$TC/aarch64-linux-android${API}-clang"
CXX="$TC/aarch64-linux-android${API}-clang++"
READELF="$TC/llvm-readelf"
STRIP="$TC/llvm-strip"
[[ -x "$CC" && -x "$CXX" ]] || { echo "no NDK clang under $TC" >&2; exit 1; }
fetch() { # url sha256 dest
curl -fsSL --retry 5 --retry-delay 3 --retry-connrefused -o "$3" "$1"
echo "$2 $3" | sha256sum -c -
}
rm -rf "$WORK"; mkdir -p "$WORK" "$OUT"
PACK="$WORK/droiddeck-bionic-runtime"
mkdir -p "$PACK"/{lib,layer,preload,bin,adapter,share,etc}
echo "== imagefs (Bannerlator base, pinned)"
fetch "$IMAGEFS_URL" "$IMAGEFS_SHA256" "$WORK/imagefs.tar.zst"
mkdir -p "$WORK/imagefs"
tar --zstd -xf "$WORK/imagefs.tar.zst" -C "$WORK/imagefs"
IMG="$WORK/imagefs/usr/lib"
[[ -d "$IMG" ]] || { echo "imagefs has no usr/lib" >&2; exit 1; }
echo "== bionic DroidDeck-Proton layer (pinned; its lib/ is on the library path at run time)"
fetch "$LAYER_URL" "$LAYER_SHA256" "$WORK/layer.wcp"
mkdir -p "$WORK/layer"
tar --zstd -xf "$WORK/layer.wcp" -C "$WORK/layer" lib
LAYERLIB="$WORK/layer/lib"
echo "== Wayland adapter (pinned release)"
fetch "$ADAPTER_URL/libvulkan_wrapper.so" "$ADAPTER_SHA256" "$PACK/adapter/libvulkan_wrapper.so"
fetch "$ADAPTER_URL/adapter.json" "$ADAPTER_JSON_SHA256" "$PACK/adapter/adapter.json"
echo "== Bannerlator assets (pinned): FFmpeg 8"
fetch "$BL_ASSETS/ffmpeg8.tzst" "$FFMPEG8_SHA256" "$WORK/ffmpeg8.tzst"
echo "== D7VK ddraw.dll (DroidDeck-Proton 11-12.8 release, that file only)"
mkdir -p "$PACK/d7vk"
curl -fsSL --retry 5 --retry-delay 3 --retry-connrefused "$D7VK_FROM" | tar -xzO -f - "$D7VK_MEMBER" > "$PACK/d7vk/ddraw.dll"
echo "$D7VK_SHA256 $PACK/d7vk/ddraw.dll" | sha256sum -c -
# OpenGL: bionic Mesa (EGL + GLX + Zink, x11 and wayland platforms) for winex11's EGL backend, the set Bannerlator's
# Fast OpenGL uses, from the newer Mesa build pinned in FASTGL_URL
mkdir -p "$PACK/egl"
for e in libEGL.so.1:7d1febabcb0cb6348128bc44885886fba6a2edc103fcfc91f5f858e460b33fd6 \
libGL.so.1:8de5c26d4de6dcac4dd2605d8742622711adcdb76d9fe5f5848894e439bb3826 \
libGLESv2.so.2:2136442182ed8d724f80b2d69ee89f654694fd84439fdeb14010034c14f57658 \
libgallium-27.0.0-devel.so:392ca9d6d3127b2ac5fc232d25830111c759dc672f437794731fc2778ff0eb34 \
libwayland-client.so:fa49c2f119b84a0cf54669de1706a6bc427bb8a7f147c977328575ccbb920126 \
libarchive.so:eb3b13634bd2c188d71e886f8c690ef32f6b4a2a0e8a7197a7f974b2d341b7ab \
x11egl.json:90c1dcebb746625b81b4cf5335e177a4b7cbe608b359c9be5eaa43d8f0de499b; do
fetch "$FASTGL_URL/${e%%:*}" "${e#*:}" "$PACK/egl/${e%%:*}"
done
cp "$HERE/icd.json" "$PACK/adapter/icd.json"
echo "== libraries from the imagefs"
copy_lib() { # name: copies the file and every link on the way to it, as links (Android's own libraries are skipped)
local name=$1 src=$IMG/$1 target
[[ -e "$src" || -L "$src" ]] || { echo "missing in imagefs: $name" >&2; return 1; }
[[ -L "$src" && "$(readlink "$src")" == /* ]] && return 0
while [[ -L "$src" ]]; do
target=$(readlink "$src")
[[ -e "$PACK/lib/$(basename "$src")" || -L "$PACK/lib/$(basename "$src")" ]] || ln -s "$(basename "$target")" "$PACK/lib/$(basename "$src")"
src="$(dirname "$src")/$target"
done
[[ -e "$PACK/lib/$(basename "$src")" ]] || cp "$src" "$PACK/lib/"
}
grep -v -e '^#' -e '^$' "$HERE/runtime-libs.txt" | while read -r name; do copy_lib "$name"; done
[[ -e "$PACK/lib/libSDL2-2.0.so.0" ]] || ln -s libSDL2-2.0.so "$PACK/lib/libSDL2-2.0.so.0"
mkdir -p "$PACK/lib/gstreamer-1.0"
grep -v -e '^#' -e '^$' "$HERE/gst-plugins.txt" | while read -r p; do cp "$IMG/gstreamer-1.0/libgst$p.so" "$PACK/lib/gstreamer-1.0/"; done
tar --zstd -xf "$WORK/ffmpeg8.tzst" -C "$PACK/lib"
for f in "$PACK"/lib/libav*.so.* "$PACK"/lib/libsw*.so.*; do # soname links for the FFmpeg 8 files
[[ -L "$f" ]] && continue
so=$("$READELF" -d "$f" | sed -n 's/.*(SONAME).*\[\(.*\)\]/\1/p')
[[ -n "$so" && ! -e "$PACK/lib/$so" ]] && ln -s "$(basename "$f")" "$PACK/lib/$so"
done
# GStreamer plugins: add the libraries they need from the imagefs; drop plugins needing something it lacks
python3 "$HERE/check-needed.py" "$READELF" "$PACK" --available "$LAYERLIB" --fill "$IMG" --prune lib/gstreamer-1.0
cp -a "$WORK/imagefs/usr/share/X11" "$PACK/share/"
cp -a "$WORK/imagefs/etc/fonts" "$WORK/imagefs/etc/tls" "$PACK/etc/"
echo "== gamescope $GAMESCOPE_TAG WSI layer (+ DroidDeck patches: $GAMESCOPE_PATCHES)"
GS="$WORK/gamescope"
git clone -q --depth 1 --branch "$GAMESCOPE_TAG" https://github.com/ValveSoftware/gamescope "$GS"
[[ "$(git -C "$GS" rev-parse HEAD)" == "$GAMESCOPE_COMMIT" ]] || { echo "gamescope $GAMESCOPE_TAG is not $GAMESCOPE_COMMIT" >&2; exit 1; }
git -C "$GS" submodule update -q --init --depth 1 subprojects/vkroots || git -C "$GS" submodule update -q --init subprojects/vkroots
for p in $GAMESCOPE_PATCHES; do git -C "$GS" apply "$ROOT/tools/gamescope/patches/$p"; done
git clone -q --depth 1 --branch "$VULKAN_HEADERS_TAG" https://github.com/KhronosGroup/Vulkan-Headers "$WORK/vulkan-headers"
INC="$WORK/inc"; GEN="$WORK/gen"; mkdir -p "$INC" "$GEN"
cp -r "$WORK/vulkan-headers/include/vulkan" "$WORK/vulkan-headers/include/vk_video" "$INC/"
cp -r /usr/include/X11 /usr/include/xcb /usr/include/glm "$INC/"
cp /usr/include/wayland-*.h "$INC/"
for p in gamescope-swapchain gamescope-limiter; do
wayland-scanner client-header "$GS/protocol/$p.xml" "$GEN/$p-client-protocol.h"
wayland-scanner private-code "$GS/protocol/$p.xml" "$GEN/$p-protocol.c"
"$CC" -O2 -fPIC -c -I"$INC" "$GEN/$p-protocol.c" -o "$GEN/$p-protocol.o"
done
LINK=(-L"$PACK/lib" -Wl,-rpath-link,"$PACK/lib" -L"$LAYERLIB" -Wl,-rpath-link,"$LAYERLIB")
"$CXX" -std=c++20 -O2 -fPIC -shared -DWLR_USE_UNSTABLE -D_GNU_SOURCE -include "$HERE/bionic_compat.h" \
-I"$GS/subprojects/vkroots" -I"$GEN" -I"$INC" -I"$GS/layer" -I"$GS/src" \
"$GS/layer/VkLayer_FROG_gamescope_wsi.cpp" "$GEN"/*.o "${LINK[@]}" \
-lwayland-client -lX11-xcb -lX11 -lxcb -lxcb-composite -static-libstdc++ -Wl,--no-undefined \
-o "$PACK/layer/libVkLayer_FROG_gamescope_wsi_aarch64.so"
cp "$HERE/VkLayer_FROG_gamescope_wsi.aarch64.json" "$PACK/layer/"
echo "== DroidDeck GPU-load layer (tools/gpuload), off unless its DroidDeck variables are set"
for l in gpuload; do
"$CC" -std=c11 -shared -fPIC -O2 -Wall -Wno-unused-parameter -Wno-missing-field-initializers -fvisibility=hidden \
-pthread -Wl,-z,defs -include "$HERE/bionic_compat.h" -I"$INC" -I"$ROOT/tools/gpuload/src" \
"$ROOT/tools/gpuload/src/vk_layer_droiddeck_$l.c" -o "$PACK/layer/libVkLayer_droiddeck_$l.so"
done
for j in gpu_load:gpuload; do
sed 's#"library_path": *"[^"]*"#"library_path": "./libVkLayer_droiddeck_'"${j#*:}"'.so"#' \
"$ROOT/tools/gpuload/layer/VK_LAYER_DROIDDECK_${j%%:*}.json" > "$PACK/layer/VK_LAYER_DROIDDECK_${j%%:*}.json"
grep -q '"library_path": "./libVkLayer_droiddeck_' "$PACK/layer/VK_LAYER_DROIDDECK_${j%%:*}.json"
done
echo "== DroidDeck fake input (app/src/main/cpp/fakeinput_steam.cpp), heap-tagging off, window tagger"
"$CXX" -shared -fPIC -O2 -Wall -Wno-attributes -pthread -std=c++17 "$ROOT/app/src/main/cpp/fakeinput_steam.cpp" \
-ldl -static-libstdc++ -o "$PACK/preload/libfakeinput.so"
"$CC" -shared -fPIC -O2 -Wall "$HERE/notag.c" -ldl -o "$PACK/preload/libnotag.so"
"$CC" -shared -fPIC -O2 -Wall "$HERE/execshim.c" -ldl -o "$PACK/preload/libexecshim.so"
"$CC" -shared -fPIC -O2 -Wall -Wextra -fvisibility=hidden "$HERE/steamshm.c" -ldl -o "$PACK/preload/libsteamshm.so"
"$CC" -O2 -Wall "$HERE/gstag.c" -o "$PACK/bin/gstag"
"$STRIP" --strip-unneeded "$PACK/layer/"*.so "$PACK/preload/"*.so "$PACK/bin/gstag"
echo "== every library a pack file needs must be in the pack or on Android"
python3 "$HERE/check-needed.py" "$READELF" "$PACK" --available "$LAYERLIB"
echo "== manifest"
REV=$(git -C "$ROOT" rev-parse --short=8 HEAD)
cp "$HERE/NOTICE" "$PACK/NOTICE"
{
echo "droiddeck-bionic-runtime $REV ($(date -u +%Y-%m-%dT%H:%M:%SZ), Android API $API, NDK $(basename "$NDK"))"
echo "imagefs $IMAGEFS_URL sha256 $IMAGEFS_SHA256"
echo "bannerlator $BL_COMMIT (ffmpeg8.tzst)"
echo "fastgl $FASTGL_URL (egl/: Mesa EGL + GLX + Zink, Mesa main d8cfbe82766)"
echo "adapter $ADAPTER_URL (libvulkan_wrapper.so sha256 $ADAPTER_SHA256)"
echo "layer $LAYER_URL sha256 $LAYER_SHA256 (not packed)"
echo "d7vk $D7VK_COMMIT: i386 ddraw.dll from $D7VK_FROM"
echo "gamescope $GAMESCOPE_TAG $GAMESCOPE_COMMIT + $GAMESCOPE_PATCHES; vkroots $(git -C "$GS/subprojects/vkroots" rev-parse HEAD); Vulkan-Headers $VULKAN_HEADERS_TAG"
echo
(cd "$PACK" && find . -type f ! -name MANIFEST.txt | sort | xargs sha256sum)
} > "$PACK/MANIFEST.txt"
tar --zstd -cf "$OUT/droiddeck-bionic-runtime-$REV.tar.zst" -C "$WORK" droiddeck-bionic-runtime
(cd "$OUT" && sha256sum "droiddeck-bionic-runtime-$REV.tar.zst" > "droiddeck-bionic-runtime-$REV.tar.zst.sha256")
du -sh "$PACK" "$OUT"/*.tar.zst
echo "== DroidDeck-Bionic tool: layer + this pack + FEX + DXVK/VKD3D + tool scripts, in Proton's layout"
NAME="DroidDeck-Bionic-$LAYER_VERSION-r${BUILD_NUMBER:-0}"
T="$WORK/tool/$NAME"
mkdir -p "$T/files" "$T/bionic"
tar --zstd -xf "$WORK/layer.wcp" -C "$T/files" bin lib share prefixPack.txz
mkdir -p "$WORK/pfx" && tar -xJf "$T/files/prefixPack.txz" -C "$WORK/pfx" && rm "$T/files/prefixPack.txz"
mv "$WORK/pfx/.wine" "$T/files/default_pfx"
# No drives in the template: its links point into Winlator, and a Z: -> / link here once let DroidDeck's tool delete
# walk the whole device. launch.sh makes C: and Z: in each game's own prefix.
rm -rf "$T/files/default_pfx/dosdevices"
for c in FEX:"$FEX_URL":"$FEX_SHA256" DXVK:"$DXVK_URL":"$DXVK_SHA256" VKD3D:"$VKD3D_URL":"$VKD3D_SHA256"; do
n=${c%%:*}; rest=${c#*:}; sha=${rest##*:}; url=${rest%:*}
fetch "$url" "$sha" "$WORK/$n.wcp"
mkdir -p "$WORK/$n" && tar --zstd -xf "$WORK/$n.wcp" -C "$WORK/$n"
done
cp "$WORK/FEX/aarch64-unix/"*.so "$T/files/lib/wine/aarch64-unix/"
cp "$WORK/FEX/system32/"*.dll "$T/files/lib/wine/aarch64-windows/"
cp -r "$WORK/DXVK/files/lib/wine/dxvk" "$WORK/VKD3D/files/lib/wine/vkd3d-proton" "$T/files/lib/wine/"
cp -a "$PACK" "$T/files/runtime"
# a spare copy of the tool's FEX for launch.sh, which puts it back if DroidDeck's component check swapped in its
# own FEX (glibc unix libraries) for a game with a per-game FEX choice
mkdir -p "$T/files/runtime/fex/aarch64-unix" "$T/files/runtime/fex/aarch64-windows"
cp "$WORK/FEX/aarch64-unix/"*.so "$T/files/runtime/fex/aarch64-unix/"
cp "$WORK/FEX/system32/"*.dll "$T/files/runtime/fex/aarch64-windows/"
install -m 755 "$HERE/tool/proton" "$T/proton"
install -m 755 "$HERE/tool/launch.sh" "$T/bionic/launch.sh"
cp "$HERE/tool/desktop.reg" "$HERE/tool/Xdefaults" "$T/bionic/"
cp "$HERE/tool/toolmanifest.vdf" "$T/"
# The name Steam registers the tool under ends in -Proton: Steam maps Windows save folders (WinAppDataLocal, WinMyDocuments
# ...) into compatdata/<app>/pfx only for tools whose name contains "proton" (a case-insensitive search in
# steamclient.so's compat manager); without it Steam Cloud skipped every such save rule. The folder, the version file and
# the release keep $NAME, which is what DroidDeck matches on.
sed -e "s/@NAME@/$NAME-Proton/" -e "s/@DISPLAY@/DroidDeck-Bionic $LAYER_VERSION r${BUILD_NUMBER:-0}/" "$HERE/tool/compatibilitytool.vdf.in" > "$T/compatibilitytool.vdf"
echo "$(date -u +%s) $NAME" > "$T/version"
{
echo "$NAME: DroidDeck runtime pack $REV + layer + FEX/DXVK/VKD3D"
echo "fex $FEX_URL sha256 $FEX_SHA256"
echo "dxvk $DXVK_URL sha256 $DXVK_SHA256"
echo "vkd3d $VKD3D_URL sha256 $VKD3D_SHA256"
} > "$T/SOURCES.txt"
python3 "$HERE/check-needed.py" "$READELF" "$T/files" --available "$T/files/lib"
echo "== no link may point out of the tool (DroidDeck deletes old tool folders)"
python3 - "$T" <<'PY'
import os, sys
root = os.path.realpath(sys.argv[1])
bad = []
for d, dirs, files in os.walk(root):
for n in dirs + files:
p = os.path.join(d, n)
if os.path.islink(p):
t = os.path.realpath(p)
if t != root and not t.startswith(root + os.sep):
bad.append("%s -> %s" % (os.path.relpath(p, root), os.readlink(p)))
if bad:
sys.exit("links out of the tool:\n" + "\n".join(bad))
print("no links out of the tool")
PY
tar -C "$WORK/tool" -cf - "$NAME" | xz -T0 -6 > "$OUT/$NAME-aarch64.tar.xz"
(cd "$OUT" && sha512sum "$NAME-aarch64.tar.xz" > "$NAME-aarch64.sha512sum")
du -sh "$T" "$OUT/$NAME-aarch64.tar.xz"
+126
View File
@@ -0,0 +1,126 @@
#!/usr/bin/env python3
"""Checks that every library an ELF file in the bionic runtime pack needs is in the pack, in --available
(the Proton layer's lib/, on the library path at run time) or on Android.
usage: check-needed.py <llvm-readelf> <pack dir> [--available DIR]... [--fill IMAGEFS_LIB] [--prune SUBDIR]
--fill copies missing libraries (and the links on the way to them) from IMAGEFS_LIB into <pack>/lib, repeatedly
--prune deletes ELF files under <pack>/SUBDIR that still miss a library (plugins nothing else links to)
Exits 1 when anything is still missing."""
import argparse
import os
import shutil
import subprocess
import sys
# Android's own libraries (/system/lib64, /apex) the pack may rely on.
ANDROID = {
"libc.so", "libm.so", "libdl.so", "liblog.so", "libz.so", "libandroid.so", "libnativewindow.so", "libsync.so",
"libEGL.so", "libGLESv1_CM.so", "libGLESv2.so", "libGLESv3.so", "libvulkan.so", "libaaudio.so", "libOpenSLES.so",
"libmediandk.so", "libjnigraphics.so", "libcamera2ndk.so", "libbinder_ndk.so", "ld-android.so",
}
# Known gaps, loaded only for features the first version does not cover.
OPTIONAL = {
"libGL.so.1", # OpenGL games; a dangling link in the pinned imagefs
"libodbc.so", # odbc32
}
def elf_files(pack):
for root, _, files in os.walk(pack):
for f in files:
path = os.path.join(root, f)
if os.path.islink(path) or not os.path.isfile(path):
continue
with open(path, "rb") as fh:
if fh.read(4) == b"\x7fELF":
yield path
def needed(readelf, path):
run = subprocess.run([readelf, "-d", path], capture_output=True, text=True)
if run.returncode != 0: # a damaged ELF must fail the check, not pass with no dependencies
raise SystemExit("check-needed: %s -d %s failed (%d): %s" % (readelf, path, run.returncode, run.stderr.strip()))
return [l.split("[", 1)[1].split("]", 1)[0] for l in run.stdout.splitlines() if "(NEEDED)" in l]
def names_in(*dirs):
names = set()
for d in dirs:
for root, _, files in os.walk(d):
# a link whose target is missing provides nothing
names.update(f for f in files if os.path.isfile(os.path.join(root, f)))
return names
def missing_map(readelf, pack, available):
have = names_in(pack, *available)
missing = {}
for path in elf_files(pack):
for lib in needed(readelf, path):
if lib not in have and lib not in ANDROID and lib not in OPTIONAL:
missing.setdefault(lib, []).append(path)
return missing
def copy_from(img, name, dest):
"""Copies img/name into dest, keeping relative links; False when absent or one of Android's (absolute link)."""
src = os.path.join(img, name)
if not os.path.lexists(src):
return False
while os.path.islink(src):
target = os.readlink(src)
if target.startswith("/"):
return False
link = os.path.join(dest, os.path.basename(src))
if not os.path.lexists(link):
os.symlink(os.path.basename(target), link)
src = os.path.join(os.path.dirname(src), target)
if not os.path.exists(src):
return False
out = os.path.join(dest, os.path.basename(src))
if not os.path.exists(out):
shutil.copy2(src, out)
return True
def main():
ap = argparse.ArgumentParser()
ap.add_argument("readelf")
ap.add_argument("pack")
ap.add_argument("--available", action="append", default=[])
ap.add_argument("--fill")
ap.add_argument("--prune")
a = ap.parse_args()
if a.fill:
added = []
while True:
missing = missing_map(a.readelf, a.pack, a.available)
new = [lib for lib in sorted(missing) if copy_from(a.fill, lib, os.path.join(a.pack, "lib"))]
if not new:
break
added += new
print(f"added from the imagefs: {len(added)} ({', '.join(added)})" if added else "added from the imagefs: none")
if a.prune:
prune_root = os.path.join(a.pack, a.prune)
while True:
missing = missing_map(a.readelf, a.pack, a.available)
doomed = {p for users in missing.values() for p in users if p.startswith(prune_root + os.sep)}
if not doomed:
break
for p in sorted(doomed):
libs = sorted(l for l, users in missing.items() if p in users)
print(f"pruned {os.path.relpath(p, a.pack)}: missing {', '.join(libs)}")
os.remove(p)
missing = missing_map(a.readelf, a.pack, a.available)
for lib, users in sorted(missing.items()):
print(f"missing {lib}: needed by {', '.join(sorted(os.path.relpath(u, a.pack) for u in users)[:5])}")
if missing:
sys.exit(1)
print("all needed libraries present")
if __name__ == "__main__":
main()
+235
View File
@@ -0,0 +1,235 @@
// execshim: preloaded into the bionic Wine processes. From targetSdk 29 Android refuses execve() of files in the
// app's data directory, but the system linker still starts them: "/system/bin/linker64 <file> [args]". So an
// execve()/posix_spawn() of a dynamic ELF under /data whose interpreter is /system/bin/linker64 becomes a linker64
// start, and a "#!" script there becomes a start of its interpreter. Static ELFs (wine-preloader) and everything
// else pass through unchanged: where Android refuses them, Wine falls back to its loader, as on any failed exec.
// A program started that way sees /proc/self/exe as linker64; wineserver looks for its NLS files next to its own
// executable (server/unicode.c get_nls_dir), so realpath()/readlink() of /proc/self/exe answer with the program
// linker64 runs (the second /proc/self/cmdline entry).
#define _GNU_SOURCE
#include <dlfcn.h>
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#if __has_include(<spawn.h>)
#include <spawn.h>
#else // old Android headers (e.g. Termux's): bionic's own definitions, both opaque pointers
typedef struct __posix_spawnattr *posix_spawnattr_t;
typedef struct __posix_spawn_file_actions *posix_spawn_file_actions_t;
#endif
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#define LINKER "/system/bin/linker64"
enum kind { PASS, VIA_LINKER, VIA_INTERP };
// What starting `path` needs; for scripts, the interpreter and its optional argument.
static enum kind classify(const char *path, char *resolved, char *interp, char *iarg) {
if (!path || !realpath(path, resolved) || strncmp(resolved, "/data/", 6) != 0) return PASS;
// non-blocking, so a FIFO without a writer cannot hang the start; anything but a regular file goes to libc
int fd = open(resolved, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
if (fd < 0) return PASS;
struct stat st;
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
close(fd);
return PASS;
}
enum kind k = PASS;
unsigned char head[256];
ssize_t n = pread(fd, head, sizeof head, 0);
if (n >= (ssize_t)sizeof(Elf64_Ehdr) && memcmp(head, ELFMAG, SELFMAG) == 0 && head[EI_CLASS] == ELFCLASS64) {
Elf64_Ehdr eh;
memcpy(&eh, head, sizeof eh);
for (int i = 0; i < eh.e_phnum && k == PASS; i++) {
Elf64_Phdr ph;
if (pread(fd, &ph, sizeof ph, (off_t)(eh.e_phoff + (Elf64_Off)i * eh.e_phentsize)) != sizeof ph) break;
if (ph.p_type != PT_INTERP || ph.p_filesz == 0 || ph.p_filesz >= PATH_MAX) continue;
char name[PATH_MAX] = {0};
if (pread(fd, name, ph.p_filesz, (off_t)ph.p_offset) == (ssize_t)ph.p_filesz && strcmp(name, LINKER) == 0)
k = VIA_LINKER;
}
} else if (n > 2 && head[0] == '#' && head[1] == '!') {
char line[256];
size_t len = 0;
for (ssize_t i = 2; i < n && head[i] != '\n' && len < sizeof line - 1; i++) line[len++] = (char)head[i];
line[len] = 0;
char *p = line;
while (*p == ' ' || *p == '\t') p++;
char *end = p;
while (*end && *end != ' ' && *end != '\t') end++;
char *rest = *end ? end + 1 : end;
*end = 0;
while (*rest == ' ' || *rest == '\t') rest++;
size_t rl = strlen(rest);
while (rl && (rest[rl - 1] == ' ' || rest[rl - 1] == '\t' || rest[rl - 1] == '\r')) rest[--rl] = 0;
if (*p) {
strcpy(interp, p);
strcpy(iarg, rest);
k = VIA_INTERP;
}
}
close(fd);
return k;
}
static int argc_of(char *const argv[]) {
int n = 0;
while (argv && argv[n]) n++;
return n;
}
// New argv for the rewritten start; *file is what to start. NULL when nothing changes.
static char **rewrite(const char *path, char *const argv[], const char **file, char *storage) {
char *resolved = storage, *interp = storage + PATH_MAX, *iarg = storage + 2 * PATH_MAX;
enum kind k = classify(path, resolved, interp, iarg);
if (k == PASS) return NULL;
int argc = argc_of(argv);
// up to four leading entries, argc - 1 trailing ones and the terminator (argc may be 0)
char **out = calloc((size_t)(argc > 0 ? argc - 1 : 0) + 5, sizeof *out);
if (!out) return NULL;
int j = 0;
if (k == VIA_LINKER) {
*file = LINKER;
out[j++] = (char *)LINKER;
out[j++] = resolved;
} else {
// the interpreter may itself live in app data
char *iresolved = storage + 3 * PATH_MAX, *x = storage + 4 * PATH_MAX, *y = storage + 5 * PATH_MAX;
if (classify(interp, iresolved, x, y) == VIA_LINKER) {
*file = LINKER;
out[j++] = (char *)LINKER;
out[j++] = iresolved;
} else {
*file = interp;
out[j++] = interp;
}
if (*iarg) out[j++] = iarg;
out[j++] = resolved;
}
for (int i = 1; i < argc; i++) out[j++] = argv[i];
out[j] = NULL;
return out;
}
// libc's functions: bound when the library loads (single-threaded), so execve() in a post-fork child finds them bound.
// A call that comes before that (another library's constructor) binds through an atomic slot: concurrent binders
// store the same pointer, and readers never see a torn one.
typedef ssize_t (*readlink_fn)(const char *, char *, size_t);
typedef char *(*realpath_fn)(const char *, char *);
typedef int (*execve_fn)(const char *, char *const[], char *const[]);
typedef int (*spawn_fn)(pid_t *, const char *, const posix_spawn_file_actions_t *, const posix_spawnattr_t *,
char *const[], char *const[]);
static void *slot_readlink, *slot_realpath, *slot_execve, *slot_spawn, *slot_spawnp;
static void *bound(void **slot, const char *name) {
void *p = __atomic_load_n(slot, __ATOMIC_ACQUIRE);
if (!p) {
p = dlsym(RTLD_NEXT, name);
__atomic_store_n(slot, p, __ATOMIC_RELEASE);
}
return p;
}
#define real_readlink ((readlink_fn)bound(&slot_readlink, "readlink"))
#define real_realpath ((realpath_fn)bound(&slot_realpath, "realpath"))
#define real_execve ((execve_fn)bound(&slot_execve, "execve"))
#define real_spawn ((spawn_fn)bound(&slot_spawn, "posix_spawn"))
#define real_spawnp ((spawn_fn)bound(&slot_spawnp, "posix_spawnp"))
__attribute__((constructor)) static void bind_libc(void) {
(void)real_readlink;
(void)real_realpath;
(void)real_execve;
(void)real_spawn;
(void)real_spawnp;
}
// The program linker64 runs, when this process is such a start; 0 otherwise.
static int linker_program(char *out, size_t n) {
if (!real_readlink) return 0;
char link[PATH_MAX];
ssize_t l = real_readlink("/proc/self/exe", link, sizeof link - 1);
if (l <= 0) return 0;
link[l] = 0;
const char *base = strrchr(link, '/'); // /system/bin/linker64 is a link into /apex/com.android.runtime/bin
if (strcmp(base ? base + 1 : link, "linker64") != 0) return 0;
int fd = open("/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 0;
char buf[2 * PATH_MAX];
ssize_t got = read(fd, buf, sizeof buf - 1);
close(fd);
if (got <= 0) return 0;
buf[got] = 0;
size_t first = strlen(buf);
if ((ssize_t)first + 1 >= got || !buf[first + 1] || strlen(buf + first + 1) >= n) return 0;
strcpy(out, buf + first + 1);
return 1;
}
char *realpath(const char *path, char *resolved) {
if (!real_realpath) {
errno = ENOSYS;
return NULL;
}
char prog[PATH_MAX];
if (path && strcmp(path, "/proc/self/exe") == 0 && linker_program(prog, sizeof prog)) return real_realpath(prog, resolved);
return real_realpath(path, resolved);
}
ssize_t readlink(const char *path, char *buf, size_t size) {
char prog[PATH_MAX], full[PATH_MAX];
if (path && strcmp(path, "/proc/self/exe") == 0 && linker_program(prog, sizeof prog)) {
if (real_realpath && real_realpath(prog, full)) {
size_t l = strlen(full);
if (l > size) l = size;
memcpy(buf, full, l);
return (ssize_t)l;
}
}
if (!real_readlink) {
errno = ENOSYS;
return -1;
}
return real_readlink(path, buf, size);
}
int execve(const char *path, char *const argv[], char *const envp[]) {
execve_fn real = real_execve;
if (!real) {
errno = ENOSYS;
return -1;
}
char storage[6 * PATH_MAX]; // stack only: this may run in posix_spawn's vfork-like child (where it passes)
const char *file = path;
char **args = rewrite(path, argv, &file, storage);
int ret = real(file, args ? args : argv, envp);
int saved = errno;
free(args);
errno = saved;
return ret;
}
int posix_spawn(pid_t *pid, const char *path, const posix_spawn_file_actions_t *actions,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
spawn_fn real = real_spawn;
if (!real) return ENOSYS;
char storage[6 * PATH_MAX];
const char *file = path;
// file actions can change the child's directory before it starts: a relative path is resolved there by libc, so
// it is left to libc instead of being resolved here against the parent's directory
char **args = (actions && path && path[0] != '/') ? NULL : rewrite(path, argv, &file, storage);
int ret = real(pid, file, actions, attr, args ? args : argv, envp);
free(args);
return ret;
}
int posix_spawnp(pid_t *pid, const char *file, const posix_spawn_file_actions_t *actions,
const posix_spawnattr_t *attr, char *const argv[], char *const envp[]) {
if (file && strchr(file, '/')) return posix_spawn(pid, file, actions, attr, argv, envp);
spawn_fn real = real_spawnp;
if (!real) return ENOSYS;
return real(pid, file, actions, attr, argv, envp);
}
+41
View File
@@ -0,0 +1,41 @@
# GStreamer plugins packed for winegstreamer (game video/audio), from the imagefs's lib/gstreamer-1.0 by name
# (libgst<name>.so): Proton's usual set as far as this imagefs has it (no vpx; videoconvert+videoscale are videoconvertscale).
coreelements
app
audioconvert
audiorate
audioresample
ogg
opus
pbtypes
playback
rawparse
subparse
theora
typefindfunctions
videoconvertscale
videorate
volume
vorbis
apetag
audioparsers
autodetect
avi
deinterlace
id3demux
interleave
isomp4
matroska
mpg123
videocrop
videofilter
wavparse
flac
videoparsersbad
libav
asf
dvdsub
mpegpsdemux
mpegtsdemux
jpeg
png
+330
View File
@@ -0,0 +1,330 @@
// gstag: tags top-level X windows whose WM_CLASS contains <match> (any case) with
// STEAM_GAME=<appid>, so gamescope treats a game started outside Steam's process tree
// as the game (stand-in until a bionic winex11 sets STEAM_GAME itself).
// Usage: gstag <display> <appid> <match> <seconds> [stop when this pid exits]
// gamescope publishes focus (GAMESCOPE_FOCUSED_APP) and reads GAMESCOPECTRL_BASELAYER_APPID on its first X server
// (:0, Steam's); with several (DroidDeck: games on :1) those two are read and written there.
// If gamescope still focuses another app 8 s after the tag, it sets GAMESCOPECTRL_BASELAYER_APPID once to
// <appid>,769 (what Steam writes when it shows a game); Steam can change it again later (e.g. the Steam button).
#define _GNU_SOURCE
#include <errno.h>
#include <signal.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
static int fd, tconn = -1, cconn = -1;
static uint16_t tseq, cseq; // sequence number of the last request sent on each connection
static uint8_t rbuf[1 << 16];
static uint32_t pending[256]; static int npending;
static uint32_t tagged[256]; static int ntagged;
static int wr(const void *p, size_t n) {
const uint8_t *b = p;
while (n) { ssize_t k = write(fd, b, n); if (k <= 0) return -1; b += k; n -= (size_t)k; }
return 0;
}
static int rd(void *p, size_t n) {
uint8_t *b = p;
while (n) { ssize_t k = read(fd, b, n); if (k <= 0) return -1; b += k; n -= (size_t)k; }
return 0;
}
static size_t pad4(size_t n) { return (n + 3) & ~(size_t)3; }
// Sends one request on the current connection; its sequence number goes to *seq. 0 when sent.
static int request(const void *p, size_t n, uint16_t *seq) {
if (wr(p, n)) return -1;
uint16_t *last = (fd == cconn && cconn != tconn) ? &cseq : &tseq;
++*last;
if (seq) *seq = *last;
return 0;
}
// Reads one whole packet into rbuf; a reply (or generic event) longer than rbuf ends the connection. 0 when read.
static int packet(void) {
if (rd(rbuf, 32)) return -1;
uint8_t type = rbuf[0] & 0x7f;
if (rbuf[0] == 1 || type == 35) {
uint32_t words = *(uint32_t *)(rbuf + 4);
if (words > (sizeof rbuf - 32) / 4) return -1;
if (words && rd(rbuf + 32, words * 4u)) return -1;
}
return 0;
}
static int known(uint32_t *list, int n, uint32_t w) { for (int i = 0; i < n; i++) if (list[i] == w) return 1; return 0; }
static void forget(uint32_t *list, int *n, uint32_t w) {
for (int i = 0; i < *n; i++)
if (list[i] == w) { list[i] = list[--*n]; return; }
}
static void note_event(const uint8_t *e) {
uint8_t type = e[0] & 0x7f;
uint32_t win = *(uint32_t *)(e + 8);
if (type == 17) { // DestroyNotify: a destroyed window is neither a candidate nor a tagged game window
forget(pending, &npending, win);
forget(tagged, &ntagged, win);
return;
}
if (type != 16 && type != 19) return; // CreateNotify, MapNotify
if (win && !known(tagged, ntagged, win) && !known(pending, npending, win) && npending < 256) pending[npending++] = win;
}
// Reads until the answer to request `seq`. Returns 1 reply, 0 error, -1 io. Events are noted; errors of requests
// without a reply (a ChangeProperty on a window that is gone) and other stale packets are skipped.
static int reply(uint16_t seq) {
for (;;) {
if (packet()) return -1;
if (rbuf[0] > 1) { note_event(rbuf); continue; }
if (*(uint16_t *)(rbuf + 2) != seq) continue;
return rbuf[0] == 1;
}
}
static uint32_t intern(const char *name) {
size_t n = strlen(name);
uint8_t req[256] = {0};
req[0] = 16;
*(uint16_t *)(req + 2) = (uint16_t)(2 + pad4(n) / 4);
*(uint16_t *)(req + 4) = (uint16_t)n;
memcpy(req + 8, name, n);
uint16_t seq;
if (request(req, 8 + pad4(n), &seq)) return 0;
return reply(seq) == 1 ? *(uint32_t *)(rbuf + 8) : 0;
}
// WM_CLASS of a window into out (both strings joined by '|'); 0 if none.
static int wm_class(uint32_t win, char *out, size_t cap) {
uint8_t req[24] = {0};
req[0] = 20;
*(uint16_t *)(req + 2) = 6;
*(uint32_t *)(req + 4) = win;
*(uint32_t *)(req + 8) = 67; // WM_CLASS
*(uint32_t *)(req + 12) = 31; // STRING
*(uint32_t *)(req + 20) = 64;
uint16_t seq;
if (request(req, sizeof req, &seq) || reply(seq) != 1) return 0;
uint32_t n = *(uint32_t *)(rbuf + 16);
if (!n || n >= cap) return 0;
for (uint32_t i = 0; i < n; i++) out[i] = rbuf[32 + i] ? (char)rbuf[32 + i] : '|';
out[n] = 0;
return 1;
}
static void set_cards(uint32_t win, uint32_t prop, const uint32_t *values, uint32_t n) {
uint8_t req[24 + 4 * 8] = {0};
if (n > 8) n = 8;
req[0] = 18;
*(uint16_t *)(req + 2) = (uint16_t)(6 + n);
*(uint32_t *)(req + 4) = win;
*(uint32_t *)(req + 8) = prop;
*(uint32_t *)(req + 12) = 6; // CARDINAL
req[16] = 32;
*(uint32_t *)(req + 20) = n;
memcpy(req + 24, values, 4 * n);
request(req, 24 + 4 * n, NULL);
}
// First CARDINAL of a root property into *value (0 when unset). 0 when the property could not be read.
static int first_card(uint32_t root, uint32_t prop, uint32_t *value) {
uint8_t gp[24] = {20, 0, 6, 0};
uint16_t seq;
*(uint32_t *)(gp + 4) = root;
*(uint32_t *)(gp + 8) = prop;
*(uint32_t *)(gp + 20) = 64;
if (request(gp, sizeof gp, &seq) || reply(seq) != 1) return 0;
*value = *(uint32_t *)(rbuf + 16) ? *(uint32_t *)(rbuf + 32) : 0;
return 1;
}
// 1 when the window still exists (GetWindowAttributes answers), 0 when it is gone, -1 on an io failure.
static int alive(uint32_t win) {
uint8_t ga[8] = {3, 0, 2, 0};
uint16_t seq;
*(uint32_t *)(ga + 4) = win;
if (request(ga, sizeof ga, &seq)) return -1;
return reply(seq);
}
static void set_card(uint32_t win, uint32_t prop, uint32_t value) {
uint8_t req[28] = {0};
req[0] = 18;
*(uint16_t *)(req + 2) = 7;
*(uint32_t *)(req + 4) = win;
*(uint32_t *)(req + 8) = prop;
*(uint32_t *)(req + 12) = 6; // CARDINAL
req[16] = 32;
*(uint32_t *)(req + 20) = 1;
*(uint32_t *)(req + 24) = value;
request(req, sizeof req, NULL);
}
// Connects to display :<disp> (abstract socket) and returns the socket, its root window in *root; -1 on failure.
static int x_connect(int disp, uint32_t *root) {
struct sockaddr_un sa = {.sun_family = AF_UNIX};
int n = snprintf(sa.sun_path + 1, sizeof sa.sun_path - 1, "/tmp/.X11-unix/X%d", disp);
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (connect(fd, (struct sockaddr *)&sa, (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + n))) {
printf("gstag: connect to :%d failed: %s\n", disp, strerror(errno)); close(fd); return -1;
}
uint8_t setup[12] = {'l', 0, 11, 0};
if (wr(setup, sizeof setup) || rd(rbuf, 8)) { close(fd); return -1; }
uint32_t extra = *(uint16_t *)(rbuf + 6) * 4u;
if (extra > sizeof rbuf - 8 || rd(rbuf + 8, extra) || rbuf[0] != 1) { printf("gstag: :%d refused\n", disp); close(fd); return -1; }
uint8_t *d = rbuf + 8;
uint16_t vlen = *(uint16_t *)(d + 16);
uint8_t nformats = d[21];
*root = *(uint32_t *)(d + 32 + pad4(vlen) + 8u * nformats);
return fd;
}
int main(int argc, char **argv) {
if (argc < 5) { fprintf(stderr, "usage: %s <display> <appid> <match> <seconds> [pid]\n", argv[0]); return 2; }
setvbuf(stdout, NULL, _IONBF, 0);
int disp = atoi(argv[1]);
uint32_t appid = (uint32_t)strtoul(argv[2], NULL, 10);
const char *match = argv[3];
int seconds = atoi(argv[4]);
pid_t watch = argc > 5 ? (pid_t)atoi(argv[5]) : 0;
uint32_t root, croot;
int tfd = x_connect(disp, &root), cfd = tfd;
if (tfd < 0) return 3;
croot = root;
if (disp != 0) {
int c = x_connect(0, &croot);
if (c >= 0) cfd = c;
else croot = root;
}
tconn = tfd;
cconn = cfd;
fd = tfd;
uint32_t a_game = intern("STEAM_GAME");
uint8_t cwa[16] = {2, 0, 4, 0}; // ChangeWindowAttributes(root, CWEventMask=SubstructureNotify)
*(uint32_t *)(cwa + 4) = root;
*(uint32_t *)(cwa + 8) = 0x800;
*(uint32_t *)(cwa + 12) = 0x80000;
request(cwa, sizeof cwa, NULL);
uint8_t qt[8] = {15, 0, 2, 0}; // QueryTree(root): windows that exist already
uint16_t qseq;
*(uint32_t *)(qt + 4) = root;
if (request(qt, sizeof qt, &qseq) == 0 && reply(qseq) == 1) {
uint16_t nk = *(uint16_t *)(rbuf + 16);
uint32_t kids[1024];
if (nk > 1024) nk = 1024;
memcpy(kids, rbuf + 32, nk * 4u);
for (int i = 0; i < nk && npending < 256; i++) pending[npending++] = kids[i];
}
printf("gstag: watching display %d for WM_CLASS ~ \"%s\" -> STEAM_GAME=%u\n", disp, match, appid);
fd = cfd; // atoms belong to the server they are interned on
uint32_t a_apps = intern("GAMESCOPE_FOCUSABLE_APPS");
uint32_t a_focus = intern("GAMESCOPE_FOCUSED_APP");
uint32_t a_ctrl = intern("GAMESCOPECTRL_BASELAYER_APPID");
fd = tfd;
time_t tagged_at = 0; int focus_checked = 0, focus_reads = 0;
time_t end = time(NULL) + seconds, next_status = time(NULL) + 3;
while (time(NULL) < end) {
if (time(NULL) >= next_status) {
next_status = time(NULL) + 5;
printf("status:");
uint32_t props[3] = {a_apps, a_focus, a_ctrl};
const char *names[3] = {"focusable", "focused", "baselayer"};
fd = cfd;
for (int k = 0; k < 3; k++) {
uint8_t gp[24] = {20, 0, 6, 0};
*(uint32_t *)(gp + 4) = croot;
*(uint32_t *)(gp + 8) = props[k];
*(uint32_t *)(gp + 20) = 64;
uint16_t gseq;
if (request(gp, sizeof gp, &gseq) == 0 && reply(gseq) == 1) {
uint32_t cnt = *(uint32_t *)(rbuf + 16);
printf(" %s=[", names[k]);
for (uint32_t i = 0; i < cnt && i < 16; i++) printf("%s%u", i ? "," : "", ((uint32_t *)(rbuf + 32))[i]);
printf("]");
}
}
fd = tfd;
for (int i = 0; i < ntagged; i++) {
uint8_t ga[8] = {3, 0, 2, 0}; // GetWindowAttributes
uint16_t aseq, gseq;
*(uint32_t *)(ga + 4) = tagged[i];
int map = -1, ovr = -1, w = -1, h = -1;
if (request(ga, sizeof ga, &aseq) == 0 && reply(aseq) == 1) { map = rbuf[26]; ovr = rbuf[27]; }
uint8_t gg[8] = {14, 0, 2, 0}; // GetGeometry
*(uint32_t *)(gg + 4) = tagged[i];
if (request(gg, sizeof gg, &gseq) == 0 && reply(gseq) == 1) { w = *(uint16_t *)(rbuf + 16); h = *(uint16_t *)(rbuf + 18); }
printf(" win0x%x=%dx%d map%d ovr%d", tagged[i], w, h, map, ovr);
}
printf("\n");
}
if (tagged_at && !focus_checked && time(NULL) - tagged_at >= 8) {
// the override is only for a game that still has a window: a tagged window that was destroyed is gone
// from `tagged` (DestroyNotify), and one that is left must still answer
int live = 0;
for (int i = 0; i < ntagged && !live; i++) live = alive(tagged[i]) == 1;
uint32_t f = 0;
fd = cfd;
int read_ok = live && first_card(croot, a_focus, &f);
fd = tfd;
if (!live) {
focus_checked = 1;
printf("gstag: no tagged window left 8 s after the tag; focus left as it is\n");
} else if (!read_ok) {
// a failed read says nothing about who has focus: try again on the next pass, a few times
if (++focus_reads >= 3) { focus_checked = 1; printf("gstag: focus could not be read; left as it is\n"); }
} else {
focus_checked = 1;
if (f != appid) {
uint32_t ids[2] = {appid, 769};
fd = cfd;
set_cards(croot, a_ctrl, ids, 2);
fd = tfd;
printf("gstag: focus was %u, not %u, 8 s after the tag; set GAMESCOPECTRL_BASELAYER_APPID=%u,769\n", f, appid, appid);
} else printf("gstag: %u has focus\n", appid);
}
}
if (watch && kill(watch, 0) != 0 && errno == ESRCH) { printf("gstag: pid %d gone, stopping\n", watch); break; }
for (int i = 0; i < npending; ) {
char cls[512];
uint32_t w = pending[i];
if (wm_class(w, cls, sizeof cls) && strcasestr(cls, match)) {
set_card(w, a_game, appid);
if (ntagged < 256) tagged[ntagged++] = w;
if (!tagged_at) tagged_at = time(NULL);
printf("gstag: tagged window 0x%x (%s)\n", w, cls);
pending[i] = pending[--npending];
} else i++;
}
fd_set rs; FD_ZERO(&rs); FD_SET(fd, &rs);
struct timeval tv = {0, 500000};
if (select(fd + 1, &rs, NULL, NULL, &tv) > 0) {
if (packet()) { printf("gstag: connection closed or a packet too long\n"); break; }
if (rbuf[0] > 1) note_event(rbuf); // replies and errors here belong to no request waiting
}
if (npending > 200) {
// drop only windows that are gone; live candidates may still get WM_CLASS
for (int i = 0; i < npending; ) {
int a = alive(pending[i]);
if (a < 0) break;
if (a == 0) pending[i] = pending[--npending];
else i++;
}
if (npending > 200) { // still too many: keep the newest
memmove(pending, pending + (npending - 200), 200 * sizeof *pending);
npending = 200;
}
}
}
printf("gstag: done, %d window(s) tagged\n", ntagged);
return 0;
}
+4
View File
@@ -0,0 +1,4 @@
{
"file_format_version": "1.0.0",
"ICD": { "library_path": "./libvulkan_wrapper.so", "api_version": "1.3.0" }
}
+11
View File
@@ -0,0 +1,11 @@
// Turns off Android's heap pointer tagging (TBI) in the bionic Wine processes it is preloaded into.
// Wine/FEX paths can hand free() a pointer whose top byte was dropped; with tagging on, bionic aborts
// ("Pointer tag for 0x... was truncated"). Going from TBI to none at run time is allowed by bionic.
// mallopt is looked up at run time, so the file builds with any NDK API level.
#include <dlfcn.h>
#define M_BIONIC_SET_HEAP_TAGGING_LEVEL_OPT (-204)
#define M_HEAP_TAGGING_LEVEL_NONE_VAL 0
__attribute__((constructor(101))) static void ddbionic_notag(void) {
int (*mallopt_fn)(int, int) = (int (*)(int, int))dlsym(RTLD_DEFAULT, "mallopt");
if (mallopt_fn) mallopt_fn(M_BIONIC_SET_HEAP_TAGGING_LEVEL_OPT, M_HEAP_TAGGING_LEVEL_NONE_VAL);
}
+78
View File
@@ -0,0 +1,78 @@
# Android (bionic) libraries the bionic DroidDeck-Proton layer needs from Bannerlator's base imagefs (usr/lib), by name.
# Made 2026-11-16 from the NEEDED closure of layer v16 (proton-wine 067c719d) lib/wine/aarch64-unix + bin, plus the
# libraries Wine opens by name (strings of its unix modules), the Wayland adapter and the gamescope WSI layer.
# libGL.so.1 is left out: it is a dangling link in this imagefs (OpenGL games are not covered yet).
libSDL2.so
libX11-xcb.so
libX11-xcb.so.1
libX11.so
libX11.so.6
libXau.so.6
libXcursor.so
libXext.so
libXext.so.6
libXfixes.so
libXfixes.so.3
libXi.so
libXrandr.so
libXrender.so
libXrender.so.1
libadrenotools.so
libandroid-support.so
libandroid-sysv-semaphore.so
libandroid-sysvshm.so
libasound.so
libbrotlicommon.so.1
libbrotlidec.so.1
libbz2.so.1.0
libc++_shared.so
libexpat.so.1
libffi.so
libfile_redirect_hook.so
libfontconfig.so
libfreetype.so
libfreetype.so.6
libgio-2.0.so.0
libglib-2.0.so.0
libgmodule-2.0.so.0
libgmp.so
libgmp.so.10
libgnutls.so
libgobject-2.0.so.0
libgsl_alloc_hook.so
libgstapp-1.0.so
libgstaudio-1.0.so
libgstbase-1.0.so
libgstbase-1.0.so.0
libgstgl-1.0.so
libgstreamer-1.0.so
libgstreamer-1.0.so.0
libgsttag-1.0.so
libgsttag-1.0.so.0
libgstvideo-1.0.so
libgstvideo-1.0.so.0
libhogweed.so.6
libhook_impl.so
libiconv.so
libidn2.so.0
libmain_hook.so
libnettle.so.8
libpcre2-8.so.0
libpng16.so
libpulse.so
libpulsecommon-13.0.so
libsndfile.so
libunistring.so
libvulkan.so.1
libxcb-composite.so
libxcb-composite.so.0
libxcb-dri3.so
libxcb-present.so
libxcb-randr.so
libxcb-shm.so
libxcb-sync.so
libxcb.so
libxcb.so.1
libxml2.so.16
libz.so
libz.so.1
+549
View File
@@ -0,0 +1,549 @@
// Valve's Android libsteamclient keeps its named shared memory ("/u<uid>-Shm_<crc>" streams and the
// "/u<uid>-ValveIPCSharedObj-Steam" object that holds the named locks and events) in a table inside the process, so
// the Steam Input data DroidDeck's Linux Steam publishes in /dev/shm never reaches a game on DroidDeck-Bionic. Once
// that library is loaded, this preload makes it use the files the Linux client uses: DROIDDECK_BIONIC_SHM_DIR
// (DroidDeck's /dev/shm) under Steam's user id. DROIDDECK_BIONIC_STEAMSHM=0 turns it off.
// The library's thread semaphores come from sem_open with a per-object name ("%p"), which Android's libc does not
// implement (it always fails), so this preload also gives sem_open/sem_close a table of in-process semaphores.
#define _GNU_SOURCE
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <link.h>
#include <pthread.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <semaphore.h>
#include <sys/auxv.h>
#include <sys/mman.h>
#include <sys/syscall.h>
#include <unistd.h>
#define EXPORT __attribute__((visibility("default")))
typedef int (*shm_open_fn)(const char *name, size_t size, bool *created);
typedef void (*shm_unlink_fn)(const char *name);
static shm_open_fn orig_open;
static shm_unlink_fn orig_unlink;
static char shm_dir[PATH_MAX];
static char steam_uid[16];
static int notes;
static void say(const char *fmt, ...)
{
char b[600];
va_list a;
va_start(a, fmt);
int n = vsnprintf(b, sizeof b, fmt, a);
va_end(a);
if (n > 0) write(2, b, n < (int)sizeof b ? (size_t)n : sizeof b - 1);
}
// "/u<digits>-Shm_<hex>" or "/u<digits>-ValveIPCSharedObj-Steam": the part after the uid, else NULL.
static const char *shared_part(const char *name)
{
if (!name || name[0] != '/' || name[1] != 'u') return NULL;
const char *p = name + 2;
while (*p >= '0' && *p <= '9') p++;
if (p == name + 2 || *p != '-') return NULL;
if (!strcmp(p + 1, "ValveIPCSharedObj-Steam")) return p + 1;
const char *h = p + 5;
if (strncmp(p + 1, "Shm_", 4)) return NULL;
while ((*h >= '0' && *h <= '9') || (*h >= 'a' && *h <= 'f')) h++;
return h > p + 5 && h <= p + 13 && !*h ? p + 1 : NULL;
}
// The uid Steam put in its IPC object's name (DroidDeck's Linux side reports 0).
static const char *uid_of_steam(void)
{
if (steam_uid[0]) return steam_uid;
DIR *d = opendir(shm_dir);
struct dirent *e;
while (d && (e = readdir(d))) {
const char *n = e->d_name, *p = n + 1;
if (n[0] != 'u') continue;
while (*p >= '0' && *p <= '9') p++;
if (p > n + 1 && p - n - 1 < (long)sizeof steam_uid && !strcmp(p, "-ValveIPCSharedObj-Steam")) {
memcpy(steam_uid, n + 1, (size_t)(p - n - 1));
steam_uid[p - n - 1] = 0;
break;
}
}
if (d) closedir(d);
if (!steam_uid[0]) return "0";
return steam_uid;
}
static bool real_path(const char *part, char *out, size_t n)
{
int w = snprintf(out, n, "%s/u%s-%s", shm_dir, uid_of_steam(), part);
return w > 0 && (size_t)w < n;
}
static int hook_open(const char *name, size_t size, bool *created)
{
const char *part = shared_part(name);
char path[PATH_MAX];
if (!part || !real_path(part, path, sizeof path)) return orig_open(name, size, created);
for (int i = 0; i < 4; i++) {
int fd = open(path, O_RDWR | O_CLOEXEC);
if (fd >= 0) {
if (notes++ < 64) say("steamshm: %s opened (%zu bytes)\n", path, size);
return fd;
}
if (errno != ENOENT) break;
// made and sized under a private name, then put in place in one step: no other process can open it while it
// is still empty, and an object another process published first is opened instead
char tmp[PATH_MAX];
int w = snprintf(tmp, sizeof tmp, "%s.%d.%d", path, (int)getpid(), i);
if (w <= 0 || (size_t)w >= sizeof tmp) break;
fd = open(tmp, O_RDWR | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
if (fd < 0) break;
if (ftruncate(fd, (off_t)size) != 0) {
close(fd);
unlink(tmp);
break;
}
int placed = (int)syscall(SYS_renameat2, AT_FDCWD, tmp, AT_FDCWD, path, 1 /* RENAME_NOREPLACE */);
if (placed != 0 && (errno == ENOSYS || errno == EINVAL)) { // no renameat2: a hard link fails on EEXIST too
placed = link(tmp, path);
unlink(tmp);
}
if (placed == 0) {
if (created) *created = true;
if (notes++ < 64) say("steamshm: %s created (%zu bytes)\n", path, size);
return fd;
}
int err = errno;
close(fd);
unlink(tmp);
errno = err;
if (err != EEXIST) break;
}
say("steamshm: %s failed (errno %d)\n", path, errno);
return -1;
}
static void hook_unlink(const char *name)
{
const char *part = shared_part(name);
char path[PATH_MAX];
// Steam's IPC object belongs to Steam: never removed from a game
if (!part || !strncmp(part, "Valve", 5) || !real_path(part, path, sizeof path)) {
orig_unlink(name);
return;
}
if (unlink(path) == 0 && notes++ < 64) say("steamshm: %s removed\n", path);
}
struct object {
uintptr_t base;
uintptr_t lo[8], hi[8];
bool exec[8];
int n;
};
static int find_object(struct dl_phdr_info *info, size_t size, void *data)
{
(void)size;
struct object *o = data;
const char *n = info->dlpi_name;
size_t l = n ? strlen(n) : 0;
if (l < 18 || strcmp(n + l - 18, "/libsteamclient.so")) return 0;
o->base = info->dlpi_addr;
o->n = 0;
for (int i = 0; i < info->dlpi_phnum && o->n < 8; i++) {
const ElfW(Phdr) *p = &info->dlpi_phdr[i];
if (p->p_type != PT_LOAD) continue;
o->lo[o->n] = info->dlpi_addr + p->p_vaddr;
o->hi[o->n] = o->lo[o->n] + p->p_memsz;
o->exec[o->n] = (p->p_flags & PF_X) != 0;
o->n++;
}
return 1;
}
static bool readable(const struct object *o, uintptr_t a, size_t n)
{
for (int i = 0; i < o->n; i++)
if (a >= o->lo[i] && a + n <= o->hi[i]) return true;
return false;
}
static int64_t sext(uint64_t v, int bits)
{
return (int64_t)(v << (64 - bits)) >> (64 - bits);
}
// adrp xd at w[0] and add xd, xd, #imm at w[1]: the address they form, or 0.
static uintptr_t adrp_add(const uint32_t *w, int reg)
{
if ((w[0] & 0x9f000000) != 0x90000000 || (int)(w[0] & 31) != reg) return 0;
if ((w[1] & 0xffc00000) != 0x91000000 || (int)(w[1] & 31) != reg || (int)((w[1] >> 5) & 31) != reg) return 0;
uint64_t imm = ((uint64_t)((w[0] >> 5) & 0x7ffff) << 2) | ((w[0] >> 29) & 3);
uintptr_t page = ((uintptr_t)w & ~(uintptr_t)0xfff) + (uintptr_t)(sext(imm, 21) << 12);
return page + ((w[1] >> 10) & 0xfff);
}
static uintptr_t bl_target(const uint32_t *w)
{
if ((w[0] & 0xfc000000) != 0x94000000) return 0;
return (uintptr_t)w + (uintptr_t)(sext(w[0] & 0x3ffffff, 26) << 2);
}
// The first four instructions get copied into a trampoline: none may depend on the pc.
static bool relocatable(const uint32_t *w)
{
for (int i = 0; i < 4; i++) {
uint32_t x = w[i];
if ((x & 0x1f000000) == 0x10000000 || (x & 0x7c000000) == 0x14000000 || (x & 0xff000010) == 0x54000000 ||
(x & 0x7e000000) == 0x34000000 || (x & 0x7e000000) == 0x36000000 || (x & 0x3b000000) == 0x18000000)
return false;
}
return true;
}
// Back from w to the frame setup: stp x29, x30, [sp, #-N]!, or sub sp, sp, #N then stp x29, x30, [sp, #M].
static uint32_t *function_start(const struct object *o, uint32_t *w)
{
for (int i = 0; i < 256; i++, w--) {
if (!readable(o, (uintptr_t)w - 4, 8)) return NULL;
if ((*w & 0xffc07fff) == 0xa9807bfd) return w;
if ((*w & 0xffc07fff) == 0xa9007bfd) return (w[-1] & 0xff8003ff) == 0xd10003ff ? w - 1 : NULL;
}
return NULL;
}
// open(".", O_TMPFILE | O_RDWR, 0777) in the library's shared-memory open: its only nameless file.
static uint32_t *find_shm_open(const struct object *o)
{
uint32_t *found = NULL;
for (int s = 0; s < o->n; s++) {
if (!o->exec[s]) continue;
for (uint32_t *w = (uint32_t *)o->lo[s]; (uintptr_t)(w + 6) <= o->hi[s]; w++) {
if (w[0] != 0x52880041 || w[3] != 0x72a00801 || w[4] != 0x52803fe2 || !bl_target(w + 5)) continue;
uintptr_t str = adrp_add(w + 1, 0);
if (!str || !readable(o, str, 2) || memcmp((const char *)str, ".", 2)) continue;
if (found) return NULL;
found = w;
}
}
return found ? function_start(o, found) : NULL;
}
static const char *find_string(const struct object *o, const char *s)
{
size_t n = strlen(s) + 1;
for (int i = 0; i < o->n; i++) {
const char *p = memmem((const void *)o->lo[i], o->hi[i] - o->lo[i], s, n);
if (p) return p;
}
return NULL;
}
// CSharedMemory::Open: snprintf of "/u%d-Shm_%x", a call to the unlink with that name, then the open.
static uint32_t *find_shm_unlink(const struct object *o, uintptr_t open_fn)
{
const char *fmt = find_string(o, "/u%d-Shm_%x");
uint32_t *found = NULL;
if (!fmt) return NULL;
for (int s = 0; s < o->n; s++) {
if (!o->exec[s]) continue;
for (uint32_t *w = (uint32_t *)o->lo[s]; (uintptr_t)(w + 64) <= o->hi[s]; w++) {
if ((w[0] & 0x9f000000) != 0x90000000 || adrp_add(w, (int)(w[0] & 31)) != (uintptr_t)fmt) continue;
uint32_t *p = w + 2, *end = w + 12;
while (p < end && !bl_target(p)) p++; // snprintf
if (p == end) continue;
uint32_t *u = p + 1;
end = p + 5;
while (u < end && !bl_target(u)) u++;
if (u == end) continue;
bool opens = false;
for (uint32_t *q = u + 1; q < u + 48; q++)
if (bl_target(q) == open_fn) opens = true;
if (!opens) continue;
uint32_t *fn = (uint32_t *)bl_target(u);
if (found && found != fn) return NULL;
found = fn;
}
}
return found;
}
static void flush(uintptr_t a, size_t n)
{
uint64_t ctr;
__asm__ volatile("mrs %0, ctr_el0" : "=r"(ctr));
uintptr_t d = 4u << ((ctr >> 16) & 15), i = 4u << (ctr & 15), x;
for (x = a & ~(d - 1); x < a + n; x += d) __asm__ volatile("dc cvau, %0" ::"r"(x) : "memory");
__asm__ volatile("dsb ish" ::: "memory");
for (x = a & ~(i - 1); x < a + n; x += i) __asm__ volatile("ic ivau, %0" ::"r"(x) : "memory");
__asm__ volatile("dsb ish\n\tisb" ::: "memory");
}
static void jump_code(uint32_t *out, uintptr_t to)
{
out[0] = 0x58000050; // ldr x16, #8
out[1] = 0xd61f0200; // br x16
memcpy(out + 2, &to, 8);
}
static void *trampoline(uint32_t *fn)
{
size_t page = getauxval(AT_PAGESZ);
uint32_t *t = mmap(NULL, page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (t == MAP_FAILED) return NULL;
memcpy(t, fn, 16);
jump_code(t + 4, (uintptr_t)(fn + 4));
if (mprotect(t, page, PROT_READ | PROT_EXEC)) {
munmap(t, page);
return NULL;
}
flush((uintptr_t)t, 32);
return t;
}
static void drop_trampoline(void *t)
{
if (t) munmap(t, getauxval(AT_PAGESZ));
}
// The library's code pages are file mappings: patched anonymous copies are prepared first and then moved over the
// originals in one step each. Both hooks go in or neither: the pages of both functions (one range when they share a
// page) are copied, patched and made executable before anything is replaced, and a copy of the original pages is
// kept, so a failed second replacement puts the first range back.
struct range {
uintptr_t lo;
size_t len;
uint8_t *patched, *saved;
};
static bool prepare(struct range *r, uintptr_t lo, uintptr_t hi)
{
r->lo = lo;
r->len = hi - lo;
r->patched = mmap(NULL, r->len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
r->saved = mmap(NULL, r->len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (r->patched == MAP_FAILED || r->saved == MAP_FAILED) {
if (r->patched != MAP_FAILED) munmap(r->patched, r->len);
if (r->saved != MAP_FAILED) munmap(r->saved, r->len);
r->patched = r->saved = NULL;
return false;
}
memcpy(r->patched, (void *)lo, r->len);
memcpy(r->saved, (void *)lo, r->len);
return true;
}
static void patch(struct range *r, uint32_t *fn, uintptr_t to)
{
if ((uintptr_t)fn >= r->lo && (uintptr_t)fn + 16 <= r->lo + r->len)
jump_code((uint32_t *)(r->patched + ((uintptr_t)fn - r->lo)), to);
}
static bool seal(struct range *r)
{
return !mprotect(r->patched, r->len, PROT_READ | PROT_EXEC) && !mprotect(r->saved, r->len, PROT_READ | PROT_EXEC);
}
static bool commit(struct range *r)
{
if (mremap(r->patched, r->len, r->len, MREMAP_MAYMOVE | MREMAP_FIXED, (void *)r->lo) == MAP_FAILED) return false;
r->patched = NULL; // now the mapping at lo
flush(r->lo, r->len);
return true;
}
static void restore(struct range *r)
{
if (r->saved && mremap(r->saved, r->len, r->len, MREMAP_MAYMOVE | MREMAP_FIXED, (void *)r->lo) != MAP_FAILED) {
r->saved = NULL;
flush(r->lo, r->len);
}
}
static void release(struct range *r)
{
if (r->patched) munmap(r->patched, r->len);
if (r->saved) munmap(r->saved, r->len);
r->patched = r->saved = NULL;
}
static bool redirect_both(uint32_t *fa, uintptr_t ta, uint32_t *fb, uintptr_t tb)
{
size_t page = getauxval(AT_PAGESZ);
uintptr_t alo = (uintptr_t)fa & ~(page - 1), ahi = ((uintptr_t)fa + 16 + page - 1) & ~(page - 1);
uintptr_t blo = (uintptr_t)fb & ~(page - 1), bhi = ((uintptr_t)fb + 16 + page - 1) & ~(page - 1);
struct range r[2] = {{0}};
int n = 1;
if (alo < bhi && blo < ahi) { // overlapping pages: one range holds both patches
if (!prepare(&r[0], alo < blo ? alo : blo, ahi > bhi ? ahi : bhi)) return false;
} else if (!prepare(&r[0], alo, ahi) || !prepare(&r[1], blo, bhi)) {
release(&r[0]);
release(&r[1]);
return false;
} else n = 2;
for (int i = 0; i < n; i++) {
patch(&r[i], fa, ta);
patch(&r[i], fb, tb);
}
bool ok = true;
for (int i = 0; i < n && ok; i++) ok = seal(&r[i]);
if (ok && !commit(&r[0])) ok = false;
else if (ok && n == 2 && !commit(&r[1])) {
restore(&r[0]);
ok = false;
}
for (int i = 0; i < n; i++) release(&r[i]);
return ok;
}
static void install(void)
{
const char *mode = getenv("DROIDDECK_BIONIC_STEAMSHM");
const char *dir = getenv("DROIDDECK_BIONIC_SHM_DIR");
struct object o = {0};
uint32_t *open_fn, *unlink_fn = NULL;
if (mode && !strcmp(mode, "0")) return;
if (!dir || !*dir || strlen(dir) >= sizeof shm_dir) {
say("steamshm: no DROIDDECK_BIONIC_SHM_DIR; Steam Input data stays in the library\n");
return;
}
strcpy(shm_dir, dir);
if (!dl_iterate_phdr(find_object, &o)) {
say("steamshm: libsteamclient.so not found among the loaded libraries\n");
return;
}
open_fn = find_shm_open(&o);
unlink_fn = open_fn ? find_shm_unlink(&o, (uintptr_t)open_fn) : NULL;
if (!open_fn || !unlink_fn || !relocatable(open_fn) || !relocatable(unlink_fn)) {
say("steamshm: this libsteamclient.so does not match (open %p, unlink %p); left as it is\n",
(void *)open_fn, (void *)unlink_fn);
return;
}
orig_open = (shm_open_fn)trampoline(open_fn);
orig_unlink = (shm_unlink_fn)trampoline(unlink_fn);
if (!orig_open || !orig_unlink ||
!redirect_both(unlink_fn, (uintptr_t)hook_unlink, open_fn, (uintptr_t)hook_open)) {
drop_trampoline((void *)orig_open);
drop_trampoline((void *)orig_unlink);
orig_open = NULL;
orig_unlink = NULL;
say("steamshm: could not redirect the library's shared memory; left as it is\n");
return;
}
say("steamshm: libsteamclient.so +%#lx open / +%#lx unlink use %s (Steam uid %s)\n",
(unsigned long)((uintptr_t)open_fn - o.base), (unsigned long)((uintptr_t)unlink_fn - o.base), shm_dir,
uid_of_steam());
}
struct named_sem {
struct named_sem *next;
sem_t sem;
int refs;
char name[];
};
static struct named_sem *sems;
static pthread_mutex_t sems_lock = PTHREAD_MUTEX_INITIALIZER;
// Named semaphores of this process only: the last sem_close frees one (there is no sem_unlink to wait for).
EXPORT sem_t *sem_open(const char *name, int oflag, ...)
{
unsigned value = 0;
if (oflag & O_CREAT) {
va_list a;
va_start(a, oflag);
(void)va_arg(a, unsigned); // mode
value = va_arg(a, unsigned);
va_end(a);
}
if (!*name) {
errno = EINVAL;
return SEM_FAILED;
}
sem_t *r = SEM_FAILED;
pthread_mutex_lock(&sems_lock);
struct named_sem *s = sems;
while (s && strcmp(s->name, name)) s = s->next;
if (s && (oflag & O_CREAT) && (oflag & O_EXCL)) {
errno = EEXIST;
} else if (s) {
s->refs++;
r = &s->sem;
} else if (!(oflag & O_CREAT)) {
errno = ENOENT;
} else if ((s = calloc(1, sizeof *s + strlen(name) + 1))) {
strcpy(s->name, name);
if (sem_init(&s->sem, 0, value) == 0) {
s->refs = 1;
s->next = sems;
sems = s;
r = &s->sem;
} else {
free(s);
}
} else {
errno = ENOMEM;
}
pthread_mutex_unlock(&sems_lock);
return r;
}
EXPORT int sem_close(sem_t *sem)
{
int r = -1;
pthread_mutex_lock(&sems_lock);
struct named_sem **p = &sems;
while (*p && &(*p)->sem != sem) p = &(*p)->next;
if (*p) {
struct named_sem *s = *p;
r = 0;
if (--s->refs == 0) {
*p = s->next;
sem_destroy(&s->sem);
free(s);
}
} else {
errno = EINVAL;
}
pthread_mutex_unlock(&sems_lock);
return r;
}
static long raw_getuid(void)
{
register long x8 __asm__("x8") = 174; // __NR_getuid
register long x0 __asm__("x0");
__asm__ volatile("svc #0" : "=r"(x0) : "r"(x8) : "memory");
return x0;
}
// libsteamclient asks for the uid just before it names each shared-memory object, so its first call installs the
// redirect before the first open. Calls from anywhere else only return the uid.
EXPORT uid_t getuid(void)
{
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
static int done;
if (!__atomic_load_n(&done, __ATOMIC_ACQUIRE)) {
Dl_info i;
size_t l;
if (dladdr(__builtin_return_address(0), &i) && i.dli_fname && (l = strlen(i.dli_fname)) >= 18 &&
!strcmp(i.dli_fname + l - 18, "/libsteamclient.so")) {
pthread_mutex_lock(&lock);
if (!done) {
install();
__atomic_store_n(&done, 1, __ATOMIC_RELEASE);
}
pthread_mutex_unlock(&lock);
}
}
return (uid_t)raw_getuid();
}
+2
View File
@@ -0,0 +1,2 @@
! DroidDeck-Bionic: an empty X resource file. XENVIRONMENT points here so libX11 has a resource database to
! keep; with no file at all it looks for ~/.Xdefaults again on every XGetDefault call (each GDI font selection).
@@ -0,0 +1,13 @@
"compatibilitytools"
{
"compat_tools"
{
"@NAME@"
{
"install_path" "."
"display_name" "@DISPLAY@"
"from_oslist" "windows"
"to_oslist" "linux"
}
}
}
+13
View File
@@ -0,0 +1,13 @@
Windows Registry Editor Version 5.00
; Black instead of Wine's default colour, and no shell/taskbar or tray, if a game is run on a Wine desktop
; (launch.sh itself runs games straight on gamescope).
[HKEY_CURRENT_USER\Control Panel\Colors]
"Background"="0 0 0"
[HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\ThemeManager\Control Panel\Colors]
"Background"="0 0 0"
[HKEY_CURRENT_USER\Software\Wine\Explorer\Desktops\Default]
"EnableShell"=dword:00000000
"ShowSystray"=dword:00000000
+443
View File
@@ -0,0 +1,443 @@
#!/system/bin/sh
# DroidDeck-Bionic launcher, Android side. ../proton calls it: launch.sh <verb> <compatdata dir> <exe> [args...]
# Runs <exe> on the bionic Proton layer in ../files with the prefix <compatdata>/pfx, inside DroidDeck's
# gamescope session. Every program from app data starts through /system/bin/linker64 (targetSdk 29+ refuses
# execve of app data files); the runtime pack's execshim does the same for Wine's own starts.
verb=$1; COMPAT=$2; EXE=$3
shift 3
TOOL=$(cd "$(dirname "$0")/.." && pwd)
F=$TOOL/files
PACK=$F/runtime
ROOTFS=${DROIDDECK_BIONIC_ROOT:?started without DROIDDECK_BIONIC_ROOT}
APP=${ROOTFS%/linuxfs}
LINKER=/system/bin/linker64
VERSION=$(awk '{print $2}' "$TOOL/version" 2>/dev/null)
LOGS=${DROIDDECK_BIONIC_LOGS:-}
mkdir -p "$COMPAT"
LOG=$COMPAT/droiddeck-bionic.log
[ "$verb" = runinprefix ] || { [ -f "$LOG" ] && mv -f "$LOG" "$LOG.1"; }
# A game's log is written into DroidDeck's session folder (../proton names it), which Share logs takes only as a
# file with one name; the usual name here points to it, and dangles once that session's folder is removed.
[ -L "$LOG" ] && [ ! -e "$LOG" ] && rm -f "$LOG"
if [ -n "$LOGS" ] && [ ! -e "$LOG" ] && mkdir -p "$LOGS" 2>/dev/null && : >> "$LOGS/droiddeck-bionic.log" 2>/dev/null; then
ln -s "$LOGS/droiddeck-bionic.log" "$LOG" 2>/dev/null
fi
exec >> "$LOG" 2>&1
echo "$(date +%H:%M:%S) $verb $EXE ($VERSION, uid $(id -u), DISPLAY ${DISPLAY:-unset})"
# Keep Steam's game identity, DroidDeck's input/display/driver/sync settings and its game environment (the names
# ../proton lists in DROIDDECK_BIONIC_KEEP); drop the rest of the glibc guest's environment.
KEEP=" ${DROIDDECK_BIONIC_KEEP:-} "
for v in $(env | sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=.*/\1/p'); do
case "$KEEP" in *" $v "*) continue ;; esac
case "$v" in
SteamAppId|SteamGameId|SteamOverlayGameId|SteamClientLaunch|SteamEnv|SteamAppUser|SteamUser|STEAM_COMPAT_*) ;;
ANDROID_*|BOOTCLASSPATH|DEX2OATBOOTCLASSPATH|SYSTEMSERVERCLASSPATH|EXTERNAL_STORAGE|ASEC_MOUNTPOINT) ;;
FAKE_*|SDL_*|DD_WIDTH|DD_HEIGHT|DD_VK_DRIVER|WINEDLLOVERRIDES) ;;
DISPLAY|GAMESCOPE_WAYLAND_DISPLAY|FEX_*) ;;
TU_DEBUG|MESA_NO_ERROR|DXVK_CONFIG|DXVK_HUD|DROIDDECK_FORCE_SSBS) ;;
mesa_glthread|vblank_mode|ZINK_*|GALLIUM_HUD|GALLIUM_THREAD) ;;
DD_SYNC|DD_FSYNC_FIRST|DD_SYNC_FALLBACK|PROTON_NO_ESYNC|PROTON_NO_FSYNC|PROTON_NO_NTSYNC|WINEESYNC) ;;
PROTON_USE_D7VK) ;;
XODUS_*|RUST_LOG) ;;
WINE_OFFSCREEN_CHECK_MS|WINE_CPU_TOPOLOGY|WINE_LARGE_ADDRESS_AWARE|WINESTEAMNOEXEC|TZ) ;;
DXVK_LOG_LEVEL|DXVK_HDR|VKD3D_DEBUG|VKD3D_SHADER_DEBUG) ;;
DXVK_LOG_PATH|VKD3D_LOG_FILE|MESA_LOG_FILE) ;;
DROIDDECK_GPU_LOAD|DROIDDECK_GPU_LOAD_DIR|DROIDDECK_VRAM_CAP|DROIDDECK_VRAM_CAP_MB|DROIDDECK_DISPLAY_DRIVER) ;;
DROIDDECK_GUEST_ROOT) ;;
VKD3D_FEATURE_LEVEL|VKD3D_SHADER_MODEL|vk_x11_strict_image_count) ;;
*) unset "$v" 2>/dev/null ;;
esac
done
export PATH=/system/bin:/system/xbin
# DISPLAY: the X server Steam gives games. DroidDeck's gamescope runs two (Steam's UI on :0, games on
# STEAM_GAME_DISPLAY_0), so Steam's menus do not take X focus from the game.
export HOME=$COMPAT WINEPREFIX=$COMPAT/pfx TMPDIR=$ROOTFS/tmp LANG=en_US.UTF-8 DISPLAY=${DISPLAY:-:0}
# Proton's user name: the same C:\users\steamuser (saves, settings) as DroidDeck-Proton in a shared prefix
export USER=steamuser LOGNAME=steamuser
# Graphics: DroidDeck's chosen Turnip (its Android half) through Bannerlator's Wayland adapter, and gamescope's
# WSI layer handing the swapchain to gamescope (zero copy).
drvlib() { # an Android driver folder's library: meta.json's libraryName, else libvulkan_freedreno.so
l=$(sed -n 's/.*"libraryName"[[:space:]]*:[[:space:]]*"\([^"/]*\)".*/\1/p' "$1/meta.json" 2>/dev/null | head -1)
echo "${l:-libvulkan_freedreno.so}"
}
DRV=$(basename "$(dirname "${DD_VK_DRIVER:-/x/none/icd.json}")")
DRVDIR=$APP/graphics_driver/$DRV
if [ ! -f "$DRVDIR/$(drvlib "$DRVDIR")" ]; then
# The runtime driver has no Android build: the one DroidDeck's display uses, else the first one installed.
DRVDIR=
if [ -n "${DROIDDECK_DISPLAY_DRIVER:-}" ] && [ "${DROIDDECK_DISPLAY_DRIVER#*/}" = "$DROIDDECK_DISPLAY_DRIVER" ] && \
[ -f "$APP/graphics_driver/$DROIDDECK_DISPLAY_DRIVER/$(drvlib "$APP/graphics_driver/$DROIDDECK_DISPLAY_DRIVER")" ]; then
DRVDIR=$APP/graphics_driver/$DROIDDECK_DISPLAY_DRIVER
else
for d in "$APP"/graphics_driver/*/; do [ -f "$d$(drvlib "${d%/}")" ] && { DRVDIR=${d%/}; break; }; done
fi
echo "driver $DRV has no Android build; using ${DRVDIR:+$(basename "$DRVDIR")}${DRVDIR:-none} (display driver ${DROIDDECK_DISPLAY_DRIVER:-unknown})"
fi
echo "driver $DRVDIR"
RTD=$APP/.wayland-rt
export VK_ICD_FILENAMES=$PACK/adapter/icd.json ADRENOTOOLS_DRIVER_PATH=$DRVDIR/ ADRENOTOOLS_HOOKS_PATH=$PACK/lib
export ADRENOTOOLS_DRIVER_NAME=$(drvlib "$DRVDIR")
export VK_ADD_IMPLICIT_LAYER_PATH=$PACK/layer ENABLE_GAMESCOPE_WSI=1 GAMESCOPE_WAYLAND_DISPLAY=${GAMESCOPE_WAYLAND_DISPLAY:-gamescope-0}
export XDG_RUNTIME_DIR=$RTD DROIDDECK_WSI_BYPASS_CHECK_MS=100 GAMESCOPE_WSI_FORCE_BYPASS=1
[ -e "$RTD/droiddeck-gamescope-limiter" ] && export GAMESCOPE_LIMITER_FILE=$RTD/droiddeck-gamescope-limiter
# Wine: DXVK/VKD3D over the builtins, X11 inside gamescope (winewayland would pick DroidDeck's compositor),
# FEX for x86 code, userspace ntsync (no /dev/ntsync on Android), Valve's Android Steam client library.
export WINEDLLOVERRIDES="${WINEDLLOVERRIDES:+$WINEDLLOVERRIDES;}d3d8,d3d9,d3d10core,d3d11,dxgi,d3d12,d3d12core=n,b;winewayland.drv=d"
# Sync as chosen in DroidDeck (Wine sync, per-game PROTON_NO_*): ntsync is userspace ntsync (no /dev/ntsync on
# Android) with esync as its fallback; Android has no futex_waitv, so an fsync choice runs ntsync.
on() { case "$1" in 1|on|true|yes) return 0 ;; esac; return 1; }
NT=1; ES=1
[ "${DD_SYNC:-1}" = 0 ] && NT=0
[ "${DD_FSYNC_FIRST:-0}" = 1 ] && NT=1
[ "${DD_SYNC:-1}" = 0 ] && [ "${DD_SYNC_FALLBACK:-1}" = 0 ] && ES=0
on "${PROTON_NO_NTSYNC:-}" && NT=0
{ on "${PROTON_NO_ESYNC:-}" || [ "${WINEESYNC:-}" = 0 ]; } && ES=0
export WINENTSYNC=$NT WINEESYNC=$ES
# Userspace ntsync keeps its state in one file. Per prefix, not in the shared TMPDIR (DroidDeck-Proton's ntsync
# uses that too), and cleared before Wine starts in this prefix: a process killed while it held the file's lock
# leaves it held, and every later start in that prefix hangs at its first ntsync wait.
export NTSYNC_SHM=$COMPAT/ntsync-shm
# DroidDeck's Force SSBS (its glibc libssbs.so preload) is bionic Wine's own WINE_FORCE_SSBS
on "${DROIDDECK_FORCE_SSBS:-}" && export WINE_FORCE_SSBS=1
export HODLL=libwow64fex.dll WINEDEBUG=err+all,fixme-all
export XENVIRONMENT=$TOOL/bionic/Xdefaults
# The adapter's Wayland swapchain gets its buffers back from gamescope later than DroidDeck-Proton's Turnip does;
# with gamescope's default three images the game waits for one about a fifth of the time at high frame rates.
# droiddeck-game-env's fix for a game that needs its own image count sets vk_x11_strict_image_count instead.
case "${vk_x11_strict_image_count:-}" in
true|1) ;;
*) export GAMESCOPE_WSI_MIN_IMAGE_COUNT=${GAMESCOPE_WSI_MIN_IMAGE_COUNT:-4} GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT=${GAMESCOPE_WSI_ENSURE_MIN_IMAGE_COUNT:-1} ;;
esac
# FEX: DroidDeck-Proton's defaults (its share/fex-emu/Config.json: x87 in 64-bit precision, TSO without the vector
# and memcpy parts); droiddeck-game-env's per-game choices (FEX_* in the environment, e.g. .NET, Unity) win.
export FEX_TSOENABLED=${FEX_TSOENABLED:-1} FEX_VECTORTSOENABLED=${FEX_VECTORTSOENABLED:-0} \
FEX_MEMCPYSETTSOENABLED=${FEX_MEMCPYSETTSOENABLED:-0} FEX_HALFBARRIERTSOENABLED=${FEX_HALFBARRIERTSOENABLED:-1} \
FEX_X87REDUCEDPRECISION=${FEX_X87REDUCEDPRECISION:-1} FEX_MULTIBLOCK=${FEX_MULTIBLOCK:-1} FEX_MAXINST=${FEX_MAXINST:-500} FEX_DISKCACHE=${FEX_DISKCACHE:-1}
echo "fex $(env | grep '^FEX_' | sort | tr '\n' ' ')"
echo "sync ntsync=$WINENTSYNC esync=$WINEESYNC ssbs=${WINE_FORCE_SSBS:-0} tu_debug=${TU_DEBUG:-} kept=$(echo $KEEP)"
export WINESTEAMCLIENTPATH64=$ROOTFS/root/.local/share/Steam/androidarm64/libsteamclient.so
# The layer sends a game's steamclient(64).dll to lsteamclient (and so to DroidDeck's Steam through the library
# above) only with WINE_LSTEAMCLIENT set; without it Valve's Windows steamclient runs alone and SteamAPI_Init fails.
export WINE_LSTEAMCLIENT=${WINE_LSTEAMCLIENT:-1}
# Steam Input data (Valve's Steam Deck layouts with game actions) lives in DroidDeck's /dev/shm; libsteamshm.so
# points the Android library's shared memory there (it keeps its own in-process otherwise) and gives it the
# sem_open Android lacks (without it the game hangs once that data arrives).
export DROIDDECK_BIONIC_SHM_DIR=${APP%/files}/no_backup/guest-runtime/shm
export DXVK_LOG_PATH=${DXVK_LOG_PATH:-$COMPAT} PULSE_SERVER=unix:$APP/pulseaudio/PS0
export ANDROID_SYSVSHM_SERVER=$COMPAT/.no-sysvshm-server # its client faults on an unset name, inside a Wine lock
# The pack's imagefs libraries carry Winlator's prefix for plugins and X11 data. No FONTCONFIG_*: with the
# imagefs fonts.conf (Android's /system/fonts) DiRT Showdown quit right after start.
export GST_PLUGIN_SYSTEM_PATH=$PACK/lib/gstreamer-1.0 GST_REGISTRY=$COMPAT/gst-registry.bin GST_REGISTRY_FORK=no
export XLOCALEDIR=$PACK/share/X11/locale XKB_CONFIG_ROOT=$PACK/share/X11/xkb
export SSL_CERT_FILE=$PACK/etc/tls/cert.pem SSL_CERT_DIR=$PACK/etc/tls/certs OPENSSL_CONF=$PACK/etc/tls/openssl.cnf
export WINE_ADDITIONAL_CERTS_DIR=$PACK/etc/tls/cert.pem
# Controller: the bionic winebus has no udev bus, so Steam's virtual pad is shown to it as an Xbox 360 pad;
# Steam's ignore list names that id because of the built-in pad, which Wine does not see here.
export FAKE_EVDEV_STEAM_PAD_AS_X360=1
export SDL_GAMECONTROLLER_IGNORE_DEVICES="$(echo "${SDL_GAMECONTROLLER_IGNORE_DEVICES:-}" | sed -e 's#0x045e/0x028e,##' -e 's#,0x045e/0x028e$##')"
# OpenGL, and WineD3D on it (DirectDraw, Direct3D 1-8 without DXVK): Mesa's Zink on Vulkan through winex11's EGL
# backend (the runtime's egl/), the way Bannerlator's Fast OpenGL runs it; DroidDeck's GL settings above are kept.
export WINE_USE_EGL=1 WINE_X11FORCEGLX=1 GALLIUM_DRIVER=zink MESA_LOADER_DRIVER_OVERRIDE=zink LIBGL_KOPPER_DRI2=1
export ZINK_DESCRIPTORS=${ZINK_DESCRIPTORS:-lazy} ZINK_DEBUG=${ZINK_DEBUG:-compact} vblank_mode=${vblank_mode:-0}
# Gallium's threaded context off, as in Bannerlator's Fast OpenGL: with it, WineD3D (DirectDraw / Direct3D 1-7)
# crashed in native code within seconds (AIO Direct3D 7, SIGSEGV).
export GALLIUM_THREAD=${GALLIUM_THREAD:-0}
# Mesa's GL thread off unless the game's own DroidDeck environment sets it: with DroidDeck's session-wide
# mesa_glthread=true, WineD3D's persistent buffer writes lost vertex colours on this Mesa build (AIO 64-bit
# Direct3D 7 drew its cube white; DroidDeck-Proton's Mesa does not do this).
case "$KEEP" in *" mesa_glthread "*) ;; *) export mesa_glthread=false ;; esac
# egl/ first: the layer's own lib/ carries a Wayland-only Mesa EGL of the same names, which winex11 cannot use
LIBS=$PACK/egl:$F/lib:$PACK/lib:/system/lib64
PRELOAD=$PACK/preload/libexecshim.so:$PACK/preload/libnotag.so:$PACK/preload/libfakeinput.so:$PACK/preload/libsteamshm.so
wine_() { LD_LIBRARY_PATH=$LIBS LD_PRELOAD=$PRELOAD "$LINKER" "$F/lib/wine/aarch64-unix/wine" "$@"; }
wineserver_() { LD_LIBRARY_PATH=$LIBS LD_PRELOAD=$PRELOAD "$LINKER" "$F/bin/wineserver" "$@"; }
is_builtin() { head -c 128 "$1" 2>/dev/null | grep -q "Wine builtin DLL"; }
# Names wine.inf has Wine's update delete from system32 (section FakeDlls) or syswow64 (FakeDllsWow64), "11,,name,-":
# in Windows they live only under Microsoft.NET or winsxs. Wine deletes through a link, so a link there cost this
# tool its own fusion.dll, ngen.exe, comctl32_v6.dll and the rest, and later prefixes their .NET stubs and comctl32 v6.
inf_drops() {
awk -v s="[$1]" '/^\[/ { h = $0; sub(/[ \t\r]+$/, "", h); on = (h == s); next }
on && /^11,,[^,]+,-[ \t\r]*$/ { split($0, a, ","); print a[3] }' "$F/share/wine/wine.inf" 2>/dev/null
}
dropped() { # name patterns
set -f
for p in $2; do case "$1" in $p) set +f; return 0 ;; esac; done
set +f; return 1
}
link_dir() { # src dst [names]: links every file of src into dst; replaces links and Wine builtin copies, keeps native
# DLLs; names (wine.inf patterns) are not linked and a link left under one is removed
[ -d "$1" ] || return 0
for f in "$1"/*; do
[ -f "$f" ] || continue
t=$2/${f##*/}
if [ -n "${3:-}" ] && dropped "${f##*/}" "$3"; then
[ -L "$t" ] && rm -f "$t"
continue
fi
if [ -L "$t" ]; then
[ "$(readlink "$t")" = "$f" ] && continue
rm -f "$t"
elif [ -e "$t" ]; then
is_builtin "$t" || continue
rm -f "$t"
fi
ln -s "$f" "$t"
done
}
winpath() { echo "Z:$1" | sed 's#/#\\#g'; }
# The prefix carries this tool's builtins when it was last set up by this version; another Proton (or an
# older DroidDeck-Bionic) leaves its own links there, and the compatdata version file tells DroidDeck-Proton
# to relink when it runs this prefix again.
# Drive Z: is the whole device for this tool: winpath, getcompatpath and the Xbox paths name Android paths on Z:.
# Proton copies a prefix's links as relative ones, and DroidDeck-Proton's relative z: reaches only the Linux userland
# here, so a game outside it (SD card, shared storage) was on no drive and Wine crashed on its path at start.
# DroidDeck-Proton follows z: -> / in the guest's view, with proot and without.
drive_z() {
z=$1/dosdevices/z:
[ -d "$1/dosdevices" ] || return 0
[ -L "$z" ] || { [ -e "$z" ] && return 0; }
old=$(readlink "$z" 2>/dev/null)
[ "$old" = / ] && return 0
rm -f "$z" && ln -s / "$z" && echo "$(date +%H:%M:%S) drive z: -> / (was ${old:-missing})"
}
prepare_prefix() {
P=$COMPAT/pfx
drive_z "$P"
if [ -f "$P/.droiddeck-bionic" ] && [ "$(cat "$P/.droiddeck-bionic")" = "$VERSION" ] && \
[ "$(cat "$COMPAT/version" 2>/dev/null)" = "$VERSION" ]; then return 0; fi
if [ ! -f "$P/system.reg" ]; then
echo "$(date +%H:%M:%S) new prefix from the layer's template"
mkdir -p "$P" && cp -a "$F/default_pfx/." "$P/"
fi
W=$P/drive_c/windows
mkdir -p "$W/system32" "$W/syswow64" "$P/dosdevices"
echo "$(date +%H:%M:%S) linking builtins"
link_dir "$F/lib/wine/aarch64-windows" "$W/system32" "$(inf_drops FakeDlls)"
link_dir "$F/lib/wine/i386-windows" "$W/syswow64" "$(inf_drops FakeDllsWow64)"
for c in dxvk vkd3d-proton; do
link_dir "$F/lib/wine/$c/aarch64-windows" "$W/system32"
link_dir "$F/lib/wine/$c/i386-windows" "$W/syswow64"
done
# This layer's Wine always uses the profile C:\users\xuser, Proton's is C:\users\steamuser: one links to the
# other so saves and settings are the same whichever tool runs the game.
U=$P/drive_c/users
if [ -d "$U/steamuser" ] && [ ! -e "$U/xuser" ]; then ln -s steamuser "$U/xuser"
elif [ -d "$U/xuser" ] && [ ! -L "$U/xuser" ] && [ ! -e "$U/steamuser" ]; then ln -s xuser "$U/steamuser"; fi
[ -e "$P/dosdevices/c:" ] || ln -s ../drive_c "$P/dosdevices/c:"
[ -e "$P/dosdevices/z:" ] || ln -s / "$P/dosdevices/z:"
wine_ regedit /S "$(winpath "$TOOL/bionic/desktop.reg")"
wineserver_ -w
echo "$VERSION" > "$P/.droiddeck-bionic"
echo "$VERSION" > "$COMPAT/version"
# Proton (DroidDeck-Proton, GE, ...) reads tracked_files when it takes this prefix over; one this tool made has
# none. The version above is not a Proton prefix version, so Proton updates the prefix and never treats it as
# one from a newer Proton (which would delete its tracked files).
[ -e "$COMPAT/tracked_files" ] || : > "$COMPAT/tracked_files"
echo "$(date +%H:%M:%S) prefix ready"
}
prefix_busy() { # a process of this prefix is running
for p in /proc/[0-9]*; do
[ "${p#/proc/}" = "$$" ] && continue
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
done
return 1
}
programs_left() { # a program of this prefix is still running, apart from Wine's own services and this script's helpers
for p in /proc/[0-9]*; do
q=${p#/proc/}
[ -O "$p" ] || continue
[ "$q" = "$$" ] || [ "$q" = "${GT:-x}" ] && continue
c=; read -r c < "$p/comm" 2>/dev/null
case "$c" in
""|wineserver|services.exe|winedevice.exe|plugplay.exe|explorer.exe|svchost.exe|rpcss.exe|conhost.exe|start.exe|\
winemenubuilder|wineboot.exe|tabtip.exe) continue ;;
esac
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" && return 0
done
return 1
}
stop_wine() { # wineserver -k, then whatever of this prefix is left (e.g. a game's crash reporter)
wineserver_ -k 2>/dev/null
sleep 1
for p in /proc/[0-9]*; do
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qx "WINEPREFIX=$COMPAT/pfx" || continue
[ "${p#/proc/}" = "$$" ] && continue
echo "$(date +%H:%M:%S) left over: ${p#/proc/} $(cat "$p/comm" 2>/dev/null)"
kill -9 "${p#/proc/}" 2>/dev/null
done
}
# A FEX from DroidDeck's components runs here only as an Android build (its unix libraries link Android's libc).
# Missing or glibc unix libraries (an older app put its glibc FEX here): put the tool's own FEX back.
fex_ok=1
for f in aarch64-unix/libwow64fex.so aarch64-unix/libarm64ecfex.so; do
if [ ! -f "$F/lib/wine/$f" ] || grep -q "ld-linux-aarch64" "$F/lib/wine/$f"; then fex_ok=0; fi
done
if [ $fex_ok = 0 ]; then
for f in aarch64-unix/libwow64fex.so aarch64-unix/libarm64ecfex.so aarch64-windows/libwow64fex.dll aarch64-windows/libarm64ecfex.dll; do
[ -f "$PACK/fex/$f" ] || continue
cmp -s "$PACK/fex/$f" "$F/lib/wine/$f" || { cat "$PACK/fex/$f" > "$F/lib/wine/$f" && echo "$(date +%H:%M:%S) restored the tool's FEX $f"; }
done
fi
echo "fex build: $(grep -a -o -m1 'FEX-[0-9][0-9.]*[0-9A-Za-z.+-]*' "$F/lib/wine/aarch64-windows/libarm64ecfex.dll" | head -1)"
if [ "$verb" != runinprefix ] && prefix_busy; then
echo "$(date +%H:%M:%S) Wine left running in this prefix; stopping it"
stop_wine
fi
prefix_busy || rm -f "$NTSYNC_SHM".v*
# Links into a tool that is gone (an older DroidDeck-Bionic, a deleted DroidDeck-Proton) or to a file it no longer has.
# Wine's update cannot write over them, so drivers (network, controller) and other files stay missing. Drop them and
# clear both stamps: prepare_prefix relinks this tool's files and Wine's update puts its own back.
dead=0
for d in system32 syswow64 system32/drivers Fonts; do
for f in "$COMPAT/pfx/drive_c/windows/$d"/*; do
[ -L "$f" ] && [ ! -e "$f" ] && rm -f "$f" && dead=$((dead + 1))
done
done
if [ $dead -gt 0 ]; then
rm -f "$COMPAT/pfx/.update-timestamp" "$COMPAT/pfx/.droiddeck-bionic"
echo "$(date +%H:%M:%S) removed $dead dead link(s) from the prefix; relinking and Wine's update follow"
fi
prepare_prefix
# FEX keeps translated code per program in the prefix (AppData/Local/fex-emu/DiskCache) and reuses it with whatever FEX
# runs the prefix next. Code cached by another FEX build (DroidDeck-Proton's, or a different FEX picked in the
# Components tab) made this FEX crash in Steam's install-script step, and Wine then looped on the crash, so Steam never
# started the game. The cache is cleared when the FEX that runs the prefix is not the one that filled it.
# The stamp holds this FEX's ID and what the caches held when this tool last finished with the prefix, so a cache that
# another FEX wrote to since (DroidDeck-Proton running the same game) is cleared too.
fexid=$(cat "$F/lib/wine/aarch64-windows/libarm64ecfex.dll" "$F/lib/wine/aarch64-windows/libwow64fex.dll" \
"$F/lib/wine/aarch64-unix/libarm64ecfex.so" "$F/lib/wine/aarch64-unix/libwow64fex.so" 2>/dev/null | md5sum | cut -c1-16)
fex_cache_sum() { # names, sizes and times of the files in the prefix's FEX code caches
for u in "$COMPAT/pfx/drive_c/users"/*; do
[ -L "$u" ] && continue
c=$u/AppData/Local/fex-emu/DiskCache
[ -d "$c" ] && find "$c" -type f -exec stat -c '%n %s %Y' {} + 2>/dev/null
done | sort | md5sum | cut -c1-16
}
save_fex_stamp() { echo "$fexid $(fex_cache_sum)" > "$COMPAT/pfx/.droiddeck-fex-cache" 2>/dev/null; }
if [ "$(cat "$COMPAT/pfx/.droiddeck-fex-cache" 2>/dev/null)" != "$fexid $(fex_cache_sum)" ]; then
for u in "$COMPAT/pfx/drive_c/users"/*; do
c=$u/AppData/Local/fex-emu/DiskCache
[ -L "$u" ] || [ ! -d "$c" ] && continue
rm -rf "$c" && echo "$(date +%H:%M:%S) FEX code cache of ${u##*/} cleared (another FEX build wrote to it, or it is unknown)"
done
save_fex_stamp
fi
# Steam's Windows client files in the prefix, the ones Proton copies from Steam's legacycompat folder: a game's
# steam_api loads C:\Program Files (x86)\Steam\steamclient64.dll, and a prefix this tool made has none.
SC=$ROOTFS/root/.local/share/Steam/legacycompat
D="$COMPAT/pfx/drive_c/Program Files (x86)/Steam"
if [ -d "$SC" ]; then
mkdir -p "$D"
for c in steamclient.dll:steamclient.dll steamclient64.dll:steamclient64.dll GameOverlayRenderer64.dll:GameOverlayRenderer64.dll \
SteamService.exe:steam.exe Steam.dll:Steam.dll; do
s=$SC/${c%%:*}; d=$D/${c#*:}
[ -f "$s" ] || continue
[ -f "$d" ] && [ ! "$s" -nt "$d" ] && continue
cp "$s" "$d.new" && mv -f "$d.new" "$d" && touch -r "$s" "$d" && echo "$(date +%H:%M:%S) Steam client file ${c#*:}"
done
fi
# DXVK and VKD3D-Proton: the prefix uses this tool's files, where DroidDeck puts its component choices. Another Proton
# that ran this prefix left its own copies, which link_dir keeps as native DLLs. A name the tool's DXVK does not ship
# (d3d10.dll, d3d10_1.dll) goes back to Wine's own.
for a in aarch64-windows:system32 i386-windows:syswow64; do
arch=${a%%:*}; W=$COMPAT/pfx/drive_c/windows/${a#*:}
[ -d "$W" ] || continue
for n in d3d8 d3d9 d3d10 d3d10_1 d3d10core d3d11 dxgi d3d12 d3d12core; do
s=$F/lib/wine/dxvk/$arch/$n.dll
[ -f "$s" ] || s=$F/lib/wine/vkd3d-proton/$arch/$n.dll
[ -f "$s" ] || s=$F/lib/wine/$arch/$n.dll
[ -f "$s" ] || continue
t=$W/$n.dll
[ -L "$t" ] && [ "$(readlink "$t")" = "$s" ] && continue
rm -f "$t" && ln -s "$s" "$t" && echo "$(date +%H:%M:%S) ${a#*:}/$n.dll -> ${s#$F/lib/wine/}"
done
done
# D7VK (Direct3D 7 and older on Vulkan) for 32-bit games when PROTON_USE_D7VK is set and not 0, as DroidDeck-Proton:
# its ddraw.dll in syswow64 with Wine's own beside it as ddraw_.dll. Switched off, Wine's link goes back. Only the
# links in the prefix are removed, never the files they point to.
S=$COMPAT/pfx/drive_c/windows/syswow64
if [ -n "${PROTON_USE_D7VK:-}" ] && [ "$PROTON_USE_D7VK" != 0 ] && [ -f "$PACK/d7vk/ddraw.dll" ]; then
rm -f "$S/ddraw.dll" "$S/ddraw_.dll"
ln -s "$PACK/d7vk/ddraw.dll" "$S/ddraw.dll" && ln -s "$F/lib/wine/i386-windows/ddraw.dll" "$S/ddraw_.dll"
export WINEDLLOVERRIDES="$WINEDLLOVERRIDES;ddraw=n,b"
echo "$(date +%H:%M:%S) D7VK on (32-bit ddraw)"
elif [ -L "$S/ddraw_.dll" ] || [ -e "$S/ddraw_.dll" ]; then
rm -f "$S/ddraw.dll" "$S/ddraw_.dll"
ln -s "$F/lib/wine/i386-windows/ddraw.dll" "$S/ddraw.dll"
echo "$(date +%H:%M:%S) D7VK off: Wine's ddraw again"
fi
# A Windows path (an Xbox game on its own drive letter) starts in the folder Steam gave.
case "$EXE" in [A-Za-z]:[\\/]*) ;; *) cd "$(dirname "$EXE")" || exit 1 ;; esac
if [ "$verb" = runinprefix ]; then
wine_ "$EXE" "$@"
rc=$?
save_fex_stamp
exit $rc
fi
name=${EXE##*/}; name=${name##*\\}
comm=$(echo "$name" | cut -c1-15)
game_pids() { # processes of this prefix with the game's name (two prefixes can run programs with the same name)
for p in $(grep -lFx "$comm" /proc/[0-9]*/comm 2>/dev/null); do
p=${p%/comm}
tr '\0' '\n' < "$p/environ" 2>/dev/null | grep -qxF "WINEPREFIX=$COMPAT/pfx" && echo "${p#/proc/}"
done
}
# The game's windows go straight to gamescope's X server, as with DroidDeck-Proton (no Wine desktop): the game
# sees gamescope's real modes and refresh rate, and gamescope manages its windows.
wine_ "$EXE" "$@" &
WP=$!
# Steam's overlay library marks a game's windows with the app ID Steam tracks (STEAM_GAME); that library is
# glibc-only, so this prefix's windows (WM_CLASS = the Windows program name) are tagged from outside, or gamescope
# never shows them.
GT=
if [ "${SteamAppId:-0}" != 0 ]; then
XD=${DISPLAY#*:}; XD=${XD%%.*}
"$LINKER" "$PACK/bin/gstag" "${XD:-0}" "$SteamAppId" .exe 86400 > "$COMPAT/gstag.log" 2>&1 &
GT=$!
fi
trap 'echo "$(date +%H:%M:%S) stopped by Steam"; [ -n "$GT" ] && kill $GT 2>/dev/null; stop_wine; save_fex_stamp; exit 0' TERM INT HUP
n=0
while [ $n -lt 90 ] && [ -z "$(game_pids)" ]; do
# A program that ended before it was seen (Steam's install-script step takes about a second) leaves nothing
# to wait for; a launcher that left a game running is still waited for as before.
if [ $n -ge 2 ] && ! kill -0 $WP 2>/dev/null && ! programs_left; then break; fi
sleep 1; n=$((n + 1))
done
echo "$(date +%H:%M:%S) game process $(game_pids | tr '\n' ' ')after ${n}s"
# The program Steam started counts while it runs: a program that names its main thread (Chromium-based games call
# it CrBrowserMain) changes its process name, which Wine copies, and is then no longer found by name. A launcher
# that started the game and ended leaves the game as another program of this prefix, so the wait goes on while any
# program of the prefix runs, apart from Wine's own services (Proton waits for the prefix's programs the same way).
while [ -n "$(game_pids)" ] || kill -0 $WP 2>/dev/null || programs_left; do sleep 2; done
echo "$(date +%H:%M:%S) game exited"
[ -n "$GT" ] && kill $GT 2>/dev/null
stop_wine
wait $WP
rc=$?
save_fex_stamp
echo "$(date +%H:%M:%S) done (exit $rc)"
exit $rc
+120
View File
@@ -0,0 +1,120 @@
#!/bin/bash
# DroidDeck-Bionic: a Steam compatibility tool that runs Windows games on the bionic (Android libc) Proton layer
# under files/, outside the Linux userland. Steam calls it inside DroidDeck's no-proot guest; it turns guest paths
# into Android paths and hands over to bionic/launch.sh, an Android /system/bin/sh script.
# Verbs: run/waitforexitandrun (start the game), runinprefix (run a program in the prefix), getcompatpath/
# getnativepath (path conversion); the rest are accepted and ignored.
set -u
verb=${1:-}
[ $# -gt 0 ] && shift
if [ -z "${DDNATV_ROOT:-}" ]; then
echo "DroidDeck-Bionic needs Settings > Run without proot" >&2
exit 1
fi
# guest path -> Android path: the longest no-proot bind whose guest side starts the path, else inside the rootfs
real() {
local p="$1" best="" host="" b g h
local -a binds
IFS='|' read -r -a binds <<< "${DDNATV_BINDS:-}"
for b in "${binds[@]}"; do
h="${b%%:*}"; g="${b#*:}"
case "$p" in "$g"|"$g"/*) [ ${#g} -gt ${#best} ] && { best="$g"; host="$h"; } ;; esac
done
if [ -n "$best" ]; then echo "$host${p#"$best"}"; return; fi
case "$p" in /data/*|/storage/*|/sdcard/*|/system/*|/apex/*|/vendor/*) echo "$p" ;; *) echo "$DDNATV_ROOT$p" ;; esac
}
# A guest Z: path (also as NAME=Z:..., e.g. an installer's /DIR=) -> the Z: path of its Android file; anything else unchanged
zpath() {
local p k
case "$1" in
[Zz]:[\\/]*) p=${1:2}; p=$(real "${p//\\//}"); printf 'Z:%s\n' "${p//\//\\}" ;;
*=[Zz]:[\\/]*) k=${1%%=[Zz]:[\\/]*}; printf '%s=%s\n' "$k" "$(zpath "${1#"$k="}")" ;;
*) printf '%s\n' "$1" ;;
esac
}
# Where a game launch's log goes in DroidDeck's session folder (Share logs takes that folder): the game's log folder
# when Detailed graphics logs made one (droiddeck-game-env), else a folder of its own; nothing for other verbs
session_logs() {
[ "$verb" = waitforexitandrun ] && [ -n "${DD_DEBUG_DIR:-}" ] || return 0
if [ -n "${PROTON_LOG_DIR:-}" ]; then
real "$PROTON_LOG_DIR"
else
local id=${SteamAppId:-0}
printf '%s/games/%s-bionic-%s\n' "$(real "${DD_DEBUG_DIR%/}")" "$(date +%Y-%m-%d-%H%M%S)" "${id//[^0-9]/}"
fi
}
here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
tool=$(real "$here")
compat=$(real "${STEAM_COMPAT_DATA_PATH:-$HOME/.local/share/Steam/steamapps/compatdata/0}")
case "$verb" in
run|waitforexitandrun|runinprefix)
[ $# -gt 0 ] || exit 0
# Another Windows path (DroidDeck's Xbox launch names the game on a drive letter of its own) or a bare program
# name (DroidDeck's store steps run cmd.exe, which Wine finds in system32) goes to Wine unchanged.
case "$1" in
[Zz]:[\\/]*) exe=$(zpath "$1") ;;
[A-Za-z]:[\\/]*) exe=$1 ;;
/*) exe=$(real "$1") ;;
*/*) exe=$(real "$PWD/$1") ;;
*) exe=$1 ;;
esac
shift
# DroidDeck's store and Xbox helpers name guest files by Z: paths (reg.exe import, cmd.exe /c, msiexec /i, setup
# /DIR=); this Wine's Z: is Android's root.
args=()
for a in "$@"; do args+=("$(zpath "$a")"); done
export DROIDDECK_BIONIC_ROOT="$DDNATV_ROOT"
# The guest's root as this Wine names it; the store launch files DroidDeck writes (StoreLaunch.kt) start their
# helpers from it.
r=$(real /); r=${r%/}; DROIDDECK_GUEST_ROOT="Z:${r//\//\\}"; export DROIDDECK_GUEST_ROOT
# The Xbox runtime's DLC and mount folders come as ;-separated Z: paths of the guest.
zreal() {
local out="" part
local -a parts
IFS=';' read -r -a parts <<< "$1"
for part in "${parts[@]}"; do
out="${out:+$out;}$(zpath "$part")"
done
echo "$out"
}
for v in XODUS_MOUNT_ROOT XODUS_CONTENT_ROOTS; do
[ -n "${!v:-}" ] && { printf -v "$v" '%s' "$(zreal "${!v}")"; export "${v?}"; }
done
# The HUD's GPU-load folder is a guest path; the bionic game writes to it by its Android path.
[ -n "${DROIDDECK_GPU_LOAD_DIR:-}" ] && { DROIDDECK_GPU_LOAD_DIR=$(real "$DROIDDECK_GPU_LOAD_DIR"); export DROIDDECK_GPU_LOAD_DIR; }
# So are the graphics log locations Detailed graphics logs or game debugging set for this launch.
for v in DXVK_LOG_PATH VKD3D_LOG_FILE MESA_LOG_FILE; do
[ -n "${!v:-}" ] && { printf -v "$v" '%s' "$(real "${!v}")"; export "${v?}"; }
done
DROIDDECK_BIONIC_LOGS=$(session_logs); export DROIDDECK_BIONIC_LOGS
# DroidDeck's game environment (shared entries and this game's), already applied by droiddeck-game-env: the
# names launch.sh keeps when it drops the rest of the guest environment.
DROIDDECK_BIONIC_KEEP=$(python3 - "${STEAM_COMPAT_DATA_PATH:-}" 2>/dev/null <<'PY'
import json, os, re, sys
try:
config = json.load(open(os.path.expanduser("~/.config/droiddeck/game-environment.json"), encoding="utf-8"))
except (OSError, ValueError):
sys.exit(0)
scope = os.path.basename(sys.argv[1].rstrip("/"))
names = set((config.get("shared") or {}).keys())
if re.fullmatch(r"[1-9][0-9]{0,9}", scope):
names |= set(((config.get("games") or {}).get(scope) or {}).keys())
print(" ".join(sorted(n for n in names if re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", n) and n in os.environ)))
PY
)
export DROIDDECK_BIONIC_KEEP
exec /system/bin/sh "$tool/bionic/launch.sh" "$verb" "$compat" "$exe" ${args[@]+"${args[@]}"} ;;
getcompatpath)
p=$(real "${1:-}")
printf 'Z:%s\n' "${p//\//\\}" ;;
getnativepath)
p=${1:-}; p=${p#[Zz]:}; p=${p//\\//}
echo "$p" ;;
*) exit 0 ;;
esac
@@ -0,0 +1,5 @@
"manifest"
{
"version" "2"
"commandline" "/proton %verb%"
}
+89
View File
@@ -28,10 +28,99 @@ find "$XDG_RUNTIME_DIR" -mindepth 1 -maxdepth 1 ! -name 'wayland-0*' ! -name 'ke
chmod 700 "$XDG_RUNTIME_DIR" 2>/dev/null
mkdir -p /tmp/.X11-unix /tmp/.ICE-unix && chmod 1777 /tmp/.X11-unix /tmp/.ICE-unix 2>/dev/null
export DD_DESKTOP=1
sh /usr/local/bin/droiddeck-diversion-stub /usr/bin/pkexec /usr/local/bin/pkexec migrate
sh /usr/local/bin/droiddeck-diversion-stub /usr/lib/snapd/snap-confine /usr/local/bin/droiddeck-snap-confine migrate
ln -sf /usr/local/bin/droiddeck-steam-launch /usr/local/bin/steamdeck-steam 2>/dev/null
ln -sf /usr/local/bin/droiddeck-steam-shim /usr/local/bin/steam 2>/dev/null
python3 /usr/local/bin/droiddeck-desktop-games 2>&1 | sed 's/^/[games] /'
python3 /usr/local/bin/droiddeck-desktop-programs 2>&1 | sed 's/^/[programs] /'
# Plasma lays out the SteamOS panel only for a profile without one. The layout is written at every
# start, and a panel made before this version (Kubuntu's own, or the first SteamOS one without the
# pager, clock and Plasma's stock pins) is set aside once so Plasma lays out the current one.
dd_layout=/usr/share/plasma/look-and-feel/com.valve.vapor.desktop/contents/layouts
if [ -d "$dd_layout" ]; then
cat > "$dd_layout/org.kde.plasma.desktop-layout.js" <<'LAYOUT'
var desktops = desktopsForActivity(currentActivity());
for (var i = 0; i < desktops.length; i++) {
desktops[i].wallpaperPlugin = "org.kde.image";
desktops[i].currentConfigGroup = ["Wallpaper", "org.kde.image", "General"];
desktops[i].writeConfig("Image", "file:///usr/share/wallpapers/DroidDeck");
}
var panel = new Panel;
var panelScreen = panel.screen;
panel.location = "bottom";
panel.height = 2 * Math.ceil(gridUnit * 2.5 / 2);
const maximumAspectRatio = 21 / 9;
if (panel.formFactor === "horizontal") {
const geo = screenGeometry(panelScreen);
const maximumWidth = Math.ceil(geo.height * maximumAspectRatio);
if (geo.width > maximumWidth) {
panel.alignment = "center";
panel.minimumLength = maximumWidth;
panel.maximumLength = maximumWidth;
}
}
var kickoff = panel.addWidget("org.kde.plasma.kickoff");
kickoff.currentConfigGroup = ["Shortcuts"];
kickoff.writeConfig("global", "Alt+F1");
kickoff.currentConfigGroup = ["General"];
kickoff.writeConfig("icon", "distributor-logo-steamdeck");
kickoff.writeConfig("favorites", [
"preferred://browser",
"applications:org.kde.dolphin.desktop",
"applications:org.kde.konsole.desktop",
"applications:org.kde.kate.desktop",
"applications:org.kde.discover.desktop",
"applications:systemsettings.desktop",
]);
panel.addWidget("org.kde.plasma.pager");
var tasks = panel.addWidget("org.kde.plasma.icontasks");
tasks.currentConfigGroup = ["General"];
tasks.writeConfig("launchers", [
"applications:steamdeck-steam.desktop",
"applications:systemsettings.desktop",
"applications:org.kde.discover.desktop",
"preferred://filemanager",
"preferred://browser",
"applications:org.kde.konsole.desktop",
"applications:org.kde.kate.desktop",
]);
panel.addWidget("org.kde.plasma.marginsseparator");
const inputMethodLanguages = ["as", "bn", "bo", "brx", "doi", "gu", "hi", "ja", "kn", "ko", "kok", "ks", "lep", "mai",
"ml", "mni", "mr", "ne", "or", "pa", "sa", "sat", "sd", "si", "ta", "te", "th", "ur", "vi", "zh_CN", "zh_TW"];
if (inputMethodLanguages.indexOf(languageId) != -1) {
panel.addWidget("org.kde.plasma.kimpanel");
}
var tray = panel.addWidget("org.kde.plasma.systemtray");
var trayId = tray.readConfig("SystrayContainmentId");
if (trayId) {
var trayContainment = desktopById(trayId);
trayContainment.currentConfigGroup = ["General"];
trayContainment.writeConfig("scaleIconsToFit", true);
}
var clock = panel.addWidget("org.kde.plasma.digitalclock");
clock.currentConfigGroup = ["Appearance"];
clock.writeConfig("dateFormat", "isoDate");
panel.addWidget("org.kde.plasma.showdesktop");
LAYOUT
fi
dd_panel_rc="${XDG_CONFIG_HOME:-$HOME/.config}/plasma-org.kde.plasma.desktop-appletsrc"
dd_panel_stamp="${XDG_CONFIG_HOME:-$HOME/.config}/droiddeck-panel-layout"
if [ "$(cat "$dd_panel_stamp" 2>/dev/null)" != steamos-2 ]; then
dd_panel_backup="$dd_panel_rc.before-steamos-2"
[ -e "$dd_panel_backup" ] && dd_panel_backup="$dd_panel_backup.$$"
if [ ! -f "$dd_panel_rc" ] || mv "$dd_panel_rc" "$dd_panel_backup"; then
mkdir -p "$(dirname "$dd_panel_stamp")" && echo steamos-2 > "$dd_panel_stamp"
fi
fi
# startplasma applies this file over the session environment, and keeps what an earlier session wrote.
kwriteconfig6 --file plasma-localerc --group Formats --key LANG "${LANG:-C.UTF-8}"
if [ -n "${LANGUAGE:-}" ]; then
@@ -299,6 +299,27 @@ def map_drive(root, volume):
return None
def rootfs():
host = os.environ.get("DDNATV_ROOT")
return os.path.realpath(host) if host else None
def guest_path(path):
host = rootfs()
if not host or not inside(path, host):
return None
return "/" + path[len(host):].strip("/")
def rootfs_drive(root, text):
found = re.match(r"(?i)^([abd-y]):[\\/]", text)
host = rootfs()
if not found or not host:
return False
link = os.path.join(dosdevices(root), found.group(1).lower() + ":")
return os.path.islink(link) and inside(host, os.path.realpath(link))
def install_path(root, library):
library = library.rstrip("/") or "/"
try:
@@ -308,6 +329,9 @@ def install_path(root, library):
return "Z:" + library
if volume == "/":
return "Z:" + library
host = rootfs()
if host and inside(host, volume):
return "Z:" + (guest_path(path) or library)
drive = mapped_drive(root, path, volume)
if drive is None and not wine_processes(os.path.join(prefix(root), "pfx")):
drive = map_drive(root, volume)
@@ -586,11 +610,15 @@ def drive_folder(root, value):
text = value.decode("utf-8")
except UnicodeDecodeError:
return value
if not re.match(r"(?i)^z:[\\/]", text):
holds_root = rootfs_drive(root, text)
if not holds_root and not re.match(r"(?i)^z:[\\/]", text):
return value
folder = windows_path(root, text)
if not folder or not os.path.isdir(folder):
return value
if holds_root:
guest = guest_path(os.path.realpath(folder))
return value if guest is None else ("Z:" + guest).encode("utf-8")
moved = install_path(root, folder)
return value if moved.startswith("Z:") else moved.replace("\\", "/").encode("utf-8")
@@ -608,11 +636,115 @@ def move_installs(root):
return False
except (OSError, ValueError):
return False
write_bytes(path, moved)
return True
def rootfs_drives(root):
host = rootfs()
folder = dosdevices(root)
if not host:
return {}
try:
names = sorted(os.listdir(folder))
except OSError:
return {}
drives = {}
for name in names:
link = os.path.join(folder, name)
if len(name) == 2 and name[0].lower() in DRIVES and name[1] == ":" and os.path.islink(link):
target = os.path.realpath(link)
if inside(host, target):
drives[name[0].lower()] = host[len(target):].strip("/")
return drives
def write_bytes(path, data):
with open(path + ".tmp", "wb") as f:
f.write(moved)
f.write(data)
shutil.copymode(path, path + ".tmp")
os.replace(path + ".tmp", path)
return True
def install_folders(root):
try:
with open(os.path.join(drive_c(root), *PRODUCT_DB), "rb") as f:
data = f.read()
except FileNotFoundError:
return []
folders = []
rewrite_field(data, INSTALL_FOLDER, lambda value: folders.append(value) or value)
return folders
def json_strings(value):
if isinstance(value, str):
yield value
elif isinstance(value, dict):
for key, item in value.items():
yield key
yield from json_strings(item)
elif isinstance(value, list):
for item in value:
yield from json_strings(item)
def escapes(tail):
depth = 0
for part in re.split(rb"[\\/]+", tail):
if part == b"..":
depth -= 1
if depth < 0:
return True
elif part and part != b".":
depth += 1
return False
def drop_rootfs_drives(root):
pfx = os.path.join(prefix(root), "pfx")
drives = rootfs_drives(root)
if not drives or wine_processes(pfx):
return []
try:
folders = install_folders(root)
except ValueError:
return []
texts = {}
for path in (os.path.join(pfx, "system.reg"), os.path.join(pfx, "user.reg"), os.path.join(drive_c(root), *CONFIG)):
try:
with open(path, "rb") as f:
texts[path] = f.read()
except FileNotFoundError:
pass
sep = rb"(?:\\\\|/)"
changed = dict(texts)
for letter, rest in drives.items():
head = rb"(?<![A-Za-z0-9])[" + letter.encode() + letter.upper().encode() + rb"]:"
inner = b"".join(sep + re.escape(part.encode()) for part in rest.split("/") if part)
for path in changed:
changed[path] = re.sub(head + inner + rb"(?=(" + sep + rb"[^\"\r\n]*))",
lambda m: m.group(0) if escapes(m.group(1)) else b"Z:", changed[path])
for path, data in changed.items():
if data != texts[path]:
write_bytes(path, data)
seen = list(changed.values())
config = os.path.join(drive_c(root), *CONFIG)
if config in changed:
try:
seen += [text.encode("utf-8", "replace") for text in json_strings(json.loads(changed[config].decode("utf-8-sig")))]
except ValueError:
return []
dropped = []
for letter in sorted(drives):
drive = letter.encode() + letter.upper().encode()
used = rb"(?<![A-Za-z0-9])[" + drive + rb"]:[\\/]"
if any(re.match(rb"[" + drive + rb"]:[\\/]", folder.lstrip()) for folder in folders):
continue
if not any(re.search(used, data) for data in seen):
os.unlink(os.path.join(dosdevices(root), letter + ":"))
dropped.append(letter)
return dropped
def wow_folders(root):
@@ -725,9 +857,14 @@ def configure(root, library=None):
return
try:
if move_installs(root):
say("Battle.net's installed games on a mapped volume now use its Wine drive")
say("Battle.net's installed games now use the Wine drive of their volume")
except OSError as error:
say("Battle.net's installed games not moved to their Wine drive: %s" % error)
try:
for letter in drop_rootfs_drives(root):
say("Wine drive %s: held the runtime and is no longer used; removed" % letter.upper())
except OSError as error:
say("Battle.net's unused runtime drive not removed: %s" % error)
try:
wallpaper(root)
except OSError as error:
@@ -3,13 +3,16 @@ import base64
import fcntl
import json
import os
import secrets
import signal
import socket
import struct
import subprocess
import sys
import threading
SOCKET_FILE = "/etc/droiddeck/bwrap-socket"
MAX_FORWARDED_FDS = 253
def socket_name():
@@ -94,6 +97,7 @@ class Spec:
self.json_fds = []
self.keep_fds = []
self.lock_files = []
self.lock_fds = []
self.command = []
self.argv0 = None
self.env_tool = None
@@ -363,6 +367,7 @@ def hold_locks(s):
sys.stderr.write("bwrap: Can't lock file %s: %s\n" % (path, e.strerror))
sys.exit(1)
os.set_inheritable(fd, True)
s.lock_fds.append(fd)
def report_pid(s, pid):
@@ -379,8 +384,28 @@ def report_pid(s, pid):
pass
def bind_flatpak_info(s):
if not s.env.get("DDNATV_ROOT"):
return
for op in s.ops:
if op["t"] != "file" or op["dest"] != "/.flatpak-info":
continue
try:
fd = os.memfd_create("flatpak-info", 0)
except (AttributeError, OSError):
return
data = memoryview(op["data"])
while data:
data = data[os.write(fd, data):]
os.lseek(fd, 0, os.SEEK_SET)
entry = "/proc/%d/fd/%d:/.flatpak-info" % (os.getpid(), fd)
binds = s.env.get("DDNATV_BINDS")
s.env["DDNATV_BINDS"] = binds + "|" + entry if binds else entry
def run_here(s):
report_pid(s, os.getpid())
bind_flatpak_info(s)
for fd in s.json_fds:
os.close(fd)
if s.cwd:
@@ -410,7 +435,53 @@ def recv_exact(sock, n):
return buf
def inherited_fds(s):
own = set(s.info_fds + s.json_fds + s.keep_fds + s.lock_fds)
fds = []
for name in os.listdir("/proc/self/fd"):
fd = int(name)
if fd <= 2 or fd in own:
continue
try:
if os.get_inheritable(fd):
fds.append(fd)
except OSError:
pass
return sorted(fds)
def hand_over(listener, fds):
try:
conn, _ = listener.accept()
except OSError:
return
finally:
listener.close()
with conn:
creds = conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, struct.calcsize("3i"))
if struct.unpack("3i", creds)[1] != os.getuid():
return
conn.sendmsg([",".join(map(str, fds)).encode()],
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, struct.pack("%di" % len(fds), *fds))])
def offer_fds(s):
fds = inherited_fds(s)
if not fds:
return
if len(fds) > MAX_FORWARDED_FDS:
sys.stderr.write("bwrap: Too many inherited file descriptors: %d\n" % len(fds))
sys.exit(1)
name = "droiddeck-fds-" + secrets.token_hex(16)
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
listener.bind("\0" + name)
listener.listen(1)
s.env["DROIDDECK_FDS"] = name
threading.Thread(target=hand_over, args=(listener, fds), daemon=True).start()
def run_by_app(s):
offer_fds(s)
ops = []
for op in s.ops:
op = dict(op)
@@ -0,0 +1,14 @@
#!/bin/sh
set -eu
path=$1 target=$2 mode=$3
if [ "$mode" = migrate ]; then
resolved=$(readlink -f "$target") || exit 0
[ -n "$resolved" ] && [ -L "$path" ] && [ "$(readlink -f "$path")" = "$resolved" ] || exit 0
elif [ "$mode" != install ]; then
exit 1
fi
tmp=$(mktemp "${path}.XXXXXX")
trap 'rm -f "$tmp"' EXIT
printf '#!/bin/sh\nexec %s "$@"\n' "$target" > "$tmp"
chmod 755 "$tmp"
mv -f "$tmp" "$path"
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/python3
import configparser
import os
import stat
import sys
import gi
gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib
NAME = "org.freedesktop.portal.Documents"
PATH = "/org/freedesktop/portal/documents"
VERSION = 5
PROC = sys.argv[1] if len(sys.argv) > 1 else "/proc"
AS_NEEDED_BY_APP = 1 << 2
DIRECTORY = 1 << 3
FAILED = "org.freedesktop.portal.Error.Failed"
NOT_FOUND = "org.freedesktop.portal.Error.NotFound"
NOT_ALLOWED = "org.freedesktop.portal.Error.NotAllowed"
INVALID = "org.freedesktop.portal.Error.InvalidArgument"
INTROSPECTION = """
<node>
<interface name="org.freedesktop.portal.Documents">
<method name="GetMountPoint"><arg type="ay" direction="out"/></method>
<method name="Add">
<arg type="h" direction="in"/><arg type="b" direction="in"/><arg type="b" direction="in"/>
<arg type="s" direction="out"/>
</method>
<method name="AddNamed">
<arg type="h" direction="in"/><arg type="ay" direction="in"/><arg type="b" direction="in"/>
<arg type="b" direction="in"/><arg type="s" direction="out"/>
</method>
<method name="AddFull">
<arg type="ah" direction="in"/><arg type="u" direction="in"/><arg type="s" direction="in"/>
<arg type="as" direction="in"/><arg type="as" direction="out"/><arg type="a{sv}" direction="out"/>
</method>
<method name="AddNamedFull">
<arg type="h" direction="in"/><arg type="ay" direction="in"/><arg type="u" direction="in"/>
<arg type="s" direction="in"/><arg type="as" direction="in"/><arg type="s" direction="out"/>
<arg type="a{sv}" direction="out"/>
</method>
<method name="GrantPermissions">
<arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="as" direction="in"/>
</method>
<method name="RevokePermissions">
<arg type="s" direction="in"/><arg type="s" direction="in"/><arg type="as" direction="in"/>
</method>
<method name="Delete"><arg type="s" direction="in"/></method>
<method name="Lookup"><arg type="ay" direction="in"/><arg type="s" direction="out"/></method>
<method name="Info">
<arg type="s" direction="in"/><arg type="ay" direction="out"/><arg type="a{sas}" direction="out"/>
</method>
<method name="List"><arg type="s" direction="in"/><arg type="a{say}" direction="out"/></method>
<method name="GetHostPaths"><arg type="as" direction="in"/><arg type="a{say}" direction="out"/></method>
<property name="version" type="u" access="read"/>
</interface>
</node>
"""
def passed_fds(invocation, handles):
fd_list = invocation.get_message().get_unix_fd_list()
fds = fd_list.peek_fds() if fd_list else []
return [fds[h] if 0 <= h < len(fds) else -1 for h in handles]
def usable(fd, flags):
try:
mode = os.fstat(fd).st_mode
except OSError:
return False
return stat.S_ISDIR(mode) if flags & DIRECTORY else stat.S_ISREG(mode)
def app_name(pid):
info = configparser.ConfigParser(interpolation=None)
try:
with open(os.path.join(PROC, pid, "root/.flatpak-info")) as f:
info.read_file(f)
except (OSError, UnicodeDecodeError, configparser.Error):
return None
return info.get("Application", "name", fallback=None)
def root_of(pid):
try:
return os.stat(os.path.join(PROC, str(pid), "root", "."))
except OSError:
return None
def app_pids(app_id):
roots = {pid: root_of(pid) for pid in os.listdir(PROC) if pid.isdigit() and app_name(pid) == app_id}
own = root_of(os.getpid())
apart = [pid for pid, root in roots.items() if not (own and root and os.path.samestat(own, root))]
return apart or list(roots)
def access_mode(permissions):
mode = os.R_OK if "read" in permissions else 0
return mode | os.W_OK if "write" in permissions else mode
def under(path, prefix):
return path == prefix or path.startswith(prefix.rstrip("/") + "/")
def spellings(path):
root = os.environ.get("DDNATV_ROOT", "").rstrip("/")
if root and under(path, root):
path = path[len(root):] or "/"
names = [path]
for bind in filter(None, os.environ.get("DDNATV_BINDS", "").split("|")):
host, _, guest = bind.partition(":")
if host and guest and under(path, guest):
name = host + path[len(guest.rstrip("/")):]
if not (root and under(name, root)) and name not in names:
names.append(name)
return names
def same_file(path, picked):
try:
return os.path.samestat(os.stat(path), picked)
except OSError:
return False
def app_reaches(app_id, path, picked, permissions):
if not app_id:
return True
mode = access_mode(permissions) or os.F_OK
roots = [os.path.join(PROC, pid, "root") for pid in app_pids(app_id)]
return any(same_file(root + name, picked) and os.access(root + name, mode)
for root in roots for name in spellings(path))
def fd_path(fd):
try:
path = os.readlink("/proc/self/fd/%d" % fd)
except OSError:
return None
return path if path.startswith("/") else None
def reachable_in_place(invocation, flags, handles, directories, app_id, permissions):
if not flags & AS_NEEDED_BY_APP:
invocation.return_dbus_error(NOT_ALLOWED, "Documents can only be shared in place")
return False
fds = passed_fds(invocation, handles)
if not all(fd >= 0 and usable(fd, DIRECTORY if directories else flags) for fd in fds):
invocation.return_dbus_error(INVALID, "Invalid fd passed")
return False
if not all(fd_path(fd) and app_reaches(app_id, fd_path(fd), os.fstat(fd), permissions) for fd in fds):
invocation.return_dbus_error(NOT_ALLOWED, "The application can't reach this location without the document store")
return False
return True
def on_call(connection, sender, path, interface, method, params, invocation):
args = params.unpack()
if method == "AddFull":
handles, flags = args[0], args[1]
if reachable_in_place(invocation, flags, handles, False, args[2], args[3]):
invocation.return_value(GLib.Variant("(asa{sv})", ([""] * len(handles), {})))
elif method == "AddNamedFull":
if reachable_in_place(invocation, args[2], [args[0]], True, args[3], args[4]):
invocation.return_value(GLib.Variant("(sa{sv})", ("", {})))
elif method == "Lookup":
invocation.return_value(GLib.Variant("(s)", ("",)))
elif method == "List":
invocation.return_value(GLib.Variant("(a{say})", ({},)))
elif method == "GetHostPaths":
invocation.return_value(GLib.Variant("(a{say})", ({},)))
elif method in ("Add", "AddNamed"):
invocation.return_dbus_error(NOT_ALLOWED, "Documents can only be shared in place")
elif method in ("GrantPermissions", "RevokePermissions", "Delete", "Info"):
invocation.return_dbus_error(NOT_FOUND, "Invalid document id")
else:
invocation.return_dbus_error(FAILED, "No document store mount")
def on_get(connection, sender, path, interface, prop):
return GLib.Variant("u", VERSION) if prop == "version" else None
def main():
loop = GLib.MainLoop()
info = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION).interfaces[0]
bus = Gio.bus_get_sync(Gio.BusType.SESSION, None)
bus.register_object(PATH, info, on_call, on_get, None)
Gio.bus_own_name_on_connection(bus, NAME, Gio.BusNameOwnerFlags.DO_NOT_QUEUE, None, lambda *_: loop.quit())
loop.run()
return 1
if __name__ == "__main__":
sys.exit(main())
@@ -1,4 +1,5 @@
#!/usr/bin/python3
import fcntl
import hashlib
import json
import os
@@ -6,6 +7,8 @@ import platform
import re
import runpy
import signal
import stat
import struct
import subprocess
import sys
import tempfile
@@ -182,6 +185,11 @@ def arkham_city_x87(game):
return {"FEX_X87REDUCEDPRECISION": "0"}, [], "Batman: Arkham City: FEX with full x87 precision"
@fix
def split_second_x87_fip(game):
if game.app_id == "297860" or game.stem == "splitsecond":
return {"FEX_JITFEATURES": "enablex87fip"}, [], "Split/Second: FEX x87 FIP emulation on (its SecuROM stops with error 8016 without it)"
@fix
def doom_2016_swapchain_images(game):
@@ -876,6 +884,8 @@ def read_vdf(text):
def run_keys(items, appid=""):
# (hasrunkey, value name, MinimumHasRunValue) of each "run process" entry; Steam runs the process unless the
# value is a DWORD of at least that minimum (1 when the script does not say)
appid = next((value for name, value in items if name.lower() == "appid" and isinstance(value, str)), appid)
found = set()
for name, value in items:
@@ -884,30 +894,44 @@ def run_keys(items, appid=""):
if any(isinstance(v, str) and re.fullmatch(r"process [0-9]+", n.lower()) for n, v in value):
key = next((v for n, v in value if n.lower() == "hasrunkey" and isinstance(v, str)),
"HKEY_LOCAL_MACHINE\\Software\\Valve\\Steam\\Apps\\" + appid)
found.add((key.lower(), name.lower()))
minimum = next((v for n, v in value if n.lower() == "minimumhasrunvalue" and isinstance(v, str)), "1")
try:
minimum = int(minimum.strip(), 0)
except ValueError:
minimum = int(minimum.strip()) if minimum.strip().isdigit() else 1
found.add((key.lower(), name.lower(), minimum))
found |= run_keys(value, appid)
return found
def registry_values(path):
found, section = set(), None
# {(key, value name): DWORD, or None for a value of another type}
found, section = {}, None
with open(path, encoding="utf-8", errors="replace") as reg:
for line in reg:
if line.startswith("["):
section = line[1:line.find("]")].replace("\\\\", "\\").lower() if "]" in line else None
elif section and line.startswith('"') and '"=' in line:
found.add((section, line[1:line.index('"=')].replace("\\\\", "\\").lower()))
name = line[1:line.index('"=')].replace("\\\\", "\\").lower()
data = line[line.index('"=') + 2:].strip()
dword = None
if data.lower().startswith("dword:"):
try:
dword = int(data[6:], 16)
except ValueError:
pass
found[(section, name)] = dword
return found
def has_run(key, value, values):
def has_run(key, value, values, minimum=1):
path = key[len("hkey_local_machine\\"):] if key.startswith("hkey_local_machine\\") else None
if path is None:
return False
views = [path]
if path.startswith("software\\"):
views.append("software\\wow6432node\\" + path[len("software\\"):])
return any((view, value) in values for view in views)
return any(isinstance(values.get((view, value)), int) and values[(view, value)] >= minimum for view in views)
def scripts_digest(scripts):
@@ -918,18 +942,49 @@ def scripts_digest(scripts):
return digest.hexdigest()
def only_guarded_runs(items):
# True when every action in the scripts is a "run process" entry. With all their hasrunkeys set, Steam's
# evaluator would run nothing, so the scripts need no run even when Steam has rewritten the file (its
# SteamID, language, install path or order change between launches).
found = False
for _, entries in items:
if not isinstance(entries, list):
return False
for _, entry in entries:
if not isinstance(entry, list):
return False
for _, block in entry:
if not isinstance(block, list):
continue
for section, actions in block:
if section.lower() != "run process" or not isinstance(actions, list):
return False
for _, action in actions:
if not isinstance(action, list) or not any(
isinstance(v, str) and re.fullmatch(r"process [0-9]+", n.lower()) for n, v in action):
return False
found = True
return found
def install_scripts_done(scripts, env):
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
try:
if (prefix / INSTALL_STAMP).read_text().strip() != scripts_digest(scripts):
return False
keys = set()
keys, parsed = set(), []
for path in scripts:
keys |= run_keys(read_vdf(Path(path).read_text(encoding="utf-8", errors="replace")))
parsed.append(read_vdf(Path(path).read_text(encoding="utf-8", errors="replace")))
keys |= run_keys(parsed[-1])
values = registry_values(prefix / "system.reg")
except (OSError, ValueError):
return False
return bool(keys) and all(has_run(key, value, values) for key, value in keys)
if not keys or not all(has_run(key, value, values, minimum) for key, value, minimum in keys):
return False
try:
if (prefix / INSTALL_STAMP).read_text().strip() == scripts_digest(scripts):
return True
except OSError:
pass
return all(only_guarded_runs(items) for items in parsed)
def record_install_scripts(digest, env):
@@ -994,6 +1049,9 @@ WINE_DLL_DIRS = ("/lib/wine/i386-windows", "/lib/wine/x86_64-windows", "/lib/win
FOREIGN_SUFFIX = ".foreign-arch"
WINE_SD = "user.wine.sd"
SHARED_DATA = "pfx/drive_c/ProgramData"
MACHINE_ID = "/etc/machine-id"
PE = runpy.run_path(str(Path(__file__).resolve().parent / "droiddeck-wine-pe"))
pe_machine = PE["pe_machine"]
@@ -1092,6 +1150,124 @@ def repair_foreign_system_dlls(prefix, proton, env=None):
return repaired
def wine_user_sid():
try:
with open(MACHINE_ID, "rb") as handle:
text = handle.read(16)
except OSError:
return (21, 0, 0, 0, 1000)
if len(text) != 16:
return (21, 0, 0, 0, 1000)
sign, digits = re.match(rb"\s*([+-]?)(?:0[xX])?([0-9a-fA-F]*)", text).groups()
machine = int(digits, 16) if digits else 0
if sign == b"-":
machine = -machine % (1 << 64)
return (21, machine >> 32, machine & 0xffffffff, os.getuid(), 1000)
def wine_sd_owner(path):
try:
data = os.getxattr(path, WINE_SD, follow_symlinks=False)
except OSError:
return None
if len(data) < 22:
return None
sid = data[22:22 + struct.unpack_from("<I", data, 6)[0]]
if len(sid) < 8 or len(sid) < 8 + 4 * sid[1]:
return None
return sid[0], int.from_bytes(sid[2:8], "big"), struct.unpack_from("<%dI" % sid[1], sid, 8)
def is_stale_owner(owner, user):
if owner is None:
return False
revision, authority, subs = owner
return revision == 1 and authority == 5 and len(subs) == 5 and subs[0] == 21 and subs[4] == 1000 \
and subs != user
def heal_wine_entry(path, is_dir, user):
try:
mode = stat.S_IMODE(os.lstat(path).st_mode)
except OSError:
return None, False
readable = mode
if not mode & stat.S_IRUSR:
readable = mode | stat.S_IRUSR
try:
os.chmod(path, readable)
except OSError:
return None, False
final = mode
stale = is_stale_owner(wine_sd_owner(path), user)
cleared = False
if stale and (not mode & stat.S_IRUSR or is_dir and not mode & stat.S_IXUSR):
final = mode | (stat.S_IRWXU if is_dir else stat.S_IRUSR | stat.S_IWUSR)
try:
if stale:
os.chmod(path, final | stat.S_IWUSR)
try:
os.removexattr(path, WINE_SD, follow_symlinks=False)
cleared = True
except OSError:
pass
if not final & stat.S_IWUSR:
os.chmod(path, final)
elif final != readable:
os.chmod(path, final)
except OSError:
return None, cleared
return (mode, final), cleared
def heal_shared_data(prefix):
root = Path(prefix) / SHARED_DATA
if root.is_symlink() or not root.is_dir():
return [], []
try:
lock = os.open(root.parent.parent, os.O_RDONLY | os.O_DIRECTORY)
except OSError:
return [], []
try:
fcntl.flock(lock, fcntl.LOCK_EX)
return heal_shared_data_locked(root)
finally:
os.close(lock)
def heal_shared_data_locked(root):
user = wine_user_sid()
unlocked = []
cleared = []
pending = [(str(root), True)]
while pending:
path, is_dir = pending.pop()
modes, was_cleared = heal_wine_entry(path, is_dir, user)
name = os.path.relpath(path, root)
if was_cleared:
cleared.append(name)
if modes is None:
continue
mode, final = modes
if final != mode:
unlocked.append(name)
if not is_dir or final & (stat.S_IRUSR | stat.S_IXUSR) != stat.S_IRUSR | stat.S_IXUSR:
continue
try:
with os.scandir(path) as entries:
for entry in entries:
try:
if entry.is_dir(follow_symlinks=False):
pending.append((entry.path, True))
elif entry.is_file(follow_symlinks=False):
pending.append((entry.path, False))
except OSError:
continue
except OSError:
continue
return sorted(unlocked), sorted(cleared)
def is_wine_dll_link(path):
try:
return os.path.islink(path) and os.path.dirname(os.readlink(path)).endswith(WINE_DLL_DIRS)
@@ -1434,6 +1610,14 @@ def main():
except OSError as error:
restored = fixed = []
print("droiddeck-game-env: prefix system DLL check skipped (%s)" % error, file=sys.stderr)
try:
unlocked, cleared = heal_shared_data(prefix_path)
except OSError as error:
unlocked = cleared = []
print("droiddeck-game-env: ProgramData owner check skipped (%s)" % error, file=sys.stderr)
if cleared:
print("droiddeck-game-env: cleared %d stale Windows owners in ProgramData; unlocked: %s"
% (len(cleared), ", ".join(unlocked) or "none"), file=sys.stderr)
if restored:
print("droiddeck-game-env: restored system DLLs this Proton's own programs do not load: %s" % ", ".join(restored),
file=sys.stderr)
@@ -243,6 +243,7 @@ def run_patch(folder, appid, installer, game):
previous = dict(os.environ)
try:
os.environ.update(env)
os.environ["DD_STORE_PROTON"] = command
pfx = Path(prefix) / "pfx"
if not (pfx / "system.reg").is_file() or not (pfx / "drive_c/windows/system32/reg.exe").is_file():
subprocess.run([command, "run", "wineboot.exe", "-u"], env=env, timeout=90, check=True)
@@ -1,4 +1,5 @@
#!/usr/bin/python3
import glob
import os
HOME = os.environ.get("HOME", "/root")
@@ -904,25 +905,103 @@ input_r_y_minus_axis = "-3"
"""
RETROARCH_SYSTEM_CFG = "/etc/retroarch.cfg"
RETROARCH_PACKAGED = {
"assets_directory": "~/.config/retroarch/assets",
"libretro_directory": "~/.config/retroarch/cores",
"libretro_info_path": "~/.config/retroarch/cores",
"menu_show_core_updater": "true",
}
def cfg_value(line):
key, sep, value = line.partition("=")
return key.strip(), value.strip().strip('"') if sep else None
def retroarch_system_values():
try:
with open(RETROARCH_SYSTEM_CFG, encoding="utf-8", errors="replace") as f:
pairs = [cfg_value(l) for l in f if not l.lstrip().startswith("#")]
except OSError:
return {}
return {k: v for k, v in pairs if k in RETROARCH_PACKAGED and v is not None}
def retroarch_has_cores(directory):
return bool(glob.glob(os.path.join(os.path.expanduser(directory), "*.so")))
def retroarch_installed_cores(d):
for directory in (os.path.join(d, "cores"), RETROARCH_PACKAGED["libretro_directory"]):
if retroarch_has_cores(directory):
return directory
return None
def retroarch():
d = os.path.join(CONFIG, "retroarch")
seed(os.path.join(d, "autoconfig/sdl2/Xbox 360 Controller.cfg"), RETROARCH_PROFILE, "RetroArch (profile)")
cfg = os.path.join(d, "retroarch.cfg")
system = retroarch_system_values()
if not os.path.isfile(cfg):
seed(cfg, 'input_joypad_driver = "sdl2"\ninput_autodetect_enable = "true"\n', "RetroArch")
if retroarch_installed_cores(d):
system.pop("libretro_directory", None)
text = 'input_joypad_driver = "sdl2"\ninput_autodetect_enable = "true"\n'
text += "".join(f'{k} = "{v}"\n' for k, v in system.items())
seed(cfg, text, "RetroArch")
return
with open(cfg, encoding="utf-8", errors="replace") as f:
lines = f.read().splitlines()
changed = False
paths = {}
for i, line in enumerate(lines):
key, value = cfg_value(line)
if key in system and key != "menu_show_core_updater" and value is not None:
paths.setdefault(key, []).append((i, value))
for key, entries in paths.items():
if not any(value == "" for _, value in entries):
continue
fallback = system[key]
if key == "libretro_directory":
fallback = retroarch_installed_cores(d) or fallback
value = next((value for _, value in entries if value), fallback)
first = entries[0][0]
replacement = f'{key} = "{value}"'
if lines[first] != replacement or len(entries) > 1:
changed = True
lines[first] = replacement
for i, _ in entries[1:]:
lines[i] = None
lines = [line for line in lines if line is not None]
seen = set()
for i, l in enumerate(lines):
if l.replace(" ", "").startswith('input_joypad_driver="udev"'):
lines[i] = 'input_joypad_driver = "sdl2"'
changed = True
key, value = cfg_value(l)
if key in system and value is not None:
seen.add(key)
if (
key == "libretro_directory"
and value == RETROARCH_PACKAGED[key]
and (retroarch_has_cores(value) or retroarch_has_cores(os.path.join(d, "cores")))
):
continue
if key in system and key != "menu_show_core_updater" and value == RETROARCH_PACKAGED[key] and system[key] != value:
lines[i] = f'{key} = "{system[key]}"'
changed = True
for key, value in system.items():
if key not in seen:
if key == "libretro_directory" and retroarch_installed_cores(d):
continue
lines.append(f'{key} = "{value}"')
changed = True
if changed:
with open(cfg + ".tmp", "w", encoding="utf-8") as f:
f.write("\n".join(lines) + "\n")
os.replace(cfg + ".tmp", cfg)
print(f"droiddeck-pad-defaults: RetroArch: joypad driver udev -> sdl2 ({cfg})")
print(f"droiddeck-pad-defaults: RetroArch: controller driver and packaged paths ({cfg})")
SWITCH_PAD = "engine:sdl,port:0,guid:030000005e0400008e02000010010000,"
@@ -13,8 +13,10 @@ RELEASES = "https://api.github.com/repos/%s/releases"
SOURCES = {
"ge": ("GloriousEggroll/proton-ge-custom", re.compile(r"aarch64\.tar\.(gz|xz)$")),
"cachyos": ("CachyOS/proton-cachyos", re.compile(r"arm64\.tar\.(gz|xz)$")),
"droiddeck": ("Droid-Deck/DroidDeck-Proton", re.compile(r"aarch64\.tar\.(gz|xz)$")),
"droiddeck": ("Droid-Deck/DroidDeck-Proton", re.compile(r"^DroidDeck-Proton-.*aarch64\.tar\.(gz|xz)$")),
"bionic": ("Droid-Deck/DroidDeck-Proton", re.compile(r"^DroidDeck-Bionic-.*aarch64\.tar\.(gz|xz)$")),
}
PRERELEASES = {"bionic"}
USER_AGENT = "droiddeck-proton-extra"
NEED_BYTES = 4 * 1024 * 1024 * 1024
@@ -33,7 +35,7 @@ def fetch_json(url):
def pick_asset(source):
repo, pattern = SOURCES[source]
for release in fetch_json(RELEASES % repo + "?per_page=15"):
if release.get("draft") or release.get("prerelease"):
if release.get("draft") or (release.get("prerelease") and source not in PRERELEASES):
continue
assets = {a["name"]: a["browser_download_url"] for a in release.get("assets", ())}
for name in sorted(assets):
@@ -66,6 +66,14 @@ ensure_machine_id() {
} 2>/dev/null
ensure_machine_id
write_document_store_service() {
[ -x /usr/local/bin/droiddeck-documents ] || return 0
mkdir -p /usr/local/share/dbus-1/services &&
printf '[D-BUS Service]\nName=org.freedesktop.portal.Documents\nExec=/usr/local/bin/droiddeck-documents\n' \
> /usr/local/share/dbus-1/services/org.freedesktop.portal.Documents.service
} 2>/dev/null
write_document_store_service
write_system_bus_config() {
mkdir -p /run/dbus /usr/local/share/droiddeck
cat > /usr/local/share/droiddeck/system-bus.conf <<'BUSCONF'
@@ -2,6 +2,7 @@
import base64
import binascii
import functools
import json
import os
import re
@@ -156,7 +157,27 @@ def ask(channel, request, timeout=TIMEOUT, claim=False):
def windows_path(unix):
return "Z:" + unix.replace("/", "\\")
tool = bionic_tool(os.environ.get("DD_STORE_PROTON", ""))
return (tool and bionic_path(tool, unix)) or "Z:" + unix.replace("/", "\\")
def bionic_tool(proton):
if not proton or not os.environ.get("DDNATV_ROOT"):
return None
tool = Path(proton).parent
return str(tool / "proton") if (tool / "bionic" / "launch.sh").is_file() else None
@functools.lru_cache(maxsize=None)
def bionic_path(proton, unix):
# DroidDeck-Bionic's Wine sees Android's root on Z:, so a guest path is named by the Android file it maps to.
try:
result = subprocess.run([proton, "getcompatpath", unix], stdin=subprocess.DEVNULL, capture_output=True,
text=True, timeout=TIMEOUT)
except (OSError, subprocess.SubprocessError):
return None
path = result.stdout.strip()
return path if result.returncode == 0 and path[:3] == "Z:\\" else None
def reg_escape(value):
@@ -1479,14 +1500,32 @@ def ea_touchup(folder, sidecar, compat_data, proton, timeout=900):
except OSError:
pass
args = touchup_args(str(extra.get("touchupArgs") or ""), str(extra.get("locale") or "en_US"), windows_path(str(folder)).rstrip("\\"))
try:
sink = tempfile.TemporaryFile()
except OSError:
sink = None
try:
run = subprocess.run([proton, "run", str(exe)] + args, cwd=str(exe.parent), stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
stdout=sink or subprocess.DEVNULL, stderr=subprocess.STDOUT, timeout=timeout)
result = "ok" if run.returncode == 0 else "exit-%d" % run.returncode
except subprocess.TimeoutExpired:
result = "timeout"
except OSError:
return "failed"
finally:
output = b""
if sink is not None:
try:
sink.seek(0, os.SEEK_END)
sink.seek(max(0, sink.tell() - 65536))
output = sink.read()
except OSError:
pass
sink.close()
for line in output.decode("utf-8", "replace").splitlines()[-200:]:
log("touchup: " + line)
if result != "ok":
return result
try:
marker.write_text(stamp)
except OSError:
@@ -187,6 +187,9 @@ dd_components() {
# The selected system PowerVR runtime supplies DXVK at launch. Keep saved selections
# for a later manual-driver session without rewriting this Proton's bundled files now.
[ "$comp" = dxvk ] && [ -n "${DROIDDECK_POWERVR_RUNTIME:-}" ] && continue
# DroidDeck-Bionic loads only Android-built FEX unix libraries: -bionic packages or its own saved copy.
# A row without such a source (a glibc package, or a removal) is skipped and the tool keeps its FEX files.
if [ "$comp" = fex ] && [[ "$cm_tool" == DroidDeck-Bionic* ]] && [[ "${src,,}" != *bionic* ]]; then continue; fi
cm_rows+=("$comp"$'\\t'"$rel"$'\\t'"$sum"$'\\t'"$src")
[ "$src" != "-" ] && [ -f "$base/$rel" ] && cm_files+=("$base/$rel")
done <<< "$cm_selected"
@@ -290,6 +293,23 @@ dd_vacdiag() {
}
"""
# DroidDeck-Bionic runs only without proot. With proot on, a launch Steam sends to a DroidDeck-Bionic tool goes to the
# newest DroidDeck-Proton's wrapper before anything else runs, as if that Proton had been picked; the picks stay as set.
DD_BIONIC_PROOT_FALLBACK = """
if [ -f "$here/bionic/launch.sh" ] && [ -z "${DDNATV_ROOT:-}" ]; then
dd_fallback=$(cd "$here/.." 2>/dev/null && for d in DroidDeck-Proton*; do
[ -x "$d/droiddeck-proton-wrap" ] && [ ! -e "$d/bionic/launch.sh" ] || continue
v=${d#DroidDeck-Proton}; printf '%s\\t%s/%s\\n' "${v#[ -]}" "$PWD" "$d"
done | sort -V | tail -n 1 | cut -f 2-)
if [ -n "$dd_fallback" ]; then
echo "droiddeck-proton: DroidDeck-Bionic needs Run without proot; this launch uses ${dd_fallback##*/}" >&2
exec "$dd_fallback/droiddeck-proton-wrap" "$verb" "$@"
fi
echo "droiddeck-proton: DroidDeck-Bionic needs Run without proot, and no DroidDeck-Proton is installed to run this launch instead; turn on Run without proot or install DroidDeck-Proton" >&2
exit 1
fi
"""
DD_DRIVER_QUERY_SKIP = """
case "$verb:${1##*/}:${STEAM_COMPAT_DATA_PATH%/}" in
run:d3ddriverquery64.exe:*/compatdata/0 | run:d3ddriverquery.exe:*/compatdata/0)
@@ -487,7 +507,7 @@ dd_run ${DD_TASKSET:-} /usr/local/bin/droiddeck-game-env "$DD_STORE_PROTON" "$ve
def extra_wrapper_sh(entry_point):
return (EXTRA_WRAPPER_SH % entry_point).replace(
'here=$(dirname "$0")',
'here=$(dirname "$0")\n' + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
'here=$(dirname "$0")\n' + DD_BIONIC_PROOT_FALLBACK + DD_DRIVER_QUERY_SKIP + DD_DESKTOP_GPU_SETUP + DD_DIRECTAUDIO_SETUP + DD_GAME_CPUS_SETUP
+ DD_IDTECH3_SETUP + DD_VACDIAG_SETUP + DD_COMPONENTS_SETUP + DD_LIBPATH_SETUP + DD_STORE_SETUP, 1)
+5 -3
View File
@@ -419,9 +419,11 @@ static void *real_dlsym(void);
* searches, so the handle the program opened is the only way back to the real implementation. */
static _Atomic(void *) udev_handle;
__attribute__((visibility("hidden"))) void bl_inputudev_note_dlopen(const char *path, void *handle) {
if (handle != NULL && path != NULL && strstr(path, "libudev") != NULL)
atomic_store_explicit(&udev_handle, handle, memory_order_release);
__attribute__((visibility("hidden"))) void bl_inputudev_note_dlopen(const char *path, void *handle,
void *(*open)(const char *, int)) {
if (handle == NULL || path == NULL || strstr(path, "libudev") == NULL) return;
if (open(path, RTLD_LAZY | RTLD_NOLOAD | RTLD_NODELETE) == NULL) return;
atomic_store_explicit(&udev_handle, handle, memory_order_release);
}
static void *next_symbol(const char *name) {
+3 -2
View File
@@ -100,7 +100,8 @@ static long path_statx(int dirfd, const char *path, int flags, unsigned int mask
return next_statx(dirfd, path, flags, mask, out);
}
void bl_inputudev_note_dlopen(const char *path, void *handle) __attribute__((weak, visibility("hidden")));
void bl_inputudev_note_dlopen(const char *path, void *handle, void *(*open)(const char *, int))
__attribute__((weak, visibility("hidden")));
void *dlopen(const char *filename, int flags) {
void *handle;
@@ -114,7 +115,7 @@ void *dlopen(const char *filename, int flags) {
flags &= ~RTLD_DEEPBIND;
}
handle = real_dlopen != NULL ? real_dlopen(filename, flags) : NULL;
if (handle != NULL && bl_inputudev_note_dlopen != NULL) bl_inputudev_note_dlopen(filename, handle);
if (handle != NULL && bl_inputudev_note_dlopen != NULL) bl_inputudev_note_dlopen(filename, handle, real_dlopen);
return handle;
}
+1 -2
View File
@@ -54,12 +54,11 @@ static void resolve_symlinks(const char *path, char *out, size_t out_size, int d
if (used >= sizeof(done) - 1) return;
if (!follow_link(done, link_target, sizeof(link_target))) {
struct stat st;
if (rest[strspn(rest, "/")] && (syscall(SYS_newfstatat, AT_FDCWD, done, &st, 0) != 0 || !S_ISDIR(st.st_mode))) return;
if (*rest && (syscall(SYS_newfstatat, AT_FDCWD, done, &st, 0) != 0 || !S_ISDIR(st.st_mode))) return;
continue;
}
if (++links > 40) return;
size_t m = ddnatv_append(next_path, sizeof(next_path), 0, link_target, strlen(link_target));
m = ddnatv_append(next_path, sizeof(next_path), m, "/", 1);
m = ddnatv_append(next_path, sizeof(next_path), m, rest, strlen(rest));
if (m >= sizeof(next_path) - 1) return;
if (link_target[0] == '/') {
+21 -3
View File
@@ -505,7 +505,7 @@ int is_selinux_enabled(void) { return 0; }
ssize_t getxattr(const char *path, const char *name, void *value, size_t size) {
static ssize_t (*orig_getxattr)(const char *, const char *, void *, size_t) = NULL;
if (!orig_getxattr) orig_getxattr = (ssize_t (*)(const char *, const char *, void *, size_t))dlsym(RTLD_NEXT, "getxattr");
if (is_selinux_xattr(name)) {
if (is_selinux_xattr(name) || (name && strcmp(name, "security.capability") == 0)) {
errno = ENODATA;
return -1;
}
@@ -516,7 +516,7 @@ ssize_t getxattr(const char *path, const char *name, void *value, size_t size) {
ssize_t lgetxattr(const char *path, const char *name, void *value, size_t size) {
static ssize_t (*orig_lgetxattr)(const char *, const char *, void *, size_t) = NULL;
if (!orig_lgetxattr) orig_lgetxattr = (ssize_t (*)(const char *, const char *, void *, size_t))dlsym(RTLD_NEXT, "lgetxattr");
if (is_selinux_xattr(name)) {
if (is_selinux_xattr(name) || (name && strcmp(name, "security.capability") == 0)) {
errno = ENODATA;
return -1;
}
@@ -543,7 +543,7 @@ ssize_t llistxattr(const char *path, char *list, size_t size) {
ssize_t fgetxattr(int fd, const char *name, void *value, size_t size) {
static ssize_t (*orig_fgetxattr)(int, const char *, void *, size_t) = NULL;
if (!orig_fgetxattr) orig_fgetxattr = (ssize_t (*)(int, const char *, void *, size_t))dlsym(RTLD_NEXT, "fgetxattr");
if (is_selinux_xattr(name)) {
if (is_selinux_xattr(name) || (name && strcmp(name, "security.capability") == 0)) {
errno = ENODATA;
return -1;
}
@@ -558,6 +558,7 @@ ssize_t flistxattr(int fd, char *list, size_t size) {
}
int setxattr(const char *path, const char *name, const void *value, size_t size, int flags) {
if (name && strcmp(name, "security.capability") == 0) return 0;
static int (*orig_setxattr)(const char *, const char *, const void *, size_t, int) = NULL;
if (!orig_setxattr) orig_setxattr = (int (*)(const char *, const char *, const void *, size_t, int))dlsym(RTLD_NEXT, "setxattr");
char pbuf[PATH_MAX];
@@ -565,6 +566,7 @@ int setxattr(const char *path, const char *name, const void *value, size_t size,
}
int lsetxattr(const char *path, const char *name, const void *value, size_t size, int flags) {
if (name && strcmp(name, "security.capability") == 0) return 0;
static int (*orig_lsetxattr)(const char *, const char *, const void *, size_t, int) = NULL;
if (!orig_lsetxattr) orig_lsetxattr = (int (*)(const char *, const char *, const void *, size_t, int))dlsym(RTLD_NEXT, "lsetxattr");
char pbuf[PATH_MAX];
@@ -572,6 +574,7 @@ int lsetxattr(const char *path, const char *name, const void *value, size_t size
}
int removexattr(const char *path, const char *name) {
if (name && strcmp(name, "security.capability") == 0) return 0;
static int (*orig_removexattr)(const char *, const char *) = NULL;
if (!orig_removexattr) orig_removexattr = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "removexattr");
char pbuf[PATH_MAX];
@@ -579,12 +582,27 @@ int removexattr(const char *path, const char *name) {
}
int lremovexattr(const char *path, const char *name) {
if (name && strcmp(name, "security.capability") == 0) return 0;
static int (*orig_lremovexattr)(const char *, const char *) = NULL;
if (!orig_lremovexattr) orig_lremovexattr = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "lremovexattr");
char pbuf[PATH_MAX];
return orig_lremovexattr ? orig_lremovexattr(rewrite_path(path, pbuf, sizeof(pbuf)), name) : -1;
}
int fsetxattr(int fd, const char *name, const void *value, size_t size, int flags) {
static int (*orig)(int, const char *, const void *, size_t, int) = NULL;
if (name && strcmp(name, "security.capability") == 0) return 0;
if (!orig) orig = dlsym(RTLD_NEXT, "fsetxattr");
return orig ? orig(fd, name, value, size, flags) : -1;
}
int fremovexattr(int fd, const char *name) {
static int (*orig)(int, const char *) = NULL;
if (name && strcmp(name, "security.capability") == 0) return 0;
if (!orig) orig = dlsym(RTLD_NEXT, "fremovexattr");
return orig ? orig(fd, name) : -1;
}
// Hook symlink
int symlink(const char *target, const char *linkpath) {
static int (*orig_symlink)(const char *, const char *) = NULL;
+12 -4
View File
@@ -213,7 +213,8 @@ int open(const char *pathname, int flags, ...) {
int status_fd = open_proc_status(pathname, flags);
if (status_fd != -2) return status_fd;
char buf[PATH_MAX];
const char *target = ((flags & O_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf));
const char *target = proc_root_host(pathname, buf, sizeof(buf), !(flags & O_NOFOLLOW), !(flags & O_NOFOLLOW));
if (!target) target = ((flags & O_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf));
if (open_needs_mode(flags)) {
va_list args;
va_start(args, flags);
@@ -221,9 +222,12 @@ int open(const char *pathname, int flags, ...) {
va_end(args);
int fd = orig_open(target, flags, mode);
if (fd < 0 && (flags & O_CREAT) && refused_in_repaired_dir(AT_FDCWD, target)) fd = orig_open(target, flags, mode);
forget_proc_root_fd(fd);
return fd;
}
return orig_open(target, flags);
int fd = orig_open(target, flags);
remember_proc_root_fd(fd, pathname);
return fd;
}
// Hook openat
@@ -243,7 +247,8 @@ int openat(int dirfd, const char *pathname, int flags, ...) {
int status_fd = (pathname && pathname[0] == '/') ? open_proc_status(pathname, flags) : open_proc_status_at(dirfd, pathname, flags);
if (status_fd != -2) return status_fd;
char buf[PATH_MAX];
const char *target = (pathname && pathname[0] == '/') ? ((flags & O_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname;
const char *target = proc_root_host(pathname, buf, sizeof(buf), !(flags & O_NOFOLLOW), !(flags & O_NOFOLLOW));
if (!target) target = (pathname && pathname[0] == '/') ? ((flags & O_NOFOLLOW) ? rewrite_path : rewrite_path_follow)(pathname, buf, sizeof(buf)) : pathname;
if (open_needs_mode(flags)) {
va_list args;
va_start(args, flags);
@@ -251,9 +256,12 @@ int openat(int dirfd, const char *pathname, int flags, ...) {
va_end(args);
int fd = orig_openat(dirfd, target, flags, mode);
if (fd < 0 && (flags & O_CREAT) && refused_in_repaired_dir(dirfd, target)) fd = orig_openat(dirfd, target, flags, mode);
forget_proc_root_fd(fd);
return fd;
}
return orig_openat(dirfd, target, flags);
int fd = orig_openat(dirfd, target, flags);
remember_proc_root_fd(fd, pathname);
return fd;
}
// Hook creat
+7 -2
View File
@@ -244,6 +244,7 @@ int close(int fd) {
if (g_kept_fd_count > 0 && is_kept_fd(fd)) return 0;
clear_dns_redirect(fd);
set_chosen_port_fd(fd, 0);
forget_proc_root_fd(fd);
return orig_close ? orig_close(fd) : -1;
}
@@ -254,7 +255,9 @@ int dup2(int oldfd, int newfd) {
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
}
return orig_dup2 ? orig_dup2(oldfd, newfd) : -1;
int ret = orig_dup2 ? orig_dup2(oldfd, newfd) : -1;
if (ret >= 0) copy_proc_root_fd(oldfd, ret);
return ret;
}
int dup3(int oldfd, int newfd, int flags) {
@@ -264,7 +267,9 @@ int dup3(int oldfd, int newfd, int flags) {
clear_dns_redirect(newfd);
set_chosen_port_fd(newfd, is_chosen_port_fd(oldfd));
}
return orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1;
int ret = orig_dup3 ? orig_dup3(oldfd, newfd, flags) : -1;
if (ret >= 0) copy_proc_root_fd(oldfd, ret);
return ret;
}
static int get_dns_redirect(int fd, struct sockaddr_storage *orig, socklen_t *orig_len) {
+16
View File
@@ -171,6 +171,11 @@ static int is_android_host_path(const char *path) {
}
static const char *rewrite_path_in_root(const char *path, char *buffer, size_t bufsize);
#ifndef DDNATV_HOST_TEST
static const char *proc_root_host(const char *path, char *buf, size_t size, int bare, int follow);
static const char *rewrite_path_follow(const char *path, char *buffer, size_t bufsize);
static const char *proc_root_at(int dirfd, const char *rel, char *buf, size_t size);
#endif
#if defined(__aarch64__)
static long raw_readlinkat(int dirfd, const char *path, char *buf, size_t size) {
@@ -371,6 +376,13 @@ static const char *rewrite_path_in_root(const char *path, char *buffer, size_t b
return buffer;
}
#ifndef DDNATV_HOST_TEST
if (path[1] == 'p' && strncmp(path, "/proc/", 6) == 0 && path[6] >= '1' && path[6] <= '9') {
const char *other = proc_root_host(path, buffer, bufsize, 0, 0);
if (other) return other;
}
#endif
for (int i = 0; i < g_nbinds; i++) {
const struct ddnatv_bind *b = &g_binds[i];
if (path[1] == b->dst[1] && is_path_prefix(path, b->dst, b->dst_len)) {
@@ -839,6 +851,10 @@ static const char *map_parent_walk(int dirfd, const char *rel, char *buf, size_t
static const char *map_at(int dirfd, const char *rel, char *buf, size_t size) {
#if defined(__aarch64__)
if (!rel || rel[0] == '\0' || rel[0] == '/') return NULL;
#ifndef DDNATV_HOST_TEST
const char *other = proc_root_at(dirfd, rel, buf, size);
if (other) return other;
#endif
if (strstr(rel, "..")) {
const char *walked = map_parent_walk(dirfd, rel, buf, size);
if (walked || dirfd == AT_FDCWD) return walked;
+1
View File
@@ -446,6 +446,7 @@ static int close_range_part(unsigned int first, unsigned int last, void *flags)
}
int close_range(unsigned int first, unsigned int last, int flags) {
if (!(flags & CLOSE_RANGE_CLOEXEC)) forget_proc_root_range(first, last);
// Close-on-exec only (CLOSE_RANGE_CLOEXEC) leaves the translator's files open
if (g_kept_fd_count > 0 && !(flags & CLOSE_RANGE_CLOEXEC)) {
return for_each_range_without(first, last, g_kept_fds, g_kept_fd_count, close_range_part, &flags);
+286
View File
@@ -136,7 +136,95 @@ static void init_ddnatv_hook(void) {
// time it was read.
static void compact_loader_args(int argc, char **argv);
#define DDNATV_MAX_FORWARDED_FDS 253
static int forwarded_targets(char *text, int *targets, int max) {
int count = 0;
for (char *p = text; *p && count < max;) {
char *end;
long fd = strtol(p, &end, 10);
if (end == p) break;
targets[count++] = fd >= 0 && fd <= INT_MAX ? (int)fd : -1;
p = *end == ',' ? end + 1 : end;
}
return count;
}
static int is_forwarded_target(int fd, const int *targets, int wanted) {
for (int i = 0; i < wanted; i++) {
if (targets[i] == fd) return 1;
}
return 0;
}
static void adopt_forwarded_fds(void) {
const char *name = getenv("DROIDDECK_FDS");
if (!name) return;
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
size_t len = strlen(name);
int usable = len > 0 && len + 1 <= sizeof(addr.sun_path);
if (usable) memcpy(addr.sun_path + 1, name, len);
unsetenv("DROIDDECK_FDS");
if (!usable) return;
int sock = (int)syscall(SYS_socket, AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0);
if (sock < 0) return;
static char text[4096];
static int got[DDNATV_MAX_FORWARDED_FDS];
int count = 0;
int truncated = 0;
ssize_t n = -1;
socklen_t addr_len = (socklen_t)(offsetof(struct sockaddr_un, sun_path) + 1 + len);
if (syscall(SYS_connect, sock, &addr, addr_len) == 0) {
static union {
struct cmsghdr header;
char buf[CMSG_SPACE(sizeof(got))];
} control;
struct iovec iov = {text, sizeof(text) - 1};
struct msghdr msg;
memset(&msg, 0, sizeof(msg));
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = control.buf;
msg.msg_controllen = sizeof(control.buf);
do {
n = syscall(SYS_recvmsg, sock, &msg, MSG_CMSG_CLOEXEC);
} while (n < 0 && errno == EINTR);
truncated = n >= 0 && (msg.msg_flags & (MSG_CTRUNC | MSG_TRUNC)) != 0;
for (struct cmsghdr *c = n >= 0 ? CMSG_FIRSTHDR(&msg) : NULL; c; c = CMSG_NXTHDR(&msg, c)) {
if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS) continue;
size_t k = (c->cmsg_len - CMSG_LEN(0)) / sizeof(int);
for (size_t i = 0; i < k && count < DDNATV_MAX_FORWARDED_FDS; i++) {
memcpy(&got[count++], CMSG_DATA(c) + i * sizeof(int), sizeof(int));
}
}
}
syscall(SYS_close, sock);
text[n > 0 ? n : 0] = '\0';
static int targets[DDNATV_MAX_FORWARDED_FDS];
int wanted = truncated ? 0 : forwarded_targets(text, targets, DDNATV_MAX_FORWARDED_FDS);
if (wanted != count) wanted = 0;
static int parked[DDNATV_MAX_FORWARDED_FDS];
int n_parked = 0;
for (int i = 0; i < count; i++) {
int fd = got[i];
while (fd >= 0 && is_forwarded_target(fd, targets, wanted) && n_parked < DDNATV_MAX_FORWARDED_FDS) {
parked[n_parked++] = fd;
fd = (int)syscall(SYS_fcntl, fd, F_DUPFD_CLOEXEC, 3);
}
got[i] = is_forwarded_target(fd, targets, wanted) ? -1 : fd;
}
for (int i = 0; i < n_parked; i++) syscall(SYS_close, parked[i]);
for (int i = 0; i < count; i++) {
if (got[i] < 0) continue;
if (i < wanted && targets[i] > 2) syscall(SYS_dup3, got[i], targets[i], 0);
syscall(SYS_close, got[i]);
}
}
__attribute__((constructor(103))) static void init_ddnatv_hook_early(int argc, char **argv) {
adopt_forwarded_fds();
init_ddnatv_hook();
compact_loader_args(argc, argv);
// The kernel names the process after what it executed, the rootfs ld.so: process monitors, and
@@ -280,6 +368,200 @@ static int proc_env_value(pid_t pid, const char *key, char *out, size_t outsz) {
return found;
}
static pid_t proc_root_pid(const char *path, const char **rest) {
if (!path || strncmp(path, "/proc/", 6) != 0 || path[6] < '1' || path[6] > '9') return 0;
const char *p = path + 6;
long pid = 0;
while (*p >= '0' && *p <= '9') {
pid = pid * 10 + (*p++ - '0');
if (pid > 0x3fffffff) return 0;
}
if (strncmp(p, "/root", 5) != 0 || (p[5] != '\0' && p[5] != '/')) return 0;
*rest = p + 5;
return (pid_t)pid;
}
static int proc_view_of(pid_t pid, char **root, char **binds) {
char path[64];
snprintf(path, sizeof(path), "/proc/%d/environ", (int)pid);
size_t used;
int whole;
*root = NULL;
*binds = NULL;
char *env = read_proc_file(path, &used, &whole);
if (!env) return 0;
for (char *e = env; e < env + used; e += strlen(e) + 1) {
if (!*root && strncmp(e, "DDNATV_ROOT=", 12) == 0 && e[12] == '/') *root = strdup(e + 12);
else if (!*binds && strncmp(e, "DDNATV_BINDS=", 13) == 0) *binds = strdup(e + 13);
}
free(env);
if (*root) return 1;
free(*binds);
*binds = NULL;
return 0;
}
static const char *proc_view_path(const char *root, char *binds, const char *guest, char *buf, size_t size) {
const char *best_src = NULL, *best_dst = NULL;
size_t best_len = 0;
char *save = NULL;
for (char *entry = binds ? strtok_r(binds, "|", &save) : NULL; entry; entry = strtok_r(NULL, "|", &save)) {
char *colon = strchr(entry, ':');
const char *dst = colon ? colon + 1 : entry;
if (colon) *colon = '\0';
size_t len = strlen(dst);
while (len > 1 && dst[len - 1] == '/') len--;
if (entry[0] != '/' || dst[0] != '/' || len < 2 || len <= best_len || !is_path_prefix(guest, dst, len)) continue;
best_src = entry;
best_dst = dst;
best_len = len;
}
if (best_src && strncmp(best_src, best_dst, best_len) == 0 && best_src[best_len] == '\0') {
ddnatv_copy_cstr(buf, size, guest);
} else if (best_src) {
size_t n = strncmp(best_src, "/proc/", 6) == 0 && best_src[6] >= '0' && best_src[6] <= '9'
? ddnatv_copy_cstr(buf, size, best_src)
: ddnatv_kernel_path(best_src, strlen(best_src), buf, size);
ddnatv_append(buf, size, n, guest + best_len, strlen(guest + best_len));
} else if (is_android_host_path(guest)) {
ddnatv_copy_cstr(buf, size, guest);
} else {
size_t n = ddnatv_copy_cstr(buf, size, root);
if (guest[1]) ddnatv_append(buf, size, n, guest, strlen(guest));
}
return buf;
}
static const char *proc_view_host(const char *root, const char *binds, const char *guest, char *buf, size_t size) {
char *copy = binds ? strdup(binds) : NULL;
proc_view_path(root, copy, guest, buf, size);
free(copy);
return buf;
}
static const char *proc_root_host(const char *path, char *buf, size_t size, int bare, int follow) {
const char *rest = NULL;
pid_t pid = proc_root_pid(path, &rest);
if (pid <= 0 || (!bare && rest[0] == '\0')) return NULL;
char *root, *binds;
if (!proc_view_of(pid, &root, &binds)) return NULL;
size_t root_len = strlen(root);
while (root_len > 1 && root[root_len - 1] == '/') root_len--;
char root_k[PATH_MAX], guest[PATH_MAX];
ddnatv_kernel_path(root, root_len, root_k, sizeof(root_k));
ddnatv_copy_cstr(guest, sizeof(guest), rest[0] ? rest : "/");
normalize_path(guest);
if (strcmp(root_k, g_ddnatv_root) == 0 && strcmp(binds ? binds : "", g_binds_raw ? g_binds_raw : "") == 0) {
const char *own = (follow ? rewrite_path_follow : rewrite_path_in_root)(guest, buf, size);
if (own != buf) ddnatv_copy_cstr(buf, size, own);
} else {
proc_view_host(root_k, binds, guest, buf, size);
#if defined(__aarch64__)
for (int depth = 0; follow && depth < 8 && strncmp(buf, "/proc/", 6) != 0; depth++) {
char target[PATH_MAX];
long n = raw_readlinkat(AT_FDCWD, buf, target, sizeof(target) - 1);
if (n <= 0) break;
target[n] = '\0';
char joined[PATH_MAX];
if (target[0] == '/') {
ddnatv_copy_cstr(joined, sizeof(joined), target);
} else {
const char *slash = strrchr(guest, '/');
size_t used = ddnatv_append(joined, sizeof(joined), 0, guest, slash ? (size_t)(slash - guest) : 0);
used = ddnatv_append(joined, sizeof(joined), used, "/", 1);
ddnatv_append(joined, sizeof(joined), used, target, strlen(target));
}
normalize_path(joined);
ddnatv_copy_cstr(guest, sizeof(guest), joined);
proc_view_host(root_k, binds, guest, buf, size);
}
#endif
}
free(root);
free(binds);
return buf;
}
struct ddnatv_proc_root_fd {
int fd;
pid_t pid;
unsigned long dev, ino;
};
static struct ddnatv_proc_root_fd g_proc_root_fds[32];
static int g_n_proc_root_fds = 0;
static pthread_mutex_t g_proc_root_mutex = PTHREAD_MUTEX_INITIALIZER;
static void forget_proc_root_range(unsigned int first, unsigned int last) {
if (__atomic_load_n(&g_n_proc_root_fds, __ATOMIC_ACQUIRE) == 0) return;
pthread_mutex_lock(&g_proc_root_mutex);
for (int i = 0; i < g_n_proc_root_fds;) {
unsigned int fd = (unsigned int)g_proc_root_fds[i].fd;
if (fd >= first && fd <= last) g_proc_root_fds[i] = g_proc_root_fds[--g_n_proc_root_fds];
else i++;
}
pthread_mutex_unlock(&g_proc_root_mutex);
}
static void forget_proc_root_fd(int fd) {
if (fd >= 0) forget_proc_root_range((unsigned int)fd, (unsigned int)fd);
}
static void store_proc_root_fd(struct ddnatv_proc_root_fd entry) {
pthread_mutex_lock(&g_proc_root_mutex);
int slot = 0;
while (slot < g_n_proc_root_fds && g_proc_root_fds[slot].fd != entry.fd) slot++;
if (slot == g_n_proc_root_fds && slot == (int)(sizeof(g_proc_root_fds) / sizeof(g_proc_root_fds[0]))) slot = 0;
g_proc_root_fds[slot] = entry;
if (slot == g_n_proc_root_fds) __atomic_store_n(&g_n_proc_root_fds, g_n_proc_root_fds + 1, __ATOMIC_RELEASE);
pthread_mutex_unlock(&g_proc_root_mutex);
}
static void copy_proc_root_fd(int oldfd, int newfd) {
if (newfd < 0 || oldfd == newfd) return;
forget_proc_root_fd(newfd);
if (oldfd < 0 || __atomic_load_n(&g_n_proc_root_fds, __ATOMIC_ACQUIRE) == 0) return;
struct ddnatv_proc_root_fd entry = {-1, 0, 0, 0};
pthread_mutex_lock(&g_proc_root_mutex);
for (int i = 0; i < g_n_proc_root_fds; i++) {
if (g_proc_root_fds[i].fd == oldfd) entry = g_proc_root_fds[i];
}
pthread_mutex_unlock(&g_proc_root_mutex);
if (entry.fd < 0) return;
entry.fd = newfd;
store_proc_root_fd(entry);
}
static void remember_proc_root_fd(int fd, const char *path) {
const char *rest = NULL;
pid_t pid = proc_root_pid(path, &rest);
struct stat st;
if (fd < 0) return;
if (pid <= 0 || rest[strspn(rest, "/")] != '\0' || syscall(SYS_fstat, fd, &st) != 0 || !S_ISDIR(st.st_mode)) {
forget_proc_root_fd(fd);
return;
}
store_proc_root_fd((struct ddnatv_proc_root_fd){fd, pid, (unsigned long)st.st_dev, (unsigned long)st.st_ino});
}
static const char *proc_root_at(int dirfd, const char *rel, char *buf, size_t size) {
if (dirfd < 0 || __atomic_load_n(&g_n_proc_root_fds, __ATOMIC_ACQUIRE) == 0) return NULL;
pid_t pid = 0;
unsigned long dev = 0, ino = 0;
pthread_mutex_lock(&g_proc_root_mutex);
for (int i = 0; i < g_n_proc_root_fds; i++) {
if (g_proc_root_fds[i].fd != dirfd) continue;
pid = g_proc_root_fds[i].pid;
dev = g_proc_root_fds[i].dev;
ino = g_proc_root_fds[i].ino;
break;
}
pthread_mutex_unlock(&g_proc_root_mutex);
struct stat st;
if (pid <= 0 || syscall(SYS_fstat, dirfd, &st) != 0 || (unsigned long)st.st_dev != dev || (unsigned long)st.st_ino != ino) return NULL;
if (snprintf(buf, size, "/proc/%d/root/%s", (int)pid, rel) >= (int)size) return NULL;
return buf;
}
static int is_loader_option(const char *arg) {
return strcmp(arg, "--preload") == 0 || strcmp(arg, "--library-path") == 0 || strcmp(arg, "--argv0") == 0;
}
@@ -475,6 +757,10 @@ static const char *rewrite_path_follow(const char *path, char *buffer, size_t bu
if (!path) return NULL;
if (path[0] != '/') return rewrite_path(path, buffer, bufsize);
init_ddnatv_hook();
if (path[1] == 'p' && strncmp(path, "/proc/", 6) == 0 && path[6] >= '1' && path[6] <= '9') {
const char *other = proc_root_host(path, buffer, bufsize, 0, 1);
if (other) return other;
}
int moved = 0;
for (int i = 0; i < g_nbinds; i++) {
const struct ddnatv_bind *b = &g_binds[i];
+128
View File
@@ -376,6 +376,134 @@ class DriveTest(Temp):
self.assertEqual(os.readlink(self.devices / "d:"), str(self.card))
self.assertFalse(BNET["move_installs"](self.root))
def test_the_volume_holding_the_native_rootfs_gets_no_drive(self):
rootfs = self.card / "files/linuxfs"
library = rootfs / "root/Games/Stores/Battle.net"
library.mkdir(parents=True)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
self.assertEqual(BNET["install_path"](self.root, str(library)), "Z:/root/Games/Stores/Battle.net")
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "Z:" + str(self.library))
self.assertFalse(self.devices.exists())
self.assertEqual(BNET["install_path"](self.root, str(self.library)), "D:\\Games\\Battle.net")
def test_games_moved_to_a_drive_holding_the_native_rootfs_go_back_to_the_root_drive(self):
rootfs = self.card / "files/linuxfs"
game = rootfs / "root/Games/Stores/Battle.net/World of Warcraft"
game.mkdir(parents=True)
card = self.tmp / "sd"
(card / "Diablo").mkdir(parents=True)
self.devices.mkdir(parents=True)
os.symlink(str(self.card), self.devices / "d:")
os.symlink(str(card), self.devices / "e:")
client = self.product("battle.net", "C:/Program Files (x86)/Battle.net")
sd = self.product("d3", "E:/Diablo")
gone = self.product("gone", "D:/files/linuxfs/root/Games/Missing")
path = self.database(client, self.product("wowf", "D:/files/linuxfs/root/Games/Stores/Battle.net/World of Warcraft"), sd, gone)
before = path.read_bytes()
self.assertFalse(BNET["move_installs"](self.root))
self.assertEqual(path.read_bytes(), before)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
self.assertTrue(BNET["move_installs"](self.root))
self.assertEqual(path.read_bytes(), client + self.product("wowf", "Z:/root/Games/Stores/Battle.net/World of Warcraft")
+ sd + gone + self.field(7, b"tail"))
self.assertFalse(BNET["move_installs"](self.root))
def rootfs_prefix(self):
rootfs = self.card / "files/linuxfs"
game = rootfs / "root/Games/Stores/Battle.net/World of Warcraft"
game.mkdir(parents=True)
card = self.tmp / "sd"
card.mkdir()
self.devices.mkdir(parents=True)
for letter, target in (("d", self.card), ("e", card), ("s", self.card)):
os.symlink(str(target), self.devices / (letter + ":"))
pfx = self.devices.parent
system = pfx / "system.reg"
system.write_text('[Software\\\\Uninstall\\\\wow] 1\n'
'"InstallLocation"="D:\\\\files\\\\linuxfs\\\\root\\\\Games\\\\Stores\\\\Battle.net\\\\World of Warcraft"\n'
'"DisplayIcon"="\\"d:\\\\files\\\\linuxfs\\\\root\\\\Games\\\\Wow.exe\\""\n'
'"Card"="E:\\\\Diablo"\n"Other"="AD:\\\\files\\\\linuxfs\\\\x"\n')
system.chmod(0o640)
config = Path(BNET["drive_c"](self.root)).joinpath(*BNET["CONFIG"])
config.parent.mkdir(parents=True)
config.write_text(json.dumps({"Client": {"Install": {"DefaultInstallPath": "D:\\files\\linuxfs\\root\\Games\\Stores\\Battle.net"}}}))
self.database(self.product("wowf", "D:/files/linuxfs/root/Games/Stores/Battle.net/World of Warcraft"))
return rootfs, system, config
def test_an_unused_drive_holding_the_native_rootfs_is_removed_once_its_paths_use_the_root_drive(self):
rootfs, system, config = self.rootfs_prefix()
before = system.read_text()
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
self.assertEqual(system.read_text(), before)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
self.running = [(5, ["C:\\ProgramData\\Battle.net\\Agent\\Agent.exe"])]
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
self.running = []
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
self.assertTrue(os.path.islink(self.devices / "d:"))
self.assertTrue(BNET["move_installs"](self.root))
self.assertEqual(BNET["drop_rootfs_drives"](self.root), ["d"])
self.assertEqual(sorted(os.listdir(self.devices)), ["e:", "s:"])
self.assertEqual(system.read_text(), before.replace("D:\\\\files\\\\linuxfs\\\\root", "Z:\\\\root")
.replace("d:\\\\files\\\\linuxfs\\\\root", "Z:\\\\root"))
self.assertEqual(system.stat().st_mode & 0o777, 0o640)
self.assertEqual(json.loads(config.read_text())["Client"]["Install"]["DefaultInstallPath"], "Z:\\root\\Games\\Stores\\Battle.net")
self.assertTrue(self.card.is_dir())
self.assertTrue((rootfs / "root/Games/Stores/Battle.net/World of Warcraft").is_dir())
def test_a_drive_holding_the_native_rootfs_stays_while_a_path_outside_the_runtime_uses_it(self):
rootfs, system, _ = self.rootfs_prefix()
system.write_text(system.read_text() + '"Elsewhere"="D:\\\\Other\\\\Game"\n')
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
self.assertTrue(BNET["move_installs"](self.root))
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
self.assertTrue(os.path.islink(self.devices / "d:"))
self.assertIn('"InstallLocation"="Z:\\\\root\\\\Games', system.read_text())
self.assertIn('"Elsewhere"="D:\\\\Other\\\\Game"', system.read_text())
def test_a_drive_holding_the_native_rootfs_stays_while_a_game_outside_the_runtime_is_installed_on_it(self):
rootfs, _, _ = self.rootfs_prefix()
for folder in ("D:/Other/" + "x" * 40, "D:\\Other\\" + "x" * 39, " D:/Other/" + "x" * 39):
with self.subTest(folder=folder):
self.database(self.product("wowf", "D:/files/linuxfs/root/Games/Stores/Battle.net/World of Warcraft"),
self.product("other", folder))
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
BNET["move_installs"](self.root)
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
self.assertTrue(os.path.islink(self.devices / "d:"))
def test_a_path_that_climbs_out_of_the_runtime_keeps_its_drive(self):
rootfs, system, _ = self.rootfs_prefix()
up = '"Up"="D:\\\\files\\\\linuxfs\\\\root\\\\..\\\\..\\\\Other"\n'
system.write_text(system.read_text() + up)
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
BNET["move_installs"](self.root)
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
self.assertTrue(os.path.islink(self.devices / "d:"))
self.assertIn(up, system.read_text())
self.assertIn('"InstallLocation"="Z:\\\\root\\\\Games', system.read_text())
def test_a_config_path_with_escaped_characters_keeps_its_drive(self):
rootfs, _, config = self.rootfs_prefix()
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
BNET["move_installs"](self.root)
settings = config.read_text()
for text in (settings[:-1] + ', "Other": "D:\\/Other\\/Game"}', settings[:-1] + ', "Other": "D\\u003a/Other/Game"}', '{"Client": '):
with self.subTest(text=text):
config.write_text(text)
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
self.assertTrue(os.path.islink(self.devices / "d:"))
config.write_text(settings)
self.assertEqual(BNET["drop_rootfs_drives"](self.root), ["d"])
def test_an_unreadable_database_keeps_the_drive(self):
rootfs, _, _ = self.rootfs_prefix()
path = Path(BNET["drive_c"](self.root)) / "ProgramData/Battle.net/Agent/product.db"
path.write_bytes(b"\x0a\xff")
with mock.patch.dict(os.environ, {"DDNATV_ROOT": str(rootfs)}):
self.assertEqual(BNET["drop_rootfs_drives"](self.root), [])
self.assertTrue(os.path.islink(self.devices / "d:"))
def test_registrations_stay_while_the_prefix_runs_or_the_database_is_unreadable(self):
game = self.library / "World of Warcraft"
game.mkdir()
+180
View File
@@ -0,0 +1,180 @@
import importlib.machinery
import importlib.util
import os
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
TOOLS = Path(__file__).resolve().parents[1]
PROTON = TOOLS / 'bionic-runtime/tool/proton'
LAUNCH = TOOLS / 'bionic-runtime/tool/launch.sh'
BIN = TOOLS / 'linuxfs/overlay/usr/local/bin'
SHARE = TOOLS.parent / 'app/src/main/java/com/droiddeck/launcher/session/EnhancedSessionLogShare.kt'
ANDROID = '/data/user/0/com.droiddeck.launcher/files/linuxfs'
BINDS = '/storage/emulated/0/Games:/home/games|/storage/1234-5678/Steam:/mnt/sd'
def load(name):
loader = importlib.machinery.SourceFileLoader(name.replace('-', '_'), str(BIN / name))
spec = importlib.util.spec_from_loader(loader.name, loader)
module = importlib.util.module_from_spec(spec)
loader.exec_module(module)
return module
store = load('droiddeck-store-launch')
def proton_function(call, *args, **env):
text = PROTON.read_text()
functions = text[text.index('real() {'):text.index('\nhere=')]
env = dict(os.environ, DDNATV_ROOT=ANDROID, DDNATV_BINDS=BINDS, **env)
return subprocess.run(['bash', '-c', functions + '\n' + call, 'proton', *args], env=env,
capture_output=True, text=True, check=True).stdout.rstrip('\n')
def zpath(arg):
return proton_function('zpath "$1"', arg)
def session_logs(verb, **env):
return proton_function('verb=$1; session_logs', verb, **env)
class ToolArguments(unittest.TestCase):
def test_a_guest_path_names_its_android_file(self):
self.assertEqual('Z:\\data\\user\\0\\com.droiddeck.launcher\\files\\linuxfs\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe',
zpath('Z:\\usr\\local\\lib\\droiddeck-ubisoft\\droiddeck-upc.exe'))
def test_a_bound_folder_names_its_android_side(self):
self.assertEqual('Z:\\storage\\emulated\\0\\Games\\Brotato\\setup.exe', zpath('Z:\\home\\games\\Brotato\\setup.exe'))
self.assertEqual('Z:\\storage\\1234-5678\\Steam\\a.reg', zpath('z:/mnt/sd/a.reg'))
def test_a_switch_value_is_mapped(self):
self.assertEqual('/DIR=Z:\\storage\\emulated\\0\\Games\\Game', zpath('/DIR=Z:\\home\\games\\Game'))
def test_android_and_other_paths_stay(self):
for arg in ('Z:\\storage\\emulated\\0\\Download\\a.exe', 'Z:\\data\\user\\0\\com.droiddeck.launcher\\files\\linuxfs\\tmp\\a.bat',
'C:\\windows\\system32\\reg.exe', 'X:\\Brotato.exe', '-dx12', '-n', '-e', 'cmd.exe', '/d', ''):
self.assertEqual(arg, zpath(arg))
def test_wine_keeps_the_guest_root(self):
self.assertIn('DROIDDECK_GUEST_ROOT) ;;', LAUNCH.read_text())
class SessionLogs(unittest.TestCase):
SESSION = '/data/user/0/com.droiddeck.launcher/files/logs/2026-11-22-09-steam'
def test_a_game_launch_gets_a_folder_of_its_own_in_the_session(self):
folder = session_logs('waitforexitandrun', DD_DEBUG_DIR=self.SESSION + '/', SteamAppId='341940')
self.assertRegex(folder, '^' + re.escape(self.SESSION) + r'/games/[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}-bionic-341940$')
def test_the_folder_name_survives_share_logs(self):
pattern = re.search(r'Regex\("(\[0-9\]\{4\}-[^"]+)"\)', SHARE.read_text()).group(1).replace('\\\\', '\\')
name = session_logs('waitforexitandrun', DD_DEBUG_DIR=self.SESSION, SteamAppId='341940').rsplit('/', 1)[1]
self.assertRegex(name, '^(?:' + pattern + ')$')
self.assertIn('"droiddeck-bionic.log"', SHARE.read_text())
def test_detailed_graphics_logs_keep_the_game_log_folder(self):
self.assertEqual(ANDROID + '/tmp/logs/games/20261122-201105-ab12-341940',
session_logs('waitforexitandrun', DD_DEBUG_DIR=self.SESSION, PROTON_LOG_DIR='/tmp/logs/games/20261122-201105-ab12-341940'))
def test_other_verbs_and_sessions_without_a_folder_get_none(self):
self.assertEqual('', session_logs('run', DD_DEBUG_DIR=self.SESSION))
self.assertEqual('', session_logs('runinprefix', DD_DEBUG_DIR=self.SESSION))
env = dict(os.environ)
env.pop('DD_DEBUG_DIR', None)
with patch.dict(os.environ, env, clear=True):
self.assertEqual('', session_logs('waitforexitandrun'))
class LaunchLog(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.root = Path(self.tmp.name)
self.compat = self.root / 'compatdata/341940'
self.logs = self.root / 'session/games/2026-11-22-201105-bionic-341940'
def run_block(self, verb, logs=''):
text = LAUNCH.read_text()
block = text[text.index('mkdir -p "$COMPAT"'):text.index('exec >> "$LOG" 2>&1')]
script = 'set -e\n' + block + 'echo "line from %s" >> "$LOG"\n' % verb
subprocess.run(['sh', '-c', script], check=True, env=dict(os.environ, COMPAT=str(self.compat), LOGS=str(logs), verb=verb))
return self.compat / 'droiddeck-bionic.log'
def test_a_game_log_lives_in_the_session_folder_with_one_name(self):
self.compat.mkdir(parents=True)
(self.compat / 'droiddeck-bionic.log').write_text('previous launch\n')
log = self.run_block('waitforexitandrun', self.logs)
shared = self.logs / 'droiddeck-bionic.log'
self.assertTrue(log.is_symlink())
self.assertEqual(shared, Path(os.readlink(log)))
self.assertEqual('line from waitforexitandrun\n', shared.read_text())
self.assertEqual(1, shared.stat().st_nlink)
self.assertEqual('previous launch\n', (self.compat / 'droiddeck-bionic.log.1').read_text())
def test_a_removed_session_folder_leaves_no_dangling_log(self):
self.run_block('waitforexitandrun', self.logs)
shutil.rmtree(self.root / 'session')
log = self.run_block('runinprefix')
self.assertFalse(log.is_symlink())
self.assertEqual('line from runinprefix\n', log.read_text())
def test_without_a_session_folder_the_log_stays_in_the_prefix(self):
log = self.run_block('run')
self.assertFalse(log.is_symlink())
self.assertEqual('line from run\n', log.read_text())
def test_graphics_logs_follow_the_launch(self):
text = LAUNCH.read_text()
self.assertIn('DXVK_LOG_PATH|VKD3D_LOG_FILE|MESA_LOG_FILE) ;;', text)
self.assertIn('DXVK_LOG_PATH=${DXVK_LOG_PATH:-$COMPAT}', text)
class StorePaths(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.tool = Path(self.tmp.name) / 'compatibilitytools.d/DroidDeck-Bionic-12.8-r41-Proton'
(self.tool / 'bionic').mkdir(parents=True)
shutil.copy(PROTON, self.tool / 'proton')
(self.tool / 'proton').chmod(0o755)
(self.tool / 'bionic/launch.sh').write_text('')
def env(self, **extra):
values = {'DD_STORE_PROTON': str(self.tool / 'proton'), 'DDNATV_ROOT': ANDROID, 'DDNATV_BINDS': BINDS}
values.update(extra)
return patch.dict(os.environ, values)
def test_a_bionic_game_gets_android_paths(self):
with self.env():
self.assertEqual('Z:\\data\\user\\0\\com.droiddeck.launcher\\files\\linuxfs\\root\\.cache\\droiddeck-ubisoft\\bridge-274',
store.windows_path('/root/.cache/droiddeck-ubisoft/bridge-274'))
self.assertEqual('Z:\\storage\\emulated\\0\\Games\\Watch_Dogs\\bin\\Watch_Dogs.exe',
store.windows_path('/home/games/Watch_Dogs/bin/Watch_Dogs.exe'))
def test_the_wrapper_names_the_same_tool(self):
with self.env(DD_STORE_PROTON=str(self.tool / 'droiddeck-proton-wrap')):
self.assertEqual('Z:\\storage\\emulated\\0\\Games\\a.reg', store.windows_path('/home/games/a.reg'))
def test_other_tools_keep_guest_paths(self):
(self.tool / 'bionic/launch.sh').unlink()
with self.env():
self.assertEqual('Z:\\home\\games\\a.reg', store.windows_path('/home/games/a.reg'))
with patch.dict(os.environ, {'DD_STORE_PROTON': str(self.tool / 'proton')}):
os.environ.pop('DDNATV_ROOT', None)
self.assertEqual('Z:\\home\\games\\b.reg', store.windows_path('/home/games/b.reg'))
def test_a_failing_tool_keeps_the_guest_path(self):
(self.tool / 'proton').write_text('#!/bin/sh\nexit 1\n')
with self.env():
self.assertEqual('Z:\\home\\games\\c.reg', store.windows_path('/home/games/c.reg'))
if __name__ == '__main__':
unittest.main()
+72
View File
@@ -0,0 +1,72 @@
import json
import os
import subprocess
import sys
import unittest
from pathlib import Path
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
PROBE = """
import json, os
print(json.dumps({"pid": os.getpid(), "binds": os.environ.get("DDNATV_BINDS")}))
"""
INFO = b"[Application]\nname=org.example.App\n\n[Instance]\ninstance-id=42\n"
class BwrapFlatpakInfoInPlaceTest(unittest.TestCase):
def run_shim(self, env):
read, write = os.pipe()
os.write(write, INFO)
os.close(write)
self.addCleanup(os.close, read)
full = {k: v for k, v in os.environ.items() if not k.startswith("DDNATV_")}
full.update(env)
out = subprocess.run([sys.executable, str(BWRAP), "--ro-bind-data", str(read), "/.flatpak-info", "--",
sys.executable, "-c", PROBE], env=full, pass_fds=(read,), capture_output=True,
text=True, timeout=30)
self.assertEqual(0, out.returncode, out.stderr)
return json.loads(out.stdout)
def file_bind(self, binds, pid):
entries = [e for e in (binds or "").split("|") if e.endswith(":/.flatpak-info")]
self.assertEqual(1, len(entries))
src = entries[0][:-len(":/.flatpak-info")]
self.assertTrue(src.startswith("/proc/%d/fd/" % pid), src)
return src
def test_a_native_program_run_in_place_sees_its_flatpak_info(self):
got = self.run_shim({"DDNATV_ROOT": "/data/rootfs"})
self.file_bind(got["binds"], got["pid"])
self.assertEqual(1, len(got["binds"].split("|")))
def test_the_session_binds_are_kept_in_front(self):
got = self.run_shim({"DDNATV_ROOT": "/data/rootfs", "DDNATV_BINDS": "/proc:/proc|/sdcard:/media/sdcard"})
self.file_bind(got["binds"], got["pid"])
self.assertEqual(["/proc:/proc", "/sdcard:/media/sdcard"], got["binds"].split("|")[:2])
def test_the_bound_file_holds_the_data_and_outlives_exec(self):
script = (
"import os, sys; b = os.environ['DDNATV_BINDS'].split('|')[-1].split(':')[0]; "
"sys.stdout.write(open(b.replace('/proc/%d/' % os.getpid(), '/proc/self/')).read())"
)
read, write = os.pipe()
os.write(write, INFO)
os.close(write)
self.addCleanup(os.close, read)
env = {k: v for k, v in os.environ.items() if not k.startswith("DDNATV_")}
env["DDNATV_ROOT"] = "/data/rootfs"
out = subprocess.run([sys.executable, str(BWRAP), "--ro-bind-data", str(read), "/.flatpak-info", "--",
sys.executable, "-c", script], env=env, pass_fds=(read,), capture_output=True,
timeout=30)
self.assertEqual(0, out.returncode, out.stderr)
self.assertEqual(INFO, out.stdout)
def test_without_the_native_hook_nothing_is_added(self):
got = self.run_shim({})
self.assertIsNone(got["binds"])
if __name__ == "__main__":
unittest.main()
+226
View File
@@ -0,0 +1,226 @@
import json
import os
from pathlib import Path
import resource
import secrets
import socket
import struct
import subprocess
import sys
import tempfile
import threading
import unittest
from tools.tests.test_usr2_preload import runner
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
HOOK_BUILD = Path(__file__).resolve().parents[1] / "nativeguest/build.sh"
PROBE = r"""
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char **argv) {
printf("env\t%s\n", getenv("DROIDDECK_FDS") ? "set" : "-");
for (int i = 1; i < argc; i++) {
int fd = atoi(argv[i]);
char buf[64];
int flags = fcntl(fd, F_GETFD);
ssize_t n = flags < 0 ? -1 : read(fd, buf, sizeof(buf) - 1);
buf[n > 0 ? n : 0] = 0;
printf("%d\t%s\t%s\n", fd, n > 0 ? buf : "-", flags < 0 ? "closed" : flags & FD_CLOEXEC ? "cloexec" : "kept");
}
return 0;
}
"""
def pipe_holding(data):
read, write = os.pipe()
os.write(write, data)
os.close(write)
return read
def serve(listener, fds, targets):
conn, _ = listener.accept()
with conn, listener:
conn.sendmsg([",".join(map(str, targets)).encode()],
[(socket.SOL_SOCKET, socket.SCM_RIGHTS, struct.pack("%di" % len(fds), *fds))])
class FakeApp:
def __init__(self, test, launch):
self.name = "droiddeck-test-" + secrets.token_hex(8)
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.listener.bind("\0" + self.name)
self.listener.listen(1)
self.launch = launch
self.request = None
self.thread = threading.Thread(target=self.run, daemon=True)
self.thread.start()
test.addCleanup(self.listener.close)
def run(self):
conn, _ = self.listener.accept()
with conn:
head = conn.recv(5, socket.MSG_WAITALL)
body = conn.recv(struct.unpack(">I", head[1:])[0], socket.MSG_WAITALL)
self.request = json.loads(body)
output, status = self.launch(self.request)
for kind, payload in ((b"O", output), (b"X", str(status).encode())):
conn.sendall(kind + struct.pack(">I", len(payload)) + payload)
def fetch(name):
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as conn:
conn.connect("\0" + name)
text, fds, _, _ = socket.recv_fds(conn, 1024, 16)
try:
return text.decode(), [os.read(fd, 64) for fd in fds]
finally:
for fd in fds:
os.close(fd)
class BwrapForwardsFdsTest(unittest.TestCase):
def run_shim(self, launch, extra, pass_fds):
app = FakeApp(self, launch)
env = {k: v for k, v in os.environ.items() if not k.startswith("DDNATV_")}
env["DROIDDECK_BWRAP_SOCKET"] = app.name
work = tempfile.TemporaryDirectory()
self.addCleanup(work.cleanup)
out = subprocess.run([sys.executable, str(BWRAP), "--bind", work.name, "/mnt/elsewhere", *extra, "--",
"/nonexistent/program"], env=env, pass_fds=pass_fds, capture_output=True, timeout=30)
self.assertEqual(0, out.returncode, out.stderr)
return app.request, out.stdout
def test_inherited_fds_are_offered_to_the_sandboxed_program(self):
forwarded = pipe_holding(b"dbus peer")
sync = pipe_holding(b"sync")
self.addCleanup(os.close, forwarded)
self.addCleanup(os.close, sync)
got = {}
def launch(request):
got.update(zip(("targets", "data"), fetch(request["env"]["DROIDDECK_FDS"])))
return b"", 0
request, _ = self.run_shim(launch, ["--sync-fd", str(sync)], (forwarded, sync))
self.assertEqual(str(forwarded), got["targets"])
self.assertEqual([b"dbus peer"], got["data"])
def test_the_offer_is_taken_once(self):
forwarded = pipe_holding(b"once")
self.addCleanup(os.close, forwarded)
second = []
def launch(request):
fetch(request["env"]["DROIDDECK_FDS"])
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as conn:
try:
conn.connect("\0" + request["env"]["DROIDDECK_FDS"])
second.append("connected")
except OSError:
second.append("refused")
return b"", 0
self.run_shim(launch, [], (forwarded,))
self.assertEqual(["refused"], second)
def test_more_descriptors_than_can_be_passed_stop_the_launch(self):
fds = [pipe_holding(b"x") for _ in range(254)]
for fd in fds:
self.addCleanup(os.close, fd)
app = FakeApp(self, lambda request: (b"", 0))
env = {k: v for k, v in os.environ.items() if not k.startswith("DDNATV_")}
env["DROIDDECK_BWRAP_SOCKET"] = app.name
work = tempfile.TemporaryDirectory()
self.addCleanup(work.cleanup)
out = subprocess.run([sys.executable, str(BWRAP), "--bind", work.name, "/mnt/elsewhere", "--",
"/nonexistent/program"], env=env, pass_fds=fds, capture_output=True, timeout=30)
self.assertNotEqual(0, out.returncode)
self.assertIn(b"Too many inherited file descriptors", out.stderr)
self.assertIsNone(app.request)
def test_nothing_is_offered_without_inherited_fds(self):
request, _ = self.run_shim(lambda request: (b"", 0), [], ())
self.assertNotIn("DROIDDECK_FDS", request["env"])
class NativeHookAdoptsFdsTest(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)
cls.hook = tmp / "hook.so"
subprocess.run(["bash", str(HOOK_BUILD), str(cls.hook), cls.cc], check=True, capture_output=True)
(tmp / "probe.c").write_text(PROBE)
subprocess.run([cls.cc, "-O1", "-o", str(tmp / "probe"), str(tmp / "probe.c")], check=True)
cls.probe_path = tmp / "probe"
@classmethod
def tearDownClass(cls):
cls.tmp.cleanup()
def offer(self, fds, targets):
name = "droiddeck-test-" + secrets.token_hex(8)
listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
listener.bind("\0" + name)
listener.listen(1)
listener.settimeout(60)
threading.Thread(target=serve, args=(listener, fds, targets), daemon=True).start()
self.addCleanup(listener.close)
return name
def run_probe(self, name, *wanted, fd_limit=None):
hook_env = {"DROIDDECK_FDS": name, "LD_PRELOAD": str(self.hook)}
env = {k: v for k, v in os.environ.items() if k != "LD_PRELOAD" and not k.startswith("DDNATV_")}
if self.prefix:
cmd = list(self.prefix) + [arg for key, value in hook_env.items() for arg in ("-E", f"{key}={value}")]
else:
cmd = []
env.update(hook_env)
limit = (lambda: resource.setrlimit(resource.RLIMIT_NOFILE, (fd_limit, fd_limit))) if fd_limit else None
out = subprocess.run(cmd + [str(self.probe_path), *map(str, wanted)], env=env, capture_output=True,
text=True, timeout=120, preexec_fn=limit)
self.assertEqual(0, out.returncode, out.stderr)
return {line.split("\t")[0]: line.split("\t")[1:] for line in out.stdout.splitlines()}
def held(self, *data):
fds = [pipe_holding(d) for d in data]
for fd in fds:
self.addCleanup(os.close, fd)
return fds
def test_forwarded_fds_land_on_their_numbers_and_stay_inheritable(self):
fds = self.held(b"peer", b"sync")
got = self.run_probe(self.offer(fds, [22, 5]), 22, 5)
self.assertEqual(["peer", "kept"], got["22"])
self.assertEqual(["sync", "kept"], got["5"])
self.assertEqual(["-"], got["env"])
def test_targets_that_overlap_the_received_numbers_are_not_mixed_up(self):
fds = self.held(b"first", b"second")
got = self.run_probe(self.offer(fds, [4, 3]), 4, 3)
self.assertEqual("first", got["4"][0])
self.assertEqual("second", got["3"][0])
def test_a_target_at_the_descriptor_limit_is_installed(self):
fds = self.held(b"edge")
got = self.run_probe(self.offer(fds, [255]), 255, fd_limit=256)
self.assertEqual(["edge", "kept"], got["255"])
def test_a_missing_offer_changes_nothing(self):
got = self.run_probe("droiddeck-test-gone-" + secrets.token_hex(4), 22)
self.assertEqual(["-", "closed"], got["22"])
self.assertEqual(["-"], got["env"])
if __name__ == "__main__":
unittest.main()
+110
View File
@@ -0,0 +1,110 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[1]
DESKTOP = (ROOT / 'linuxfs/desktop/droiddeck-desktop').read_text()
OVERLAY_LAYOUT = (ROOT / 'ubuntu/overlay-desktop/usr/share/plasma/look-and-feel/com.valve.vapor.desktop'
'/contents/layouts/org.kde.plasma.desktop-layout.js').read_text()
LAYOUT_DIR = '/usr/share/plasma/look-and-feel/com.valve.vapor.desktop/contents/layouts'
RC = 'plasma-org.kde.plasma.desktop-appletsrc'
STAMP = 'droiddeck-panel-layout'
def block(first, last):
start = DESKTOP.index(first)
return DESKTOP[start:DESKTOP.index(last, start) + len(last)]
def run(script, home):
environment = {key: value for key, value in os.environ.items() if key != 'XDG_CONFIG_HOME'}
environment['HOME'] = str(home)
result = subprocess.run(['bash', '-c', script], env=environment, capture_output=True, text=True, timeout=5)
if result.returncode != 0:
raise AssertionError(result.stderr)
class DesktopSteamosPanelTest(unittest.TestCase):
def reset(self, home, panel=None, stamp=None):
config = home / '.config'
config.mkdir()
if panel is not None:
(config / RC).write_text(panel)
if stamp is not None:
(config / STAMP).write_text(stamp)
run(block('dd_panel_rc=', '\nfi\n'), home)
return config
def test_an_older_panel_is_set_aside_once_so_plasma_lays_out_the_current_one(self):
for panel in ('icon=start-here-kubuntu\n', 'icon=distributor-logo-steamdeck\n'):
with tempfile.TemporaryDirectory() as home:
config = self.reset(Path(home), panel)
self.assertFalse((config / RC).exists())
self.assertEqual(panel, (config / (RC + '.before-steamos-2')).read_text())
self.assertEqual('steamos-2', (config / STAMP).read_text().strip())
def test_an_earlier_backup_is_never_overwritten(self):
with tempfile.TemporaryDirectory() as home:
config = Path(home) / '.config'
config.mkdir()
(config / (RC + '.before-steamos-2')).write_text('original backup')
(config / RC).write_text('icon=start-here-kubuntu\n')
run(block('dd_panel_rc=', '\nfi\n'), Path(home))
self.assertEqual('original backup', (config / (RC + '.before-steamos-2')).read_text())
self.assertFalse((config / RC).exists())
self.assertEqual(1, len([entry for entry in config.iterdir() if entry.name.startswith(RC + '.before-steamos-2.')]))
self.assertEqual('steamos-2', (config / STAMP).read_text().strip())
def test_the_stamp_is_not_written_when_the_panel_could_not_be_moved(self):
with tempfile.TemporaryDirectory() as home:
config = Path(home) / '.config'
config.mkdir()
(config / RC).write_text('icon=start-here-kubuntu\n')
script = block('dd_panel_rc=', '\nfi\n').replace('mv "$dd_panel_rc"', 'false "$dd_panel_rc"')
run(script, Path(home))
self.assertTrue((config / RC).exists())
self.assertFalse((config / STAMP).exists())
def test_a_panel_laid_out_by_this_version_is_left_alone(self):
with tempfile.TemporaryDirectory() as home:
config = self.reset(Path(home), 'icon=my-logo\n', 'steamos-2\n')
self.assertEqual('icon=my-logo\n', (config / RC).read_text())
self.assertFalse((config / (RC + '.before-steamos-2')).exists())
def test_a_profile_without_a_panel_only_gets_the_stamp(self):
with tempfile.TemporaryDirectory() as home:
config = self.reset(Path(home))
self.assertEqual([STAMP], [entry.name for entry in config.iterdir()])
def test_the_layout_written_at_each_start_is_the_overlays(self):
with tempfile.TemporaryDirectory() as home:
target = Path(home) / 'layouts'
target.mkdir()
run(block('dd_layout=', '\nfi\n').replace(LAYOUT_DIR, target.as_posix()), home)
written = (target / 'org.kde.plasma.desktop-layout.js').read_text()
self.assertEqual(OVERLAY_LAYOUT.replace('\r\n', '\n').rstrip('\n'), written.rstrip('\n'))
def test_the_layout_follows_plasmas_stock_panel_with_the_steam_deck_launcher(self):
for widget in ('kickoff', 'pager', 'icontasks', 'marginsseparator', 'systemtray', 'digitalclock', 'showdesktop'):
self.assertIn('org.kde.plasma.' + widget, OVERLAY_LAYOUT)
self.assertIn('distributor-logo-steamdeck', OVERLAY_LAYOUT)
for pin in ('steamdeck-steam', 'systemsettings', 'org.kde.discover', 'preferred://filemanager', 'preferred://browser'):
self.assertIn(pin, OVERLAY_LAYOUT)
def test_the_layout_keeps_plasmas_stock_wide_screen_cap_and_input_method_panel(self):
self.assertIn('const maximumAspectRatio = 21 / 9;', OVERLAY_LAYOUT)
self.assertIn('panel.maximumLength = maximumWidth;', OVERLAY_LAYOUT)
self.assertIn('org.kde.plasma.kimpanel', OVERLAY_LAYOUT)
for language in ('ja', 'ko', 'th', 'zh_CN', 'zh_TW', 'hi'):
self.assertIn('"' + language + '"', OVERLAY_LAYOUT)
def test_the_panel_is_prepared_before_plasma_starts(self):
for marker in ('dd_layout=', 'dd_panel_rc='):
self.assertLess(DESKTOP.index(marker), DESKTOP.index('dbus-run-session -- startplasma-wayland'))
if __name__ == '__main__':
unittest.main()
@@ -0,0 +1,83 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
from tools.tests.test_usr2_preload import runner
TOOLS = Path(__file__).resolve().parents[1]
STUB = TOOLS / 'linuxfs/overlay/usr/local/bin/droiddeck-diversion-stub'
PROBE = r'''
#include <errno.h>
#include <fcntl.h>
#include <sys/xattr.h>
#include <unistd.h>
int main(int argc, char **argv) {
int fd = open(argv[1], O_RDWR);
char value[] = "test", out[8];
if (fd < 0) return 1;
if (setxattr(argv[1], "security.capability", value, 4, 0) ||
lsetxattr(argv[1], "security.capability", value, 4, 0) ||
fsetxattr(fd, "security.capability", value, 4, 0)) return 2;
if (getxattr(argv[1], "security.capability", out, 8) != -1 || errno != ENODATA ||
lgetxattr(argv[1], "security.capability", out, 8) != -1 || errno != ENODATA ||
fgetxattr(fd, "security.capability", out, 8) != -1 || errno != ENODATA) return 3;
if (removexattr(argv[1], "security.capability") ||
lremovexattr(argv[1], "security.capability") ||
fremovexattr(fd, "security.capability")) return 4;
if (fsetxattr(fd, "user.ddtest", value, 4, 0) ||
fgetxattr(fd, "user.ddtest", out, 8) != 4 ||
fremovexattr(fd, "user.ddtest")) return 5;
close(fd);
return 0;
}
'''
class DiversionCapabilitiesTest(unittest.TestCase):
def test_stubs_and_migration(self):
with tempfile.TemporaryDirectory() as d:
path = Path(d) / 'entry'
target = Path(d) / 'target'
target.write_text('#!/bin/sh\nprintf "%s\\n" "$@"\n')
target.chmod(0o755)
path.symlink_to(target.name)
subprocess.run(['sh', str(STUB), str(path), str(target), 'migrate'], check=True)
self.assertFalse(path.is_symlink())
self.assertEqual(path.stat().st_mode & 0o777, 0o755)
self.assertEqual(subprocess.check_output([str(path), 'one two'], text=True), 'one two\n')
before = path.read_bytes()
subprocess.run(['sh', str(STUB), str(path), str(target), 'migrate'], check=True)
self.assertEqual(path.read_bytes(), before)
path.unlink()
path.symlink_to('other')
subprocess.run(['sh', str(STUB), str(path), str(target), 'migrate'], check=True)
self.assertEqual(os.readlink(path), 'other')
subprocess.run(['sh', str(STUB), str(path), str(target), 'install'], check=True)
self.assertFalse(path.is_symlink())
self.assertEqual(path.read_bytes(), before)
def test_capability_xattrs_and_other_attributes(self):
cc, prefix = runner()
if cc is None:
self.skipTest('no aarch64 compiler and runner')
if not shutil.which('aarch64-linux-gnu-gcc') and not (shutil.which('clang') and shutil.which('ld.lld')):
self.skipTest('no aarch64 cross compiler for the hook build')
with tempfile.TemporaryDirectory(dir='/tmp') as d:
root = Path(d)
hook, source, probe, target = (root / name for name in ('hook.so', 'probe.c', 'probe', 'file'))
subprocess.run(['bash', str(TOOLS / 'nativeguest/build.sh'), str(hook), cc], check=True, capture_output=True)
source.write_text(PROBE)
subprocess.run([cc, '-o', str(probe), str(source)], check=True)
target.touch()
env = {k: v for k, v in os.environ.items() if k not in ('LD_PRELOAD', 'DDNATV_ROOT')}
variables = {'LD_PRELOAD': str(hook), 'DDNATV_ROOT': str(root)}
if prefix:
command = list(prefix) + [arg for k, v in variables.items() for arg in ('-E', f'{k}={v}')]
else:
command = []
env.update(variables)
result = subprocess.run(command + [str(probe), str(target)], env=env, capture_output=True, text=True)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn('security.capability', os.listxattr(target))
+205
View File
@@ -0,0 +1,205 @@
import os
from pathlib import Path
import subprocess
import tempfile
import time
import unittest
try:
import gi
gi.require_version("Gio", "2.0")
from gi.repository import Gio, GLib
except ImportError:
Gio = GLib = None
SCRIPT = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-documents"
NAME = "org.freedesktop.portal.Documents"
PATH = "/org/freedesktop/portal/documents"
REUSE_EXISTING = 1
PERSISTENT = 2
AS_NEEDED_BY_APP = 4
DIRECTORY = 8
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
class DocumentStoreTest(unittest.TestCase):
def setUp(self):
self.directory = tempfile.TemporaryDirectory()
self.dir = Path(self.directory.name)
self.file = self.dir / "picked.iso"
self.file.write_text("data")
self.proc = self.dir / "proc"
self.sandbox = self.dir / "sandbox"
(self.proc / "1234").mkdir(parents=True)
(self.sandbox / self.dir.relative_to("/")).mkdir(parents=True)
(self.sandbox / ".flatpak-info").write_text("[Application]\nname=org.example.App\n")
(self.proc / "1234/root").symlink_to(self.sandbox)
self.visible = self.share(self.file)
self.saves = self.dir / "saves"
self.saves.mkdir()
(self.sandbox / self.saves.relative_to("/")).symlink_to(self.saves)
self.bus = Gio.DBusConnection.new_for_address_sync(
os.environ["DBUS_SESSION_BUS_ADDRESS"],
Gio.DBusConnectionFlags.AUTHENTICATION_CLIENT | Gio.DBusConnectionFlags.MESSAGE_BUS_CONNECTION,
None, None)
self.alias = self.dir / "alias"
self.shared = self.dir / "shared"
self.alias.mkdir()
(self.alias / "game.iso").write_text("data")
self.share(self.alias / "game.iso", self.shared / "game.iso")
(self.alias / "inside.iso").write_text("data")
self.share(self.alias / "inside.iso")
(self.alias / "private.iso").write_text("data")
(self.dir / "rootfs").mkdir()
self.share(self.alias / "private.iso", self.dir / "rootfs/alias/private.iso")
env = dict(os.environ, DDNATV_ROOT=str(self.dir / "rootfs"),
DDNATV_BINDS="%s:%s|%s/rootfs/alias:%s" % (self.shared, self.alias, self.dir, self.alias))
self.process = subprocess.Popen(["/usr/bin/python3", str(SCRIPT), str(self.proc)], stdout=subprocess.DEVNULL,
env=env)
self.session = self.dir / "session"
(self.session / self.dir.relative_to("/")).mkdir(parents=True)
(self.dir / "hidden.iso").write_text("data")
os.link(self.dir / "hidden.iso", self.session / self.dir.relative_to("/") / "hidden.iso")
(self.session / ".flatpak-info").write_text("[Application]\nname=org.example.App\n")
for pid in (self.process.pid, 99):
(self.proc / str(pid)).mkdir()
(self.proc / str(pid) / "root").symlink_to(self.session)
deadline = time.monotonic() + 10
while not self.owned():
self.assertIsNone(self.process.poll())
self.assertLess(time.monotonic(), deadline)
time.sleep(0.05)
def share(self, source, name=None):
seen = self.sandbox / (name or source).relative_to("/")
seen.parent.mkdir(parents=True, exist_ok=True)
os.link(source, seen)
return seen
def tearDown(self):
self.process.terminate()
self.process.wait(timeout=5)
self.bus.close_sync(None)
self.directory.cleanup()
def owned(self):
reply = self.bus.call_sync("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus",
"NameHasOwner", GLib.Variant("(s)", (NAME,)), None,
Gio.DBusCallFlags.NONE, -1, None)
return reply.unpack()[0]
def call(self, method, signature, args, paths=()):
fds = Gio.UnixFDList.new()
opened = [os.open(p, os.O_PATH | os.O_CLOEXEC) for p in paths]
try:
for fd in opened:
fds.append(fd)
reply, _ = self.bus.call_with_unix_fd_list_sync(
NAME, PATH, NAME, method, GLib.Variant(signature, args), None, Gio.DBusCallFlags.NONE, -1,
fds, None)
return reply.unpack()
finally:
for fd in opened:
os.close(fd)
def error_of(self, *args, **kwargs):
with self.assertRaises(GLib.Error) as caught:
self.call(*args, **kwargs)
return Gio.DBusError.get_remote_error(caught.exception)
def test_a_picked_file_is_handed_back_in_place(self):
got = self.call("AddFull", "(ahusas)", ([0], REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP, "org.example.App",
["read", "write"]), [self.file])
self.assertEqual(([""], {}), got)
def test_a_saved_file_name_is_handed_back_in_place(self):
got = self.call("AddNamedFull", "(hayusas)", (0, b"new.txt\0", AS_NEEDED_BY_APP, "org.example.App", ["read"]),
[self.saves])
self.assertEqual(("", {}), got)
def test_a_picked_folder_needs_the_directory_flag(self):
flags = REUSE_EXISTING | AS_NEEDED_BY_APP
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags | DIRECTORY, "", []), [self.dir]))
self.assertEqual("org.freedesktop.portal.Error.InvalidArgument",
self.error_of("AddFull", "(ahusas)", ([0], flags, "", []), [self.dir]))
self.assertEqual("org.freedesktop.portal.Error.InvalidArgument",
self.error_of("AddFull", "(ahusas)", ([0], flags | DIRECTORY, "", []), [self.file]))
def test_a_file_the_application_cannot_reach_is_refused(self):
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
hidden = self.dir / "hidden.iso"
self.assertTrue((self.proc / "99/root" / hidden.relative_to("/")).exists())
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [hidden]))
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.Other", ["read"]), [self.file]))
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags, "", ["read"]), [hidden]))
def test_a_file_seen_through_a_bound_folder_is_found_under_its_host_name(self):
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]),
[self.alias / "game.iso"]))
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]),
[self.alias / "inside.iso"]))
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]),
[self.alias / "private.iso"]))
(self.sandbox / self.shared.relative_to("/") / "game.iso").unlink()
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]),
[self.alias / "game.iso"]))
def test_a_file_inside_the_root_filesystem_is_judged_by_its_own_name(self):
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
home = self.dir / "rootfs/home.iso"
home.write_text("data")
self.share(home)
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [home]))
os.link(home, self.sandbox / "home.iso")
self.assertEqual(([""], {}), self.call("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [home]))
def test_a_different_file_at_the_same_name_is_refused(self):
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
other = self.dir / "other.iso"
other.write_text("data")
(self.sandbox / other.relative_to("/")).write_text("data")
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [other]))
@unittest.skipIf(os.getuid() == 0, "root reads every file")
def test_a_location_the_application_cannot_use_as_asked_is_refused(self):
flags = REUSE_EXISTING | PERSISTENT | AS_NEEDED_BY_APP
self.visible.chmod(0)
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddFull", "(ahusas)", ([0], flags, "org.example.App", ["read"]), [self.file]))
self.saves.chmod(0o500)
try:
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddNamedFull", "(hayusas)",
(0, b"new.txt\0", AS_NEEDED_BY_APP, "org.example.App", ["read", "write"]),
[self.saves]))
finally:
self.saves.chmod(0o700)
def test_documents_that_would_need_the_store_mount_are_refused(self):
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("AddFull", "(ahusas)", ([0], REUSE_EXISTING, "", []), [self.file]))
self.assertEqual("org.freedesktop.portal.Error.NotAllowed",
self.error_of("Add", "(hbb)", (0, True, False), [self.file]))
self.assertEqual("org.freedesktop.portal.Error.Failed", self.error_of("GetMountPoint", "()", ()))
def test_a_missing_descriptor_is_refused(self):
self.assertEqual("org.freedesktop.portal.Error.InvalidArgument",
self.error_of("AddFull", "(ahusas)", ([3], AS_NEEDED_BY_APP, "", []), [self.file]))
def test_no_documents_are_listed(self):
self.assertEqual(("",), self.call("Lookup", "(ay)", (str(self.file).encode() + b"\0",)))
self.assertEqual(({},), self.call("List", "(s)", ("org.example.App",)))
version = self.bus.call_sync(NAME, PATH, "org.freedesktop.DBus.Properties", "Get",
GLib.Variant("(ss)", (NAME, "version")), None, Gio.DBusCallFlags.NONE, -1, None)
self.assertEqual(5, version.unpack()[0])
if __name__ == "__main__":
unittest.main()
+80
View File
@@ -0,0 +1,80 @@
from pathlib import Path
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
SOURCE = Path(__file__).resolve().parents[2] / "app/src/main/cpp/fakeinput_steam.cpp"
LIBRARY = r"""
#include <stdatomic.h>
#include <sys/statfs.h>
#include <unistd.h>
extern _Atomic int loading;
__attribute__((constructor)) static void start(void) {
struct statfs buf;
atomic_store_explicit(&loading, 1, memory_order_release);
usleep(300000);
statfs("/", &buf);
}
"""
PROGRAM = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <stdio.h>
#include <sys/statfs.h>
_Atomic int loading;
static void *load(void *path) {
return dlopen(path, RTLD_NOW);
}
int main(int argc, char **argv) {
pthread_t loader;
struct statfs buf;
pthread_create(&loader, NULL, load, argv[1]);
while (!atomic_load_explicit(&loading, memory_order_acquire)) sched_yield();
statfs("/", &buf);
void *handle = NULL;
pthread_join(loader, &handle);
puts(handle ? "ok" : dlerror());
return 0;
}
"""
@unittest.skipUnless(sys.platform == "linux" and shutil.which("gcc") and shutil.which("g++"),
"needs Linux, gcc and g++")
class FakeinputLoaderLockTest(unittest.TestCase):
def test_a_first_hooked_call_while_another_thread_loads_a_library_does_not_deadlock(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp)
(path / "program.c").write_text(PROGRAM)
(path / "library.c").write_text(LIBRARY)
subprocess.run(["gcc", "-rdynamic", "-pthread", "-o", str(path / "program"), str(path / "program.c"),
"-ldl"], check=True)
subprocess.run(["gcc", "-shared", "-fPIC", "-o", str(path / "library.so"), str(path / "library.c")],
check=True)
subprocess.run(["g++", "-shared", "-fPIC", "-O2", "-Wno-attributes", "-pthread",
"-std=c++17", "-static-libstdc++", "-static-libgcc",
"-Wl,--exclude-libs,ALL", "-o", str(path / "libfakeinput.so"),
str(SOURCE), "-ldl"], check=True)
for _ in range(5):
result = subprocess.run([str(path / "program"), str(path / "library.so")],
env=dict(os.environ, LD_PRELOAD=str(path / "libfakeinput.so")),
capture_output=True, text=True, timeout=20)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(result.stdout, "ok\n")
if __name__ == "__main__":
unittest.main()
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more