Merge main into Steam client download PR

This commit is contained in:
xXJsonDeruloXx committed 2026-10-22 10:01:34 -04:00
commit c8cc17bf3a
491 files changed
+34864 -2441

No files matched your search

+5 -3
View File
@@ -23,7 +23,8 @@ if [[ ! -d "$TOOLCHAIN" && "$NDK_HOST" == linux-aarch64 && -d "$NDK/toolchains/l
TOOLCHAIN="$NDK/toolchains/llvm/prebuilt/linux-x86_64/bin"
fi
CC="$TOOLCHAIN/aarch64-linux-android${API}-clang"
if [[ ! -x "$CC" ]]; then
CC28="$TOOLCHAIN/aarch64-linux-android28-clang"
if [[ ! -x "$CC" || ! -x "$CC28" ]]; then
echo "Android NDK toolchain not found at $TOOLCHAIN" >&2
exit 1
fi
@@ -34,8 +35,8 @@ sed -e 's/@PA_MAJOR@/13/g' -e 's/@PA_MINOR@/0/g' -e 's/@PA_API_VERSION@/12/g' -e
"$PA_SRC/src/pulse/version.h.in" > "$INC/pulse/version.h"
cp "$HERE/config.h" "$HERE/ltdl.h" "$INC/"
build_one() {
local src=$1 OUT=$2 extra=$3
"$CC" -O2 -shared -fPIC -Wall -Wno-unused-parameter -Wno-error=int-conversion -Wno-visibility -DHAVE_CONFIG_H \
local src=$1 OUT=$2 extra=$3 cc=${4:-$CC}
"$cc" -O2 -shared -fPIC -Wall -Wno-unused-parameter -Wno-error=int-conversion -Wno-visibility -DHAVE_CONFIG_H \
-I"$INC" -I"$PA_SRC/src" -I"$HERE" \
-o "$OUT" "$HERE/$src" \
-L"$LIBS" -l:libpulsecore-13.0.so -l:libpulsecommon-13.0.so -l:libpulse.so $extra
@@ -54,3 +55,4 @@ build_one() {
ls -l "$OUT"
}
build_one module-aaudio-sink.c "$OUTDIR/module-aaudio-sink.so" -laaudio
build_one ../directaudio/sink/module-directaudio-native-sink.c "$OUTDIR/module-directaudio-native-sink.so" -laaudio "$CC28"
+2 -2
View File
@@ -61,9 +61,9 @@ def build(full, lite, palm, output):
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--full', type=Path, default=Path('app/src/main/assets/models/hand_landmarker.task'))
parser.add_argument('--full', type=Path, required=True)
parser.add_argument('--lite', type=Path, required=True, help='Pinned hand_landmark_lite.tflite from storage.googleapis.com/mediapipe-assets/')
parser.add_argument('--palm', type=Path, required=True, help='Pinned palm_detection_lite.tflite from storage.googleapis.com/mediapipe-assets/')
parser.add_argument('--output', type=Path, default=Path('app/src/main/assets/models/hand_landmarker_lite.task'))
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
build(args.full, args.lite, args.palm, args.output)
+30 -1
View File
@@ -12,7 +12,18 @@ else
export DROIDDECK_BUILD_TREE_STATE=unknown
fi
sdk_dir=${ANDROID_HOME:-${ANDROID_SDK_ROOT:-"${HOME}/Library/Android/sdk"}}
java_dir=${JAVA_HOME:-"/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home"}
java_dir="${JAVA_HOME:-/opt/homebrew/opt/openjdk@17/libexec/openjdk.jdk/Contents/Home}"
[[ -x "$java_dir/bin/java" ]] || {
mise_java="$(mise -C "${repo_root}" which java 2>/dev/null)"
if [[ -n "$mise_java" ]]; then
mise_home="$(dirname "$mise_java")"
[[ "$mise_home" == */bin ]] && mise_home="$(dirname "$mise_home")"
[[ -x "$mise_home/bin/java" ]] && java_dir="$mise_home"
fi
}
[[ -x "$java_dir/bin/java" ]] || java_dir="${HOME}/.local/share/mise/installs/java/temurin-17"
[[ "$java_dir" == */homebrew/* ]] && echo "using homebrew java path: $java_dir"
[[ "$java_dir" == */mise/* ]] && echo "using mise java path: $java_dir"
image_name=${DROIDDECK_BUILD_IMAGE:-droiddeck-local-cross:24.04-v3}
build_variant=${DROIDDECK_BUILD_VARIANT:-release}
case "$build_variant" in
@@ -278,6 +289,16 @@ docker run --rm --platform linux/amd64 --user "$(id -u):$(id -g)" -v "${repo_roo
mkdir -p "${linuxfs_dir}/usr/local/bin"
install -m644 "${repo_root}/tools/mangoapp/mangoapp" "${linuxfs_dir}/usr/local/bin/mangoapp"
pw_pkgs="${staging_dir}/pw-pkgs"
mkdir -p "${pw_pkgs}"
while read -r package_sha256 package_url; do
[[ -n "${package_url}" ]] || continue
package_archive=$(cached "${package_sha256}" "$(basename "${package_url}")" \
bash -c 'curl -fsSL --retry 3 -o "$out" "$0"' "${package_url}")
zstd -dc "${package_archive}" | tar -xf - -C "${pw_pkgs}"
done < <(grep -v '^#' "${repo_root}/tools/pipewire/packages.txt")
"${repo_root}/tools/pipewire/assemble.sh" "${pw_pkgs}" "${linuxfs_dir}/usr/local/lib/droiddeck-pipewire.tzst"
pa_source=${DROIDDECK_PA13_SOURCE_DIR:-"${staging_dir}/pulseaudio-13.0"}
if [[ -z "${DROIDDECK_PA13_SOURCE_DIR:-}" ]]; then
pa_tarball="${cache_dir}/pulseaudio-13.0.tar.gz"
@@ -351,12 +372,20 @@ fi
cd "${repo_root}"
python3 tools/quest/build-driver.py "${NDK}"
xbox_out="${linuxfs_dir}/usr/local/lib/droiddeck-xbox"
xbox_key=$(inputs_hash "native-arm64-ubuntu24.04" tools/xbox)
if ! restore_step xbox "${xbox_key}" "${xbox_out}"; then
bash tools/xbox/build-local.sh
save_step xbox "${xbox_key}" "${xbox_out}"
fi
comet_out="${linuxfs_dir}/usr/local/lib/droiddeck-comet"
comet_key=$(inputs_hash "${image_id}" tools/comet)
if ! restore_step comet "${comet_key}" "${comet_out}"; then
DROIDDECK_BUILD_IMAGE="${image_name}" bash tools/comet/build-local.sh
save_step comet "${comet_key}" "${comet_out}"
fi
bash tools/packs/build.sh app/build/packs
python3 tools/release/runtime_inputs.py record
./gradlew "${gradle_task}" --console=plain -PndkVersion="${ndk_version}" ${gradle_rust_arg}
python3 tools/release/check_session_assets.py "app/build/outputs/apk/${build_variant}/app-${build_variant}.apk"
+12
View File
@@ -40,6 +40,18 @@ if [ -n "${KDE_KWIN_OVERRIDE:-}" ]; then
install -m 755 "$KDE_KWIN_OVERRIDE/libkwin.so.6.7.5" "$work/root/usr/lib/libkwin.so.6.7.5"
fi
if [ -d "$work/root/usr/share/locale" ]; then
for dir in "$work/root"/usr/share/locale/*/; do
loc=${dir#$work/root/usr/share/locale/}; loc=${loc%/}
case $loc in en*) continue ;; esac
[ -d "$dir/LC_MESSAGES" ] || continue
file=$out/desktop-kde-i18n-$loc.tar.zst
tar -C "$work/root" --zstd -cf "$file" "./usr/share/locale/$loc"
printf '%s %s %s\n' "$loc" "$(sha256sum "$file" | cut -d' ' -f1)" "$(stat -c %s "$file")"
done > "$out/desktop-kde.i18n.txt"
echo "i18n: $(wc -l < "$out/desktop-kde.i18n.txt") language packs"
fi
rm -rf "$work/root/usr/share/doc" "$work/root/usr/share/man" "$work/root/usr/share/info" \
"$work/root/usr/share/gtk-doc" "$work/root/usr/include" "$work/root/usr/lib/pkgconfig" \
"$work/root/usr/lib/cmake" "$work/root/usr/share/help"
+502
View File
@@ -0,0 +1,502 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
+209
View File
@@ -0,0 +1,209 @@
/* DirectAudio relay - the contract between the driver and the relay helper.
*
* Copyright 2026 The412Banner
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* WHY THIS EXISTS. The driver's whole premise is an in-process AAudio client:
* the guest's WASAPI buffers are mixed and handed to Android's audio server
* from inside the game, no daemon in the path. That is only possible when the
* game process is a bionic process. Under a glibc runtime (the Linux Steam
* client, where the game runs inside a proot'd Arch rootfs on Valve's own
* ARM64 Proton) libaaudio cannot be loaded at all: it is a bionic library and
* the rootfs's dynamic linker does not know how to bring it into a glibc
* process. The game side therefore has to stop at a boundary it CAN cross, and
* the only thing both worlds agree on is the kernel: a unix socket, a memfd and
* a futex word.
*
* SHAPE. One helper process (directaudio-relay, bionic, links libaaudio) runs
* on the Android side and listens on a unix socket. Each game process that
* needs audio connects once, sends its launch config (the same knobs the
* in-process build reads from BANNER_AUDIO_DIRECT_*), and gets back one or two
* shared rings (memfds passed with SCM_RIGHTS):
*
* render ring game (producer) -> helper (consumer) -> AAudio OUTPUT
* capture ring helper (producer, AAudio INPUT) -> game (consumer)
*
* The driver keeps its mixer and its per-voice WASAPI rings exactly as in the
* in-process build; what used to be the AAudio data callback is now a pump
* thread that keeps the render ring topped up, and the capture callback is a
* pump that drains the capture ring into the capture voices. Everything that
* needs an AAudioStream (open, adaptive buffer growth and decay, route-change
* reopen, the stalled-callback watchdog, the live-config mailbox) moves to the
* helper unchanged in spirit.
*
* COST. One extra hand-off: the ring. The helper's callback pulls a burst from
* the ring, so the ring must hold at least one burst at every callback; the
* driver keeps DA_RING_TARGET_BURSTS bursts queued and the helper raises that
* target when a callback finds the ring short. Everything else - the AAudio
* buffer, AudioFlinger's own latency - is what the in-process build pays too.
*
* WIRE FORMAT. Fixed-width, native-endian, same-machine only. The two sides are
* different libcs but the same CPU, so no marshalling beyond fixed-size structs.
* Bump DA_RELAY_VERSION on any layout change; the helper refuses a mismatch.
*/
#ifndef DA_RELAY_PROTO_H
#define DA_RELAY_PROTO_H
#include <stdint.h>
#include <stddef.h>
#define DA_RELAY_VERSION 1
#define DA_RING_MAGIC 0x44415247u /* 'DARG' */
#define DA_HELLO_MAGIC 0x44414831u /* 'DAH1' */
#define DA_ACK_MAGIC 0x44414131u /* 'DAA1' */
/* Socket path. The driver reads BANNER_AUDIO_DIRECT_RELAY; when unset it falls
* back to $XDG_RUNTIME_DIR/DA_RELAY_DEFAULT_NAME, which a host that already
* hands its runtime dir into the session gets for free. */
#define DA_RELAY_ENV "BANNER_AUDIO_DIRECT_RELAY"
#define DA_RELAY_DEFAULT_NAME "directaudio-relay"
/* Both rings carry float32 interleaved stereo. The render ring is always
* 48 kHz (the mixer's output rate); the capture ring runs at whatever rate the
* input stream was granted, published in da_ring.rate, and the driver resamples
* per voice as the in-process build already does. */
#define DA_RING_RATE 48000
#define DA_RING_CHANNELS 2
/* Render ring sizing. Capacity is the ceiling adaptive growth can reach; the
* initial target is what the driver keeps queued. Two bursts: the helper's
* callback consumes one burst and wakes the pump, which then has a full burst
* period to refill before the next callback. */
#define DA_RING_CAP_MS 250
#define DA_RING_TARGET_BURSTS 2
#define DA_RING_MAX_TARGET_MS 100
/* Capture ring: 200 ms is far more than a game ever leaves queued; on overrun
* the helper drops the newest block, matching the in-process "guest is not
* draining" behaviour of dropping data rather than blocking the mic thread. */
#define DA_CAPTURE_RING_MS 200
enum da_ring_state
{
DA_RING_OPENING = 0,
DA_RING_PLAYING = 1,
DA_RING_ERROR = 2,
};
struct da_ring
{
uint32_t magic;
uint32_t version;
uint32_t cap_frames; /* ring capacity in frames */
uint32_t rate; /* frames per second of the data in this ring */
uint32_t channels; /* DA_RING_CHANNELS */
uint32_t _pad0;
/* Single producer, single consumer; monotonic frame totals, wrap-safe with
* unsigned arithmetic. Producer writes widx with RELEASE after the data;
* consumer writes ridx with RELEASE after it has copied the data out. */
volatile uint32_t widx;
volatile uint32_t ridx;
/* Futex word the CONSUMER of a render ring / PRODUCER of a capture ring
* bumps after each block, so the other side can sleep on it instead of
* polling. Waiters always use a timeout, so a missed wake only costs one
* period. */
volatile uint32_t wake;
volatile uint32_t quit; /* either side: tear down */
volatile uint32_t state; /* enum da_ring_state, helper-owned */
/* Render ring only, helper-owned, read by the driver: */
volatile int32_t target_frames; /* keep at least this many queued */
volatile int32_t hw_buf_frames; /* AAudio buffer size right now (get_latency) */
volatile int32_t hw_burst; /* frames per burst of the output stream */
volatile uint32_t underruns; /* callbacks that found fewer than they needed */
volatile uint32_t cb_count; /* data callbacks so far (liveness) */
uint32_t _pad1[3];
float data[]; /* cap_frames * channels */
};
static inline size_t da_ring_bytes(uint32_t cap_frames)
{
return sizeof(struct da_ring) + (size_t)cap_frames * DA_RING_CHANNELS * sizeof(float);
}
static inline uint32_t da_ring_avail(const struct da_ring *r)
{
uint32_t w = __atomic_load_n(&r->widx, __ATOMIC_ACQUIRE);
uint32_t rd = __atomic_load_n(&r->ridx, __ATOMIC_ACQUIRE);
return w - rd;
}
static inline uint32_t da_ring_space(const struct da_ring *r)
{
return r->cap_frames - da_ring_avail(r);
}
/* ---- wire messages ------------------------------------------------------- */
#define DA_HELLO_MIC 0x01u /* also open an INPUT stream + capture ring */
#define DA_HELLO_EXCLUSIVE 0x02u /* AAUDIO_SHARING_MODE_EXCLUSIVE requested */
#define DA_HELLO_ADAPTIVE 0x04u
#define DA_HELLO_DECAY 0x08u
#define DA_HELLO_WATCHDOG 0x10u
/* First message on a fresh connection, driver -> helper. Mirrors the launch
* config the in-process build derives from BANNER_AUDIO_DIRECT_* so a preset
* means the same thing under both runtimes. */
struct da_hello
{
uint32_t magic; /* DA_HELLO_MAGIC */
uint32_t version; /* DA_RELAY_VERSION */
uint32_t flags; /* DA_HELLO_* */
int32_t perf; /* 0 NONE, 1 LOW_LATENCY, 2 POWER_SAVING (host convention) */
int32_t target_ms; /* AAudio buffer, ms; 0 = use target_frames or the default */
int32_t max_ms; /* adaptive ceiling, ms; 0 = max_frames or the default */
int32_t target_frames; /* frame forms, used only when the ms forms are 0 */
int32_t max_frames;
uint32_t stall_ms; /* watchdog: callback silent this long => rebuild */
uint32_t quiet_ms; /* decay pacing, see the driver */
uint32_t punish_ms;
uint32_t max_backoff;
int32_t pid; /* the game process, for the log */
uint32_t log; /* BANNER_AUDIO_DIRECT_LOG */
char runtime_path[256]; /* BANNER_AUDIO_DIRECT_RUNTIME mailbox, "" = none */
char name[64]; /* process name, for the log */
};
#define DA_ACK_MIC_FAILED 0x01u /* mic asked for, input stream would not open */
/* Reply, helper -> driver, followed by SCM_RIGHTS carrying the ring fds:
* fd[0] = render ring, fd[1] = capture ring (present iff in_cap_frames > 0). */
struct da_ack
{
uint32_t magic; /* DA_ACK_MAGIC */
int32_t status; /* 0 = ok, else an AAudio error code (negative) */
int32_t rate; /* output stream rate (48000) */
int32_t burst; /* output frames per burst */
int32_t buf_frames; /* output buffer size as opened */
int32_t out_cap_frames; /* render ring capacity */
int32_t in_cap_frames; /* capture ring capacity, 0 = no capture ring */
int32_t in_rate; /* rate of the capture ring's data */
uint32_t flags; /* DA_ACK_* */
uint32_t _pad;
};
/* Subsequent messages, driver -> helper, on the same socket. The helper never
* writes after the ack; everything it has to say is in the ring header. EOF on
* the socket is how the helper learns the game is gone. */
enum da_msg_type
{
DA_MSG_MIC_START = 1, /* first capture voice started: make the mic hot */
DA_MSG_MIC_STOP = 2, /* last capture voice gone: stop (keep open) */
DA_MSG_PING = 3,
};
struct da_msg
{
uint32_t type;
int32_t arg;
};
#endif /* DA_RELAY_PROTO_H */
@@ -0,0 +1,817 @@
/*
* module-directaudio-native-sink: a PulseAudio 13 sink that is DirectAudio's AAudio engine,
* in-process. For the native Linux Steam client on Android (DroidDeck, Bannerlator's Linux
* session), whose sound can only ever reach a PulseAudio daemon: this module is where that
* daemon's mixed output meets Android, one step away from AudioFlinger, with the same engine the
* game driver has - adaptive device buffer that grows a burst on every xrun, optional decay with a
* remembered floor, a primed ring with fades instead of clicks, route-change / error reopen on a
* fresh stream, and a stall watchdog.
*
* It is the relay helper's per-client OUTPUT engine (directaudio-relay.c) with the socket and the
* shared-memory ring replaced by a ring in this process, fed by the sink's IO thread exactly as
* module-directaudio-sink feeds the relay. Compared with that module there is no second process
* and no 40 ms proot safety margin: the ring here only has to cover the IO thread's own
* scheduling jitter, so it starts at two bursts and grows only if a callback finds it short.
*
* The daemon must run on the Android side (the host app's process), not inside proot, for AAudio
* to be reachable at all - which is where both host apps already run it.
*
* Field fixes carried from the relay (MaxsTechReview, Droid-Deck/DroidDeck#338): prime before
* playing, fade on an underrun, one consumer per ring across a reopen, a device buffer of at
* least two bursts.
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <errno.h>
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/resource.h>
#include <sys/syscall.h>
#include <time.h>
#include <unistd.h>
#include <aaudio/AAudio.h>
#include <pulse/rtclock.h>
#include <pulse/timeval.h>
#include <pulse/util.h>
#include <pulse/xmalloc.h>
#include <pulsecore/core-util.h>
#include <pulsecore/log.h>
#include <pulsecore/macro.h>
#include <pulsecore/modargs.h>
#include <pulsecore/module.h>
#include <pulsecore/rtpoll.h>
#include <pulsecore/sink.h>
#include <pulsecore/thread-mq.h>
#include <pulsecore/thread.h>
#include "da_relay_proto.h" /* struct da_ring + the ring helpers; nothing of the socket protocol */
PA_MODULE_AUTHOR("The412Banner");
PA_MODULE_DESCRIPTION("Android audio output: DirectAudio's AAudio engine, in-process");
PA_MODULE_VERSION(PACKAGE_VERSION);
PA_MODULE_LOAD_ONCE(false);
PA_MODULE_USAGE(
"sink_name=<name for the sink> "
"sink_properties=<properties for the sink> "
"volume=<initial volume, linear, 1.0 = full> "
"performance_mode=<0 none, 1 low latency, 2 power saving> "
"buffer_ms=<device buffer to start with, ms; rounded up to whole bursts, never below two> "
"max_ms=<largest the device buffer may grow to, ms> "
"ring_ms=<queue kept ahead of the device, ms; never below two bursts> "
"adaptive=<grow the buffers after underruns: 0 or 1> "
"decay=<shrink the device buffer again after a quiet spell: 0 or 1> "
"limiter=<soft-knee limiter on the way out: 0 or 1> "
"watchdog=<rebuild the stream when its callback stalls: 0 or 1>");
#define DEFAULT_SINK_NAME "DirectAudio"
#define STATS_EVERY_USEC (30 * PA_USEC_PER_SEC)
#define WATCHDOG_TICK_USEC (1 * PA_USEC_PER_SEC)
#define AUDIO_NICE (-16)
/* ---- tunables: the in-process driver's, same defaults ----------------------- */
#define DA_KNEE 0.75f
#define DA_DEFAULT_MS 12
#define DA_DEFAULT_MAX_MS 100
#define DA_DEFAULT_RING_MS 12
#define DA_RING_CAP_MS_LOCAL 250
#define DA_FREEZE_GAP_NS 500000000ull
#define DA_CB_STALL_NS 1000000000ull
#define DA_DECAY_QUIET_NS 10000000000ull
#define DA_DECAY_PUNISH_NS 5000000000ull
#define DA_DECAY_MAX_BACKOFF 32
#define DA_MIN_BUFFER_BURSTS 2
#define DA_FADE_FRAMES 64
static const char* const valid_modargs[] = {
"sink_name", "sink_properties", "volume", "performance_mode", "buffer_ms", "max_ms", "ring_ms",
"adaptive", "decay", "limiter", "watchdog", NULL
};
struct userdata {
pa_core *core;
pa_module *module;
pa_sink *sink;
pa_thread *thread;
pa_thread_mq thread_mq;
pa_rtpoll *rtpoll;
pa_sample_spec ss;
size_t frame_size;
/* configuration */
aaudio_performance_mode_t perf;
int32_t target_ms, max_ms, ring_ms;
bool adaptive, decay, limiter, watchdog_on;
/* the ring: this process's, same layout as the relay's so the engine is shared */
struct da_ring *ring;
int32_t burst;
int32_t ring_max_target;
/* the one OUTPUT stream and its adaptive state (the relay's struct client, minus the socket) */
AAudioStream *aq;
pthread_mutex_t lock;
int32_t last_xrun;
uint64_t last_cb_ns, last_xrun_ns, last_decay_ns, wd_last_tick_ns;
int32_t base_buf_frames, decay_floor;
unsigned int decay_backoff, cb_count, wd_last_cb;
int reopen_running, reopen_redo;
int consuming, primed, starved;
int suspended;
volatile int dead;
/* what the IO thread last logged, so engine changes made on the AAudio thread get a line */
int32_t seen_target, seen_hw_buf;
uint32_t seen_underruns;
pa_usec_t next_watchdog, settled_at, stats_at;
unsigned int opens;
};
static uint64_t now_ns(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t) ts.tv_sec * 1000000000ull + (uint64_t) ts.tv_nsec;
}
static void request_reopen(struct userdata *u, const char *why);
/* ---- the engine: the relay's out_cb / open_output / reopen / watchdog, on a local ring ---- */
static void fade(float *p, uint32_t frames, int in) {
uint32_t i, ch;
for (i = 0; i < frames; i++) {
float g = (float) (in ? i + 1 : frames - i) / (float) (frames + 1);
for (ch = 0; ch < DA_RING_CHANNELS; ch++)
p[(size_t) i * DA_RING_CHANNELS + ch] *= g;
}
}
/* The driver's soft-knee limiter: below DA_KNEE the signal is untouched, so ordinary material is
* bit-identical; above it a smooth knee folds the overshoot back under full scale. */
static void limit(float *p, uint32_t samples) {
uint32_t i;
for (i = 0; i < samples; i++) {
float x = p[i], a = x < 0.0f ? -x : x;
if (a > DA_KNEE) {
float t = (a - DA_KNEE) / (1.0f - DA_KNEE);
float y = DA_KNEE + (1.0f - DA_KNEE) * (t / (1.0f + t));
p[i] = x < 0.0f ? -y : y;
}
}
}
static aaudio_data_callback_result_t out_cb(AAudioStream *aq, void *user, void *audioData, int32_t numFrames) {
struct userdata *u = user;
struct da_ring *r = u->ring;
float *out = audioData;
AAudioStream *live = __atomic_load_n(&u->aq, __ATOMIC_SEQ_CST);
uint32_t cap = r->cap_frames;
uint32_t frames = (uint32_t) numFrames;
uint32_t ridx, avail, n = 0, i;
int fade_in = 0, short_read = 0, starving = 0;
uint64_t now;
/* Only the promoted stream reads the ring; an outgoing one during a reopen plays silence. */
if ((live && aq != live) || __atomic_exchange_n(&u->consuming, 1, __ATOMIC_ACQUIRE)) {
memset(out, 0, (size_t) frames * DA_RING_CHANNELS * sizeof(float));
return AAUDIO_CALLBACK_RESULT_CONTINUE;
}
ridx = __atomic_load_n(&r->ridx, __ATOMIC_ACQUIRE);
avail = __atomic_load_n(&r->widx, __ATOMIC_ACQUIRE) - ridx;
if (!u->primed) {
uint32_t start = (uint32_t) __atomic_load_n(&r->target_frames, __ATOMIC_ACQUIRE);
if (start < frames) start = frames;
if (start > cap) start = cap;
u->primed = fade_in = avail >= start;
if (u->primed) u->starved = 0;
else starving = u->starved;
}
if (u->primed) {
uint32_t slot = ridx % cap, first;
n = frames < avail ? frames : avail;
first = cap - slot < n ? cap - slot : n;
memcpy(out, &r->data[(size_t) slot * DA_RING_CHANNELS], (size_t) first * DA_RING_CHANNELS * sizeof(float));
if (n > first)
memcpy(out + (size_t) first * DA_RING_CHANNELS, r->data, (size_t) (n - first) * DA_RING_CHANNELS * sizeof(float));
if (u->limiter)
limit(out, n * DA_RING_CHANNELS);
if (fade_in)
fade(out, n < DA_FADE_FRAMES ? n : DA_FADE_FRAMES, 1);
if (n < frames) {
uint32_t tail = n < DA_FADE_FRAMES ? n : DA_FADE_FRAMES;
fade(out + (size_t) (n - tail) * DA_RING_CHANNELS, tail, 0);
u->primed = 0;
u->starved = 1;
short_read = 1;
}
__atomic_store_n(&r->ridx, ridx + n, __ATOMIC_RELEASE);
}
for (i = n * DA_RING_CHANNELS; i < frames * DA_RING_CHANNELS; i++)
out[i] = 0.0f;
__atomic_store_n(&u->consuming, 0, __ATOMIC_RELEASE);
now = now_ns();
{
uint64_t prev = __atomic_exchange_n(&u->last_cb_ns, now, __ATOMIC_SEQ_CST);
if (prev && now - prev > DA_FREEZE_GAP_NS) {
u->last_xrun = AAudioStream_getXRunCount(aq);
u->last_xrun_ns = now;
}
}
__atomic_add_fetch(&u->cb_count, 1, __ATOMIC_SEQ_CST);
__atomic_store_n(&r->cb_count, u->cb_count, __ATOMIC_RELAXED);
/* The ring's own adaptive step: a short ring means the IO thread did not get scheduled in
* time - an xrun one stage earlier - so keep one more burst queued. Only grows. */
if (short_read)
__atomic_add_fetch(&r->underruns, 1, __ATOMIC_RELAXED);
if ((short_read || starving) && u->adaptive) {
int32_t burst = AAudioStream_getFramesPerBurst(aq);
int32_t cur = __atomic_load_n(&r->target_frames, __ATOMIC_RELAXED);
int32_t want = cur + (burst > 0 ? burst : numFrames);
if (want > u->ring_max_target) want = u->ring_max_target;
if (want > cur)
__atomic_store_n(&r->target_frames, want, __ATOMIC_RELEASE);
}
/* The device buffer: grow a burst per xrun; decay a burst after a quiet spell, never below
* the floor a punished decay taught us. */
if (u->adaptive) {
int32_t xruns = AAudioStream_getXRunCount(aq);
int32_t burst = AAudioStream_getFramesPerBurst(aq);
int32_t cur = AAudioStream_getBufferSizeInFrames(aq);
if (xruns > u->last_xrun) {
int32_t capf = AAudioStream_getBufferCapacityInFrames(aq);
int32_t want = cur + (burst > 0 ? burst : 1);
int32_t max_frames = u->max_ms > 0 ? u->max_ms * DA_RING_RATE / 1000 : 0;
if (max_frames > 0 && want > max_frames) want = max_frames;
if (want > capf) want = capf;
if (want > cur) AAudioStream_setBufferSizeInFrames(aq, want);
if (u->decay && u->last_decay_ns && now - u->last_decay_ns < DA_DECAY_PUNISH_NS) {
if (want > u->decay_floor) u->decay_floor = want;
if (u->decay_backoff < DA_DECAY_MAX_BACKOFF) u->decay_backoff *= 2;
}
u->last_xrun = xruns;
u->last_xrun_ns = now;
__atomic_store_n(&r->hw_buf_frames, AAudioStream_getBufferSizeInFrames(aq), __ATOMIC_RELAXED);
} else if (u->decay && burst > 0) {
uint64_t quiet = DA_DECAY_QUIET_NS * u->decay_backoff;
int32_t floor = u->base_buf_frames;
if (u->decay_floor > floor) floor = u->decay_floor;
if (cur > floor && u->last_xrun_ns && now - u->last_xrun_ns > quiet &&
(!u->last_decay_ns || now - u->last_decay_ns > quiet)) {
int32_t want = cur - burst;
if (want < floor) want = floor;
if (want < cur) {
AAudioStream_setBufferSizeInFrames(aq, want);
u->last_decay_ns = now;
__atomic_store_n(&r->hw_buf_frames, AAudioStream_getBufferSizeInFrames(aq), __ATOMIC_RELAXED);
}
}
}
}
return AAUDIO_CALLBACK_RESULT_CONTINUE;
}
static void out_error_cb(AAudioStream *aq, void *user, aaudio_result_t error) {
struct userdata *u = user;
if (aq != __atomic_load_n(&u->aq, __ATOMIC_SEQ_CST)) return;
if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST)) return;
/* A disconnected stream (headphones plugged or unplugged, a Bluetooth route coming or going)
* can never be restarted: it has to be closed and a new one opened on the current route. */
if (error != AAUDIO_ERROR_DISCONNECTED &&
error != AAUDIO_ERROR_INVALID_STATE &&
error != AAUDIO_ERROR_INVALID_HANDLE &&
error != AAUDIO_ERROR_TIMEOUT)
return;
request_reopen(u, "stream error");
}
/* 48 kHz / float / stereo, buffer from the ms form rounded up to a burst and never below two,
* capacity from the ceiling. The ring target floor is two bursts or ring_ms, whichever is more. */
static aaudio_result_t open_output(struct userdata *u, AAudioStream **out) {
AAudioStreamBuilder *builder = NULL;
AAudioStream *aq = NULL;
aaudio_result_t res;
int32_t capf, burst, want;
res = AAudio_createStreamBuilder(&builder);
if (res != AAUDIO_OK || !builder) return res != AAUDIO_OK ? res : AAUDIO_ERROR_NO_MEMORY;
AAudioStreamBuilder_setDirection(builder, AAUDIO_DIRECTION_OUTPUT);
AAudioStreamBuilder_setSharingMode(builder, AAUDIO_SHARING_MODE_SHARED);
AAudioStreamBuilder_setPerformanceMode(builder, u->perf);
AAudioStreamBuilder_setUsage(builder, AAUDIO_USAGE_GAME);
AAudioStreamBuilder_setFormat(builder, AAUDIO_FORMAT_PCM_FLOAT);
AAudioStreamBuilder_setChannelCount(builder, DA_RING_CHANNELS);
AAudioStreamBuilder_setSampleRate(builder, DA_RING_RATE);
AAudioStreamBuilder_setDataCallback(builder, out_cb, u);
AAudioStreamBuilder_setErrorCallback(builder, out_error_cb, u);
AAudioStreamBuilder_setBufferCapacityInFrames(builder, (u->max_ms > 0 ? u->max_ms : DA_DEFAULT_MAX_MS) * DA_RING_RATE / 1000);
res = AAudioStreamBuilder_openStream(builder, &aq);
AAudioStreamBuilder_delete(builder);
if (res != AAUDIO_OK || !aq) return res != AAUDIO_OK ? res : AAUDIO_ERROR_INTERNAL;
capf = AAudioStream_getBufferCapacityInFrames(aq);
burst = AAudioStream_getFramesPerBurst(aq);
want = (u->target_ms > 0 ? u->target_ms : DA_DEFAULT_MS) * DA_RING_RATE / 1000;
if (burst > 0) {
int32_t nb = (want + burst - 1) / burst;
want = (nb < 1 ? 1 : nb) * burst;
if (want < DA_MIN_BUFFER_BURSTS * burst) want = DA_MIN_BUFFER_BURSTS * burst;
}
if (want > capf) want = capf;
if (want > 0) AAudioStream_setBufferSizeInFrames(aq, want);
if (burst <= 0) burst = 192;
u->burst = burst;
u->ring_max_target = DA_RING_MAX_TARGET_MS * DA_RING_RATE / 1000;
if (u->ring_max_target > (int32_t) u->ring->cap_frames) u->ring_max_target = (int32_t) u->ring->cap_frames;
{
int32_t floor = DA_RING_TARGET_BURSTS * burst;
int32_t asked = (u->ring_ms > 0 ? u->ring_ms : DA_DEFAULT_RING_MS) * DA_RING_RATE / 1000;
if (floor < asked) floor = asked;
if (floor > u->ring_max_target) floor = u->ring_max_target;
if (__atomic_load_n(&u->ring->target_frames, __ATOMIC_ACQUIRE) < floor)
__atomic_store_n(&u->ring->target_frames, floor, __ATOMIC_RELEASE);
}
__atomic_store_n(&u->ring->hw_burst, burst, __ATOMIC_RELAXED);
u->last_xrun = AAudioStream_getXRunCount(aq);
u->base_buf_frames = AAudioStream_getBufferSizeInFrames(aq);
u->decay_floor = 0;
u->decay_backoff = 1;
u->last_xrun_ns = now_ns();
u->last_decay_ns = 0;
__atomic_store_n(&u->ring->hw_buf_frames, u->base_buf_frames, __ATOMIC_RELAXED);
pa_log("directaudio-native-sink: open #%u: device buffer %d frames (%d ms), burst %d, capacity %d, performance mode %d (asked %d), ring target %d frames - Android adds its own output latency on top",
++u->opens, u->base_buf_frames, u->base_buf_frames * 1000 / DA_RING_RATE, AAudioStream_getFramesPerBurst(aq),
capf, AAudioStream_getPerformanceMode(aq), u->perf, (int) u->ring->target_frames);
res = AAudioStream_requestStart(aq);
if (res != AAUDIO_OK) { AAudioStream_close(aq); return res; }
__atomic_store_n(&u->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST);
u->wd_last_tick_ns = 0;
__atomic_store_n(&u->ring->state, DA_RING_PLAYING, __ATOMIC_RELEASE);
*out = aq;
return AAUDIO_OK;
}
static void *reopen_thread(void *user) {
struct userdata *u = user;
for (;;) {
AAudioStream *old = NULL, *neu = NULL;
int expected = 0;
__atomic_store_n(&u->reopen_redo, 0, __ATOMIC_SEQ_CST);
if (u->dead) break;
if (open_output(u, &neu) == AAUDIO_OK) {
pthread_mutex_lock(&u->lock);
old = u->aq;
__atomic_store_n(&u->aq, neu, __ATOMIC_SEQ_CST);
if (__atomic_load_n(&u->suspended, __ATOMIC_SEQ_CST))
AAudioStream_requestStop(neu);
pthread_mutex_unlock(&u->lock);
} else
pa_log("directaudio-native-sink: reopen failed; keeping the old stream");
if (old) {
AAudioStream_requestStop(old);
AAudioStream_close(old);
pa_log("directaudio-native-sink: reopened the output on the current route");
}
if (__atomic_load_n(&u->reopen_redo, __ATOMIC_SEQ_CST)) { usleep(20000); continue; }
__atomic_store_n(&u->reopen_running, 0, __ATOMIC_SEQ_CST);
if (!__atomic_load_n(&u->reopen_redo, __ATOMIC_SEQ_CST)) break;
if (!__atomic_compare_exchange_n(&u->reopen_running, &expected, 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
break;
}
return NULL;
}
static void request_reopen(struct userdata *u, const char *why) {
int expected = 0;
__atomic_store_n(&u->reopen_redo, 1, __ATOMIC_SEQ_CST);
if (__atomic_compare_exchange_n(&u->reopen_running, &expected, 1, 0, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
pthread_t th;
pa_log("directaudio-native-sink: reopen: %s", why);
if (pthread_create(&th, NULL, reopen_thread, u))
__atomic_store_n(&u->reopen_running, 0, __ATOMIC_SEQ_CST);
else
pthread_detach(th);
}
}
/* Ticked once a second from the IO thread: a callback silent for a second is a dead stream. */
static void watchdog(struct userdata *u) {
uint64_t now = now_ns(), last_cb, prev_tick;
unsigned int cb;
if (!u->watchdog_on) return;
if (!__atomic_load_n(&u->aq, __ATOMIC_SEQ_CST)) return;
prev_tick = u->wd_last_tick_ns;
u->wd_last_tick_ns = now;
cb = __atomic_load_n(&u->cb_count, __ATOMIC_SEQ_CST);
if (!prev_tick || now - prev_tick > 2 * DA_FREEZE_GAP_NS + 1000000000ull) {
u->wd_last_cb = cb;
__atomic_store_n(&u->last_cb_ns, now, __ATOMIC_SEQ_CST);
return;
}
if (cb != u->wd_last_cb) { u->wd_last_cb = cb; return; }
last_cb = __atomic_load_n(&u->last_cb_ns, __ATOMIC_SEQ_CST);
if (!last_cb || now - last_cb < DA_CB_STALL_NS) return;
__atomic_store_n(&u->last_cb_ns, now, __ATOMIC_SEQ_CST);
request_reopen(u, "data callback stalled");
}
static void close_output(struct userdata *u) {
AAudioStream *aq;
u->dead = 1;
pthread_mutex_lock(&u->lock);
aq = u->aq;
__atomic_store_n(&u->aq, NULL, __ATOMIC_SEQ_CST);
pthread_mutex_unlock(&u->lock);
if (aq) {
AAudioStream_requestStop(aq);
AAudioStream_close(aq);
}
/* A reopen still in flight sees u->dead and stops; give it a moment to let go of u. */
while (__atomic_load_n(&u->reopen_running, __ATOMIC_SEQ_CST))
usleep(10000);
}
/* ---- the PulseAudio side: module-directaudio-sink's producer, on the local ring ---- */
static pa_usec_t frames_to_usec(const struct userdata *u, int64_t frames) {
return (pa_usec_t) (frames * (int64_t) PA_USEC_PER_SEC / (int64_t) u->ss.rate);
}
static pa_usec_t sink_latency(struct userdata *u) {
return frames_to_usec(u, (int64_t) da_ring_avail(u->ring) + (u->ring->hw_buf_frames > 0 ? u->ring->hw_buf_frames : 0));
}
static void produce(struct userdata *u, uint32_t frames) {
struct da_ring *r = u->ring;
uint32_t w = __atomic_load_n(&r->widx, __ATOMIC_ACQUIRE);
uint32_t pos = w % r->cap_frames;
uint32_t first = PA_MIN(frames, r->cap_frames - pos);
float *dst = r->data + (size_t) pos * DA_RING_CHANNELS;
size_t bytes = (size_t) frames * u->frame_size;
if (PA_SINK_IS_OPENED(u->sink->thread_info.state)) {
pa_memchunk chunk;
const uint8_t *src;
if (u->sink->thread_info.rewind_requested)
pa_sink_process_rewind(u->sink, 0);
pa_sink_render_full(u->sink, bytes, &chunk);
src = pa_memblock_acquire_chunk(&chunk);
memcpy(dst, src, (size_t) first * u->frame_size);
if (frames > first)
memcpy(r->data, src + (size_t) first * u->frame_size, (size_t) (frames - first) * u->frame_size);
pa_memblock_release(chunk.memblock);
pa_memblock_unref(chunk.memblock);
} else {
memset(dst, 0, (size_t) first * u->frame_size);
if (frames > first)
memset(r->data, 0, (size_t) (frames - first) * u->frame_size);
}
__atomic_store_n(&r->widx, w + frames, __ATOMIC_RELEASE);
}
/* Tops the ring up to the engine's target and narrates what the engine changed. */
static void service_ring(struct userdata *u) {
struct da_ring *r = u->ring;
uint32_t avail, space;
int32_t target = __atomic_load_n(&r->target_frames, __ATOMIC_ACQUIRE);
int32_t hw = __atomic_load_n(&r->hw_buf_frames, __ATOMIC_RELAXED);
uint32_t under = __atomic_load_n(&r->underruns, __ATOMIC_RELAXED);
pa_usec_t now = pa_rtclock_now();
if (target <= 0) target = 2 * u->burst;
avail = da_ring_avail(r);
space = da_ring_space(r);
if (avail < (uint32_t) target) {
uint32_t want = PA_MIN((uint32_t) target - avail, space);
if (want > 0)
produce(u, want);
}
if (target != u->seen_target || hw != u->seen_hw_buf) {
pa_sink_set_max_request_within_thread(u->sink, (size_t) target * u->frame_size);
pa_sink_set_fixed_latency_within_thread(u->sink, frames_to_usec(u, (int64_t) target + (hw > 0 ? hw : 0)));
}
if (target != u->seen_target) {
if (u->seen_target)
pa_log("directaudio-native-sink: ring grow: target %d -> %d frames (%d ms)", u->seen_target, target, target * 1000 / DA_RING_RATE);
u->seen_target = target;
}
if (hw != u->seen_hw_buf) {
if (u->seen_hw_buf)
pa_log("directaudio-native-sink: device buffer %d -> %d frames (%d ms)", u->seen_hw_buf, hw, hw * 1000 / DA_RING_RATE);
u->seen_hw_buf = hw;
}
if (u->settled_at && now >= u->settled_at) {
pa_log("directaudio-native-sink: after 10 s: device buffer %d frames, ring target %d, ring underruns %u, stream xruns %d",
hw, target, under, u->aq ? AAudioStream_getXRunCount(u->aq) : -1);
u->settled_at = 0;
}
if (under != u->seen_underruns && now - u->stats_at >= STATS_EVERY_USEC) {
pa_log("directaudio-native-sink: %u ring underrun(s) so far, target %d frames, device buffer %d", under, target, hw);
u->seen_underruns = under;
u->stats_at = now;
}
if (now >= u->next_watchdog) {
watchdog(u);
u->next_watchdog = now + WATCHDOG_TICK_USEC;
}
}
static int sink_process_msg(pa_msgobject *o, int code, void *data, int64_t offset, pa_memchunk *chunk) {
struct userdata *u = PA_SINK(o)->userdata;
switch (code) {
case PA_SINK_MESSAGE_GET_LATENCY:
*((pa_usec_t*) data) = sink_latency(u);
return 0;
}
return pa_sink_process_msg(o, code, data, offset, chunk);
}
/* A started AAudio stream keeps audioserver's AudioMix wake lock held, so the device never
* suspends while the session sleeps: stop it, and the IO thread's timer, until the sink reopens. */
static int sink_set_state_in_io_thread_cb(pa_sink *s, pa_sink_state_t new_state, pa_suspend_cause_t new_suspend_cause) {
struct userdata *u = s->userdata;
aaudio_result_t res = AAUDIO_OK;
if (new_state == PA_SINK_SUSPENDED && !u->suspended) {
pthread_mutex_lock(&u->lock);
__atomic_store_n(&u->suspended, 1, __ATOMIC_SEQ_CST);
if (u->aq) AAudioStream_requestStop(u->aq);
pthread_mutex_unlock(&u->lock);
pa_rtpoll_set_timer_disabled(u->rtpoll);
pa_log("directaudio-native-sink: suspended; output stopped");
} else if (PA_SINK_IS_OPENED(new_state) && u->suspended) {
pthread_mutex_lock(&u->lock);
__atomic_store_n(&u->suspended, 0, __ATOMIC_SEQ_CST);
u->primed = 0;
__atomic_store_n(&u->last_cb_ns, now_ns(), __ATOMIC_SEQ_CST);
u->wd_last_tick_ns = 0;
if (u->aq) res = AAudioStream_requestStart(u->aq);
pthread_mutex_unlock(&u->lock);
if (res != AAUDIO_OK || !u->aq) request_reopen(u, "resume");
pa_rtpoll_set_timer_relative(u->rtpoll, 0);
pa_log("directaudio-native-sink: resumed");
}
return 0;
}
static void thread_func(void *userdata) {
struct userdata *u = userdata;
pa_log_debug("IO thread starting");
pa_thread_mq_install(&u->thread_mq);
if (setpriority(PRIO_PROCESS, (id_t) syscall(SYS_gettid), AUDIO_NICE) < 0)
pa_log_debug("directaudio-native-sink: could not raise the IO thread's priority (%s)", strerror(errno));
if (u->core->realtime_scheduling)
pa_thread_make_realtime(u->core->realtime_priority);
pa_rtpoll_set_timer_relative(u->rtpoll, 0);
for (;;) {
int ret;
/* Half a burst between visits, never blocking on the stream: clients' audio reaches this
* thread as messages pa_rtpoll_run handles, and a thread stuck in a write or a wait lets
* them run dry (the crackle #338 fixed). */
if (!u->suspended) {
service_ring(u);
pa_rtpoll_set_timer_relative(u->rtpoll, PA_MAX(frames_to_usec(u, u->burst) / 2, PA_USEC_PER_MSEC));
}
if ((ret = pa_rtpoll_run(u->rtpoll)) < 0)
goto fail;
if (ret == 0)
goto finish;
}
fail:
pa_asyncmsgq_post(u->thread_mq.outq, PA_MSGOBJECT(u->core), PA_CORE_MESSAGE_UNLOAD_MODULE, u->module, 0, NULL, NULL);
pa_asyncmsgq_wait_for(u->thread_mq.inq, PA_MESSAGE_SHUTDOWN);
finish:
pa_log_debug("IO thread shutting down");
}
void pa__done(pa_module *m);
int pa__init(pa_module *m) {
struct userdata *u = NULL;
pa_modargs *ma = NULL;
pa_sink_new_data data;
pa_channel_map map;
pa_cvolume volume;
uint32_t perf = 1, buffer_ms = DA_DEFAULT_MS, max_ms = DA_DEFAULT_MAX_MS, ring_ms = DA_DEFAULT_RING_MS;
double linear_volume = 1.0;
bool adaptive = true, decay = false, limiter = true, watchdog_on = true;
AAudioStream *aq = NULL;
aaudio_result_t res;
uint32_t cap_frames;
pa_assert(m);
if (!(ma = pa_modargs_new(m->argument, valid_modargs))) {
pa_log("Failed to parse module arguments.");
goto fail;
}
if (pa_modargs_get_value_u32(ma, "performance_mode", &perf) < 0 || perf > 2) {
pa_log("performance_mode must be 0, 1 or 2");
goto fail;
}
if (pa_modargs_get_value_u32(ma, "buffer_ms", &buffer_ms) < 0 || buffer_ms == 0 || buffer_ms > 200) {
pa_log("buffer_ms must be between 1 and 200");
goto fail;
}
if (pa_modargs_get_value_u32(ma, "max_ms", &max_ms) < 0 || max_ms < buffer_ms || max_ms > 250) {
pa_log("max_ms must be between buffer_ms and 250");
goto fail;
}
if (pa_modargs_get_value_u32(ma, "ring_ms", &ring_ms) < 0 || ring_ms == 0 || ring_ms > 100) {
pa_log("ring_ms must be between 1 and 100");
goto fail;
}
if (pa_modargs_get_value_boolean(ma, "adaptive", &adaptive) < 0 ||
pa_modargs_get_value_boolean(ma, "decay", &decay) < 0 ||
pa_modargs_get_value_boolean(ma, "limiter", &limiter) < 0 ||
pa_modargs_get_value_boolean(ma, "watchdog", &watchdog_on) < 0) {
pa_log("adaptive, decay, limiter and watchdog must be 0 or 1");
goto fail;
}
if (pa_modargs_get_value_double(ma, "volume", &linear_volume) < 0 || linear_volume < 0.0 || linear_volume > 10.0) {
pa_log("volume must be a linear factor between 0 and 10");
goto fail;
}
m->userdata = u = pa_xnew0(struct userdata, 1);
u->core = m->core;
u->module = m;
u->perf = perf == 0 ? AAUDIO_PERFORMANCE_MODE_NONE : perf == 2 ? AAUDIO_PERFORMANCE_MODE_POWER_SAVING : AAUDIO_PERFORMANCE_MODE_LOW_LATENCY;
u->target_ms = (int32_t) buffer_ms;
u->max_ms = (int32_t) max_ms;
u->ring_ms = (int32_t) ring_ms;
u->adaptive = adaptive;
u->decay = decay;
u->limiter = limiter;
u->watchdog_on = watchdog_on;
u->ss.format = PA_SAMPLE_FLOAT32NE;
u->ss.rate = DA_RING_RATE;
u->ss.channels = DA_RING_CHANNELS;
u->frame_size = pa_frame_size(&u->ss);
u->burst = 192;
pthread_mutex_init(&u->lock, NULL);
pa_channel_map_init_stereo(&map);
/* The ring: the relay's layout in this process's memory. */
cap_frames = DA_RING_CAP_MS_LOCAL * DA_RING_RATE / 1000;
u->ring = pa_xmalloc0(da_ring_bytes(cap_frames));
u->ring->magic = DA_RING_MAGIC;
u->ring->version = DA_RELAY_VERSION;
u->ring->cap_frames = cap_frames;
u->ring->rate = DA_RING_RATE;
u->ring->channels = DA_RING_CHANNELS;
u->ring->target_frames = 0;
if ((res = open_output(u, &aq)) != AAUDIO_OK) {
pa_log("directaudio-native-sink: could not open the AAudio output (%s); is the daemon running on the Android side?", AAudio_convertResultToText(res));
goto fail;
}
__atomic_store_n(&u->aq, aq, __ATOMIC_SEQ_CST);
u->seen_hw_buf = u->base_buf_frames;
u->seen_target = u->ring->target_frames;
u->settled_at = pa_rtclock_now() + 10 * PA_USEC_PER_SEC;
u->stats_at = pa_rtclock_now();
u->rtpoll = pa_rtpoll_new();
if (pa_thread_mq_init(&u->thread_mq, m->core->mainloop, u->rtpoll) < 0) {
pa_log("pa_thread_mq_init() failed.");
goto fail;
}
pa_sink_new_data_init(&data);
data.driver = __FILE__;
data.module = m;
pa_sink_new_data_set_name(&data, pa_modargs_get_value(ma, "sink_name", DEFAULT_SINK_NAME));
pa_sink_new_data_set_sample_spec(&data, &u->ss);
pa_sink_new_data_set_channel_map(&data, &map);
pa_cvolume_set(&volume, u->ss.channels, pa_sw_volume_from_linear(linear_volume));
pa_sink_new_data_set_volume(&data, &volume);
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_STRING, "directaudio");
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_DESCRIPTION, "Android audio output (DirectAudio)");
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_CLASS, "sound");
pa_proplist_sets(data.proplist, PA_PROP_DEVICE_API, "directaudio");
if (pa_modargs_get_proplist(ma, "sink_properties", data.proplist, PA_UPDATE_REPLACE) < 0) {
pa_log("Invalid properties");
pa_sink_new_data_done(&data);
goto fail;
}
u->sink = pa_sink_new(m->core, &data, PA_SINK_HARDWARE | PA_SINK_LATENCY);
pa_sink_new_data_done(&data);
if (!u->sink) {
pa_log("Failed to create sink.");
goto fail;
}
u->sink->parent.process_msg = sink_process_msg;
u->sink->set_state_in_io_thread = sink_set_state_in_io_thread_cb;
u->sink->userdata = u;
pa_sink_set_asyncmsgq(u->sink, u->thread_mq.inq);
pa_sink_set_rtpoll(u->sink, u->rtpoll);
pa_sink_set_max_request(u->sink, (size_t) u->ring->target_frames * u->frame_size);
/* What clients should keep queued on their side: the ring's starting target plus the device
* buffer. Grows are reported live through GET_LATENCY. */
pa_sink_set_fixed_latency(u->sink, frames_to_usec(u, (int64_t) u->ring->target_frames + u->base_buf_frames));
if (!(u->thread = pa_thread_new("directaudio-native-sink", thread_func, u))) {
pa_log("Failed to create thread.");
goto fail;
}
pa_sink_put(u->sink);
pa_modargs_free(ma);
return 0;
fail:
if (ma)
pa_modargs_free(ma);
pa__done(m);
return -1;
}
int pa__get_n_used(pa_module *m) {
struct userdata *u;
pa_assert(m);
pa_assert_se(u = m->userdata);
return pa_sink_linked_by(u->sink);
}
void pa__done(pa_module *m) {
struct userdata *u;
pa_assert(m);
if (!(u = m->userdata))
return;
if (u->sink)
pa_sink_unlink(u->sink);
if (u->thread) {
pa_asyncmsgq_send(u->thread_mq.inq, NULL, PA_MESSAGE_SHUTDOWN, NULL, 0, NULL);
pa_thread_free(u->thread);
}
pa_thread_mq_done(&u->thread_mq);
if (u->sink)
pa_sink_unref(u->sink);
close_output(u);
if (u->rtpoll)
pa_rtpoll_free(u->rtpoll);
pthread_mutex_destroy(&u->lock);
pa_xfree(u->ring);
pa_xfree(u);
}
+7
View File
@@ -56,6 +56,13 @@ library list, before anything is published.
own limiter slips such a frame by one refresh. The fixed-refresh branch now paces each window by
time, as the VRR branch already did: its next frame goes out on the first refresh a capped interval
after its last one, with half a refresh of tolerance so an on-time window keeps every Nth refresh.
- `0116-hold-overlay-repaint-for-next-frame.patch` - this app: on a fixed-refresh output every
mangoapp commit asked for a repaint of its own, and mangoapp draws once per game frame just after
that frame was shown, so a 60 fps game on a 120 Hz panel was composited twice per frame - 75 frames
a second reached the screen, one in two 8 ms after the last with no new picture (Valheim, Stardew
Valley, Among Us). The VRR path already leaves such repaints to the next game frame; on a fixed
refresh output they now wait for it too, for at most `external_overlay_hold_cycles` refreshes (4,
so 30 fps at 120 Hz still merges), and are painted on their own after that.
Sixteen more of Armada's patches are DRM/lease/HDR-on-KMS work for a native display, which this
app's Wayland-hosted gamescope never reaches, or need a newer gamescope than the runtime has.
@@ -0,0 +1,64 @@
diff --git a/src/steamcompmgr.cpp b/src/steamcompmgr.cpp
index 214677d..6c9299d 100644
--- a/src/steamcompmgr.cpp
+++ b/src/steamcompmgr.cpp
@@ -298,6 +298,7 @@ update_runtime_info();
gamescope::ConVar<bool> cv_adaptive_sync( "adaptive_sync", false, "Whether or not adaptive sync is enabled if available." );
gamescope::ConVar<bool> cv_adaptive_sync_ignore_overlay( "adaptive_sync_ignore_overlay", false, "Whether or not to ignore overlay planes for pushing commits with adaptive sync." );
gamescope::ConVar<int> cv_adaptive_sync_overlay_cycles( "adaptive_sync_overlay_cycles", 1, "Number of vblank cycles to ignore overlay repaints before forcing a commit with adaptive sync." );
+gamescope::ConVar<int> cv_external_overlay_hold_cycles( "external_overlay_hold_cycles", 4, "Number of vblank cycles an external overlay's repaint waits for the next base plane commit on a fixed refresh output, 0 repaints at once." );
gamescope::ConVar<bool> cv_adaptive_sync_uncapped( "adaptive_sync_uncapped", true, "Whether or not to allow mailbox/immediate clients to run uncapped with adaptive sync by deferring paints until the display can take a new flip." );
gamescope::ConVar<bool> cv_upscale_preemptive( "upscale_preemptive", true, "Allow pre-emptive upscaling" );
@@ -1119,6 +1120,7 @@ uint32_t lastPublishedInputCounter;
std::atomic<bool> hasRepaint = false;
bool hasRepaintNonBasePlane = false;
+bool hasRepaintExternalOverlay = false;
bool g_bUpdateForwardedVROverlays = false;
@@ -8015,7 +8017,10 @@ bool handle_done_commit( steamcompmgr_win_t *w, xwayland_ctx_t *ctx, uint64_t co
if ( ( w == pFocus->externalOverlayWindow && w->opacity != TRANSLUCENT ) &&
( GetBackend()->GetCurrentConnector() && !GetBackend()->GetCurrentConnector()->IsVRRActive() ) )
{
- hasRepaintNonBasePlane = true;
+ if ( cv_external_overlay_hold_cycles > 0 )
+ hasRepaintExternalOverlay = true;
+ else
+ hasRepaintNonBasePlane = true;
}
// If this is the main plane, repaint
@@ -10573,6 +10578,14 @@ steamcompmgr_main(int argc, char **argv)
hasRepaint = true;
bool bPainted = false;
+ bool bPaintedOutput = false;
+
+ static int nHeldExternalOverlayCycles = 0;
+
+ if ( !hasRepaintExternalOverlay )
+ nHeldExternalOverlayCycles = 0;
+ else if ( vblank && ++nHeldExternalOverlayCycles >= cv_external_overlay_hold_cycles )
+ hasRepaintNonBasePlane = true;
static int nIgnoredOverlayRepaints = 0;
@@ -10733,6 +10746,7 @@ steamcompmgr_main(int argc, char **argv)
paint_all( pPaintFocus, eFlipType == FlipType::Async );
bPainted = true;
+ bPaintedOutput = true;
}
}
@@ -10751,6 +10765,8 @@ steamcompmgr_main(int argc, char **argv)
hasRepaint = false;
hasRepaintNonBasePlane = false;
+ if ( bPaintedOutput )
+ hasRepaintExternalOverlay = false;
nIgnoredOverlayRepaints = 0;
{
+2 -2
View File
@@ -1,3 +1,3 @@
GAMESCOPE_REPO=Droid-Deck/DroidDeck-Components
GAMESCOPE_TAG=gamescope-3.16.29-cursor-045e5a31-qa
GAMESCOPE_SHA256=76929e93804450e7352421b76a457c825a6251de8b704d942c363a211bd99424
GAMESCOPE_TAG=gamescope-3.16.29-p12
GAMESCOPE_SHA256=07b69944a1ebf2741d4a867afa6327dcc63ec458f432a8f7483089dce2197010
+1 -1
View File
@@ -9,7 +9,7 @@ for bad in libstdc++.so.6 libgcc_s.so.1; do
done
syms() { "${READELF:-readelf}" -Ws "$1" | awk '$4 == "FUNC" && $5 == "GLOBAL" {sub(/@.*/, "", $8); print $8}'; }
FAKE=$(syms "$D/libfakeinput.so")
for sym in open openat ioctl read close poll ppoll select stat fstat access scandir; do
for sym in open openat ioctl read readv close poll ppoll select stat fstat access scandir; do
grep -qx "$sym" <<<"$FAKE" || { echo "::error::libfakeinput.so does not export $sym"; exit 1; }
done
if grep -qxE '__gxx_personality_v0|__cxa_throw|_Unwind_Resume' <<<"$FAKE"; then
@@ -23,6 +23,7 @@ import json
import math
import re
import os
import select
import selectors
import signal
import socket
@@ -532,6 +533,151 @@ def cdp_eval(agent_dir, expression, target=None, await_promise=True, timeout=15)
ws.close()
KEYBOARD_BINDING = "droiddeckSteamKeyboard"
KEYBOARD_CHECK_SECONDS = 30
KEYBOARD_JS = r"""
(() => {
const self = window.__droiddeckKeyboard || (window.__droiddeckKeyboard = { watched: new WeakSet(), last: null });
self.check = () => {
let showing = false;
for (const win of Array.from(globalThis.SteamUIStore?.WindowStore?.SteamUIWindows || [])) {
const value = win?.VirtualKeyboardManager?.IsShowingVirtualKeyboard;
if (!value) continue;
if (!self.watched.has(value) && typeof value.Subscribe === "function") {
self.watched.add(value);
value.Subscribe(() => setTimeout(() => self.check()));
}
if (value.m_currentValue === true) showing = true;
}
if (showing !== self.last) {
self.last = showing;
if (typeof window.__BINDING__ === "function") window.__BINDING__(String(showing));
}
return showing;
};
self.timer = self.timer || setInterval(() => self.check(), 500);
return self.check();
})()
""".replace("__BINDING__", KEYBOARD_BINDING)
class KeyboardWatcher(threading.Thread):
def __init__(self, agent_dir):
super().__init__(daemon=True, name="keyboard")
self.agent_dir = agent_dir
self.path = agent_dir / "keyboard.json"
self.showing = None
self.seq = 0
self.next_id = 0
self.attached = False
def report(self, showing):
if showing == self.showing:
return
self.showing = showing
self.seq += 1
write_json(self.path, {"steamKeyboard": showing, "seq": self.seq})
def run(self):
failures, last = 0, None
while True:
try:
self.watch()
except Exception as e:
if self.attached:
log("Steam keyboard: lost the client (%s); reattaching" % e)
failures = 0
elif str(e) != last:
log("Steam keyboard: waiting for the client (%s)" % e)
self.attached = False
last = str(e)
self.report(False)
failures += 1
time.sleep(min(2 * failures, 10))
def watch(self):
targets = [t for t in cdp_targets(self.agent_dir)
if t.get("title") == "SharedJSContext" and t.get("webSocketDebuggerUrl")]
if not targets:
raise AgentError("NO_TARGET", "No SharedJSContext yet")
ws = WebSocket(targets[0]["webSocketDebuggerUrl"], 5)
try:
self.call(ws, "Runtime.addBinding", {"name": KEYBOARD_BINDING})
self.report(self.install(ws))
self.attached = True
while True:
if not ws.buffer and not select.select([ws.s], [], [], KEYBOARD_CHECK_SECONDS)[0]:
self.report(self.install(ws))
continue
self.event(json.loads(ws.recv()))
finally:
ws.close()
def install(self, ws):
result = self.call(ws, "Runtime.evaluate", {"expression": KEYBOARD_JS, "returnByValue": True})
if result.get("exceptionDetails"):
raise AgentError("JS_EXCEPTION", json.dumps(result["exceptionDetails"])[:500])
return result.get("result", {}).get("value") is True
def call(self, ws, method, params):
self.next_id += 1
ws.send(json.dumps({"id": self.next_id, "method": method, "params": params}))
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
message = json.loads(ws.recv())
if message.get("id") == self.next_id:
if "error" in message:
raise AgentError("CDP_ERROR", json.dumps(message["error"]))
return message.get("result", {})
self.event(message)
raise AgentError("TIMEOUT", "No answer to %s from DevTools" % method)
def event(self, message):
params = message.get("params") or {}
if message.get("method") == "Runtime.bindingCalled" and params.get("name") == KEYBOARD_BINDING:
self.report(params.get("payload") == "true")
def steam_idle_inhibit(agent_dir, inhibit):
expression = """(async want => {
const toggle = () => new Promise(done => {
let handle = null;
let timer = null;
const finish = value => {
clearTimeout(timer);
handle?.unregister?.();
done(value);
};
timer = setTimeout(() => finish(null), 2500);
handle = SteamClient.Console.RegisterForSpewOutput(entry => {
const found = /Suspend inhibit: ([01])/.exec(entry?.spew || "");
if (found) finish(found[1] === "1");
});
SteamClient.Console.ExecCommand("toggle_idle_suspend_inhibit 1");
});
let state = await toggle();
if (state === !want) state = await toggle();
return state === want;
})(%s)""" % ("true" if inhibit else "false")
return cdp_eval(agent_dir, expression, timeout=12).get("value") is True
def steam_idle_suspend_seconds(agent_dir, vpower=Path("/run/vpower/ac_status")):
expression = """(() => {
const settings = globalThis.settingsStore?.clientSettings;
return settings ? [settings.system_idle_suspend_ac_sec, settings.system_idle_suspend_battery_sec] : null;
})()"""
seconds = cdp_eval(agent_dir, expression, await_promise=False, timeout=5).get("value")
if not isinstance(seconds, list) or len(seconds) != 2:
return None
try:
on_ac = vpower.read_text().strip() != "Disconnected"
except OSError:
on_ac = True
value = seconds[0 if on_ac else 1]
return max(0, int(value)) if isinstance(value, (int, float)) else None
def steam_selection(agent_dir, timeout=5):
result = cdp_eval(
agent_dir,
@@ -878,6 +1024,8 @@ def serve(agent_dir, focus=True, poll=0.1):
can_focus = focus and bool(os.environ.get("DISPLAY"))
if can_focus:
FocusWatcher(agent_dir / "focus.json").start()
if focus:
KeyboardWatcher(agent_dir).start()
write_json(agent_dir / "hello.json", {"pid": os.getpid(), "version": VERSION, "started": int(time.time() * 1000),
"displays": displays(), "focus": can_focus})
log("serving %s (focus %s)" % (agent_dir, "on" if can_focus else "off"))
@@ -912,6 +1060,24 @@ def main(argv):
return 3
print("droiddeck-agent: Steam overview is ready for shortcut app %d" % prepared["appId"])
return 0
if argv and argv[0] == "--steam-supports-vr":
if len(argv) != 2 or not argv[1].isascii() or not argv[1].isdecimal():
print("usage: droiddeck-agent --steam-supports-vr <appid>", file=sys.stderr)
return 2
# Optional-VR games (Thumper, VRChat) carry vr_supported without vr_only.
expression = ("(o => o ? (o.vr_supported === true || o.vr_only === true) : null)"
"(window.appStore?.GetAppOverviewByGameID?.(%s))" % json.dumps(argv[1]))
value = None
deadline = time.monotonic() + 12 # Steam's UI is busiest while a game starts.
while value is None and time.monotonic() < deadline:
try:
value = cdp_eval(Path(base) / "agent", expression, await_promise=False, timeout=8).get("value")
except (AgentError, OSError, ValueError):
pass
if value is None:
time.sleep(0.5)
print({True: "yes", False: "no"}.get(value, "unknown"))
return {True: 0, False: 5}.get(value, 1)
if argv and argv[0] == "--steam-asleep":
expression = """(() => {
const store = globalThis.SuspendResumeStore;
@@ -923,6 +1089,26 @@ def main(argv):
state = "unknown"
print(state)
return {"yes": 0, "no": 5}.get(state, 1)
if argv and argv[0] == "--steam-idle-inhibit":
if len(argv) != 2 or argv[1] not in ("on", "off"):
print("usage: droiddeck-agent --steam-idle-inhibit on|off", file=sys.stderr)
return 2
try:
done = steam_idle_inhibit(Path(base) / "agent", argv[1] == "on")
except (AgentError, OSError, ValueError) as error:
print("droiddeck-agent: could not reach the client's idle sleep: %s" % error, file=sys.stderr)
return 1
return 0 if done else 1
if argv and argv[0] == "--steam-idle-suspend-seconds":
try:
seconds = steam_idle_suspend_seconds(Path(base) / "agent")
except (AgentError, OSError, ValueError) as error:
print("droiddeck-agent: could not read the client's idle sleep: %s" % error, file=sys.stderr)
return 1
if seconds is None:
return 1
print(seconds)
return 0
if argv and argv[0] == "--steam-shortcut-state":
if len(argv) not in (2, 3):
print("usage: droiddeck-agent --steam-shortcut-state <cgameid> [timeout-seconds]", file=sys.stderr)
@@ -17,7 +17,7 @@ if [ -s /etc/ld.so.preload ]; then
export LD_PRELOAD="${preload%:}${LD_PRELOAD:+:$LD_PRELOAD}" SHARUN_ALLOW_LD_PRELOAD=1
fi
flags=()
if [ -e "$APPDIR/chrome-sandbox" ] || compgen -G "$APPDIR/*/chrome-sandbox" >/dev/null; then
if [ -n "$(find -H "$APPDIR" -maxdepth 4 \( -name chrome-sandbox -o -name chrome_100_percent.pak -o -name v8_context_snapshot.bin \) -print -quit 2>/dev/null)" ]; then
flags+=(--no-sandbox)
if [ -n "${DISPLAY:-}" ]; then
export XDG_SESSION_TYPE=x11
@@ -7,7 +7,21 @@ import socket
import struct
import sys
SOCKET = "\0" + os.environ.get("DROIDDECK_BWRAP_SOCKET", "com.droiddeck.launcher.bwrap")
SOCKET_FILE = "/etc/droiddeck/bwrap-socket"
def socket_name():
name = os.environ.get("DROIDDECK_BWRAP_SOCKET", "")
if not name:
try:
with open(SOCKET_FILE, encoding="utf-8") as f:
name = f.read().strip()
except OSError:
pass
return "\0" + (name or "com.droiddeck.launcher.bwrap")
SOCKET = socket_name()
VERSION = "bubblewrap 0.11.0 (droiddeck)"
NO_ARG = {
@@ -1232,6 +1232,7 @@ class Session:
seed_settings()
install_shims()
install_preload(files)
fex_module()["install_fonts"](files)
clear_playing()
sync_installations()
forget_sign_in()
@@ -30,9 +30,11 @@ FEX_APPID = "3127680"
SNIPER_APPID = "1628350"
SLR4_APPID = "4183110"
INSTALL_DIRS = {FEX_APPID: "FEX-Emu", SNIPER_APPID: "SteamLinuxRuntime_sniper", SLR4_APPID: "SteamLinuxRuntime_4"}
RUNTIMES = {SNIPER_APPID: ("sniper_platform_", "Steam Linux Runtime 3.0 (sniper"),
SLR4_APPID: ("steamrt4_platform_", "Steam Linux Runtime 4.0 (steamrt4")}
MARKER = ".droiddeck-fex"
LAYOUT = 1
ROOTFS_LAYOUT = 1
ROOTFS_LAYOUT = 2
ARCH_DIRS = ("x86_64-linux-gnu", "i386-linux-gnu")
INTERPRETERS = ("ld-linux-x86-64.so.2", "ld-linux.so.2")
PROVIDED = frozenset((
@@ -40,6 +42,7 @@ PROVIDED = frozenset((
"librt.so.1", "libutil.so.1", "libresolv.so.2", "libanl.so.1", "libBrokenLocale.so.1", "libnsl.so.1",
"libnss_compat.so.2", "libnss_dns.so.2", "libnss_files.so.2", "libnss_hesiod.so.2", "libthread_db.so.1",
"libmemusage.so", "libpcprofile.so", "libc_malloc_debug.so.0", "gconv", "libstdc++.so.6", "libgcc_s.so.1",
"libssl.so.3", "libcrypto.so.3",
))
GLIBC_BUILD = re.compile(r"^(?:ld|lib[A-Za-z_]+)-2\.[0-9]+\.so$|^libSegFault\.so$")
GUEST_LIBDIRS = (("x86_64", "lib/x86_64-linux-gnu"), ("i386", "lib/i386-linux-gnu"))
@@ -48,6 +51,7 @@ FAULT_REPORT = "libfaultreport.so"
VULKAN_PIN = "libvulkan-thunk.so"
VULKAN_PIN_DIR = "lib/x86_64-linux-gnu/droiddeck/vulkan"
VULKAN_THUNK = "libvulkan-guest.so"
ASOUND_CONF = "pcm.!default {\n type pulse\n}\nctl.!default {\n type pulse\n}\n"
RUNTIME_LIBRARIES = (("libc.so.6", b"GLIBC_"), ("libstdc++.so.6", b"GLIBCXX_"))
VERSION_NAME = re.compile(rb"GLIBC(?:XX)?_[0-9][0-9.]*[0-9]")
BUNDLE_DEPTH = 3
@@ -59,6 +63,8 @@ SCAN_LIMIT = 4000
MODES = ("auto", "on", "off")
STEAM_VERBS = ("run", "waitforexitandrun")
ESCAPE = re.compile(rb"\\([0-7]{3})")
DEVICE_FONTS = "/usr/local/share/fonts/android"
FONT_RULES = "/etc/fonts/conf.d/66-droiddeck-device-fonts.conf"
def say(message):
@@ -174,15 +180,15 @@ def platform_version(path):
return tuple(int(part) for part in re.findall(r"\d+", os.path.basename(path)))
def runtime_platform(appid=SNIPER_APPID, prefix="sniper_platform_"):
runtime = app_dir(appid)
def runtime_platform(app=SNIPER_APPID):
runtime = app_dir(app)
if not runtime:
return None
try:
entries = os.listdir(runtime)
except OSError:
return None
platforms = [os.path.join(runtime, entry) for entry in entries if entry.startswith(prefix)]
platforms = [os.path.join(runtime, entry) for entry in entries if entry.startswith(RUNTIMES[app][0])]
platforms = [path for path in platforms if os.path.isdir(os.path.join(path, "files"))
and os.path.isfile(os.path.join(path, "usr-mtree.txt.gz"))]
return max(platforms, key=platform_version, default=None)
@@ -245,7 +251,7 @@ def materialize(platform):
def graphics_platform():
return runtime_platform(SLR4_APPID, "steamrt4_platform_")
return runtime_platform(SLR4_APPID)
def provides_newer(base, provider):
@@ -338,6 +344,7 @@ def install_preloads(root):
if len(shipped.get(FAULT_REPORT, ())) == len(GUEST_LIBDIRS):
wanted.append(FAULT_REPORT)
write_if_changed(os.path.join(root, "etc", "ld.so.preload"), "".join("/usr/$LIB/droiddeck/%s\n" % name for name in wanted))
write_if_changed(os.path.join(root, "etc", "asound.conf"), ASOUND_CONF)
def write_config(fex, root):
@@ -350,6 +357,16 @@ def write_config(fex, root):
write_if_changed(os.path.join(CONFIG_DIR, "Config.json"), json.dumps(config, indent=2) + "\n")
def install_fonts(root):
target = os.path.join(root, FONT_RULES.lstrip("/"))
rules = read_text(FONT_RULES) or ""
if not os.path.isdir(DEVICE_FONTS) or "<fontconfig>" not in rules:
with contextlib.suppress(FileNotFoundError):
os.unlink(target)
return
write_if_changed(target, rules.replace("<fontconfig>", "<fontconfig>\n<dir>%s</dir>" % DEVICE_FONTS, 1))
def link_steam_sdk():
for sdk, candidates in (("sdk64", ("linux64", "ubuntu12_64")), ("sdk32", ("linux32", "ubuntu12_32"))):
link = os.path.join(HOME, ".steam", sdk)
@@ -366,6 +383,24 @@ def link_steam_sdk():
break
def link_guest_sdk(root):
# Proton's lsteamclient only looks in $HOME/.steam/sdk64; on ARM Steam that is the arm64 client, so
# the x86 runtime gets its own link, which FEX resolves before the host path.
for sdk, candidates in (("sdk64", ("linux64", "ubuntu12_64")), ("sdk32", ("linux32", "ubuntu12_32"))):
want = "x86_64" if sdk == "sdk64" else "i386"
directory = next((os.path.join(STEAM_ROOT, candidate) for candidate in candidates
if elf_arch(os.path.join(STEAM_ROOT, candidate, "steamclient.so")) == want), None)
if not directory:
continue
link = os.path.join(root, HOME.lstrip("/"), ".steam", sdk)
if os.path.islink(link) and os.readlink(link) == directory:
continue
os.makedirs(os.path.dirname(link), exist_ok=True)
if os.path.lexists(link):
os.unlink(link)
os.symlink(directory, link)
def steam_running():
for pid in os.listdir("/proc"):
if not pid.isdigit():
@@ -380,13 +415,15 @@ def steam_running():
return False
def request_install():
def request_install(app=SNIPER_APPID):
os.makedirs(os.path.dirname(WANTED), exist_ok=True)
write_if_changed(WANTED, "1\n")
if not steam_running():
return []
try:
compat = runpy.run_path(os.path.join(BIN_DIR, "steam-compatibility"))
if app != SNIPER_APPID and app_dir(app) is None:
return compat["request_app"](STEAM_ROOT, app)
return compat["request_fex"](STEAM_ROOT, set())
except Exception as error:
say("could not ask the client to install FEX (%s)" % error)
@@ -406,10 +443,10 @@ def describe(fex, platform, graphics=None):
}
def prepare():
def prepare(app=SNIPER_APPID):
with locked():
fex = fex_install()
platform = runtime_platform()
platform = runtime_platform(app)
status = describe(fex, platform)
if not status["ready"]:
missing = []
@@ -422,8 +459,8 @@ def prepare():
elif not fex["server"]:
missing.append("FEXServer beside %s" % fex["bin"])
if not platform:
missing.append("Steam Linux Runtime 3.0 (sniper, Steam app %s)" % SNIPER_APPID)
requested = request_install()
missing.append("%s, Steam app %s)" % (RUNTIMES[app][1], app))
requested = request_install(app)
say("x86 Linux programs need %s; %s" % (" and ".join(missing),
"the Steam client was asked to install it" if requested else "open Steam once and it is installed for you"))
write_if_changed(STATUS_FILE, json.dumps(status, indent=2) + "\n")
@@ -432,20 +469,25 @@ def prepare():
if materialize(platform):
say("prepared %s as the x86 runtime" % os.path.basename(platform))
install_preloads(root)
provider = graphics_platform()
if provider and materialize(provider):
say("prepared %s for the x86 runtime's C and C++ libraries" % os.path.basename(provider))
if not provider:
say("Steam Linux Runtime 4.0 (Steam app %s) is not installed yet; x86 games may not find their graphics drivers"
% SLR4_APPID)
elif not provides_newer(platform, provider):
say("%s has no newer C and C++ libraries than %s" % (os.path.basename(provider), os.path.basename(platform)))
provider = None
else:
if build_rootfs(platform, provider):
say("built the x86 runtime from %s with the C and C++ libraries of %s"
% (os.path.basename(platform), os.path.basename(provider)))
root = os.path.join(STATE, "rootfs")
install_fonts(root)
provider = None
if app == SNIPER_APPID:
provider = graphics_platform()
if provider and materialize(provider):
say("prepared %s for the x86 runtime's C and C++ libraries" % os.path.basename(provider))
if not provider:
say("Steam Linux Runtime 4.0 (Steam app %s) is not installed yet; x86 games may not find their graphics drivers"
% SLR4_APPID)
elif not provides_newer(platform, provider):
say("%s has no newer C and C++ libraries than %s" % (os.path.basename(provider), os.path.basename(platform)))
provider = None
else:
if build_rootfs(platform, provider):
say("built the x86 runtime from %s with the C and C++ libraries of %s"
% (os.path.basename(platform), os.path.basename(provider)))
root = os.path.join(STATE, "rootfs")
with contextlib.suppress(OSError):
link_guest_sdk(root)
write_config(fex, root)
fex["rootfs"] = root
try:
@@ -530,6 +572,8 @@ def guest_environment(fex, env):
result["STEAM_COMPAT_DATA_PATH"] = short
result.setdefault("FEX_SILENTLOG", "0")
result.setdefault("FEX_OUTPUTLOG", "stderr")
# The session's tunables are for the host libc; an x86 ld.so copying them under FEX fails in sbrk.
result.pop("GLIBC_TUNABLES", None)
# Mono's incremental Boehm collector corrupts its heap under FEX, so Unity games crash at their first collections.
result.setdefault("GC_DISABLE_INCREMENTAL", "1")
if fex["portable"]:
@@ -594,6 +638,12 @@ def vulkan_thunk_loads(fex, folder):
return True
def required_runtime(program):
text = read_text(os.path.join(os.path.dirname(program), "toolmanifest.vdf")) or ""
match = re.search(r'"require_tool_appid"\s+"(\d+)"', text)
return match.group(1) if match and match.group(1) in RUNTIMES else SNIPER_APPID
def resolve(program, env):
if "/" in program:
return os.path.abspath(program)
@@ -605,7 +655,7 @@ def launch(command, env, mode, decide=None):
use = mode == "on" or (mode == "auto" and needs_fex(decide or program))
if not use:
return os.execvpe(command[0], command, env)
fex = prepare()
fex = prepare(required_runtime(program))
if fex is None:
return 126
guest = guest_environment(fex, env)
@@ -624,6 +674,7 @@ def launch(command, env, mode, decide=None):
def game_environment(env):
try:
game_env = runpy.run_path(os.path.join(BIN_DIR, "droiddeck-game-env"))
env = game_env["game_gpu"](env)
app = game_env["game_id"](env) or env.get("SteamAppId") or env.get("SteamGameId")
if not app:
return env
@@ -1,4 +1,5 @@
#!/usr/bin/python3
import hashlib
import json
import os
import re
@@ -7,6 +8,7 @@ import subprocess
import sys
from pathlib import Path
GAME_TU_DEBUG = "DROIDDECK_GAME_TU_DEBUG"
SYNC_KEYS = ("BL_SYNC", "BL_SYNC_FALLBACK", "BL_FSYNC_FIRST", "BL_SYNC_MIN_NOFILE", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC", "PROTON_NO_NTSYNC", "WINEESYNC")
SEED_REDISTS = "/usr/local/bin/droiddeck-seed-redists"
PACK_KEYS = ("WINESERVER", "BL_SYNC_PACK", "WINEESYNC", "PROTON_NO_ESYNC", "PROTON_NO_FSYNC")
@@ -98,6 +100,12 @@ def godot_sentry(game):
return {"WINEDLLOVERRIDES": ";".join(n + "=d" for n in sentry)}, [], "Godot: Sentry crash handler off"
@fix
def deep_rock_gdk_raytracing(game):
if game.stem == "fsd-wingdk-shipping" and not any(game.has_arg(arg) for arg in ("-raytracing", "-noraytracing")):
return {}, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"], "Deep Rock Galactic GDK: ray tracing off (D3D12 pipeline creation fails on Thor)"
@fix
def arkham_city_x87(game):
"""Batman: Arkham City (BatmanAC.exe, also started through BmLauncher.exe beside it) leans on x87
@@ -119,6 +127,35 @@ def skip_red_launcher(command):
return command
def offline_without_anticheat(command, env):
"""Start the configured game executable when the player opts into launching without EAC."""
if (env.get("DROIDDECK_ANTICHEAT_OFFLINE") != "1" or len(command) <= 2
or command[1] != "waitforexitandrun"
or not re.fullmatch(r"start_protected_game(?:_?x64|_?64)?\.exe",
os.path.basename(command[2]), re.IGNORECASE)):
return command
folder = os.path.dirname(command[2])
try:
with open(os.path.join(folder, "EasyAntiCheat", "settings.json"), encoding="utf-8-sig") as source:
executable = json.load(source).get("executable")
except (OSError, ValueError, AttributeError):
return command
if not isinstance(executable, str) or not executable:
return command
relative = os.path.normpath(executable.replace("\\", "/"))
game = os.path.join(folder, relative)
if os.path.isabs(relative) or relative.startswith("..") or not os.path.isfile(game):
return command
# Resolve symlinks before accepting an executable inside the game directory.
root = os.path.realpath(folder)
if os.path.commonpath((root, os.path.realpath(game))) != root:
return command
if os.path.normcase(os.path.abspath(game)) == os.path.normcase(os.path.abspath(command[2])):
return command
print("droiddeck-game-env: started without Easy Anti-Cheat (offline only)", file=sys.stderr)
return command[:2] + [game] + command[3:]
def engine_fixes(exe, args):
"""Environment and extra arguments a game needs because of what it is built with."""
game = Game(exe, args)
@@ -147,6 +184,18 @@ def win_components(compat, app_id):
return ""
def game_gpu(env):
if GAME_TU_DEBUG not in env:
return env
result = env.copy()
value = result.pop(GAME_TU_DEBUG)
if value:
result["TU_DEBUG"] = value
else:
result.pop("TU_DEBUG", None)
return result
def apply_config(env, config, app_id, fixes=None):
if config.get("version") != 1:
raise ValueError("unsupported environment configuration")
@@ -260,26 +309,134 @@ def mark_install_scripts(command, env):
starts - on first launch the shared ones may still be downloading, and on ARM64 Proton the VC++
ones stop with an error."""
if not any(arg.lower().replace("\\", "/").endswith("iscriptevaluator.exe") for arg in command):
return
return []
root = env.get("BL_X64_STEAM_ROOT") or env.get("STEAM_COMPAT_CLIENT_INSTALL_PATH") or str(Path.home() / ".local/share/Steam")
scripts = [str(Path(root) / arg.replace("\\", "/")) for arg in command if EVALUATOR_SCRIPT.search(arg)]
scripts = [path for path in scripts if os.path.isfile(path)]
if not scripts:
return
return []
try:
subprocess.run([SEED_REDISTS, root], env=dict(env, DROIDDECK_SEED_SCRIPTS="\n".join(scripts)),
stdout=sys.stderr, timeout=60, check=False)
except (OSError, subprocess.SubprocessError) as error:
print("droiddeck-game-env: install scripts not marked (%s)" % error, file=sys.stderr)
return scripts
INSTALL_STAMP = ".droiddeck-install-scripts"
VDF_TOKEN = re.compile(r'"((?:[^"\\]|\\.)*)"|([{}])')
def read_vdf(text):
tokens = iter(VDF_TOKEN.findall(text))
def block():
items = []
for word, brace in tokens:
if brace == "}":
return items
if brace:
raise ValueError("a block without a name")
value, opens = next(tokens, ("", "}"))
if opens == "}":
raise ValueError("a name without a value")
items.append((re.sub(r"\\(.)", r"\1", word), block() if opens else re.sub(r"\\(.)", r"\1", value)))
return items
return block()
def run_keys(items, appid=""):
appid = next((value for name, value in items if name.lower() == "appid" and isinstance(value, str)), appid)
found = set()
for name, value in items:
if not isinstance(value, list):
continue
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()))
found |= run_keys(value, appid)
return found
def registry_values(path):
found, section = set(), 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()))
return found
def has_run(key, value, values):
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)
def scripts_digest(scripts):
digest = hashlib.sha256()
for path in sorted(scripts):
digest.update(os.path.basename(path).encode() + b"\0")
digest.update(Path(path).read_bytes())
return digest.hexdigest()
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()
for path in scripts:
keys |= run_keys(read_vdf(Path(path).read_text(encoding="utf-8", errors="replace")))
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)
def record_install_scripts(digest, env):
prefix = Path(env.get("STEAM_COMPAT_DATA_PATH", "/nonexistent")) / "pfx"
try:
if prefix.is_dir():
staged = prefix / (INSTALL_STAMP + ".tmp")
staged.write_text(digest + "\n")
staged.replace(prefix / INSTALL_STAMP)
except OSError as error:
print("droiddeck-game-env: install scripts not recorded (%s)" % error, file=sys.stderr)
def start(launch, launch_env, digest):
if digest:
code = subprocess.run(launch, env=launch_env, check=False).returncode
if code == 0:
record_install_scripts(digest, launch_env)
return code
return os.execvpe(launch[0], launch, launch_env)
def main():
command = sys.argv[1:]
if not command:
return 2
env = os.environ.copy()
env = game_gpu(os.environ.copy())
mic_enabled = env.get("BL_MIC_ENABLED")
mark_install_scripts(command, env)
scripts = mark_install_scripts(command, env)
if scripts and install_scripts_done(scripts, env):
print("droiddeck-game-env: install scripts already run in this prefix; evaluator skipped", file=sys.stderr)
return 0
try:
digest = scripts_digest(scripts) if scripts else None
except OSError:
digest = None
app_id = game_id(env)
if app_id:
waiting = len(command) > 1 and command[1] == "waitforexitandrun"
@@ -307,19 +464,33 @@ def main():
env = apply_config(env, {"version": 1}, app_id, fixes)
except (OSError, ValueError, TypeError, AttributeError):
print("droiddeck-game-env: invalid configuration; using inherited environment", file=sys.stderr)
if app_id and len(command) > 1 and command[1] == "waitforexitandrun":
command = offline_without_anticheat(command, env)
if mic_enabled == "0":
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
env = force_ssbs(command, env)
try:
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
except Exception as error:
print("droiddeck-game-env: Xbox support unavailable (%s); stock launch" % error, file=sys.stderr)
xbox = {"launch": lambda command, env: None}
try:
xbox_result = xbox["launch"](command, env)
except (OSError, ValueError, KeyError, RuntimeError) as error:
print("droiddeck-game-env: Xbox launch could not start (%s)" % error, file=sys.stderr)
return 1
if xbox_result is not None:
return xbox_result
sync = load_sync()
launch, launch_env = select_sync(command, env, sync)
if launch[0] != command[0]:
try:
os.execvpe(launch[0], launch, launch_env)
return start(launch, launch_env, digest)
except OSError as error:
print("droiddeck-game-env: %s could not start (%s); stock launch" % (launch[0], error), file=sys.stderr)
launch, launch_env = command, without_pack(launch_env, env)
record_stock(sync, launch, launch_env)
os.execvpe(launch[0], launch, launch_env)
return start(launch, launch_env, digest)
if __name__ == "__main__":
@@ -28,6 +28,8 @@ UPOWER_ROOT = "/org/freedesktop/UPower"
NATIVE_PREPARE_MS = 1500
AGENT = Path(__file__).resolve().with_name("droiddeck-agent")
ASLEEP_WAIT = 6
INHIBIT_WAIT = 12
RELEASE_RETRIES = 8
INTROSPECTION = """
<node>
<interface name="org.freedesktop.login1.Manager">
@@ -58,8 +60,14 @@ class LoginManager:
self.native_request = self.directory / "steam-native-sleep"
self.native_ready = self.directory / "steam-native-ready"
self.pending = None
self.pending_idle = False
self.waiting = set()
self.timeout = None
self.preparation = None
self.inhibited = False
self.inhibit_lock = threading.Lock()
self.release = None
self.generation = 0
info = Gio.DBusNodeInfo.new_for_xml(INTROSPECTION).interfaces[0]
self.registration = bus.register_object(ROOT, info, self.method, self.property, None)
upower_info = Gio.DBusNodeInfo.new_for_xml(UPOWER_INTROSPECTION).interfaces[0]
@@ -89,6 +97,7 @@ class LoginManager:
reply.return_dbus_error(NAME + ".OperationInProgress", "The session is already pausing")
return
self.pending = uuid.uuid4().hex
self.pending_idle = False
self.notify(True)
reply.return_value(None)
self.bus.flush(None, self.publish_after_flush, self.pending)
@@ -101,7 +110,7 @@ class LoginManager:
self.resume()
return
if self.pending == token:
self.publish(self.request)
self.hold(token, self.publish, self.request)
def publish(self, request):
self.check_state()
@@ -119,15 +128,21 @@ class LoginManager:
def prepare_native(self):
try:
token = self.native_request.read_text().strip()
words = self.native_request.read_text().split()
self.native_request.unlink(missing_ok=True)
except OSError:
return
if not re.fullmatch(r"[a-f0-9]{32}", token) or self.pending is not None:
token = words[0] if words else ""
if not re.fullmatch(r"[a-f0-9]{32}", token) or words[1:] not in ([], ["idle"]) or self.pending is not None:
return
if self.read_state() == token + ":awake":
return
self.pending = token
self.pending_idle = words[1:] == ["idle"]
self.waiting = {"hold"} if self.pending_idle else {"hold", "prepare"}
self.hold(token, self.prepared, token, "hold")
if self.pending_idle:
return
self.notify(True)
self.bus.flush(None, self.prepare_after_flush, token)
@@ -144,10 +159,73 @@ class LoginManager:
def finish_preparation(self, token):
self.preparation = None
if self.pending == token:
self.prepared(token, "prepare")
return False
def prepared(self, token, step):
if self.pending != token:
return False
self.waiting.discard(step)
if not self.waiting:
self.publish(self.native_ready)
return False
def hold(self, token, then, *args):
self.cancel_release()
def work():
self.set_inhibit(True)
GLib.idle_add(self.after_hold, token, then, args)
threading.Thread(target=work, daemon=True).start()
def after_hold(self, token, then, args):
if self.pending == token:
then(*args)
elif self.pending is None:
self.release_later()
return False
def set_inhibit(self, inhibit, generation=None):
with self.inhibit_lock:
if (generation is not None and generation != self.generation) or self.inhibited == inhibit:
return
if steam_idle_inhibit(inhibit):
self.inhibited = inhibit
print("== login1: Steam idle sleep " + ("held" if inhibit else "released"), flush=True)
else:
self.inhibited = None
def cancel_release(self):
self.generation += 1
if self.release is not None:
GLib.source_remove(self.release)
self.release = None
def release_later(self):
self.cancel_release()
if self.inhibited is False:
return
generation = self.generation
threading.Thread(target=lambda: GLib.idle_add(self.schedule_release, generation, steam_idle_suspend_seconds()),
daemon=True).start()
def schedule_release(self, generation, seconds, attempt=0):
if generation == self.generation and self.pending is None:
self.release = GLib.timeout_add_seconds(seconds or 0, self.release_now, generation, attempt)
return False
def release_now(self, generation, attempt):
self.release = None
def work():
self.set_inhibit(False, generation)
if self.inhibited is not False and attempt < RELEASE_RETRIES:
GLib.idle_add(self.schedule_release, generation, 1 << attempt, attempt + 1)
threading.Thread(target=work, daemon=True).start()
return False
def changed(self, monitor, file, other, event):
if file.get_basename() == self.native_request.name or (other and other.get_basename() == self.native_request.name):
self.prepare_native()
@@ -178,8 +256,10 @@ class LoginManager:
def woken(self):
if self.pending is not None:
idle = self.pending_idle
self.resume(force=True)
return
if not idle:
return
threading.Thread(target=lambda: GLib.idle_add(self.replay_unless_awake, steam_asleep()), daemon=True).start()
def replay_unless_awake(self, asleep):
@@ -195,14 +275,18 @@ class LoginManager:
self.notify(True)
self.bus.flush(None, self.finish_recovery, None)
return
idle = self.pending_idle
self.pending = None
self.pending_idle = False
if self.preparation is not None:
GLib.source_remove(self.preparation)
self.preparation = None
if self.timeout is not None:
GLib.source_remove(self.timeout)
self.timeout = None
self.notify(False)
if not idle:
self.notify(False)
self.release_later()
def finish_recovery(self, connection, result, _data):
try:
@@ -213,13 +297,26 @@ class LoginManager:
self.notify(False)
def steam_asleep():
def agent(*args, timeout=ASLEEP_WAIT):
try:
code = subprocess.run([str(AGENT), "--steam-asleep"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, timeout=ASLEEP_WAIT).returncode
done = subprocess.run([str(AGENT), *args], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, text=True, timeout=timeout)
except (OSError, subprocess.SubprocessError):
return None
return {0: True, 5: False}.get(code)
return None, ""
return done.returncode, done.stdout
def steam_asleep():
return {0: True, 5: False}.get(agent("--steam-asleep")[0])
def steam_idle_inhibit(inhibit):
return agent("--steam-idle-inhibit", "on" if inhibit else "off", timeout=INHIBIT_WAIT)[0] == 0
def steam_idle_suspend_seconds():
code, output = agent("--steam-idle-suspend-seconds")
return int(output) if code == 0 and output.strip().isdigit() else None
def load_netmanager():
+62
View File
@@ -0,0 +1,62 @@
#!/bin/sh
# Audio stays on the session's PulseAudio, so WirePlumber runs its upstream video-only profile.
set -u
bundle=/usr/local/lib/droiddeck-pipewire.tzst
dir=/usr/local/lib/droiddeck-pipewire
state=${XDG_RUNTIME_DIR:-/tmp}/droiddeck-pipewire
client_env() {
echo "export PIPEWIRE_CONFIG_DIR=$dir/share/pipewire PIPEWIRE_MODULE_DIR=$dir/lib/pipewire-0.3 SPA_PLUGIN_DIR=$dir/lib/spa-0.2"
}
unpack() {
[ -f "$bundle" ] || { echo "droiddeck-pipewire: $bundle is missing" >&2; return 1; }
sum=$(cksum < "$bundle")
[ "$(cat "$dir/.bundle" 2>/dev/null)" = "$sum" ] && return 0
rm -rf "$dir.new" && mkdir -p "$dir.new" &&
zstd -dc "$bundle" | tar -xf - -C "$dir.new" &&
printf '%s\n' "$sum" > "$dir.new/.bundle" &&
rm -rf "$dir" && mv "$dir.new" "$dir" ||
{ rm -rf "$dir.new"; echo "droiddeck-pipewire: could not unpack $bundle" >&2; return 1; }
}
stop() {
for pid in $(cat "$state/pids" 2>/dev/null); do kill "$pid" 2>/dev/null; done
rm -f "$state/pids"
}
case "${1:-}" in
env)
client_env
;;
start)
unpack || exit 1
stop
mkdir -p "$state"
eval "$(client_env)"
export LD_LIBRARY_PATH=$dir/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}
export WIREPLUMBER_MODULE_DIR=$dir/lib/wireplumber-0.5 WIREPLUMBER_CONFIG_DIR=$dir/share/wireplumber \
WIREPLUMBER_DATA_DIR=$dir/share/wireplumber
socket=${XDG_RUNTIME_DIR:-/tmp}/pipewire-0
rm -f "$socket" "$socket.lock" "$socket-manager" "$socket-manager.lock"
"$dir/bin/pipewire" < /dev/null &
echo $! > "$state/pids"
i=0
while [ ! -S "$socket" ]; do
i=$((i + 1))
[ "$i" -le 50 ] || { echo "droiddeck-pipewire: pipewire did not open $socket" >&2; stop; exit 1; }
sleep 0.1
done
"$dir/bin/wireplumber" --profile video-only < /dev/null &
echo $! >> "$state/pids"
echo "droiddeck-pipewire: pipewire and wireplumber (video-only) up at $socket"
;;
stop)
stop
;;
*)
echo "usage: droiddeck-pipewire env|start|stop" >&2
exit 2
;;
esac
@@ -188,6 +188,7 @@ present() { awk -F'\t' '
}
' - "$1"; }
regs=()
for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/mnt/droiddeck-sd/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
/root/Games/*/steamapps/common/Proton*/files/share/default_pfx*/system.reg \
@@ -195,8 +196,21 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
"$steam_root"/steamapps/compatdata/*/pfx/system.reg \
/mnt/droiddeck-sd/steamapps/compatdata/*/pfx/system.reg \
/root/Games/*/steamapps/compatdata/*/pfx/system.reg; do
[ -f "$reg" ] || continue
[ -f "$reg" ] && regs+=("$reg")
done
declare -A regid=()
if [ ${#regs[@]} -gt 0 ]; then
while IFS=$'\t' read -r id name; do
regid[$name]=$id
done < <(stat -c $'%i %s %.9Y\t%n' -- "${regs[@]}" 2>/dev/null)
fi
for reg in "${regs[@]}"; do
seeded=${reg%/*}/.droiddeck-redists
checked=${reg%/*}/.droiddeck-redists-checked
id=${regid[$reg]:-}
prev=
[ -f "$checked" ] && read -r prev <"$checked"
legacy=${reg%/*}/.bannerlator-redists
if [ -f "$legacy" ] && [ ! -f "$seeded" ]; then
mv -f "$legacy" "$seeded"
@@ -210,12 +224,13 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
if [ -n "${vulkan[$line]:-}" ]; then stale+=("$line"); else kept+=("$line"); fi
done
if [ ${#stale[@]} -gt 0 ] && unseed "$reg" "${stale[@]}"; then
id=
had=()
for line in "${kept[@]}"; do had[$line]=1; done
printf '%s\n' "${kept[@]}" >"$seeded"
echo "== took Vulkan runtime markers out of $reg"
fi
if [ ${#had[@]} -gt 0 ]; then
if [ ${#had[@]} -gt 0 ] && { [ -z "$id" ] || [ "$id" != "$prev" ]; }; then
declare -A held=()
while IFS= read -r line; do [[ $line == *$'\t'* ]] && held[$line]=1; done < <(printf '%s\n' "${!had[@]}" | present "$reg")
if [ ${#held[@]} -lt ${#had[@]} ]; then
@@ -228,7 +243,11 @@ for reg in "$steam_root"/steamapps/common/Proton*/files/share/default_pfx*/syste
fi
missing=()
for line in "${want[@]}"; do [ -n "${had[$line]:-}" ] || missing+=("$line"); done
[ ${#missing[@]} -eq 0 ] && continue
if [ ${#missing[@]} -eq 0 ]; then
[ -n "$id" ] && [ "$id" != "$prev" ] && printf '%s\n' "$id" >"$checked"
continue
fi
rm -f "$checked"
dated=$(mktemp) || continue
touch -r "$reg" "$dated"
if printf '%s\n' "$(block_for "${missing[@]}")" >>"$reg"; then
@@ -4,6 +4,11 @@ export HOME=${HOME:-/root}
mode=${1:-desktop}
shift || true
step() { echo "== STEP $(date -u +%H:%M:%S) $*"; }
steam_setup_failed() {
echo "== steam: the Steam client could not be set up (status $1)"
[ -z "${BL_STEAM_EXIT_FILE:-}" ] || printf '%s\n' "$1" > "$BL_STEAM_EXIT_FILE"
exit "$1"
}
if [ -n "${BL_LOG:-}" ] && [ -z "${BL_INSIDE:-}" ]; then
mkdir -p "$(dirname "$BL_LOG")" 2>/dev/null
if [ "$(stat -c %s "$BL_LOG" 2>/dev/null || echo 0)" -gt 8388608 ]; then
@@ -129,6 +134,8 @@ export XDG_CONFIG_HOME=${XDG_CONFIG_HOME:-$HOME/.config}
export XDG_CACHE_HOME=${XDG_CACHE_HOME:-$HOME/.cache}
mkdir -p "$XDG_DATA_HOME" "$XDG_CONFIG_HOME" "$XDG_CACHE_HOME"
rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-steamvr/active"
rm -f "${XDG_RUNTIME_DIR:-/run/droiddeck}/droiddeck-remote-play"
/usr/local/bin/droiddeck-steamvr unregister >/dev/null 2>&1 || true
if [ "$mode" = lxqt ] || [ "$mode" = desktop ]; then
/usr/local/bin/droiddeck-desktop-bookmarks || true
fi
@@ -245,8 +252,15 @@ if [ -z "${BL_INSIDE:-}" ]; then
fi
export BL_INSIDE=1
if [ "$mode" = steam ]; then
if /usr/local/bin/droiddeck-pipewire start; then
eval "$(/usr/local/bin/droiddeck-pipewire env)"
else
echo "== pipewire: not running; Remote Play and game recording have no picture"
fi
run_gamescope "${args[@]}" -- "$0" "$mode" "$@"
exit $?
_bl_status=$?
/usr/local/bin/droiddeck-pipewire stop
exit $_bl_status
fi
exec gamescope "${args[@]}" -- "$0" "$mode" "$@"
fi
@@ -302,6 +316,9 @@ case $mode in
taskset -cp "$cores" $$ >/dev/null 2>&1 || true
fi
python3 /usr/local/bin/droiddeck-pad-defaults 2>&1 || true
if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
export WAYLAND_DISPLAY= XDG_SESSION_TYPE=x11
fi
run_program() {
local rc=0 child sig forwarded=0
{ trap - INT QUIT; exec "$@"; } <&0 &
@@ -330,6 +347,10 @@ case $mode in
*.appimage)
export APPIMAGE_EXTRACT_AND_RUN=1
chmod +x "$target" 2>/dev/null
if [ ${#fex[@]} -eq 0 ] && [ -x /usr/local/lib/droiddeck/uruntime ]; then
export TARGET_APPIMAGE=$target
run_program /usr/local/lib/droiddeck/uruntime "$@"
fi
run_program "${fex[@]}" "$target" "$@"
;;
*.sh)
@@ -345,6 +366,12 @@ case $mode in
esac
;;
steam)
if [ -n "${GAMESCOPE_WAYLAND_DISPLAY:-}" ]; then
export WAYLAND_DISPLAY= XDG_SESSION_TYPE=x11
fi
export MOZ_DISABLE_CONTENT_SANDBOX=1 MOZ_DISABLE_GMP_SANDBOX=1 MOZ_DISABLE_RDD_SANDBOX=1
export MOZ_DISABLE_SOCKET_PROCESS_SANDBOX=1 MOZ_DISABLE_UTILITY_SANDBOX=1
export MOZ_SHM_NO_SEALS=1
steam_x64=0
[ "${BL_STEAM_CLIENT_ARCH:-}" = x86_64 ] && steam_x64=1
steam_cef_gpu=1
@@ -353,10 +380,10 @@ case $mode in
# droiddeck-steam-install removes the repair request: read it first so Repair Steam covers both clients.
_bl_x64_repair=0
[ -e "$HOME/.bl-steam-repair" ] && _bl_x64_repair=1
droiddeck-steam-install || exit $?
droiddeck-steam-install || steam_setup_failed $?
droiddeck-steam-install --sync steamdeck_publicbeta || step "could not update the arm64 client's parts; the x86-64 client keeps its own web helper"
step "checking the x86-64 Steam client (FEX, experimental; the first run downloads ~2 GB)"
BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || exit $?
BL_X64_REPAIR=$_bl_x64_repair droiddeck-steam-x64 --prepare || steam_setup_failed $?
step "x86-64 Steam client ready"
steam_root=${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam
steam_client=(droiddeck-steam-x64 --exec)
@@ -366,9 +393,9 @@ case $mode in
fi
else
# A first run downloads the client (about 360 MB in 2026): minutes on a slow connection, with
# the progress in megabytes on the loading screen.
step "checking the Steam client (a first run downloads it)"
droiddeck-steam-install || exit $?
# the progress in megabytes on the loading screen.
step "checking the Steam client (first run downloads it, ~1-2 min with nothing on screen)"
droiddeck-steam-install || steam_setup_failed $?
step "Steam client ready"
steam_root=$XDG_DATA_HOME/Steam
if [ -f "${BL_X64_HOME:-$HOME/.droiddeck-x64}/.local/share/Steam/local.vdf" ]; then
@@ -597,6 +624,7 @@ case $mode in
steam_hold_launch() {
local game=$1 shortcut= waited=0 status=0
_bl_focused() { xprop -root GAMESCOPE_FOCUSED_APP 2>/dev/null | sed -n 's/.*= *//p'; }
_bl_starting() { pgrep -f "reaper SteamLaunch AppId=$(((game >> 32) & 0xffffffff))( |$)" >/dev/null 2>&1; }
_bl_hand_off() {
printf '%s\n' "$game" > "$BL_LAUNCH_DIR/steam-game.tmp" && mv -f "$BL_LAUNCH_DIR/steam-game.tmp" "$BL_LAUNCH_DIR/steam-game"
}
@@ -611,16 +639,22 @@ case $mode in
_bl_hand_off
[ -n "$shortcut" ] || return 0
# Steam can drop a shortcut launch it gets before the shortcut's overview exists (large libraries).
# Hand it over again only if the game never took focus, so a launch that worked is not started twice.
# A launch can be running before it creates its first window.
while [ "$(_bl_focused)" = 769 ] && [ "$waited" -lt 20 ]; do
sleep 1
waited=$((waited + 1))
done
[ "$(_bl_focused)" = 769 ] || return 0
if _bl_starting; then
echo "== steam: the requested game is already starting; not launching again"
return 0
fi
echo "== steam: the game is not in front after about 20 s; waiting for the shortcut overview"
/usr/local/bin/droiddeck-agent --wait-steam-shortcut-overview "$game" 45 || status=$?
if [ "$status" -eq 3 ]; then
echo "== steam: not a shortcut CGameID; not launching again"
elif _bl_starting; then
echo "== steam: the requested game started while waiting; not launching again"
elif [ "$(_bl_focused)" = 769 ]; then
echo "== steam: launching the requested game again $game (overview status $status)"
_bl_hand_off
@@ -105,7 +105,7 @@ INSTALL_JS = r"""
const body = [];
uint(1, appid, body);
const r = await send("CompatManager.GetCompatTools#1", body);
if (!r.ok) throw new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")");
if (!r.ok) throw Object.assign(new Error("GetCompatTools " + appid + " failed (" + r.eresult + " " + r.error + ")"), { eresult: r.eresult });
return { selected: text(r.body, 3), fallback: text(r.body, 4), tools: (r.body[1] || []).map((t) => text(parse(t), 1)) };
};
self.set = async (appid, name) => {
@@ -119,7 +119,13 @@ INSTALL_JS = r"""
};
self.many = async (apps) => {
const out = {};
for (const app of apps) out[app] = (await self.get(Number(app))).selected;
for (const app of apps) {
try {
out[app] = (await self.get(Number(app))).selected;
} catch (e) {
if (e.eresult !== 128) throw e;
}
}
return out;
};
window.__droiddeckCompat = self;
@@ -555,11 +561,24 @@ class Helper:
# "native" from earlier builds also lists dual-platform games nobody chose to run natively.
prior_native = state.get("native_choices", ())
native_choices = set(prior_native if isinstance(prior_native, (list, tuple, set)) else ())
picked = COMPAT["picked_apps"](state)
runnable = {t["name"].lower() for t in live}
apps = sorted(set(installed) | set(picks) | set(prior_auto) | native_choices, key=COMPAT["app_order"])
overrides = COMPAT["requested_games"](
COMPAT["game_requests"](), catalog, [t["name"] for t in live])
apps = sorted(set(apps) | set(overrides), key=COMPAT["app_order"])
current = dict(page.compat("many(%s)" % json.dumps(apps)) or {})
refused = set(apps) - set(current)
refused_native = native_choices & refused
if refused:
apps = [app for app in apps if app not in refused]
installed = [app for app in installed if app not in refused]
picks = [app for app in picks if app not in refused]
prior_auto = {app: tool for app, tool in prior_auto.items() if app not in refused}
if isinstance(state.get("auto"), dict):
state["auto"] = prior_auto
native_choices -= refused
overrides = {app: tool for app, tool in overrides.items() if app not in refused}
current["0"] = top["selected"]
native = COMPAT["native_targets"](self.steam_root, apps)
raw_mapping = COMPAT["read_config_mapping"](
@@ -568,7 +587,7 @@ class Helper:
for app in native_choices:
current[app] = ""
for app in set(native) - native_choices:
if not current.get(app):
if not current.get(app) and app not in picked:
current.pop(app, None)
else:
for app in set(native) | native_choices:
@@ -576,7 +595,8 @@ class Helper:
# The client shows an explicit native choice as the tool it inherits, and writes config.vdf late.
if raw_mapping[app] == "" or current.get(app) not in self.known:
current[app] = raw_mapping[app]
elif app in prior_auto or app in native_choices:
elif app in prior_auto or app in native_choices or app in picked and (
not current.get(app) or COMPAT["unrunnable"](current[app], runnable)):
current[app] = ""
elif not current.get(app):
current.pop(app, None)
@@ -590,8 +610,8 @@ class Helper:
tool if tool is not None else "Steam native default"))
state.update(
auto={app: tool for app, tool in auto.items() if tool is not COMPAT["NATIVE_CHOICE"]},
native_choices=sorted(app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]),
tools=catalog, live=True)
native_choices=sorted(refused_native | {app for app, tool in auto.items() if tool is COMPAT["NATIVE_CHOICE"]}),
picked=COMPAT["picked_after"](current, changes), tools=catalog, live=True)
state.pop("native", None)
if waiting:
state["pending"] = wanted
@@ -291,7 +291,7 @@ def libraries(steam_root):
except OSError:
text = ""
paths = [path.replace("\\\\", "\\") for path in re.findall(r'"path"\s+"((?:[^"\\]|\\.)*)"', text)]
return list(dict.fromkeys([Path(steam_root), Path(LIBRARY)] + [Path(path) for path in paths]))
return list(dict.fromkeys([Path(steam_root)] + [Path(path) for path in paths]))
def ours(manifest, appid):
@@ -311,6 +311,16 @@ def unpark(steamapps):
os.replace(manifest, live)
def seeded(steamapps, game, appid):
target = steamapps / "common" / f"DroidDeck-{appid}"
manifest = steamapps / f"appmanifest_{appid}.acf"
try:
return (target.is_symlink() and target.is_dir() and manifest.is_file() and ours(manifest, appid)
and os.readlink(target) in (game.get("folder", ""), legacy_path(game.get("folder", ""))))
except OSError:
return False
def park(steamapps):
for target in sorted((steamapps / "common").glob("DroidDeck-*")):
appid = target.name.removeprefix("DroidDeck-")
@@ -428,6 +438,9 @@ def route(steam_root, acct, games):
continue
except OSError as error:
print(f"droiddeck-steam-games: import unavailable ({error})")
elif isinstance(appid, int) and 0 < appid < 0x80000000 and seeded(steamapps, game, appid):
routes[str(game["appid"])] = appid
continue
shortcuts.append(game)
try:
park(steamapps)
@@ -8,7 +8,7 @@ ROOTFS_SHA256=2854b06d3ff1b8f6e526135bfb6dd5b7b30ab3ab73e79ae933a3d9fed959a178
CDN=https://client-update.fastly.steamstatic.com
# Must match the -clientbeta droiddeck-session starts this client with (steam_channel).
X64_CHANNEL=steamdeck_publicbeta
MANIFEST=steam_client_${X64_CHANNEL}_ubuntu12
MANIFEST=steam_client_${X64_CHANNEL}_steamrt64
REAL_HOME=${HOME:-/root}
X64_HOME=${BL_X64_HOME:-$REAL_HOME/.droiddeck-x64}
@@ -37,17 +37,17 @@ x64_client_parts() {
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
END { for (b in file) if (b ~ /_all$/ || b ~ /_ubuntu12$/) print b, file[b], sha[b] }
END { for (b in file) if (b ~ /_all$/ || b ~ /_steamrt64$/) print b, file[b], sha[b] }
' "$1" | sort
}
x64_sync_client() {
local chan cur version work total i block file sum old
chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL")
old=$STEAM_X64/package/steam_client_${chan}_ubuntu12.manifest
old=$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest
cur=$(awk -F'"' '$2 == "version" { print $4; exit }' "$old" 2>/dev/null || true)
work=$(mktemp -d)
if ! curl -fsSL "$CDN/steam_client_${chan}_ubuntu12" -o "$work/manifest"; then
if ! curl -fsSL "$CDN/steam_client_${chan}_steamrt64" -o "$work/manifest"; then
rm -rf "$work"; return 0
fi
version=$(awk -F'"' '$2 == "version" { print $4; exit }' "$work/manifest")
@@ -471,7 +471,7 @@ if [ ! -x "$STEAM_X64/steamrt64/steam" ] || [ ! -f "$STEAM_X64/package/droiddeck
/^\t"/ && NF >= 3 && $4 == "" { block = $2 }
$2 == "file" { file[block] = $4 }
$2 == "sha2" { sha[block] = $4 }
END { for (b in file) if (b ~ /_all$/ || b ~ /_ubuntu12$/) print b, file[b], sha[b] }
END { for (b in file) if (b ~ /_all$/ || b ~ /_steamrt64$/) print b, file[b], sha[b] }
' "$work/manifest" | sort > "$work/parts"
[ -s "$work/parts" ] || { step "no client components in $MANIFEST"; exit 1; }
mkdir -p "$STEAM_X64/package"
@@ -910,7 +910,7 @@ x64_exec() {
[ -x "$ARM_STEAM/steamrtarm64/steamwebhelper" ]; then
local chan x86_build arm_build
chan=$(cat "$STEAM_X64/package/beta" 2>/dev/null || echo "$X64_CHANNEL")
x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_ubuntu12.manifest" 2>/dev/null || true)
x86_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$STEAM_X64/package/steam_client_${chan}_steamrt64.manifest" 2>/dev/null || true)
arm_build=$(awk -F'"' '$2 == "version" { print $4; exit }' "$ARM_STEAM/package/steam_client_${chan}_linuxarm64.manifest" 2>/dev/null || true)
if [ -n "$x86_build" ] && [ "$x86_build" = "$arm_build" ]; then
export BL_X64_ARM_WEBHELPER=/usr/local/bin/droiddeck-x64-arm-webhelper
@@ -937,7 +937,7 @@ x64_exec() {
touch "$STEAM_X64/logs/bootstrap_log.txt"
( tail -n0 -F --pid=$$ "$STEAM_X64/logs/bootstrap_log.txt" 2>/dev/null |
grep --line-buffered -oE 'Downloading update \([0-9,]+ of [0-9,]+ KB\)' | sed -u 's/,//g' >&2 ) &
echo "== x86-64 client: ubuntu12 $(x64_manifest_version ubuntu12), steamrt64 $(x64_manifest_version steamrt64) (the client may update itself)" >&2
echo "== x86-64 client: steamrt64 $(x64_manifest_version steamrt64) (the client may update itself)" >&2
x64_webhelper_gpu && { x64_gpu_watch >&2 & }
exec "${BL_FEX:-/usr/local/bin/FEX}" "$STEAM_X64/steamrt64/steam" "$@"
}
@@ -952,6 +952,76 @@ arm, x64, arm_reg, x64_reg = sys.argv[1:5]
FILES = ("config/loginusers.vdf", "local.vdf")
def read(path):
try:
return open(path, encoding="utf-8", errors="surrogateescape").read()
except OSError:
return None
def write(path, text):
open(path, "w", encoding="utf-8", errors="surrogateescape").write(text)
def block(text, name):
m = re.search(r'"%s"\s*\{' % name, text)
if not m:
return None
depth, k = 1, m.end()
while depth and k < len(text):
depth += text[k] == "{"
depth -= text[k] == "}"
k += 1
return m, k
def accounts(root):
text = read(os.path.join(root, "config/config.vdf")) or ""
found = block(text, "Accounts")
if not found:
return {}
return dict(re.findall(r'"([^"]+)"\s*\{\s*"SteamID"\s*"(\d+)"', text[found[0].end():found[1]]))
def add_accounts(root, wanted):
path = os.path.join(root, "config/config.vdf")
text = read(path)
if text is None:
return
have = accounts(root)
missing = {name: sid for name, sid in wanted.items() if name not in have}
if not missing:
return
entries = "".join('\n\t\t\t\t\t"%s"\n\t\t\t\t\t{\n\t\t\t\t\t\t"SteamID"\t\t"%s"\n\t\t\t\t\t}' % item for item in missing.items())
found = block(text, "Accounts")
if found:
text = text[:found[0].end()] + entries + text[found[0].end():]
else:
steam = re.search(r'"Valve"\s*\{\s*"Steam"\s*\{', text)
if not steam:
return
text = text[:steam.end()] + '\n\t\t\t\t"Accounts"\n\t\t\t\t{' + entries + '\n\t\t\t\t}' + text[steam.end():]
write(path, text)
def set_keys(src_reg, dst_reg, force):
st, dt = read(src_reg), read(dst_reg)
if st is None or dt is None:
return
for key in ("AutoLoginUser", "RememberPassword"):
v = re.search(r'"%s"\s*"([^"]*)"' % key, st)
if not v:
continue
if re.search(r'"%s"\s*"' % key, dt):
if force:
dt = re.sub(r'("%s"\s*")[^"]*(")' % key, lambda m: m.group(1) + v.group(1) + m.group(2), dt, count=1)
continue
hkcu = re.search(r'"HKCU"\s*\{\s*"Software"\s*\{\s*"Valve"\s*\{\s*"Steam"\s*\{\n', dt)
if hkcu:
dt = dt[:hkcu.end()] + '\t\t\t\t\t"%s"\t\t"%s"\n' % (key, v.group(1)) + dt[hkcu.end():]
write(dst_reg, dt)
def stamp(root):
if not all(os.path.isfile(os.path.join(root, f)) for f in FILES):
return None
@@ -963,31 +1033,26 @@ def stamp(root):
a, x = stamp(arm), stamp(x64)
if a is None and x is None:
sys.exit(0)
if a is not None and x is not None and abs(a - x) < 1:
sys.exit(0)
if x is None or (a is not None and a > x):
src, dst, sreg, dreg, who = arm, x64, arm_reg, x64_reg, "arm64"
else:
src, dst, sreg, dreg, who = x64, arm, x64_reg, arm_reg, "x86-64"
for f in FILES:
os.makedirs(os.path.dirname(os.path.join(dst, f)), exist_ok=True)
# copy2 keeps the time stamp, so both match until one client signs in again.
shutil.copy2(os.path.join(src, f), os.path.join(dst, f))
if os.path.isfile(sreg):
st = open(sreg, encoding="utf-8", errors="surrogateescape").read()
if not os.path.isfile(dreg):
os.makedirs(os.path.dirname(dreg), exist_ok=True)
shutil.copy2(sreg, dreg)
if a is not None or x is not None:
if x is None or (a is not None and a > x):
src, dst, sreg, dreg, who = arm, x64, arm_reg, x64_reg, "arm64"
else:
dt = open(dreg, encoding="utf-8", errors="surrogateescape").read()
for key in ("AutoLoginUser", "RememberPassword"):
v = re.search(r'"%s"\s*"([^"]*)"' % key, st)
if v and re.search(r'"%s"\s*"' % key, dt):
dt = re.sub(r'("%s"\s*")[^"]*(")' % key, lambda m: m.group(1) + v.group(1) + m.group(2), dt, count=1)
open(dreg, "w", encoding="utf-8", errors="surrogateescape").write(dt)
print("droiddeck-steam-x64: sign-in shared from the %s client (the newer one)" % who)
src, dst, sreg, dreg, who = x64, arm, x64_reg, arm_reg, "x86-64"
copy = a is None or x is None or abs(a - x) >= 1
if copy:
for f in FILES:
os.makedirs(os.path.dirname(os.path.join(dst, f)), exist_ok=True)
# copy2 keeps the time stamp, so both match until one client signs in again.
shutil.copy2(os.path.join(src, f), os.path.join(dst, f))
if os.path.isfile(sreg) and not os.path.isfile(dreg):
os.makedirs(os.path.dirname(dreg), exist_ok=True)
shutil.copy2(sreg, dreg)
set_keys(sreg, dreg, copy)
set_keys(dreg, sreg, False)
add_accounts(dst, accounts(src))
add_accounts(src, accounts(dst))
if copy:
print("droiddeck-steam-x64: sign-in shared from the %s client (the newer one)" % who)
PY
}
@@ -41,6 +41,22 @@ configure_graphics() {
esac
}
# Any OpenXR probe (Steam runs one through Proton at every client start) starts vrserver
# while a runtime is registered, so SteamVR is registered only during a DroidDeck VR session.
unregister() {
if grep -qF "\"$steamvr\"" "$HOME/.config/openvr/openvrpaths.vrpath" 2>/dev/null; then
rm -f "$HOME/.config/openvr/openvrpaths.vrpath"
fi
case "$(readlink "$HOME/.config/openxr/1/active_runtime.json" 2>/dev/null)" in
"$steamvr"/*) rm -f "$HOME/.config/openxr/1/active_runtime.json" ;;
esac
}
idle() {
[ ! -f "$state/active" ] && ! running && ! pgrep -x vrstartup >/dev/null 2>&1 &&
( flock -n 9 ) 9>"$state/start.lock"
}
stop() {
rm -f "$state/active"
for n in vrcompositor vrserver vrmonitor vrdashboard vrstartup vrwebhelper; do
@@ -56,6 +72,7 @@ stop() {
[ "$attempts" -lt 20 ] || { echo 'SteamVR did not stop; preferences remain backed up' >&2; return 1; }
sleep 0.1
done
unregister
quest_settings restore
}
@@ -74,6 +91,7 @@ status)
i=0; installed && i=1
r=0; running && r=1
if [ "$r" = 0 ] && [ -n "$(find "$state/active" -mmin +2 2>/dev/null)" ]; then rm -f "$state/active"; fi
if idle; then unregister; fi
n=0; [ -f "$state/installing" ] && n=1
d=0; [ -f "$driver/bin/linuxarm64/driver_droiddeck.so" ] && [ -f "$layer/libVkLayer_droiddeck_vr.so" ] && d=1
echo "installed=$i running=$r installing=$n driver=$d"
@@ -100,6 +118,9 @@ install)
stop)
stop || exit 1
;;
unregister)
if idle; then unregister; fi
;;
start)
exec 9>"$state/start.lock"
flock -n 9 || { echo "SteamVR start already in progress"; exit 0; }
@@ -234,7 +255,7 @@ JSON
echo "SteamVR starting; logs in $logs and $state/vrstartup.log"
;;
*)
echo "usage: droiddeck-steamvr status|install|start|stop|launch" >&2
echo "usage: droiddeck-steamvr status|install|start|stop|launch|unregister" >&2
exit 2
;;
esac
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
# Exit 0 when this game run should open as a SteamVR panel: SteamVR is running and Steam
# lists no VR support for the app, optional or required. Under SteamVR, Steam stacks a flat game's window behind
# its own, so without the panel the game plays unseen.
[ "${1:-}" = waitforexitandrun ] || exit 1
[ -z "${DROIDDECK_STEAMVR_PANEL:-}" ] || exit 1
# Non-Steam shortcuts run with SteamAppId=0 and their CGameID in SteamGameId.
app=${SteamAppId:-}
[ "$app" = 0 ] && app=${SteamGameId:-}
case $app in '' | 0 | *[!0-9]*) exit 1 ;; esac
pgrep -x vrserver >/dev/null 2>&1 || exit 1
/usr/local/bin/droiddeck-agent --steam-supports-vr "$app" >/dev/null 2>&1
[ $? -eq 5 ]
@@ -6,6 +6,8 @@ pgrep -x vrserver >/dev/null 2>&1 || {
echo 'Start SteamVR before launching a game with droiddeck-steamvr-game.' >&2
exit 1
}
# droiddeck-steamvr-flat skips a run that a launch option already wrapped.
export DROIDDECK_STEAMVR_PANEL=1
vrdir=${DROIDDECK_VR_DIR:-/usr/local/lib/droiddeck-vr}
export VK_LAYER_PATH="$vrdir/layer${VK_LAYER_PATH:+:$VK_LAYER_PATH}"
export VK_INSTANCE_LAYERS="VK_LAYER_DROIDDECK_vr${VK_INSTANCE_LAYERS:+:$VK_INSTANCE_LAYERS}"
@@ -28,8 +28,11 @@ build wrote is removed - with it the game exited while loading.
droiddeck-store-launch <the arguments Steam gave the compat tool>
"""
import base64
import binascii
import json
import os
import re
import sys
import time
import subprocess
@@ -268,6 +271,23 @@ def provision_prefix(compat_data, wait=SERVER_WAIT):
return state + (" server-running" if busy else "")
def create_prefix(compat_data, proton, timeout=120):
if not compat_data or not proton or not Path(proton).is_file():
return "no-proton"
reg = Path(compat_data) / "pfx/user.reg"
if reg.is_file():
return "present"
try:
Path(compat_data).mkdir(parents=True, exist_ok=True)
subprocess.run([proton, "run", "cmd.exe", "/d", "/c", "exit"], stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
except subprocess.TimeoutExpired:
return "timeout"
except OSError:
return "failed"
return "created" if reg.is_file() else "failed"
CLOUD_TIMEOUT = 15.0
CLOUD_STORES = ("gog", "epic")
STORE_GAME = 10
@@ -364,6 +384,123 @@ def prepare_gog(sidecar, compat_data, launch_dir):
return state == "ready"
GOG_SCRIPTS = "goggame-*.script"
GOG_REGISTRY_MARK = ".droiddeck-gog-registry"
GOG_ROOTS = {"HKEY_LOCAL_MACHINE": "HKEY_LOCAL_MACHINE", "HKLM": "HKEY_LOCAL_MACHINE",
"HKEY_CURRENT_USER": "HKEY_CURRENT_USER", "HKCU": "HKEY_CURRENT_USER",
"HKEY_CLASSES_ROOT": "HKEY_CLASSES_ROOT", "HKCR": "HKEY_CLASSES_ROOT"}
WINE_USER = "C:\\users\\steamuser"
def gog_paths(folder, product):
app = windows_path(str(folder))
support = app + "\\support\\" + product
return {"app": app, "productid": product, "support": support, "supportdir": support,
"localappdata": WINE_USER + "\\AppData\\Local", "userdocs": WINE_USER + "\\Documents"}
def gog_expand(text, paths):
return re.sub(r"\{([A-Za-z]+)\}", lambda m: paths[m.group(1).lower()], text)
def gog_number(data):
if isinstance(data, bool):
raise ValueError
if isinstance(data, int):
return data
text = str(data).strip()
try:
return int(text, 0)
except ValueError:
return int(text, 10)
def gog_value(kind, data):
kind = str(kind).lower()
if kind == "string":
text = str(data)
if any(c in text for c in "\r\n\0"):
return None
return '"%s"' % reg_escape(text)
if kind == "dword":
return "dword:%08x" % (gog_number(data) & 0xFFFFFFFF)
if kind == "binary":
return "hex:" + ",".join("%02x" % b for b in base64.b64decode(str(data), validate=True))
return None
def gog_entry(arguments, paths):
if not isinstance(arguments, dict):
return None
try:
root = GOG_ROOTS.get(str(arguments.get("root") or "").upper())
subkey = gog_expand(str(arguments.get("subkey") or ""), paths).strip("\\")
if root is None or not subkey or any(c in subkey for c in "\r\n\0"):
return None
section = "[%s\\%s]" % (root, subkey)
if not arguments.get("valueType"):
return section
data = arguments.get("valueData")
value = gog_value(arguments["valueType"], gog_expand(data, paths) if isinstance(data, str) else data)
name = gog_expand(str(arguments.get("valueName") or ""), paths)
if value is None or any(c in name for c in "\r\n\0"):
return None
return section + "\r\n" + ('"%s"' % reg_escape(name) if name else "@") + "=" + value
except (KeyError, ValueError, TypeError, binascii.Error):
return None
def gog_registry(folder):
entries, skipped = [], 0
for script in sorted(Path(folder).glob(GOG_SCRIPTS)):
product = script.name[len("goggame-"):-len(".script")]
try:
actions = json.loads(script.read_text(encoding="utf-8-sig")).get("actions")
except (OSError, ValueError, AttributeError):
continue
paths = gog_paths(folder, product)
for action in actions if isinstance(actions, list) else []:
install = action.get("install") if isinstance(action, dict) else None
if not isinstance(install, dict) or install.get("action") != "setRegistry":
continue
entry = gog_entry(install.get("arguments"), paths)
if entry is None:
skipped += 1
else:
entries.append(entry)
return entries, skipped
def apply_gog_registry(folder, compat_data, proton, timeout=90):
entries, skipped = gog_registry(folder)
note = " skipped=%d" % skipped if skipped else ""
if not entries:
return "none" + note
if not compat_data or not proton or not Path(proton).is_file():
return "no-proton" + note
text = "Windows Registry Editor Version 5.00\r\n\r\n" + "".join(entry + "\r\n\r\n" for entry in entries)
stamp = hashlib.sha256(text.encode("utf-8")).hexdigest()
pfx = Path(compat_data) / "pfx"
marker = pfx / GOG_REGISTRY_MARK
try:
if marker.is_file() and marker.read_text() == stamp and (pfx / "system.reg").is_file():
return "ready" + note
Path(compat_data).mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="droiddeck-gog-") as tmp:
source = Path(tmp) / "registry.reg"
source.write_bytes(b"\xff\xfe" + text.encode("utf-16-le"))
run = subprocess.run([proton, "run", "reg.exe", "import", windows_path(str(source)), "/reg:32"],
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=timeout)
if run.returncode or not (pfx / "system.reg").is_file():
return "import-failed" + note
marker.write_text(stamp)
return "written=%d%s" % (len(entries), note)
except subprocess.TimeoutExpired:
return "timeout" + note
except OSError:
return "import-failed" + note
def main(argv):
if argv and argv[0] == "--exited":
rest, code = argv[1:], 0
@@ -382,8 +519,13 @@ def main(argv):
compat_data = os.environ.get("STEAM_COMPAT_DATA_PATH", "").rstrip("/")
prefix_id = os.path.basename(compat_data) if compat_data else ""
launch_dir = os.environ.get("BL_LAUNCH_DIR", "")
if launch_dir and cloud_on(sidecar):
made = create_prefix(compat_data, os.environ.get("BL_STORE_PROTON", ""))
if made != "present":
log("cloud %s %s prefix=%s" % (store, game, made))
if store == "gog":
prepare_gog(sidecar, compat_data, launch_dir)
log("gog registry: " + apply_gog_registry(folder, compat_data, os.environ.get("BL_STORE_PROTON", "")))
if store == "epic":
handled = os.environ.get(EPIC_HANDLED) == "1" and (folder / EPIC_ARGS).is_file()
if not handled:
+201
View File
@@ -0,0 +1,201 @@
#!/usr/bin/python3
"""Licensed Xbox launches through Xodus and the game's selected ARM64 Proton."""
import hmac
import json
import os
from pathlib import Path
import runpy
import secrets
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
BIN = Path(__file__).resolve().parent
RUNTIME = Path('/usr/local/lib/droiddeck-xbox')
DLLS = ('xgameruntime.dll', 'winhttp.dll', 'windows.web.dll', 'twinapi.appcore.dll', 'libnghttp2.dll')
def bridge(upstream):
key = secrets.token_hex(32).encode('ascii')
server = socket.socket()
server.bind(('127.0.0.1', 0))
server.listen(16)
clients = set()
lock = threading.Lock()
stopped = threading.Event()
def forward(source, target):
try:
while not stopped.is_set():
data = source.recv(65536)
if not data:
break
target.sendall(data)
except OSError:
pass
finally:
try:
target.shutdown(socket.SHUT_WR)
except OSError:
pass
def connect(client):
remote = None
try:
client.settimeout(10)
supplied = b''
while len(supplied) < len(key):
part = client.recv(len(key) - len(supplied))
if not part:
return
supplied += part
if not hmac.compare_digest(supplied, key):
return
remote = socket.socket(socket.AF_UNIX)
remote.connect(upstream)
client.settimeout(None)
with lock:
clients.add(remote)
writer = threading.Thread(target=forward, args=(client, remote), daemon=True)
writer.start()
forward(remote, client)
writer.join(2)
except OSError:
pass
finally:
for sock in (client, remote):
if sock is not None:
with lock:
clients.discard(sock)
sock.close()
def accept():
while not stopped.is_set():
try:
client, _ = server.accept()
except OSError:
break
with lock:
if len(clients) >= 64:
client.close()
continue
clients.add(client)
threading.Thread(target=connect, args=(client,), daemon=True).start()
threading.Thread(target=accept, daemon=True).start()
def close():
stopped.set()
server.close()
with lock:
for client in clients:
try:
client.shutdown(socket.SHUT_RDWR)
except OSError:
pass
client.close()
clients.clear()
return server.getsockname()[1], key.decode('ascii'), close
def wine(argv, source_env=None):
source_env = os.environ if source_env is None else source_env
with open(source_env['DROIDDECK_XBOX_COMMAND_FILE'], encoding='utf-8') as file:
command = json.load(file)
if len(command) < 3 or command[1] != 'waitforexitandrun' or len(argv) != 1:
raise ValueError('Invalid Xbox Proton invocation')
env = dict(source_env)
env.pop('DROIDDECK_XBOX_CREDENTIAL_SOCKET', None)
env.pop('DROIDDECK_XBOX_COMMAND_FILE', None)
prefix = Path(source_env['STEAM_COMPAT_DATA_PATH']) / 'pfx'
prefix.parent.mkdir(parents=True, exist_ok=True)
if not (prefix / 'system.reg').is_file():
result = subprocess.run([command[0], 'run', 'cmd', '/c', 'exit', '0'], stdout=sys.stderr, env=env)
if result.returncode:
return result.returncode
system = prefix / 'drive_c/windows/system32'
system.mkdir(parents=True, exist_ok=True)
for name in DLLS:
target = system / name
if target.is_symlink():
target.unlink()
shutil.copyfile(RUNTIME / 'windows' / name, target)
overrides = ';'.join(name[:-4] + '=n' for name in DLLS if name != 'libnghttp2.dll')
env['WINEDLLOVERRIDES'] = overrides + ';' + env.get('WINEDLLOVERRIDES', '')
return subprocess.call([*command[:2], argv[0], *command[3:]], env=env)
def renew_lease(ask, channel, product, lease, stopped):
while not stopped.wait(15):
response = ask(channel, {'op': 'xbox-renew', 'id': product, 'lease': lease}, timeout=10)
if response is not None and response.get('ok') is False:
return
def launch(command, env):
if len(command) < 3 or command[1] != 'waitforexitandrun' or env.get('DROIDDECK_XBOX_ACTIVE') == '1':
return None
try:
store = runpy.run_path(str(BIN / 'droiddeck-store-launch'))
except Exception as error:
print('droiddeck-xbox: store detection unavailable (%s); stock launch' % error, file=sys.stderr)
return None
found = store['find_store_game'](command[2:])
if found is None or found[1].get('store') != 'xbox':
return None
folder, sidecar = found
for name in DLLS:
if not (RUNTIME / 'windows' / name).is_file():
raise RuntimeError('Xbox Windows runtime is missing; update the Linux runtime')
launch_dir = env.get('BL_LAUNCH_DIR')
if not launch_dir:
raise RuntimeError('No Xbox account channel; start the game from DroidDeck')
reply = store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-prepare', 'id': sidecar['id']}, timeout=190)
if not reply or not reply.get('ok'):
raise RuntimeError('Xbox account service is unavailable; sign in again and retry')
stopped = threading.Event()
close = lambda: None
try:
port, key, close = bridge(reply['socket'])
threading.Thread(target=renew_lease, args=(store['ask'], Path(launch_dir) / 'stores',
sidecar['id'], reply['lease'], stopped), daemon=True).start()
with tempfile.TemporaryDirectory(prefix='droiddeck-xbox-') as temporary:
context = Path(temporary) / 'command.json'
context.write_text(json.dumps(command), encoding='utf-8')
context.chmod(0o600)
owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context),
XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key,
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off')
owned_env.pop('DROIDDECK_XBOX_CREDENTIAL_SOCKET', None)
if reply.get('playfab'):
owned_env['XODUS_XSTS_PLAYFAB'] = reply['playfab']
content = folder / '.xbox-content'
roots = []
if content.is_dir():
for entry in content.iterdir():
try:
marker = json.loads((entry / '.droiddeck-content.json').read_text())
if marker.get('parent') == sidecar['id'] and marker.get('productId') == entry.name and not entry.is_symlink():
roots.append('Z:' + str(entry).replace('/', '\\'))
except (OSError, ValueError, TypeError):
pass
if roots:
owned_env['XODUS_CONTENT_ROOTS'] = ';'.join(roots)
return wine([reply['exe']], owned_env)
finally:
stopped.set()
close()
store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-released', 'lease': reply['lease']})
if __name__ == '__main__':
try:
sys.exit(wine(sys.argv[1:]))
except (OSError, ValueError, KeyError, RuntimeError):
print('droiddeck-xbox: Xbox launch failed; check your account, runtime and package.', file=sys.stderr)
sys.exit(1)
@@ -74,6 +74,9 @@ bl_store_launch() {
}
bl_run() {
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "${verb:-}"; then
set -- /usr/local/bin/droiddeck-steamvr-game "$@"
fi
if [ -n "${BL_STORE_EXIT:-}" ]; then
"$@"
rc=$?
@@ -243,6 +246,13 @@ bl_vacdiag() {
"""
BL_DIRECTAUDIO_SETUP = """
bl_is_steam_installscript_target() {
local target=${1:-}
local steam_root=${STEAM_COMPAT_CLIENT_INSTALL_PATH:-${XDG_DATA_HOME:-$HOME/.local/share}/Steam}
local helper="$steam_root/legacycompat/iscriptevaluator.exe"
[ -f "$helper" ] && [[ -n "$target" && "$target" -ef "$helper" ]]
}
bl_directaudio() {
case "${verb:-}" in
run|waitforexitandrun|runinprefix) ;;
@@ -251,6 +261,17 @@ bl_directaudio() {
base=$1
[ -n "${BL_DIRECTAUDIO:-}" ] || return 0
[ -d "$BL_DIRECTAUDIO" ] || return 0
if bl_is_steam_installscript_target "${2:-}"; then
echo "droiddeck-proton: DirectAudio skipped for Steam's install-script evaluator" >&2
return 0
fi
streamer=$(cat "${XDG_RUNTIME_DIR:-/tmp}/droiddeck-remote-play" 2>/dev/null)
if [ -n "$streamer" ] && kill -0 "$streamer" 2>/dev/null; then
WINE_AUDIO_DRIVER=pulse
export WINE_AUDIO_DRIVER
echo "droiddeck-proton: a Remote Play client is connected - game audio goes through PulseAudio so the stream carries it" >&2
return 0
fi
version=$("$base/files/bin-arm64/wine" --version 2>/dev/null)
major=${version#wine-}
major=${major%%.*}
@@ -338,7 +359,7 @@ for name in %s; do
done
if [ -n "$depot" ]; then
bl_components "$depot"
bl_directaudio "$depot"
bl_directaudio "$depot" "$@"
bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
@@ -393,7 +414,7 @@ if [ -n "${PROOT_FP_KEY:-}" ] && [ -f "$audit" ]; then
esac
fi
bl_components "$here"
bl_directaudio "$here"
bl_directaudio "$here" "$@"
bl_game_cpus
bl_idtech3 "$@"
bl_vacdiag "$@"
@@ -445,6 +466,9 @@ verb=$1; shift
case $verb in
getcompatpath | getnativepath) printf '%s\\n' "$1"; exit 0 ;;
esac
if [ -x /usr/local/bin/droiddeck-steamvr-flat ] && /usr/local/bin/droiddeck-steamvr-flat "$verb"; then
exec /usr/local/bin/droiddeck-steamvr-game /usr/local/bin/droiddeck-fex steam "$verb" "$@"
fi
exec /usr/local/bin/droiddeck-fex steam "$verb" "$@"
"""
@@ -901,24 +925,33 @@ def fex_wanted_marker():
return os.path.join(os.environ.get("HOME", "/root"), ".config", "droiddeck", "fex-wanted")
def request_fex(steam_root, asked):
def request_app(steam_root, app):
import subprocess
client = os.path.join(steam_root, "steamrtarm64", "steam")
if not os.access(client, os.X_OK):
return []
try:
process = subprocess.Popen([client, "steam://install/%s" % app], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
except OSError:
return []
try:
process.wait(timeout=REQUEST_HANDOFF_SECONDS)
except subprocess.TimeoutExpired:
pass
return [app]
def request_fex(steam_root, asked):
client = os.path.join(steam_root, "steamrtarm64", "steam")
missing = fex_missing(steam_root)
if not os.access(client, os.X_OK) or any(app in asked for app in missing):
return []
for app in missing:
asked.add(app)
try:
process = subprocess.Popen([client, "steam://install/%s" % app], stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, start_new_session=True)
except OSError:
continue
try:
process.wait(timeout=REQUEST_HANDOFF_SECONDS)
except subprocess.TimeoutExpired:
pass
return [app]
requested = request_app(steam_root, app)
if requested:
return requested
return []
@@ -1022,6 +1055,16 @@ def plan_mapping(current, installed, runnable, default, auto, native=None, picks
return changes, kept
def picked_apps(state):
picked = state.get("picked", ())
return {app for app in picked if isinstance(app, str)} if isinstance(picked, list) else set()
def picked_after(current, changes):
return sorted(({app for app, tool in current.items() if tool} - set(changes) |
{app for app, tool in changes.items() if tool}) - {"0"}, key=app_order)
def followers(state, current):
if "auto" in state:
return state["auto"]
@@ -1267,6 +1310,8 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
native = native_targets(steam_root, set(apps) | set(picks) | set(managed) | set(native_choices))
if linux_tool != FEX_TOOL:
native = {app: linux_tool if tool == FEX_TOOL else tool for app, tool in native.items()}
for app in picked_apps(state) & set(native):
current.setdefault(app, "")
changes, auto = plan_mapping(
current, apps, names, default, followers(state, current), native, picks,
overrides, managed, native_choices)
@@ -1277,6 +1322,7 @@ def register_default(config_path, apps=(), protect=(), default=None, catalog=Non
write_changed(config_path, text)
state["auto"] = {app: tool for app, tool in auto.items() if tool is not NATIVE_CHOICE}
state["native_choices"] = sorted(app for app, tool in auto.items() if tool is NATIVE_CHOICE)
state["picked"] = picked_after(current, changes)
state.pop("native", None)
state["tools"] = catalog
state.setdefault("default", default)
+6
View File
@@ -617,9 +617,13 @@ int shm_unlink(const char *name) {
return r;
}
int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
void *(*real)(void *, size_t, int, int, int, off_t), void **out) __attribute__((weak, visibility("hidden")));
void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) {
void *p;
if (!fs_real_mmap) fs_real_mmap = (void *(*)(void *, size_t, int, int, int, off_t))dlsym(RTLD_NEXT, "mmap");
if (bl_venc_mmap && bl_venc_mmap(addr, len, prot, flags, fd, off, fs_real_mmap, &p)) return p;
p = fs_real_mmap(addr, len, prot, flags, fd, off);
if (p == MAP_FAILED && bl_noexec_retry(prot, flags, fd)) p = fs_real_mmap(addr, len, prot & ~PROT_EXEC, flags, fd, off);
if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off);
@@ -629,6 +633,8 @@ void *mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off) {
void *mmap64(void *addr, size_t len, int prot, int flags, int fd, off64_t off) {
void *p;
if (!fs_real_mmap64) fs_real_mmap64 = (void *(*)(void *, size_t, int, int, int, off64_t))dlsym(RTLD_NEXT, "mmap64");
if (bl_venc_mmap && bl_venc_mmap(addr, len, prot, flags, fd, off, (void *(*)(void *, size_t, int, int, int, off_t))fs_real_mmap64, &p))
return p;
p = fs_real_mmap64(addr, len, prot, flags, fd, off);
if (p == MAP_FAILED && bl_noexec_retry(prot, flags, fd)) p = fs_real_mmap64(addr, len, prot & ~PROT_EXEC, flags, fd, off);
if (p != MAP_FAILED && __builtin_expect(fs_fd >= 0, 0)) fs_track(p, len, flags, fd, off);
+54 -11
View File
@@ -406,6 +406,7 @@ int bl_kgsl_poll(int (*real)(int, unsigned long, void *), int fd, unsigned long
void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_ntsync_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_drm_gem_close(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_venc_ioctl(int fd, unsigned long request, void *arg, int *rc) __attribute__((visibility("hidden")));
int bl_winebus_rumble_ioctl(int (*real)(int, unsigned long, void *), int fd, unsigned long request,
void *arg, void *caller, int *rc) __attribute__((visibility("hidden")));
@@ -419,6 +420,7 @@ int ioctl(int fd, unsigned long request, ...) {
int rc;
if (bl_ntsync_ioctl(fd, request, arg, &rc)) return rc;
if (bl_venc_ioctl(fd, request, arg, &rc)) return rc;
if (bl_drm_gem_close(fd, request, arg, &rc)) return rc;
if (real == NULL) real = (ioctl_fn) dlsym(RTLD_NEXT, "ioctl");
if (bl_winebus_rumble_ioctl(real, fd, request, arg, __builtin_return_address(0), &rc)) return rc;
@@ -504,19 +506,55 @@ static void write_table(FILE *out, const char *table, const struct link *link) {
}
}
static const char *denied_table(const char *path) {
static const char *const tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp" };
#define CARRIER_TABLE 5
static const char *const net_tables[] = { "route", "ipv6_route", "if_inet6", "dev", "arp", "carrier" };
static long long net_denied_at[sizeof(net_tables) / sizeof(net_tables[0])];
#define CARRIER_SLOTS 8
static struct { char path[64]; long long at; } carrier_denied[CARRIER_SLOTS];
static int denied_recently(int table, const char *path) {
if (table != CARRIER_TABLE) return fresh(&net_denied_at[table]);
int hit = 0;
pthread_mutex_lock(&link_lock);
for (int i = 0; i < CARRIER_SLOTS && !hit; i++) {
hit = strcmp(carrier_denied[i].path, path) == 0 && fresh(&carrier_denied[i].at);
}
pthread_mutex_unlock(&link_lock);
return hit;
}
static void remember_denial(int table, const char *path) {
if (table != CARRIER_TABLE) {
__atomic_store_n(&net_denied_at[table], now_ns(), __ATOMIC_RELAXED);
return;
}
if (strlen(path) >= sizeof(carrier_denied[0].path)) return;
pthread_mutex_lock(&link_lock);
int slot = 0;
for (int i = 0; i < CARRIER_SLOTS; i++) {
if (strcmp(carrier_denied[i].path, path) == 0) { slot = i; break; }
if (carrier_denied[i].at < carrier_denied[slot].at) slot = i;
}
snprintf(carrier_denied[slot].path, sizeof(carrier_denied[slot].path), "%s", path);
carrier_denied[slot].at = now_ns();
pthread_mutex_unlock(&link_lock);
}
static int denied_table(const char *path) {
if (strncmp(path, "/proc/net/", 10) == 0) {
for (size_t i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) {
if (strcmp(path + 10, tables[i]) == 0) return tables[i];
for (int i = 0; i < CARRIER_TABLE; i++) {
if (strcmp(path + 10, net_tables[i]) == 0) return i;
}
return NULL;
return -1;
}
size_t len = strlen(path);
if (strncmp(path, "/sys/class/net/", 15) == 0 && len > 8 && strcmp(path + len - 8, "/carrier") == 0) {
return "carrier";
return CARRIER_TABLE;
}
return NULL;
return -1;
}
static FILE *synthesize(const char *table) {
@@ -548,11 +586,16 @@ static FILE *open_stream(fopen_fn real, const char *path, const char *mode, cons
if (copy == NULL) close(status);
return copy;
}
FILE *f = real(path, mode);
if (f || path == NULL || mode == NULL || mode[0] != 'r') return f;
int table = path && mode && mode[0] == 'r' ? denied_table(path) : -1;
FILE *f;
if (table >= 0 && denied_recently(table, path) && (f = synthesize(net_tables[table])) != NULL) return f;
f = real(path, mode);
if (f || table < 0) return f;
int saved = errno;
const char *table = denied_table(path);
if (table && (f = synthesize(table)) != NULL) return f;
if ((f = synthesize(net_tables[table])) != NULL) {
if (saved == EACCES) remember_denial(table, path);
return f;
}
errno = saved;
return NULL;
}
+2
View File
@@ -1253,9 +1253,11 @@ ssize_t recvmsg(int fd, struct msghdr *msg, int flags) {
}
void bl_fsync_fds_closed(unsigned int first, unsigned int last) __attribute__((visibility("hidden")));
void bl_venc_closed(int fd) __attribute__((visibility("hidden")));
int close(int fd) {
if (fd >= 0) bl_fsync_fds_closed((unsigned int)fd, (unsigned int)fd);
bl_venc_closed(fd);
uint64_t *t = __atomic_load_n(&ns_fdt, __ATOMIC_ACQUIRE);
if (t && fd >= 0 && fd < NS_FDS && __atomic_load_n(&t[fd], __ATOMIC_ACQUIRE)) ns_forget(fd);
return ns_close_fd(fd);
+3
View File
@@ -14,6 +14,7 @@
int bl_status_without_tracer(const char *path, int flags, const void *caller) __attribute__((visibility("hidden")));
int bl_writable_retry(int dirfd, const char *path, int flags) __attribute__((visibility("hidden")));
int bl_ntsync_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_venc_open(const char *path, int flags) __attribute__((visibility("hidden")));
int bl_dircache_create(int dirfd, const char *path, int flags, mode_t mode,
int (*real)(int, const char *, int, mode_t)) __attribute__((visibility("hidden")));
@@ -53,6 +54,7 @@ int open(const char *path, int flags, ...) {
}
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
if (real_open == NULL) real_open = dlsym(RTLD_NEXT, "open");
if (real_open == NULL) {
errno = ENOSYS;
@@ -78,6 +80,7 @@ int openat(int dirfd, const char *path, int flags, ...) {
}
if ((fd = bl_status_without_tracer(path, flags, __builtin_return_address(0))) >= 0) return fd;
if ((fd = bl_ntsync_open(path, flags)) != -2) return fd;
if ((fd = bl_venc_open(path, flags)) != -2) return fd;
if (real_openat == NULL) real_openat = dlsym(RTLD_NEXT, "openat");
if (real_openat == NULL) {
errno = ENOSYS;
+71 -7
View File
@@ -3,6 +3,7 @@
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <link.h>
#include <linux/futex.h>
#include <linux/magic.h>
#include <pthread.h>
@@ -28,9 +29,11 @@
#ifdef SYS_newfstatat
#define BL_SYS_FSTATAT SYS_newfstatat
#define BL_FSTATAT_NAME "fstatat"
typedef struct stat bl_stat;
#else
#define BL_SYS_FSTATAT SYS_fstatat64
#define BL_FSTATAT_NAME "fstatat64"
typedef struct stat64 bl_stat;
#endif
@@ -43,6 +46,51 @@ struct bl_open_how {
static long (*real_syscall)(long, ...);
static void *(*real_dlopen)(const char *, int);
static int openat2_missing;
static int (*next_fstatat)(int, const char *, bl_stat *, int);
static int (*next_openat)(int, const char *, int, ...);
static ssize_t (*next_readlinkat)(int, const char *, char *, size_t);
static int find_fastpath(struct dl_phdr_info *info, size_t size, void *name) {
(void)size;
const char *slash = strrchr(info->dlpi_name, '/');
if (!slash || strcmp(slash + 1, "libblfastpath.so") != 0 || strlen(info->dlpi_name) >= PATH_MAX) {
return 0;
}
strcpy(name, info->dlpi_name);
return 1;
}
__attribute__((constructor)) static void find_fastpath_calls(void) {
char name[PATH_MAX] = "";
dl_iterate_phdr(find_fastpath, name);
void *fastpath = *name ? dlopen(name, RTLD_NOLOAD | RTLD_LAZY) : NULL;
if (fastpath) {
next_fstatat = (int (*)(int, const char *, bl_stat *, int))dlsym(fastpath, BL_FSTATAT_NAME);
next_openat = (int (*)(int, const char *, int, ...))dlsym(fastpath, "openat");
next_readlinkat = (ssize_t (*)(int, const char *, char *, size_t))dlsym(fastpath, "readlinkat");
}
}
static long path_stat(int dirfd, const char *path, bl_stat *st, int flags) {
if (!next_fstatat) {
return real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)path, (long)st, (long)flags);
}
return next_fstatat(dirfd, path, st, flags);
}
static long path_open(int dirfd, const char *path, int flags, long mode) {
if (!next_openat) {
return real_syscall(SYS_openat, (long)dirfd, (long)path, (long)flags, mode);
}
return next_openat(dirfd, path, flags, (mode_t)mode);
}
static long path_readlink(int dirfd, const char *path, char *buf, size_t size) {
if (!next_readlinkat) {
return real_syscall(SYS_readlinkat, (long)dirfd, (long)path, (long)buf, (long)size);
}
return next_readlinkat(dirfd, path, buf, size);
}
void *dlopen(const char *filename, int flags) {
if (!real_dlopen) {
@@ -93,7 +141,7 @@ static struct robust_list_head *thread_robust_head(void) {
// Magic links are procfs links below a process's directory; procfs's root holds only plain ones (self, thread-self, mounts).
static int is_magic_link(int dirfd, char *link, size_t parent_len) {
int fd = (int)real_syscall(SYS_openat, (long)dirfd, (long)link, (long)(O_PATH | O_NOFOLLOW | O_CLOEXEC), 0L);
int fd = (int)path_open(dirfd, link, O_PATH | O_NOFOLLOW | O_CLOEXEC, 0L);
if (fd < 0) {
return 0;
}
@@ -106,7 +154,7 @@ static int is_magic_link(int dirfd, char *link, size_t parent_len) {
char saved = link[parent_len];
link[parent_len] = 0;
bl_stat parent;
long result = real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)(parent_len ? link : "."), (long)&parent, 0L);
long result = path_stat(dirfd, (parent_len ? link : "."), &parent, 0);
link[parent_len] = saved;
return result != 0 || parent.st_ino != BL_PROC_ROOT_INO;
}
@@ -167,7 +215,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
resolved[candidate_len] = 0;
bl_stat st;
int follow = !last || trailing_slash || !nofollow;
long stat_result = follow ? real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)resolved, (long)&st, (long)AT_SYMLINK_NOFOLLOW) : -1;
long stat_result = follow ? path_stat(dirfd, resolved, &st, AT_SYMLINK_NOFOLLOW) : -1;
if (stat_result == 0 && S_ISLNK(st.st_mode)) {
if (++symlinks > BL_MAX_SYMLINKS) {
errno = ELOOP;
@@ -176,7 +224,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
if (!have_root) {
bl_stat root;
struct statfs root_fs;
if (real_syscall(BL_SYS_FSTATAT, (long)dirfd, (long)".", (long)&root, 0L) != 0) {
if (path_stat(dirfd, ".", &root, 0) != 0) {
return -1;
}
root_dev = root.st_dev;
@@ -195,7 +243,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
}
char *tail = pending + PATH_MAX - rest_len - 1;
memmove(tail, end, rest_len + 1);
long target_len = real_syscall(SYS_readlinkat, (long)dirfd, (long)resolved, (long)pending, (long)(PATH_MAX - rest_len));
long target_len = path_readlink(dirfd, resolved, pending, PATH_MAX - rest_len);
if (target_len <= 0) {
if (target_len == 0) {
errno = ENOENT;
@@ -208,6 +256,19 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
}
memmove(pending + target_len, tail, rest_len + 1);
if (pending[0] == '/') {
char saved = pending[target_len];
pending[target_len] = 0;
const char *inside = pending;
while (*inside == '/') {
inside++;
}
bl_stat probe;
int host = *inside && path_stat(dirfd, inside, &probe, AT_SYMLINK_NOFOLLOW) != 0 &&
errno == ENOENT && path_stat(AT_FDCWD, pending, &probe, 0) == 0;
pending[target_len] = saved;
if (host) {
return path_open(AT_FDCWD, pending, flags, mode);
}
resolved_len = 0;
}
rest = pending;
@@ -233,7 +294,7 @@ static long openat_in_root(int dirfd, const char *path, int flags, long mode) {
resolved[resolved_len++] = '.';
}
resolved[resolved_len] = 0;
return real_syscall(SYS_openat, (long)dirfd, (long)resolved, (long)flags, mode);
return path_open(dirfd, resolved, flags, mode);
}
static long openat2_via_openat(const long *args) {
@@ -257,7 +318,7 @@ static long openat2_via_openat(const long *args) {
errno = EXDEV;
return -1;
}
return real_syscall(SYS_openat, args[0], (long)path, (long)(int)how->flags, (long)how->mode);
return path_open((int)args[0], path, (int)how->flags, (long)how->mode);
}
static int execveat_is_execve(const long *args) {
@@ -303,6 +364,9 @@ long syscall(long number, ...) {
}
return openat2_via_openat(args);
}
if (number == SYS_openat) {
return path_open((int)args[0], (const char *)args[1], (int)args[2], args[3]);
}
if (number == SYS_execveat && execveat_is_execve(args)) {
return real_syscall(SYS_execve, args[1], args[2], args[3]);
}
+89
View File
@@ -0,0 +1,89 @@
/* Steam's Linux Remote Play host has no touch injection: client touches arrive as an XTest mouse (absolute
* motion plus button 1). While a stream holds the encoder, those become touches into gamescope's own touch
* input, as a finger on the device screen would. */
#define _GNU_SOURCE
#include <dlfcn.h>
#include <pthread.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "../../../app/src/main/cpp/venc/venc_proto.h"
int bl_venc_streaming(void) __attribute__((visibility("hidden")));
int bl_venc_connect(void) __attribute__((visibility("hidden")));
static pthread_mutex_t rt_lock = PTHREAD_MUTEX_INITIALIZER;
static int rt_fd = -1, rt_down, rt_x, rt_y, rt_screen;
static int rt_enabled(void) {
static int enabled = -1;
if (enabled < 0) {
const char *v = getenv("BL_REMOTE_TOUCH");
enabled = v == NULL || strcmp(v, "0") != 0;
}
return enabled && bl_venc_streaming();
}
static uint32_t rt_fraction(int value, int extent) {
if (extent <= 1 || value <= 0) return 0;
if (value >= extent - 1) return 65535;
return (uint32_t)((int64_t)value * 65535 / (extent - 1));
}
static void rt_send(void *dpy, uint32_t action) {
static int (*width)(void *, int), (*height)(void *, int);
if (!width) width = (int (*)(void *, int))dlsym(RTLD_DEFAULT, "XDisplayWidth");
if (!height) height = (int (*)(void *, int))dlsym(RTLD_DEFAULT, "XDisplayHeight");
if (!width || !height) return;
struct venc_touch m = {
.type = VENC_TOUCH, .action = action,
.x = rt_fraction(rt_x, width(dpy, rt_screen)), .y = rt_fraction(rt_y, height(dpy, rt_screen)),
};
for (int attempt = 0; attempt < 2; attempt++) {
if (rt_fd < 0) rt_fd = bl_venc_connect();
if (rt_fd < 0) return;
if (send(rt_fd, &m, sizeof m, MSG_NOSIGNAL) == (ssize_t)sizeof m) return;
close(rt_fd);
rt_fd = -1;
}
}
int XTestFakeMotionEvent(void *dpy, int screen, int x, int y, unsigned long delay) {
static int (*real)(void *, int, int, int, unsigned long);
if (!real) real = (int (*)(void *, int, int, int, unsigned long))dlsym(RTLD_NEXT, "XTestFakeMotionEvent");
if (rt_enabled()) {
pthread_mutex_lock(&rt_lock);
rt_x = x;
rt_y = y;
rt_screen = screen < 0 ? 0 : screen;
int down = rt_down;
if (down) rt_send(dpy, VENC_TOUCH_MOVE);
pthread_mutex_unlock(&rt_lock);
if (down) return 1;
}
return real ? real(dpy, screen, x, y, delay) : 0;
}
int XTestFakeButtonEvent(void *dpy, unsigned int button, int press, unsigned long delay) {
static int (*real)(void *, unsigned int, int, unsigned long);
if (!real) real = (int (*)(void *, unsigned int, int, unsigned long))dlsym(RTLD_NEXT, "XTestFakeButtonEvent");
if (button == 1) {
pthread_mutex_lock(&rt_lock);
int handled = 0;
if (press && rt_enabled()) {
rt_down = 1;
rt_send(dpy, VENC_TOUCH_DOWN);
handled = 1;
} else if (!press && rt_down) {
rt_down = 0;
rt_send(dpy, VENC_TOUCH_UP);
handled = 1;
}
pthread_mutex_unlock(&rt_lock);
if (handled) return 1;
}
return real ? real(dpy, button, press, delay) : 0;
}
+81 -10
View File
@@ -403,6 +403,9 @@ struct msg_queue {
struct { uint64_t seq; long mtype; size_t len; char data[2048]; } slot[MSG_SLOTS];
};
struct msg_map { int id; int refs; struct msg_queue *q; };
static struct msg_map g_msgs[MAX_OBJECTS];
static struct msg_queue *msg_map(int id) {
int fd = open_by_id("msg", id);
if (fd < 0) return NULL;
@@ -415,6 +418,47 @@ static struct msg_queue *msg_map(int id) {
return NULL;
}
static int msg_removed(struct msg_queue *q) { return __atomic_load_n(&q->magic, __ATOMIC_ACQUIRE) != MSG_MAGIC; }
static struct msg_map *msg_get(int id) {
struct msg_map *found = NULL, *spare = NULL, *idle = NULL;
pthread_mutex_lock(&g_lock);
for (int i = 0; i < MAX_OBJECTS; i++) {
struct msg_map *e = &g_msgs[i];
if (e->q && !e->refs && msg_removed(e->q)) {
munmap(e->q, sizeof(*e->q));
e->q = NULL;
}
if (!e->q) {
if (!spare) spare = e;
} else if (e->id == id && !msg_removed(e->q)) {
found = e;
} else if (!e->refs && !idle) {
idle = e;
}
}
if (!found && !spare && idle) {
munmap(idle->q, sizeof(*idle->q));
idle->q = NULL;
spare = idle;
}
if (!found && spare && (spare->q = msg_map(id))) {
spare->id = id;
found = spare;
} else if (!found && !spare) {
errno = ENOSPC;
}
if (found) found->refs++;
pthread_mutex_unlock(&g_lock);
return found;
}
static void msg_put(struct msg_map *m) {
pthread_mutex_lock(&g_lock);
m->refs--;
pthread_mutex_unlock(&g_lock);
}
static void msg_lock(struct msg_queue *q) {
for (int32_t owner = 0; !atomic_compare_exchange_strong(&q->lock, &owner, getpid()); owner = 0) {
if (kill(owner, 0) != 0 && errno == ESRCH) atomic_compare_exchange_strong(&q->lock, &owner, 0);
@@ -446,12 +490,19 @@ int msgget(key_t key, int msgflg) {
}
int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
struct msg_queue *q = msg_map(msqid);
if (!q) return -1;
if (msgsz > sizeof(q->slot[0].data) || *(const long *)msgp < 1) { munmap(q, sizeof(*q)); errno = EINVAL; return -1; }
struct msg_map *m = msg_get(msqid);
if (!m) return -1;
struct msg_queue *q = m->q;
if (msgsz > sizeof(q->slot[0].data) || *(const long *)msgp < 1) { msg_put(m); errno = EINVAL; return -1; }
for (;;) {
msg_lock(q);
int32_t seen = atomic_load(&q->changed);
if (msg_removed(q)) {
msg_unlock(q, 0);
msg_put(m);
errno = EIDRM;
return -1;
}
for (int i = 0; i < MSG_SLOTS; i++) {
if (q->slot[i].seq) continue;
q->slot[i].mtype = *(const long *)msgp;
@@ -459,12 +510,12 @@ int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
memcpy(q->slot[i].data, (const long *)msgp + 1, msgsz);
q->slot[i].seq = ++q->next_seq;
msg_unlock(q, 1);
munmap(q, sizeof(*q));
msg_put(m);
return 0;
}
msg_unlock(q, 0);
if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) {
munmap(q, sizeof(*q));
msg_put(m);
if (msgflg & IPC_NOWAIT) errno = EAGAIN;
return -1;
}
@@ -473,11 +524,18 @@ int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg) {
ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
if (msgtyp < 0) { errno = EINVAL; return -1; }
struct msg_queue *q = msg_map(msqid);
if (!q) return -1;
struct msg_map *m = msg_get(msqid);
if (!m) return -1;
struct msg_queue *q = m->q;
for (;;) {
msg_lock(q);
int32_t seen = atomic_load(&q->changed);
if (msg_removed(q)) {
msg_unlock(q, 0);
msg_put(m);
errno = EIDRM;
return -1;
}
int best = -1;
for (int i = 0; i < MSG_SLOTS; i++)
if (q->slot[i].seq && (!msgtyp || q->slot[i].mtype == msgtyp) && (best < 0 || q->slot[i].seq < q->slot[best].seq))
@@ -488,12 +546,12 @@ ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
memcpy((long *)msgp + 1, q->slot[best].data, n);
q->slot[best].seq = 0;
msg_unlock(q, 1);
munmap(q, sizeof(*q));
msg_put(m);
return (ssize_t)n;
}
msg_unlock(q, 0);
if ((msgflg & IPC_NOWAIT) || (futex(&q->changed, FUTEX_WAIT, seen, NULL) != 0 && errno == EINTR)) {
munmap(q, sizeof(*q));
msg_put(m);
if (msgflg & IPC_NOWAIT) errno = ENOMSG;
return -1;
}
@@ -502,15 +560,28 @@ ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp, int msgflg) {
int msgctl(int msqid, int cmd, struct msqid_ds *buf) {
if (cmd != IPC_RMID) { errno = EINVAL; return -1; }
struct msg_queue *q = msg_map(msqid);
if (!q) return -1;
pthread_mutex_lock(&g_lock);
int rc = unlink_by_id("msg", msqid);
pthread_mutex_unlock(&g_lock);
int saved = errno;
if (rc == 0) {
__atomic_store_n(&q->magic, 0, __ATOMIC_SEQ_CST);
atomic_fetch_add(&q->changed, 1);
futex(&q->changed, FUTEX_WAKE, INT_MAX, NULL);
}
munmap(q, sizeof(*q));
errno = saved;
return rc;
}
static void sysv_lock_before_fork(void) { pthread_mutex_lock(&g_lock); }
static void sysv_unlock_after_fork(void) { pthread_mutex_unlock(&g_lock); }
static void sysv_reset_after_fork(void) { pthread_mutex_init(&g_lock, NULL); }
static void sysv_reset_after_fork(void) {
pthread_mutex_init(&g_lock, NULL);
for (int i = 0; i < MAX_OBJECTS; i++) g_msgs[i].refs = 0;
}
__attribute__((constructor)) static void install_sysv_fork_handlers(void) {
pthread_atfork(sysv_lock_before_fork, sysv_unlock_after_fork, sysv_reset_after_fork);
+28 -10
View File
@@ -22,15 +22,17 @@ static const char *skip_digits(const char *s) {
return end == s ? NULL : end;
}
static int is_status_path(const char *path) {
static long status_pid(const char *path) {
const char *rest;
if (path == NULL || strncmp(path, "/proc/", 6) != 0) return 0;
long pid = 0;
if (path == NULL || strncmp(path, "/proc/", 6) != 0) return -1;
path += 6;
if (strncmp(path, "self/", 5) == 0) rest = path + 4;
else if (strncmp(path, "thread-self/", 12) == 0) rest = path + 11;
else if ((rest = skip_digits(path)) == NULL) return 0;
if (strncmp(rest, "/task/", 6) == 0 && (rest = skip_digits(rest + 6)) == NULL) return 0;
return strcmp(rest, "/status") == 0;
else if ((rest = skip_digits(path)) == NULL) return -1;
else pid = strtol(path, NULL, 10);
if (strncmp(rest, "/task/", 6) == 0 && (rest = skip_digits(rest + 6)) == NULL) return -1;
return strcmp(rest, "/status") == 0 ? pid : -1;
}
static int is_web_helper(const void *caller) {
@@ -56,13 +58,26 @@ static int write_all(int fd, const char *data, size_t len) {
return 0;
}
static int read_only_copy(const char *data, size_t len, int flags) {
char path[] = "/tmp/.droiddeck-status-XXXXXX";
int rw = mkostemp(path, O_CLOEXEC);
if (rw < 0) return -1;
int ro = -1;
if (write_all(rw, data, len) == 0)
ro = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | (flags & O_CLOEXEC));
unlink(path);
close(rw);
return ro;
}
__attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *path, int flags, const void *caller) {
char text[STATUS_MAX];
size_t len = 0;
int saved = errno;
int out = -1;
if ((flags & O_ACCMODE) != O_RDONLY || !is_status_path(path) || is_web_helper(caller)) return -1;
long pid;
if ((flags & O_ACCMODE) != O_RDONLY || (pid = status_pid(path)) < 0 || is_web_helper(caller)) return -1;
int in = (int)syscall(SYS_openat, AT_FDCWD, path, O_RDONLY | O_CLOEXEC);
if (in < 0) goto done;
for (;;) {
@@ -78,13 +93,16 @@ __attribute__((visibility("hidden"))) int bl_status_without_tracer(const char *p
if (field == NULL) goto done;
char *value = field + strlen(TRACER_FIELD);
char *line_end = strchr(value, '\n');
if (line_end == NULL) goto done;
if (line_end == NULL || line_end == value) goto done;
memmove(value + 1, line_end, len - (size_t)(line_end - text) + 1);
*value = '0';
len = (size_t)(value + 1 - text) + strlen(value + 1);
if (pid != 0 && pid != getpid() && (out = read_only_copy(text, len, flags)) >= 0) goto done;
out = memfd_create("status", (flags & O_CLOEXEC) ? MFD_CLOEXEC : 0);
if (out < 0) goto done;
if (write_all(out, text, (size_t)(value - text)) != 0 || write_all(out, "0", 1) != 0
|| write_all(out, line_end, len - (size_t)(line_end - text)) != 0
|| lseek(out, 0, SEEK_SET) != 0) {
if (write_all(out, text, len) != 0 || lseek(out, 0, SEEK_SET) != 0) {
close(out);
out = -1;
}
+633
View File
@@ -0,0 +1,633 @@
/* /dev/video-enc0 for Steam's Remote Play V4L2 encoder stage, backed by the app's MediaCodec encoder. */
#define _GNU_SOURCE
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include "../../../app/src/main/cpp/venc/venc_proto.h"
#ifndef V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR
#define V4L2_CID_MPEG_VIDEO_PREPEND_SPSPPS_TO_IDR (V4L2_CID_MPEG_BASE + 644)
#endif
#define VENC_DEVICE "/dev/video-enc0"
#define VENC_INSTANCES 4
#define VENC_OFFSET_STEP 0x1000000L
#define VENC_CAPTURE_OFFSET (VENC_OFFSET_STEP * 64)
struct vq_buf {
int memfd;
uint32_t size;
};
struct vq_item {
uint32_t index, bytes, flags, sequence;
struct timeval timestamp;
};
struct vq {
struct vq_buf bufs[VENC_MAX_BUFFERS];
uint32_t count;
struct vq_item queued[VENC_MAX_BUFFERS], done[VENC_MAX_BUFFERS];
uint32_t nqueued, ndone;
int streaming;
};
struct venc {
int used, fd;
pid_t owner;
uint32_t width, height, stride, crop_w, crop_h, raw_size;
uint32_t coded_fourcc, coded_size;
uint32_t fps_num, fps_den;
uint32_t bitrate, peak, vbr, gop;
int32_t h264_profile, h264_level, hevc_profile;
int force_key, configured, sent_bitrate;
uint32_t sequence;
struct vq raw, coded;
};
static pthread_mutex_t vn_lock = PTHREAD_MUTEX_INITIALIZER;
static struct venc vn_all[VENC_INSTANCES];
static int vn_open_count;
static void vn_marker(int streaming) {
const char *dir = getenv("XDG_RUNTIME_DIR");
char path[512];
if (dir == NULL || snprintf(path, sizeof path, "%s/droiddeck-remote-play", dir) >= (int)sizeof path) return;
if (!streaming) {
unlink(path);
return;
}
FILE *f = fopen(path, "w");
if (f == NULL) return;
fprintf(f, "%d\n", (int)getpid());
fclose(f);
}
static void vn_log(const char *fmt, ...) __attribute__((format(printf, 1, 2)));
static void vn_log(const char *fmt, ...) {
va_list ap;
char line[256];
va_start(ap, fmt);
int n = vsnprintf(line, sizeof line - 1, fmt, ap);
va_end(ap);
if (n < 0) return;
if (n > (int)sizeof line - 2) n = sizeof line - 2;
line[n++] = '\n';
if (write(2, "droiddeck-venc: ", 16) < 0 || write(2, line, n) < 0) return;
}
static struct venc *vn_find(int fd) {
if (fd < 0 || __atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return NULL;
for (int i = 0; i < VENC_INSTANCES; i++) if (vn_all[i].used && vn_all[i].fd == fd) return &vn_all[i];
return NULL;
}
static int is_raw(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT || type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; }
static int is_coded(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_CAPTURE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; }
static int is_mplane(uint32_t type) { return type == V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE || type == V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE; }
static struct vq *vn_queue(struct venc *v, uint32_t type) { return is_raw(type) ? &v->raw : is_coded(type) ? &v->coded : NULL; }
static void vn_sizes(struct venc *v) {
if (v->stride < v->width) v->stride = v->width;
v->raw_size = v->stride * v->height * 3 / 2;
uint32_t coded = v->width * v->height * 3 / 2;
if (coded < 512 * 1024) coded = 512 * 1024;
if (v->coded_size < coded) v->coded_size = coded;
}
static void vn_free_queue(struct vq *q) {
for (uint32_t i = 0; i < q->count; i++) if (q->bufs[i].memfd >= 0) close(q->bufs[i].memfd);
memset(q, 0, sizeof *q);
}
__attribute__((visibility("hidden"))) int bl_venc_streaming(void) {
return __atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) > 0;
}
__attribute__((visibility("hidden"))) int bl_venc_connect(void);
int bl_venc_connect(void) {
const char *path = getenv("BL_VENC_SOCKET");
if (path == NULL || *path == '\0') return -1;
struct sockaddr_un addr = { .sun_family = AF_UNIX };
if (strlen(path) >= sizeof addr.sun_path) return -1;
strcpy(addr.sun_path, path);
int fd = socket(AF_UNIX, SOCK_SEQPACKET | SOCK_CLOEXEC, 0);
if (fd < 0) return -1;
if (connect(fd, (struct sockaddr *)&addr, sizeof addr) != 0) {
close(fd);
return -1;
}
struct timeval tv = { .tv_sec = 2 };
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof tv);
return fd;
}
__attribute__((visibility("hidden"))) int bl_venc_open(const char *path, int flags) {
(void)flags;
if (path == NULL || strcmp(path, VENC_DEVICE) != 0) return -2;
int fd = bl_venc_connect();
if (fd < 0) return -2;
pthread_mutex_lock(&vn_lock);
struct venc *v = NULL;
for (int i = 0; i < VENC_INSTANCES && v == NULL; i++) if (!vn_all[i].used) v = &vn_all[i];
if (v == NULL) {
pthread_mutex_unlock(&vn_lock);
close(fd);
errno = EBUSY;
return -1;
}
memset(v, 0, sizeof *v);
v->used = 1;
v->fd = fd;
v->owner = getpid();
v->width = v->crop_w = 1280;
v->height = v->crop_h = 720;
v->coded_fourcc = V4L2_PIX_FMT_H264;
v->fps_num = 1;
v->fps_den = 60;
v->bitrate = 20000000;
v->gop = 0xffff;
vn_sizes(v);
if (__atomic_add_fetch(&vn_open_count, 1, __ATOMIC_RELEASE) == 1) vn_marker(1);
pthread_mutex_unlock(&vn_lock);
vn_log("opened %s as fd %d (MediaCodec through the app)", path, fd);
return fd;
}
static int vn_send(struct venc *v, const void *msg, size_t len, const int *fds, int nfds) {
struct iovec iov = { .iov_base = (void *)msg, .iov_len = len };
char control[CMSG_SPACE(sizeof(int) * VENC_MAX_BUFFERS * 2)];
struct msghdr m = { .msg_iov = &iov, .msg_iovlen = 1 };
if (nfds > 0) {
memset(control, 0, sizeof control);
m.msg_control = control;
m.msg_controllen = CMSG_SPACE(sizeof(int) * nfds);
struct cmsghdr *c = CMSG_FIRSTHDR(&m);
c->cmsg_level = SOL_SOCKET;
c->cmsg_type = SCM_RIGHTS;
c->cmsg_len = CMSG_LEN(sizeof(int) * nfds);
memcpy(CMSG_DATA(c), fds, sizeof(int) * nfds);
}
return sendmsg(v->fd, &m, MSG_NOSIGNAL) == (ssize_t)len ? 0 : -1;
}
static int vn_configure(struct venc *v) {
struct venc_config c = {
.type = VENC_CONFIG,
.codec = v->coded_fourcc == V4L2_PIX_FMT_HEVC ? VENC_HEVC : VENC_H264,
.width = v->crop_w, .height = v->crop_h, .stride = v->stride, .rows = v->height,
.fps_num = v->fps_num, .fps_den = v->fps_den,
.bitrate = v->bitrate, .peak_bitrate = v->peak, .vbr = v->vbr, .gop = v->gop,
.profile = v->coded_fourcc == V4L2_PIX_FMT_HEVC ? v->hevc_profile : v->h264_profile,
.level = v->h264_level,
.inputs = v->raw.count, .outputs = v->coded.count,
.input_size = v->raw_size, .output_size = v->coded_size,
};
int fds[VENC_MAX_BUFFERS * 2], n = 0;
for (uint32_t i = 0; i < v->raw.count; i++) fds[n++] = v->raw.bufs[i].memfd;
for (uint32_t i = 0; i < v->coded.count; i++) fds[n++] = v->coded.bufs[i].memfd;
if (vn_send(v, &c, sizeof c, fds, n) != 0) return -1;
struct venc_done d;
if (recv(v->fd, &d, sizeof d, 0) != (ssize_t)sizeof d || d.type != VENC_DONE || d.status != 0) {
vn_log("the app's encoder refused %ux%u %s", c.width, c.height, c.codec == VENC_HEVC ? "HEVC" : "H.264");
return -1;
}
vn_log("encoding %ux%u at %u/%u fps, %u kbit/s %s, %s", c.width, c.height, c.fps_den, c.fps_num,
c.bitrate / 1000, c.vbr ? "VBR" : "CBR", c.codec == VENC_HEVC ? "HEVC" : "H.264");
v->configured = 1;
v->sent_bitrate = (int)v->bitrate;
return 0;
}
static void vn_pump(struct venc *v) {
while (v->raw.streaming && v->coded.streaming && v->raw.nqueued > 0 && v->coded.nqueued > 0) {
struct vq_item in = v->raw.queued[0], out = v->coded.queued[0];
memmove(v->raw.queued, v->raw.queued + 1, --v->raw.nqueued * sizeof in);
memmove(v->coded.queued, v->coded.queued + 1, --v->coded.nqueued * sizeof out);
int ok = v->configured || vn_configure(v) == 0;
if (ok && v->sent_bitrate != (int)v->bitrate) {
struct venc_bitrate b = { .type = VENC_BITRATE, .bitrate = v->bitrate };
if (vn_send(v, &b, sizeof b, NULL, 0) == 0) v->sent_bitrate = (int)v->bitrate;
}
struct venc_frame f = {
.type = VENC_FRAME, .input = in.index, .output = out.index, .bytes = in.bytes,
.keyframe = (uint32_t)v->force_key,
.pts_us = (int64_t)in.timestamp.tv_sec * 1000000 + in.timestamp.tv_usec,
};
struct venc_done d = { 0 };
ok = ok && vn_send(v, &f, sizeof f, NULL, 0) == 0 &&
recv(v->fd, &d, sizeof d, 0) == (ssize_t)sizeof d && d.type == VENC_DONE && d.status == 0;
if (!ok) vn_log("frame %u was not encoded (%s)", v->sequence, strerror(errno));
v->force_key = 0;
in.flags = V4L2_BUF_FLAG_DONE;
out.bytes = ok ? d.bytes : 0;
out.flags = V4L2_BUF_FLAG_DONE | (ok ? (d.keyframe ? V4L2_BUF_FLAG_KEYFRAME : V4L2_BUF_FLAG_PFRAME) : V4L2_BUF_FLAG_ERROR);
out.timestamp = in.timestamp;
in.sequence = out.sequence = v->sequence++;
v->raw.done[v->raw.ndone++] = in;
v->coded.done[v->coded.ndone++] = out;
}
}
static void vn_fill_format(struct venc *v, struct v4l2_format *f) {
if (is_mplane(f->type)) {
struct v4l2_pix_format_mplane *p = &f->fmt.pix_mp;
memset(p, 0, sizeof *p);
p->width = v->width;
p->height = v->height;
p->field = V4L2_FIELD_NONE;
p->num_planes = 1;
p->colorspace = V4L2_COLORSPACE_REC709;
if (is_raw(f->type)) {
p->pixelformat = V4L2_PIX_FMT_NV12;
p->plane_fmt[0].bytesperline = v->stride;
p->plane_fmt[0].sizeimage = v->raw_size;
} else {
p->pixelformat = v->coded_fourcc;
p->plane_fmt[0].sizeimage = v->coded_size;
}
} else {
struct v4l2_pix_format *p = &f->fmt.pix;
memset(p, 0, sizeof *p);
p->width = v->width;
p->height = v->height;
p->field = V4L2_FIELD_NONE;
p->colorspace = V4L2_COLORSPACE_REC709;
p->pixelformat = is_raw(f->type) ? V4L2_PIX_FMT_NV12 : v->coded_fourcc;
p->bytesperline = is_raw(f->type) ? v->stride : 0;
p->sizeimage = is_raw(f->type) ? v->raw_size : v->coded_size;
}
}
static int vn_set_format(struct venc *v, struct v4l2_format *f, int apply) {
uint32_t w, h, fourcc, stride, size;
if (is_mplane(f->type)) {
w = f->fmt.pix_mp.width; h = f->fmt.pix_mp.height; fourcc = f->fmt.pix_mp.pixelformat;
stride = f->fmt.pix_mp.plane_fmt[0].bytesperline; size = f->fmt.pix_mp.plane_fmt[0].sizeimage;
} else if (is_raw(f->type) || is_coded(f->type)) {
w = f->fmt.pix.width; h = f->fmt.pix.height; fourcc = f->fmt.pix.pixelformat;
stride = f->fmt.pix.bytesperline; size = f->fmt.pix.sizeimage;
} else {
return -EINVAL;
}
struct venc t = *v;
if (w >= 64 && h >= 64 && w <= 4096 && h <= 4096) {
t.width = (w + 1) & ~1u;
t.height = (h + 1) & ~1u;
t.crop_w = t.width;
t.crop_h = t.height;
}
if (is_raw(f->type)) {
t.stride = stride;
} else {
t.coded_fourcc = fourcc == V4L2_PIX_FMT_HEVC ? V4L2_PIX_FMT_HEVC : V4L2_PIX_FMT_H264;
t.coded_size = size;
}
vn_sizes(&t);
if (apply) {
if (t.width != v->width || t.height != v->height || t.coded_fourcc != v->coded_fourcc) v->configured = 0;
*v = t;
}
vn_fill_format(&t, f);
return 0;
}
static int vn_reqbufs(struct venc *v, struct v4l2_requestbuffers *r) {
struct vq *q = vn_queue(v, r->type);
if (q == NULL) return -EINVAL;
if (r->memory != V4L2_MEMORY_MMAP) return -EINVAL;
vn_free_queue(q);
v->configured = 0;
uint32_t n = r->count > VENC_MAX_BUFFERS ? VENC_MAX_BUFFERS : r->count;
uint32_t size = is_raw(r->type) ? v->raw_size : v->coded_size;
for (uint32_t i = 0; i < n; i++) {
int fd = memfd_create("droiddeck-venc", MFD_CLOEXEC);
if (fd < 0 || ftruncate(fd, size) != 0) {
if (fd >= 0) close(fd);
vn_free_queue(q);
return -ENOMEM;
}
q->bufs[i].memfd = fd;
q->bufs[i].size = size;
q->count = i + 1;
}
r->count = n;
#ifdef V4L2_BUF_CAP_SUPPORTS_MMAP
r->capabilities = V4L2_BUF_CAP_SUPPORTS_MMAP;
#endif
return 0;
}
static long vn_offset(struct v4l2_buffer *b) {
return (is_raw(b->type) ? 0 : VENC_CAPTURE_OFFSET) + (long)(b->index + 1) * VENC_OFFSET_STEP;
}
static void vn_describe(struct venc *v, struct v4l2_buffer *b, const struct vq_item *item) {
struct vq *q = vn_queue(v, b->type);
uint32_t size = q->bufs[b->index].size;
b->memory = V4L2_MEMORY_MMAP;
b->field = V4L2_FIELD_NONE;
b->flags = V4L2_BUF_FLAG_MAPPED | (item ? item->flags : 0);
if (item) {
b->timestamp = item->timestamp;
b->sequence = item->sequence;
}
if (is_mplane(b->type)) {
if (b->m.planes == NULL || b->length < 1) return;
b->length = 1;
b->m.planes[0].length = size;
b->m.planes[0].m.mem_offset = (uint32_t)vn_offset(b);
b->m.planes[0].data_offset = 0;
if (item) b->m.planes[0].bytesused = item->bytes;
} else {
b->length = size;
b->m.offset = (uint32_t)vn_offset(b);
if (item) b->bytesused = item->bytes;
}
}
static int vn_qbuf(struct venc *v, struct v4l2_buffer *b) {
struct vq *q = vn_queue(v, b->type);
if (q == NULL || b->index >= q->count || q->nqueued >= VENC_MAX_BUFFERS) return -EINVAL;
struct vq_item item = { .index = b->index, .timestamp = b->timestamp };
if (is_raw(b->type))
item.bytes = is_mplane(b->type) ? (b->m.planes && b->length ? b->m.planes[0].bytesused : 0) : b->bytesused;
if (item.bytes == 0 || item.bytes > q->bufs[b->index].size) item.bytes = q->bufs[b->index].size;
q->queued[q->nqueued++] = item;
vn_describe(v, b, NULL);
b->flags |= V4L2_BUF_FLAG_QUEUED;
vn_pump(v);
return 0;
}
static int vn_dqbuf(struct venc *v, struct v4l2_buffer *b) {
struct vq *q = vn_queue(v, b->type);
if (q == NULL) return -EINVAL;
if (q->ndone == 0) return -EAGAIN;
struct vq_item item = q->done[0];
memmove(q->done, q->done + 1, --q->ndone * sizeof item);
b->index = item.index;
vn_describe(v, b, &item);
return 0;
}
static void vn_set_control(struct venc *v, uint32_t id, int32_t value) {
switch (id) {
case V4L2_CID_MPEG_VIDEO_BITRATE: if (value > 0) v->bitrate = (uint32_t)value; break;
case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: if (value > 0) v->peak = (uint32_t)value; break;
case V4L2_CID_MPEG_VIDEO_BITRATE_MODE: v->vbr = value == V4L2_MPEG_VIDEO_BITRATE_MODE_VBR; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_GOP_SIZE: v->gop = (uint32_t)value; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_H264_PROFILE: v->h264_profile = value; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_H264_LEVEL: v->h264_level = value; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_HEVC_PROFILE: v->hevc_profile = value; v->configured = 0; break;
case V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME: v->force_key = 1; break;
default: break;
}
}
static int vn_get_control(struct venc *v, uint32_t id, int32_t *value) {
switch (id) {
case V4L2_CID_MPEG_VIDEO_BITRATE: *value = (int32_t)v->bitrate; return 0;
case V4L2_CID_MPEG_VIDEO_BITRATE_PEAK: *value = (int32_t)v->peak; return 0;
case V4L2_CID_MPEG_VIDEO_GOP_SIZE: *value = (int32_t)v->gop; return 0;
default: *value = 0; return 0;
}
}
static int vn_ioctl(struct venc *v, unsigned long req, void *arg) {
switch (req) {
case VIDIOC_QUERYCAP: {
struct v4l2_capability *c = arg;
memset(c, 0, sizeof *c);
strcpy((char *)c->driver, "droiddeck_venc");
strcpy((char *)c->card, "Android MediaCodec");
strcpy((char *)c->bus_info, "platform:droiddeck-venc");
c->version = 0x00060000;
c->device_caps = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_VIDEO_M2M | V4L2_CAP_STREAMING;
c->capabilities = c->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
case VIDIOC_ENUM_FMT: {
struct v4l2_fmtdesc *d = arg;
static const uint32_t coded[] = { V4L2_PIX_FMT_H264, V4L2_PIX_FMT_HEVC };
if (is_raw(d->type) && d->index == 0) {
d->pixelformat = V4L2_PIX_FMT_NV12;
strcpy((char *)d->description, "Y/CbCr 4:2:0");
d->flags = 0;
} else if (is_coded(d->type) && d->index < 2) {
d->pixelformat = coded[d->index];
strcpy((char *)d->description, d->index ? "HEVC" : "H.264");
d->flags = V4L2_FMT_FLAG_COMPRESSED;
} else {
return -EINVAL;
}
return 0;
}
case VIDIOC_ENUM_FRAMESIZES: {
struct v4l2_frmsizeenum *s = arg;
if (s->index != 0) return -EINVAL;
s->type = V4L2_FRMSIZE_TYPE_STEPWISE;
s->stepwise = (struct v4l2_frmsize_stepwise){ 64, 4096, 2, 64, 4096, 2 };
return 0;
}
case VIDIOC_G_FMT: vn_fill_format(v, arg); return 0;
case VIDIOC_S_FMT: return vn_set_format(v, arg, 1);
case VIDIOC_TRY_FMT: return vn_set_format(v, arg, 0);
case VIDIOC_REQBUFS: return vn_reqbufs(v, arg);
case VIDIOC_QUERYBUF: {
struct v4l2_buffer *b = arg;
struct vq *q = vn_queue(v, b->type);
if (q == NULL || b->index >= q->count) return -EINVAL;
vn_describe(v, b, NULL);
return 0;
}
case VIDIOC_QBUF: return vn_qbuf(v, arg);
case VIDIOC_DQBUF: return vn_dqbuf(v, arg);
case VIDIOC_STREAMON:
case VIDIOC_STREAMOFF: {
struct vq *q = vn_queue(v, *(uint32_t *)arg);
if (q == NULL) return -EINVAL;
q->streaming = req == VIDIOC_STREAMON;
if (!q->streaming) q->nqueued = q->ndone = 0;
vn_pump(v);
return 0;
}
case VIDIOC_S_PARM:
case VIDIOC_G_PARM: {
struct v4l2_streamparm *p = arg;
if (!is_raw(p->type)) return req == VIDIOC_G_PARM ? 0 : -EINVAL;
struct v4l2_fract *t = &p->parm.output.timeperframe;
if (req == VIDIOC_S_PARM && t->numerator > 0 && t->denominator > 0) {
v->fps_num = t->numerator;
v->fps_den = t->denominator;
v->configured = 0;
}
p->parm.output.capability = V4L2_CAP_TIMEPERFRAME;
t->numerator = v->fps_num;
t->denominator = v->fps_den;
return 0;
}
case VIDIOC_S_CTRL: {
struct v4l2_control *c = arg;
vn_set_control(v, c->id, c->value);
return 0;
}
case VIDIOC_G_CTRL: {
struct v4l2_control *c = arg;
return vn_get_control(v, c->id, &c->value);
}
case VIDIOC_S_EXT_CTRLS:
case VIDIOC_TRY_EXT_CTRLS:
case VIDIOC_G_EXT_CTRLS: {
struct v4l2_ext_controls *e = arg;
for (uint32_t i = 0; i < e->count && e->controls; i++) {
if (req == VIDIOC_S_EXT_CTRLS) vn_set_control(v, e->controls[i].id, e->controls[i].value);
else if (req == VIDIOC_G_EXT_CTRLS) {
int32_t value;
vn_get_control(v, e->controls[i].id, &value);
e->controls[i].value = value;
}
}
return 0;
}
case VIDIOC_QUERYCTRL: {
struct v4l2_queryctrl *q = arg;
if (q->id & V4L2_CTRL_FLAG_NEXT_CTRL) return -EINVAL;
q->type = V4L2_CTRL_TYPE_INTEGER;
q->minimum = 0;
q->maximum = 0x7fffffff;
q->step = 1;
q->flags = 0;
return 0;
}
case VIDIOC_S_SELECTION:
case VIDIOC_G_SELECTION: {
struct v4l2_selection *s = arg;
if (req == VIDIOC_S_SELECTION && s->r.width >= 64 && s->r.height >= 64 &&
s->r.width <= v->width && s->r.height <= v->height) {
v->crop_w = s->r.width & ~1u;
v->crop_h = s->r.height & ~1u;
v->configured = 0;
}
s->r = (struct v4l2_rect){ 0, 0, v->crop_w, v->crop_h };
return 0;
}
case VIDIOC_SUBSCRIBE_EVENT:
case VIDIOC_UNSUBSCRIBE_EVENT:
case VIDIOC_ENCODER_CMD:
case VIDIOC_TRY_ENCODER_CMD:
return 0;
case VIDIOC_DQEVENT:
return -ENOENT;
default: {
static unsigned long logged[32];
int seen = 0;
for (int i = 0; i < 32 && logged[i]; i++) seen |= logged[i] == req;
for (int i = 0; i < 32 && !seen; i++) if (!logged[i]) { logged[i] = req; break; }
if (!seen) vn_log("unhandled ioctl 0x%lx", req);
return -ENOTTY;
}
}
}
__attribute__((visibility("hidden"))) int bl_venc_ioctl(int fd, unsigned long req, void *arg, int *rc) {
struct venc *v = vn_find(fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vn_lock);
int r = arg ? vn_ioctl(v, req, arg) : -EFAULT;
pthread_mutex_unlock(&vn_lock);
if (r < 0) {
errno = -r;
*rc = -1;
} else {
*rc = 0;
}
return 1;
}
__attribute__((visibility("hidden"))) int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
void *(*real)(void *, size_t, int, int, int, off_t), void **out) {
struct venc *v = vn_find(fd);
if (v == NULL) return 0;
pthread_mutex_lock(&vn_lock);
struct vq *q = off >= VENC_CAPTURE_OFFSET ? &v->coded : &v->raw;
long index = (off - (off >= VENC_CAPTURE_OFFSET ? VENC_CAPTURE_OFFSET : 0)) / VENC_OFFSET_STEP - 1;
int memfd = index >= 0 && index < (long)q->count ? q->bufs[index].memfd : -1;
pthread_mutex_unlock(&vn_lock);
if (memfd < 0) {
errno = EINVAL;
*out = MAP_FAILED;
} else {
*out = real(addr, len, prot, (flags & ~MAP_PRIVATE) | MAP_SHARED, memfd, 0);
}
return 1;
}
__attribute__((visibility("hidden"))) void bl_venc_closed(int fd) {
struct venc *v = vn_find(fd);
if (v == NULL) return;
pthread_mutex_lock(&vn_lock);
vn_free_queue(&v->raw);
vn_free_queue(&v->coded);
v->used = 0;
/* A forked child closing its inherited copy must not end the stream for the parent. */
if (__atomic_sub_fetch(&vn_open_count, 1, __ATOMIC_RELEASE) == 0 && v->owner == getpid()) vn_marker(0);
pthread_mutex_unlock(&vn_lock);
}
static short vn_ready(struct venc *v) {
pthread_mutex_lock(&vn_lock);
short r = (v->coded.ndone ? POLLIN | POLLRDNORM : 0) | (v->raw.ndone ? POLLOUT | POLLWRNORM : 0);
pthread_mutex_unlock(&vn_lock);
return r;
}
static int vn_poll(struct pollfd *fds, nfds_t n, int timeout_ms, int (*real)(struct pollfd *, nfds_t, int)) {
int ours = 0, ready = 0;
int saved[64];
if (n > 64) return real(fds, n, timeout_ms);
for (nfds_t i = 0; i < n; i++) {
saved[i] = fds[i].fd;
struct venc *v = vn_find(fds[i].fd);
if (v == NULL) continue;
ours++;
fds[i].revents = vn_ready(v) & (fds[i].events | POLLERR);
if (fds[i].revents) ready++;
fds[i].fd = -1;
}
if (ours == 0) return real(fds, n, timeout_ms);
if (ready || timeout_ms < 0 || timeout_ms > 100) timeout_ms = ready ? 0 : 100;
short keep[64];
for (nfds_t i = 0; i < n; i++) keep[i] = fds[i].fd < 0 && saved[i] >= 0 ? fds[i].revents : 0;
int r = n - ours > 0 ? real(fds, n, timeout_ms) : (timeout_ms && !ready ? real(NULL, 0, timeout_ms) : 0);
if (r < 0) r = 0;
for (nfds_t i = 0; i < n; i++) {
if (fds[i].fd < 0 && saved[i] >= 0) fds[i].revents = keep[i];
fds[i].fd = saved[i];
}
return r + ready;
}
int poll(struct pollfd *fds, nfds_t n, int timeout_ms) {
static int (*real)(struct pollfd *, nfds_t, int);
if (!real) real = (int (*)(struct pollfd *, nfds_t, int))dlsym(RTLD_NEXT, "poll");
if (__atomic_load_n(&vn_open_count, __ATOMIC_ACQUIRE) == 0) return real(fds, n, timeout_ms);
return vn_poll(fds, n, timeout_ms, real);
}
+55
View File
@@ -0,0 +1,55 @@
#define _GNU_SOURCE
#define _FILE_OFFSET_BITS 64
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <sys/uio.h>
#include <unistd.h>
typedef ssize_t (*vm_writev_fn)(pid_t, const struct iovec *, unsigned long, const struct iovec *, unsigned long,
unsigned long);
static int in_wineserver(void) {
static int known = -1;
if (known < 0) {
char exe[512];
ssize_t n = readlink("/proc/self/exe", exe, sizeof exe - 1);
exe[n > 0 ? n : 0] = 0;
const char *name = strrchr(exe, '/');
known = !strcmp(name ? name + 1 : exe, "wineserver");
}
return known;
}
ssize_t process_vm_writev(pid_t pid, const struct iovec *local, unsigned long liovcnt, const struct iovec *remote,
unsigned long riovcnt, unsigned long flags) {
static vm_writev_fn real;
if (!real) real = (vm_writev_fn)dlsym(RTLD_NEXT, "process_vm_writev");
if (!real) {
errno = ENOSYS;
return -1;
}
ssize_t result = real(pid, local, liovcnt, remote, riovcnt, flags);
if (result >= 0 || errno != EFAULT || liovcnt != 1 || riovcnt != 1 || flags || !in_wineserver()) return result;
struct iovec ends[2];
struct iovec into = {ends, sizeof ends};
struct iovec from[2] = {{(void *)local, sizeof *local}, {(void *)remote, sizeof *remote}};
if (process_vm_readv(getpid(), &into, 1, from, 2, 0) != (ssize_t)sizeof ends || ends[0].iov_len != ends[1].iov_len) {
errno = EFAULT;
return -1;
}
char path[32];
snprintf(path, sizeof path, "/proc/%d/mem", (int)pid);
int fd = open(path, O_WRONLY | O_CLOEXEC);
if (fd < 0) {
errno = EFAULT;
return -1;
}
ssize_t written = pwrite(fd, ends[0].iov_base, ends[0].iov_len, (off_t)(uintptr_t)ends[1].iov_base);
close(fd);
if (written < 0) errno = EFAULT;
return written;
}
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env bash
# Builds the add-on packs the app downloads on first use instead of shipping in the APK:
# proot.tar.zst the patched proot and its loader (built by tools/proot)
# directaudio.tar.zst the Wine DirectAudio drivers (fetched by tools/directaudio/fetch.sh)
# tracking.tar.zst hand-tracking models and the OpenCV/MediaPipe native libraries
# xbox.tar.zst the Xbox backend (built by tools/xbox) for /usr/local/lib/droiddeck-xbox
# comet.tar.zst the GOG Galaxy companion (built by tools/comet) for /usr/local/lib/droiddeck-comet
# Only CI publishes these (.github/workflows/publish-packs.yml); the APK built from the same
# directory pins each pack's SHA-256.
# Usage: tools/packs/build.sh <out-dir>
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
repo=$(cd "$here/../.." && pwd)
out=${1:?usage: build.sh <out-dir>}
mkdir -p "$out"
out=$(cd "$out" && pwd)
linuxfs="$repo/app/src/main/assets/linuxfs/usr/local/lib"
# shellcheck source=tracking/release.env
source "$here/tracking/release.env"
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
sha256() { if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi; }
fetch() {
local url=$1 expected=$2 dest=$3
curl -fsSL --retry 4 -o "$dest" "$url"
local actual
actual=$(sha256 "$dest")
if [ "$actual" != "$expected" ]; then
echo "checksum mismatch for $url: $actual" >&2
exit 1
fi
}
pack() {
local name=$1 src=$2
shift 2
for required in "$@"; do
[ -f "$src/$required" ] || { echo "$name pack: $src/$required is missing" >&2; exit 1; }
done
python3 -I - "$src" "$work/$name.tar" <<'EOF'
import os, sys, tarfile
src, dest = sys.argv[1], sys.argv[2]
files = []
for base, dirs, names in os.walk(src):
dirs.sort()
for name in names:
path = os.path.join(base, name)
if os.path.islink(path) or not os.path.isfile(path):
sys.exit(f"{path}: only regular files can be packed")
files.append(os.path.relpath(path, src))
with tarfile.open(dest, "w", format=tarfile.USTAR_FORMAT) as tar:
for rel in sorted(files):
path = os.path.join(src, rel)
info = tar.gettarinfo(path, arcname=rel)
info.mtime, info.uid, info.gid, info.uname, info.gname = 0, 0, 0, "", ""
info.mode = 0o755 if os.stat(path).st_mode & 0o111 else 0o644
with open(path, "rb") as f:
tar.addfile(info, f)
EOF
zstd -q -19 -f "$work/$name.tar" -o "$out/$name.tar.zst"
echo "$name $(sha256 "$out/$name.tar.zst") $(wc -c < "$out/$name.tar.zst" | tr -d ' ')"
}
mkdir "$work/tracking"
fetch "https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task" \
fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1 "$work/tracking/hand_landmarker.task"
fetch "https://storage.googleapis.com/mediapipe-models/pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task" \
59929e1d1ee95287735ddd833b19cf4ac46d29bc7afddbbf6753c459690d574a "$work/tracking/pose_landmarker_lite.task"
cp "$here/tracking/hand_landmarker_lite.task" "$work/tracking/"
[ "$(sha256 "$work/tracking/hand_landmarker_lite.task")" = 173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8 ] || {
echo "checksum mismatch for hand_landmarker_lite.task" >&2; exit 1; }
fetch "https://repo1.maven.org/maven2/org/opencv/opencv/${OPENCV_VERSION}/opencv-${OPENCV_VERSION}.aar" \
"$OPENCV_AAR_SHA256" "$work/opencv.aar"
fetch "https://dl.google.com/dl/android/maven2/com/google/mediapipe/tasks-core/${MEDIAPIPE_VERSION}/tasks-core-${MEDIAPIPE_VERSION}.aar" \
"$MEDIAPIPE_AAR_SHA256" "$work/tasks-core.aar"
unzip -q -j "$work/opencv.aar" jni/arm64-v8a/libopencv_java4.so -d "$work/tracking"
unzip -q -j "$work/tasks-core.aar" jni/arm64-v8a/libmediapipe_tasks_jni.so -d "$work/tracking"
chmod 0644 "$work/tracking"/*
mkdir "$work/proot"
install -m755 "$repo/app/src/main/jniLibs/arm64-v8a/libproot.so" "$repo/app/src/main/jniLibs/arm64-v8a/libproot-loader.so" "$work/proot/"
pack proot "$work/proot" libproot.so libproot-loader.so
pack directaudio "$repo/app/src/main/assets/directaudio" \
linux-wine11/version.txt linux-wine11-systhread/version.txt
pack tracking "$work/tracking" hand_landmarker.task hand_landmarker_lite.task pose_landmarker_lite.task \
libopencv_java4.so libmediapipe_tasks_jni.so
pack xbox "$linuxfs/droiddeck-xbox" version xodus-cli xodus-service
pack comet "$linuxfs/droiddeck-comet" version comet
@@ -0,0 +1,9 @@
{
"url": "https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task",
"sha256": "fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1",
"bytes": 7819105,
"mediapipe": "com.google.mediapipe:tasks-vision:1.0.0",
"opencv": "org.opencv:opencv:4.13.0",
"documentation": "https://ai.google.dev/edge/mediapipe/solutions/vision/hand_landmarker",
"runtime": "Two video-mode instances; CPU default; GPU requires separate performance acceptance"
}
@@ -0,0 +1,12 @@
{
"sha256": "173c0f47ecee7e935bd4a1e93aa580756b4180c1307c07d709313e82c28672c8",
"composition": "Lite palm detector and lite hand landmarks with matching Tasks tensor metadata and associated files from the full bundle",
"palm_source": "https://storage.googleapis.com/mediapipe-assets/palm_detection_lite.tflite",
"palm_source_sha256": "e9a4aaddf90dda56a87235303cf00e4c2d3fb28725f68fd88772997dac905c18",
"landmark_source": "https://storage.googleapis.com/mediapipe-assets/hand_landmark_lite.tflite",
"landmark_source_sha256": "d7fde8ac11f8ce03f8663775bfc323f4fc9f2a38062b4f4efa142874ef5b2a48",
"metadata_source": "hand_landmarker.task",
"metadata_source_sha256": "fbc2a30080c3c557093b5ddfc334698132eb341044ccee322ccf8bcf3607cde1",
"builder": "tools/build_hand_lite.py; mediapipe==0.10.21; deterministic ZIP_STORED bundle and embedded associated-file archives",
"runtime": "com.google.mediapipe:tasks-vision:1.0.0; CPU by default; experimental stereo hand and wrist tracking"
}
Binary file not shown.
+4
View File
@@ -0,0 +1,4 @@
OPENCV_VERSION=4.13.0
OPENCV_AAR_SHA256=a8c9b0929d8d6367bb476320a1f36587db2b57ea18d8f7521ce509514903ca04
MEDIAPIPE_VERSION=1.0.0
MEDIAPIPE_AAR_SHA256=609c6fcfe59f58c9739194f65ae5882281c327710e1a616aa7f533a4d9238ca3
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
# assemble.sh <extracted packages root> <out.tzst>
# Packs the video side of SteamOS's PipeWire and WirePlumber: no audio plugins, no JACK.
set -euo pipefail
src=$1
out=$2
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT
b=$work/bundle
mkdir -p "$b/bin" "$b/lib/pipewire-0.3" "$b/lib/spa-0.2" "$b/lib/wireplumber-0.5" "$b/share/licenses"
for tool in pipewire wireplumber wpctl; do cp "$src/usr/bin/$tool" "$b/bin/$tool"; done
for library in libpipewire-0.3.so.0 libwireplumber-0.5.so.0; do cp -L "$src/usr/lib/$library" "$b/lib/$library"; done
for module in "$src"/usr/lib/pipewire-0.3/libpipewire-module-*.so; do
case ${module##*/} in *jack*) continue ;; esac
cp "$module" "$b/lib/pipewire-0.3/"
done
cp "$src/usr/lib/spa-0.2/libspa.so" "$b/lib/spa-0.2/"
for plugin in support control videoconvert v4l2; do cp -R "$src/usr/lib/spa-0.2/$plugin" "$b/lib/spa-0.2/$plugin"; done
cp "$src"/usr/lib/wireplumber-0.5/*.so "$b/lib/wireplumber-0.5/"
mkdir -p "$b/share/pipewire"
cp "$src/usr/share/pipewire/pipewire.conf" "$src/usr/share/pipewire/client.conf" "$b/share/pipewire/"
cp -R "$src/usr/share/wireplumber" "$b/share/wireplumber"
for package in pipewire libpipewire wireplumber libwireplumber; do
cp -R "$src/usr/share/licenses/$package" "$b/share/licenses/$package"
done
mkdir -p "$(dirname "$out")"
(cd "$b" && find . -type f | LC_ALL=C sort | tar -cf - -T -) | zstd -19 -q -f -o "$out"
+4
View File
@@ -0,0 +1,4 @@
55c9705ff5721f10ca18c42bd15c14b0af88cb5352f5400fda04c944a8b224f1 https://holo-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.4.x/libpipewire-1%3A1.6.8-1.2-aarch64.pkg.tar.zst
8ea2d900326eaafdd2bbbfa47fa04f5d7515dbdcd9ede04213ba149f44f41da0 https://holo-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.4.x/pipewire-1%3A1.6.8-1.2-aarch64.pkg.tar.zst
900a4c59f87806d85abe200bb014d755f73a16b2ba4fea63d6f32ff64fcf5e34 https://holo-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.4.x/libwireplumber-0.5.14-1.3-aarch64.pkg.tar.zst
bf56f040cf09832e0a8135b56b0f6d2b9b29e2bddbd35be73d0bebe603eacafb https://holo-packages.steamos.cloud/archlinux-deckard-hotfixes/release/0.4.x/wireplumber-0.5.14-1.3-aarch64.pkg.tar.zst
+7
View File
@@ -55,6 +55,13 @@ Added for Flatpak:
`linkat` fails with `EACCES` and Flatpak could not create its repo (`Creating repo: linkat:
Permission denied`). `O_TMPFILE` answers `EOPNOTSUPP`, so libglnx writes a named temporary file
and renames it, and a denied link answers `EPERM`, on which ostree's checkout copies instead.
- `0017-android-execstack-denial.patch` - the same policy denies apps executable stacks, so the
`mprotect(PROT_READ | PROT_WRITE | PROT_EXEC | PROT_GROWSDOWN)` with which `ld.so` makes the main
stack executable for an object whose `PT_GNU_STACK` asks for it fails with `EACCES`, and the
program stops before `main` ("cannot enable executable stack as shared object requires:
Permission denied", `libQt5Gui.so.5` in ONLYOFFICE's Flatpak). The filter traces `mprotect` only
for that exact request, and a denied one answers success: the stack stays non-executable, as
Android keeps it anyway, and objects that only carry the flag load.
Added by DroidDeck:
- `0011-kompat-utsname-only.patch` - `--kernel-release` (the guest's `DroidDeck` hostname) loads
+31 -9
View File
@@ -141,24 +141,46 @@ static int traced_by_match(const char *key) {
return found;
}
static long init_sys(long nr, long a, long b, long c) {
static long (*real_syscall)(long, ...);
if (!real_syscall) real_syscall = (long (*)(long, ...))dlsym(RTLD_NEXT, "syscall");
return real_syscall(nr, a, b, c);
}
static int program_32bit(const char *prog, int scripts) {
char head[256];
long fd = init_sys(SYS_openat, AT_FDCWD, (long)prog, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 1;
long n = init_sys(SYS_read, fd, (long)head, sizeof head - 1);
init_sys(SYS_close, fd, 0, 0);
if (n < 0) return 1;
head[n] = 0;
if (n >= 2 && head[0] == '#' && head[1] == '!') {
if (scripts <= 0) return 1;
char *p = head + 2;
while (*p == ' ' || *p == '\t') p++;
char *e = p;
while (*e && *e != ' ' && *e != '\t' && *e != '\n' && *e != '\r') e++;
if (e == p || (!*e && n == (long)sizeof head - 1)) return 1;
*e = 0;
return program_32bit(p, scripts - 1);
}
return !(n >= 5 && memcmp(head, "\x7f" "ELF", 4) == 0 && head[4] == 2);
}
static int fex_runs_32bit(void) {
if (strcmp(program_invocation_short_name, "FEX") != 0 && strcmp(program_invocation_short_name, "FEXInterpreter") != 0)
return 0;
char args[PATH_MAX + 64];
long fd = syscall(SYS_openat, AT_FDCWD, "/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
long fd = init_sys(SYS_openat, AT_FDCWD, (long)"/proc/self/cmdline", O_RDONLY | O_CLOEXEC);
if (fd < 0) return 1;
long n = syscall(SYS_read, fd, args, sizeof args - 1);
syscall(SYS_close, fd);
long n = init_sys(SYS_read, fd, (long)args, sizeof args - 1);
init_sys(SYS_close, fd, 0, 0);
if (n <= 0) return 1;
args[n] = 0;
const char *prog = args + strlen(args) + 1;
if (prog >= args + n || !*prog) return 1;
unsigned char ident[5];
fd = syscall(SYS_openat, AT_FDCWD, prog, O_RDONLY | O_CLOEXEC);
if (fd < 0) return 1;
n = syscall(SYS_read, fd, ident, sizeof ident);
syscall(SYS_close, fd);
return !(n == 5 && memcmp(ident, "\x7f" "ELF", 4) == 0 && ident[4] == 2);
return program_32bit(prog, 4);
}
static int in_tracer(struct bind *bd) {
@@ -0,0 +1,82 @@
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
From: DroidDeck <noreply@droiddeck.invalid>
Date: Tue, 20 Oct 2026 12:00:00 -0400
Subject: [PATCH] syscall: work around Android's denial of executable stacks
SELinux denies apps the execstack permission, so the mprotect with
which ld.so makes the main stack executable for an object whose
PT_GNU_STACK asks for it fails with EACCES, and the program does not
start ("cannot enable executable stack as shared object requires:
Permission denied", libQt5Gui.so.5 in ONLYOFFICE's Flatpak). The
filter traces mprotect only for that exact request, and a denied one
answers success: the stack stays non-executable, as Android keeps it.
---
diff --git a/src/syscall/exit.c b/src/syscall/exit.c
index e87b7e1..71b36f5 100644
--- a/src/syscall/exit.c
+++ b/src/syscall/exit.c
@@ -25,6 +25,7 @@
#include <linux/net.h> /* SYS_*, */
#include <linux/ioctl.h> /* _IOW, */
#include <string.h> /* strlen(3), */
+#include <sys/mman.h> /* PROT_*, */
#include "cli/note.h"
#include "syscall/syscall.h"
@@ -552,6 +553,13 @@ void translate_syscall_exit(Tracee *tracee)
if ((int) syscall_result == -EACCES)
poke_reg(tracee, SYSARG_RESULT, -EPERM);
goto end;
+
+ case PR_mprotect:
+ if ((int) syscall_result == -EACCES
+ && (peek_reg(tracee, ORIGINAL, SYSARG_3) & (PROT_EXEC | PROT_GROWSDOWN))
+ == (PROT_EXEC | PROT_GROWSDOWN))
+ poke_reg(tracee, SYSARG_RESULT, 0);
+ goto end;
#endif
case PR_ioctl:
diff --git a/src/syscall/seccomp.c b/src/syscall/seccomp.c
index d9be7b4..fca220b 100644
--- a/src/syscall/seccomp.c
+++ b/src/syscall/seccomp.c
@@ -46,6 +46,7 @@
#include <asm/termbits.h>
#include <linux/fs.h>
#include <assert.h> /* assert(3), */
+#include <sys/mman.h> /* PROT_*, */
#include "syscall/seccomp.h"
#include "tracee/tracee.h"
@@ -316,6 +317,10 @@ static size_t trace_length_raw(Sysnum sysnum)
return LENGTH_TRACE_PRLIMIT_STACK;
case PR_ioctl:
return LENGTH_TRACE_IOCTL;
+#ifdef __ANDROID__
+ case PR_mprotect:
+ return LENGTH_TRACE_SYSCALL_IF_ARG;
+#endif
default:
return LENGTH_TRACE_SYSCALL;
}
@@ -335,6 +340,11 @@ static int add_trace(struct sock_fprog *program, Sysnum sysnum, word_t syscall,
return add_trace_prlimit_stack(program, syscall, flag);
case PR_ioctl:
return add_trace_ioctl_requests(program, syscall, flag);
+#ifdef __ANDROID__
+ case PR_mprotect:
+ return add_trace_syscall_if_arg(program, syscall, 2,
+ PROT_READ | PROT_WRITE | PROT_EXEC | PROT_GROWSDOWN, flag);
+#endif
default:
return add_trace_syscall(program, syscall, flag);
}
@@ -599,6 +609,7 @@ static FilteredSysnum proot_sysnums[] = {
{ PR_lstat64, 0 },
#ifdef __ANDROID__
{ PR_memfd_create, 0 },
+ { PR_mprotect, FILTER_SYSEXIT },
#endif
{ PR_mkdir, 0 },
{ PR_mkdirat, 0 },
+54 -2
View File
@@ -12,13 +12,22 @@ from zipfile import ZipFile
ROOT = Path(__file__).resolve().parents[2]
MANIFEST = Path('app/build/runtime-inputs.json')
PACKS = Path('app/build/packs')
# Runtime trees shipped as add-on packs (tools/packs/build.sh) rather than inside the APK.
PACKED = {'assets/linuxfs/usr/local/lib/droiddeck-xbox/': 'xbox', 'assets/linuxfs/usr/local/lib/droiddeck-comet/': 'comet',
'assets/directaudio/': 'directaudio'}
PACKED_FILES = {'lib/arm64-v8a/libproot.so': ('proot', 'libproot.so'),
'lib/arm64-v8a/libproot-loader.so': ('proot', 'libproot-loader.so')}
PACKED_LIBRARIES = ['lib/arm64-v8a/libopencv_java4.so', 'lib/arm64-v8a/libmediapipe_tasks_jni.so']
PACK_NAMES = ['proot', 'directaudio', 'tracking', 'xbox', 'comet']
SOURCE_PATHS = ['app/build.gradle', 'app/src/main/cpp/fakeinput_steam.cpp', 'app/src/main/assets/pulseaudio.tzst',
'tools/linuxfs', 'tools/proot', 'tools/aaudio-sink', 'tools/directaudio',
'tools/gamescope/release.env', 'tools/droiddeck-esync/release.env',
'tools/mangoapp', 'tools/msitools', 'tools/comet', 'tools/build_local.sh',
'tools/mangoapp', 'tools/msitools', 'tools/pipewire', 'tools/comet', 'tools/xbox', 'tools/build_local.sh',
'tools/release/runtime_inputs.py', 'app/src/main/assets/desktop-removal',
'tools/quest', 'tools/vr/src', 'tools/vr/driver_droiddeck', 'tools/vr/layer', 'tools/vr/build.sh',
'app/src/main/cpp/waylandcomp/src/headpose_shm.h',
'app/src/main/cpp/venc/venc_proto.h',
'app/src/main/cpp/waylandcomp/src/spatialpose_shm.h',
'app/src/main/cpp/adrenotools/src/hook/kgsl.h',
'app/src/main/assets/graphics_driver/adrenotools-turnip25.1.0.tzst']
@@ -67,7 +76,8 @@ def required():
for name in ['turnip26.3.0-a6xx', 'turnip26.3.0-quest2']]
paths += ['assets/linuxfs/' + name for name in ['libfakeinput.so', 'libblsession.so',
'libblfastpath.so', 'libssbs.so', 'usr/local/bin/droiddeck-clipboard',
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime']]
'usr/local/bin/gamescope', 'usr/local/lib/droiddeck/uruntime',
'usr/local/lib/droiddeck-pipewire.tzst']]
for arch in ['x86_64', 'i386']:
paths += ['assets/linuxfs/' + arch + '/' + lib for lib in ['libfakeinput.so', 'libblsession.so']]
paths += ['assets/linuxfs/x86_64/' + lib for lib in
@@ -89,6 +99,9 @@ def required():
['mangoapp', 'libfmt.so.10', 'libspdlog.so.1.13', 'libglfw.so.3', 'libtraceevent.so.1', 'libtracefs.so.1']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-comet/' + name for name in
['comet', 'GalaxyCommunication.exe', 'update-permissions.exe', 'LICENSE', 'version']]
paths += ['assets/linuxfs/usr/local/lib/droiddeck-xbox/' + name for name in
['xodus-cli', 'xodus-service', 'version', 'backend.lock.json', 'runtime.lock.json', 'LICENSE.xodus', 'LICENSE.nexus', 'LICENSE.LGPL-2.1', 'LICENSE.nghttp2',
'windows/xgameruntime.dll', 'windows/winhttp.dll', 'windows/windows.web.dll', 'windows/twinapi.appcore.dll', 'windows/libnghttp2.dll']]
for driver in ['linux-wine11', 'linux-wine11-systhread']:
paths += ['assets/directaudio/' + driver + '/' + name for name in
['aarch64-unix/winedirectaudio.so', 'aarch64-windows/winedirectaudio.drv',
@@ -154,10 +167,49 @@ def verify(root=ROOT):
return data
def pack_digests(root, name):
path = root / PACKS / (name + '.tar.zst')
if not path.is_file():
raise ValueError('Missing add-on pack ' + name + '. Run tools/packs/build.sh app/build/packs.')
process = subprocess.Popen(['zstd', '-dc', str(path)], stdout=subprocess.PIPE)
digests = {}
try:
with tarfile.open(fileobj=process.stdout, mode='r|') as archive:
for member in archive:
if member.isfile():
digests[member.name] = hashlib.sha256(archive.extractfile(member).read()).hexdigest()
finally:
process.stdout.close()
if process.wait():
raise ValueError('Invalid add-on pack ' + name)
return digests
def check_apk(apk, root=ROOT):
data = verify(root)
packs = {name: pack_digests(root, name) for name in PACK_NAMES}
with ZipFile(apk) as package:
names = set(package.namelist())
for library in PACKED_LIBRARIES:
if library in names:
raise ValueError('APK still carries ' + library + ', which the tracking pack provides')
if library.rsplit('/', 1)[1] not in packs['tracking']:
raise ValueError('Tracking pack missing ' + library)
for name, output in data['outputs'].items():
if name in PACKED_FILES:
pack, rel = PACKED_FILES[name]
if name in names:
raise ValueError('APK still carries ' + name + ', which the ' + pack + ' pack provides')
if packs[pack].get(rel) != output['sha256']:
raise ValueError('Add-on pack ' + pack + ' is missing or has a stale ' + name)
continue
prefix = next((p for p in PACKED if name.startswith(p)), None)
if prefix:
if name in names:
raise ValueError('APK still carries ' + name + ', which the ' + PACKED[prefix] + ' pack provides')
if packs[PACKED[prefix]].get(name[len(prefix):]) != output['sha256']:
raise ValueError('Add-on pack ' + PACKED[prefix] + ' is missing or has a stale ' + name)
continue
try:
content = package.read(name)
except KeyError:
+88
View File
@@ -0,0 +1,88 @@
#define _GNU_SOURCE
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/wait.h>
#include <unistd.h>
struct note { long mtype; char text[32]; };
static int count_lines(const char *path) {
FILE *f = fopen(path, "r");
if (!f) return -1;
int n = 0, c;
while ((c = fgetc(f)) != EOF) n += c == '\n';
fclose(f);
return n;
}
static void *wait_for_note(void *arg) {
struct note n;
long rc = msgrcv(*(int *)arg, &n, sizeof(n.text), 0, 0);
return (void *)(rc < 0 && errno == EIDRM ? 1L : 0L);
}
int main(void) {
int q = msgget(0x5eed0002, IPC_CREAT | IPC_EXCL | 0600);
if (q < 0) { perror("msgget"); return 1; }
struct note n;
if (msgrcv(q, &n, sizeof(n.text), 0, IPC_NOWAIT) != -1 || errno != ENOMSG) { printf("FAIL: empty queue\n"); return 1; }
pid_t child = fork();
if (child == 0) {
struct note a = {2, "second"}, b = {1, "first"};
return msgsnd(q, &a, sizeof(a.text), 0) || msgsnd(q, &b, sizeof(b.text), 0);
}
int status;
waitpid(child, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status)) { printf("FAIL: child send\n"); return 1; }
if (msgrcv(q, &n, sizeof(n.text), 1, 0) < 0 || n.mtype != 1 || strcmp(n.text, "first")) { printf("FAIL: typed receive\n"); return 1; }
if (msgrcv(q, &n, sizeof(n.text), 0, 0) < 0 || n.mtype != 2 || strcmp(n.text, "second")) { printf("FAIL: any receive\n"); return 1; }
int maps = count_lines("/proc/self/maps");
for (int i = 0; i < 2000; i++) {
struct note p = {3, "poll"};
if (msgsnd(q, &p, sizeof(p.text), 0) || msgrcv(q, &n, sizeof(n.text), 0, 0) < 0 ||
msgrcv(q, &n, sizeof(n.text), 0, IPC_NOWAIT) != -1) { printf("FAIL: round %d\n", i); return 1; }
}
if (count_lines("/proc/self/maps") != maps) { printf("FAIL: mappings grew\n"); return 1; }
pthread_t waiter;
pthread_create(&waiter, NULL, wait_for_note, &q);
usleep(100000);
if (msgctl(q, IPC_RMID, NULL) != 0) { perror("msgctl"); return 1; }
void *woken;
pthread_join(waiter, &woken);
if (!woken) { printf("FAIL: waiter not told the queue was removed\n"); return 1; }
if (msgsnd(q, &n, sizeof(n.text), IPC_NOWAIT) != -1) { printf("FAIL: send to a removed queue\n"); return 1; }
int again = msgget(0x5eed0002, IPC_CREAT | 0600);
struct note r = {4, "again"};
if (again < 0 || msgsnd(again, &r, sizeof(r.text), 0) || msgrcv(again, &n, sizeof(n.text), 0, 0) < 0 || strcmp(n.text, "again")) {
printf("FAIL: queue made again after removal\n");
return 1;
}
msgctl(again, IPC_RMID, NULL);
int watched = msgget(0x5eed0003, IPC_CREAT | 0600);
pid_t blocked = fork();
if (blocked == 0) return msgrcv(watched, &n, sizeof(n.text), 0, 0) < 0 && errno == EIDRM ? 0 : 1;
int filler[64];
for (int i = 0; i < 64; i++) {
struct note f = {5, "fill"};
filler[i] = msgget(0x5eed0100 + i, IPC_CREAT | 0600);
if (filler[i] < 0 || msgsnd(filler[i], &f, sizeof(f.text), 0)) { printf("FAIL: filler %d\n", i); return 1; }
}
usleep(100000);
if (msgctl(watched, IPC_RMID, NULL) != 0) { perror("msgctl with a full cache"); return 1; }
waitpid(blocked, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status)) { printf("FAIL: waiter not woken with a full cache\n"); return 1; }
int extra = msgget(0x5eed0200, IPC_CREAT | 0600);
struct note x = {6, "extra"};
if (extra < 0 || msgsnd(extra, &x, sizeof(x.text), 0) || msgrcv(extra, &n, sizeof(n.text), 6, 0) < 0 || strcmp(n.text, "extra")) {
printf("FAIL: queue past a full cache\n");
return 1;
}
msgctl(extra, IPC_RMID, NULL);
for (int i = 0; i < 64; i++) msgctl(filler[i], IPC_RMID, NULL);
printf("PASS: sysv msg\n");
return 0;
}
+36
View File
@@ -0,0 +1,36 @@
import os
import runpy
import shutil
import tempfile
import unittest
from pathlib import Path
from unittest import mock
BWRAP = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-bwrap"
class BwrapSocketTest(unittest.TestCase):
def setUp(self):
self.dir = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.dir, True)
self.shim = runpy.run_path(str(BWRAP))
self.shim["socket_name"].__globals__["SOCKET_FILE"] = str(self.dir / "bwrap-socket")
def name(self, env):
with mock.patch.dict(os.environ, env, clear=True):
return self.shim["socket_name"]()
def test_flatpak_empty_environment_reaches_a_renamed_package(self):
(self.dir / "bwrap-socket").write_text("com.antutu.benchmark.full.bwrap\n")
self.assertEqual("\0com.antutu.benchmark.full.bwrap", self.name({}))
def test_the_environment_still_wins(self):
(self.dir / "bwrap-socket").write_text("com.antutu.benchmark.full.bwrap\n")
self.assertEqual("\0com.tencent.ig.bwrap", self.name({"DROIDDECK_BWRAP_SOCKET": "com.tencent.ig.bwrap"}))
def test_without_either_the_standard_package_is_asked(self):
self.assertEqual("\0com.droiddeck.launcher.bwrap", self.name({}))
if __name__ == "__main__":
unittest.main()
+51
View File
@@ -0,0 +1,51 @@
import re
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[2]
def read(path):
return path.read_text(encoding='utf-8')
BUILD = ROOT / 'tools/desktop-kde/build.sh'
WORKFLOW = ROOT / '.github/workflows/build-desktop-kde.yml'
class DesktopLanguageBuildTest(unittest.TestCase):
def setUp(self):
self.build = read(BUILD)
def test_the_main_package_keeps_english_and_every_other_language_becomes_a_pack(self):
loop = self.build.split('usr/share/locale/*/', 1)[1].split('rm -rf "$work/root/usr/share/doc"', 1)[0]
self.assertIn("case $loc in en*) continue ;; esac", loop)
self.assertIn('[ -d "$dir/LC_MESSAGES" ] || continue', loop)
self.assertIn('desktop-kde-i18n-$loc.tar.zst', loop)
self.assertIn('> "$out/desktop-kde.i18n.txt"', loop)
self.assertIn('find "$work/root/usr/share/locale" -mindepth 1 -maxdepth 1 -type d ! -name \'en*\'',
self.build.split('i18n.txt"', 1)[1])
def test_the_index_lines_carry_what_the_app_verifies(self):
record = re.search(r"printf '%s %s %s\\n' \"\$loc\" \"\$\(sha256sum \"\$file\" \| cut -d' ' -f1\)\" \"\$\(stat -c %s \"\$file\"\)\"",
self.build)
self.assertIsNotNone(record)
line = 'de ' + 'a' * 64 + ' 262144'
fields = line.split()
self.assertEqual(3, len(fields))
self.assertTrue(re.fullmatch(r'[0-9a-f]{64}', fields[1]))
self.assertEqual(262144, int(fields[2]))
def test_the_workflow_ships_the_index_and_the_packs(self):
workflow = read(WORKFLOW)
self.assertIn('out/desktop-kde.i18n.txt', workflow)
self.assertEqual(1, len([line for line in workflow.splitlines()
if line.strip() == 'out/desktop-kde-i18n-*.tar.zst']))
release = workflow.split('gh release create', 1)[1]
self.assertIn('out/desktop-kde.i18n.txt', release)
self.assertIn('out/desktop-kde-i18n-*.tar.zst', release)
if __name__ == '__main__':
unittest.main()
+251
View File
@@ -6,6 +6,7 @@ import importlib.util
import json
import os
from pathlib import Path
import shutil
import socket
import struct
import subprocess
@@ -77,6 +78,79 @@ class FakeDevTools(threading.Thread):
conn.close()
class FakeSteamClient(threading.Thread):
def __init__(self, showing):
super().__init__(daemon=True)
self.showing = showing
self.server = socket.socket()
self.server.bind(("127.0.0.1", 0))
self.server.listen(4)
self.port = self.server.getsockname()[1]
self.seen = []
self.conn = None
self.lock = threading.Lock()
def run(self):
while True:
try:
conn, _ = self.server.accept()
except OSError:
return
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
def send(self, conn, message):
payload = json.dumps(message).encode()
header = bytes([0x81, 126]) + struct.pack(">H", len(payload)) if len(payload) > 125 else bytes([0x81, len(payload)])
with self.lock:
conn.sendall(header + payload)
def push(self, payload, name=None):
self.send(self.conn, {"method": "Runtime.bindingCalled",
"params": {"name": name or agent.KEYBOARD_BINDING, "payload": payload}})
def drop(self):
self.conn.shutdown(socket.SHUT_RDWR)
self.conn.close()
def serve(self, conn):
stream = conn.makefile("rb")
head = b""
while not head.endswith(b"\r\n\r\n"):
head += stream.read(1)
request = head.decode()
if request.startswith("GET /json"):
body = json.dumps([{"title": "Steam Big Picture Mode", "url": "https://steamloopback.host/routes/",
"webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/2" % self.port},
{"title": "SharedJSContext", "url": "https://steamloopback.host/",
"webSocketDebuggerUrl": "ws://127.0.0.1:%d/devtools/page/1" % self.port}]).encode()
conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
conn.close()
return
key = [l.split(":", 1)[1].strip() for l in request.split("\r\n") if l.lower().startswith("sec-websocket-key")][0]
accept = base64.b64encode(hashlib.sha1((key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode()).digest()).decode()
conn.sendall(("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n"
"Sec-WebSocket-Accept: %s\r\n\r\n" % accept).encode())
self.conn = conn
try:
while True:
b0, b1 = stream.read(2)
n = b1 & 0x7F
if n == 126:
n = struct.unpack(">H", stream.read(2))[0]
elif n == 127:
n = struct.unpack(">Q", stream.read(8))[0]
mask = stream.read(4)
data = stream.read(n)
message = json.loads(bytes(b ^ mask[i % 4] for i, b in enumerate(data)))
self.seen.append(message)
self.push("true", name="unrelated")
result = {"result": {"type": "boolean", "value": self.showing}} if message["method"] == "Runtime.evaluate" else {}
self.send(conn, {"id": message["id"], "result": result})
except (OSError, ValueError):
conn.close()
class AgentTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
@@ -338,6 +412,45 @@ class AgentTest(unittest.TestCase):
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
self.assertEqual(1, agent.main(["--steam-asleep"]))
def test_supports_vr_command_separates_vr_flat_and_unknown_apps(self):
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
for value, code in ((True, 0), (False, 5), (None, 1)):
with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask:
self.assertEqual(code, agent.main(["--steam-supports-vr", "204360"]))
self.assertIn('GetAppOverviewByGameID?.("204360")', ask.call_args.args[1])
self.assertIn("vr_supported", ask.call_args.args[1])
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
self.assertEqual(1, agent.main(["--steam-supports-vr", "204360"]))
for bad in ([], ["1;x"], ["-1"], ["1", "2"]):
self.assertEqual(2, agent.main(["--steam-supports-vr"] + bad))
def test_idle_inhibit_command_reports_whether_steam_reached_the_state(self):
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}):
for value, code in ((True, 0), (False, 1), (None, 1)):
with self.subTest(value=value), patch.object(agent, "cdp_eval", return_value={"value": value}) as ask:
self.assertEqual(code, agent.main(["--steam-idle-inhibit", "on"]))
self.assertIn("toggle_idle_suspend_inhibit 1", ask.call_args.args[1])
self.assertTrue(ask.call_args.args[1].rstrip().endswith("(true)"))
with patch.object(agent, "cdp_eval", return_value={"value": True}) as ask:
self.assertEqual(0, agent.main(["--steam-idle-inhibit", "off"]))
self.assertTrue(ask.call_args.args[1].rstrip().endswith("(false)"))
with patch.object(agent, "cdp_eval", side_effect=agent.AgentError("NO_DEVTOOLS", "down")):
self.assertEqual(1, agent.main(["--steam-idle-inhibit", "on"]))
self.assertEqual(2, agent.main(["--steam-idle-inhibit", "maybe"]))
def test_idle_suspend_seconds_follow_the_power_source(self):
vpower = self.dir / "ac_status"
with patch.object(agent, "cdp_eval", return_value={"value": [3600, 900]}):
vpower.write_text("Connected\n")
self.assertEqual(3600, agent.steam_idle_suspend_seconds(self.dir, vpower))
vpower.write_text("Disconnected\n")
self.assertEqual(900, agent.steam_idle_suspend_seconds(self.dir, vpower))
with patch.object(agent, "cdp_eval", return_value={"value": None}):
self.assertIsNone(agent.steam_idle_suspend_seconds(self.dir, vpower))
with patch.dict(os.environ, {"BL_LAUNCH_DIR": str(self.dir.parent)}), \
patch.object(agent, "steam_idle_suspend_seconds", return_value=None):
self.assertEqual(1, agent.main(["--steam-idle-suspend-seconds"]))
def test_cdp_exception(self):
server = FakeDevTools({"result": {"result": {"type": "object"}, "exceptionDetails": {
"text": "Uncaught", "exception": {"description": "ReferenceError: SteamClient is not defined"}}}})
@@ -382,6 +495,144 @@ class AgentTest(unittest.TestCase):
self.assertIn(child.pid, agent.game_pids(424242))
class SteamKeyboardTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.dir = Path(self.temp.name)
def state(self):
try:
return json.loads((self.dir / "keyboard.json").read_text())
except (OSError, ValueError):
return None
def wait_for(self, check):
for _ in range(200):
if check():
return
time.sleep(0.02)
self.fail("timed out; keyboard.json is %s" % self.state())
def test_report_writes_only_changes(self):
watcher = agent.KeyboardWatcher(self.dir)
watcher.report(False)
self.assertEqual({"steamKeyboard": False, "seq": 1}, self.state())
watcher.report(False)
watcher.report(True)
self.assertEqual({"steamKeyboard": True, "seq": 2}, self.state())
def test_follows_the_clients_keyboard_and_rechecks_while_idle(self):
client = FakeSteamClient(False)
client.start()
self.addCleanup(client.server.close)
(self.dir / "cdp-port").write_text(str(client.port))
watcher = agent.KeyboardWatcher(self.dir)
failure = []
with patch.object(agent, "KEYBOARD_CHECK_SECONDS", 0.3):
thread = threading.Thread(target=lambda: failure.append(self.capture(watcher.watch)), daemon=True)
thread.start()
self.wait_for(lambda: self.state() == {"steamKeyboard": False, "seq": 1})
self.assertEqual("Runtime.addBinding", client.seen[0]["method"])
self.assertEqual(agent.KEYBOARD_BINDING, client.seen[0]["params"]["name"])
self.assertIn("IsShowingVirtualKeyboard", client.seen[1]["params"]["expression"])
self.assertIn(agent.KEYBOARD_BINDING, client.seen[1]["params"]["expression"])
self.assertNotIn("__BINDING__", client.seen[1]["params"]["expression"])
client.push("true")
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is True)
client.push("false")
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is False)
client.showing = True
self.wait_for(lambda: (self.state() or {}).get("steamKeyboard") is True)
self.assertGreaterEqual(len([m for m in client.seen if m["method"] == "Runtime.evaluate"]), 2)
client.drop()
thread.join(5)
self.assertFalse(thread.is_alive())
self.assertIsInstance(failure[0], OSError)
def test_any_loss_reports_the_keyboard_closed_and_backs_off(self):
watcher = agent.KeyboardWatcher(self.dir)
watcher.report(True)
def attached_then_lost():
watcher.attached = True
raise OSError("DevTools closed the connection")
steps = iter([agent.AgentError("NO_DEVTOOLS", "no port"), agent.AgentError("NO_DEVTOOLS", "no port"),
attached_then_lost, KeyError("SteamUIStore")])
def watch():
step = next(steps, None)
if step is None:
raise SystemExit
if callable(step):
step()
raise step
with patch.object(watcher, "watch", side_effect=watch), patch.object(agent.time, "sleep") as sleep, \
patch.object(agent, "log") as log:
with self.assertRaises(SystemExit):
watcher.run()
self.assertEqual({"steamKeyboard": False, "seq": 2}, self.state())
self.assertEqual([2, 4, 2, 4], [c.args[0] for c in sleep.call_args_list])
self.assertFalse(watcher.attached)
self.assertEqual(3, log.call_count)
def test_no_shared_context_yet(self):
with patch.object(agent, "cdp_targets", return_value=[{"title": "Steam", "webSocketDebuggerUrl": "ws://127.0.0.1:1/x"}]):
with self.assertRaises(agent.AgentError) as caught:
agent.KeyboardWatcher(self.dir).watch()
self.assertEqual("NO_TARGET", caught.exception.code)
@unittest.skipUnless(shutil.which("node"), "node is not installed")
def test_page_script_watches_every_window_with_or_without_subscribe(self):
harness = r"""
const assert = require('assert');
globalThis.window = globalThis;
const script = require('fs').readFileSync(process.argv[2], 'utf8');
const calls = [];
window.droiddeckSteamKeyboard = value => calls.push(value);
const tick = ms => new Promise(done => setTimeout(done, ms));
const value = subscribe => {
const v = { m_currentValue: false, m_callbacks: [] };
if (subscribe) v.Subscribe = cb => { v.m_callbacks.push(cb); return { Unsubscribe() {} }; };
v.set = next => { v.m_currentValue = next; for (const cb of v.m_callbacks) cb(next); };
return v;
};
(async () => {
assert.strictEqual(eval(script), false);
assert.deepStrictEqual(calls, ['false']);
const main = value(true), overlay = value(false);
globalThis.SteamUIStore = { WindowStore: { SteamUIWindows: [{ VirtualKeyboardManager: { IsShowingVirtualKeyboard: main } }] } };
assert.strictEqual(eval(script), false);
main.set(true);
await tick(20);
assert.deepStrictEqual(calls, ['false', 'true']);
main.set(false);
await tick(20);
SteamUIStore.WindowStore.SteamUIWindows.push({}, { VirtualKeyboardManager: { IsShowingVirtualKeyboard: overlay } });
overlay.m_currentValue = true;
await tick(700);
assert.deepStrictEqual(calls, ['false', 'true', 'false', 'true']);
assert.strictEqual(eval(script), true);
assert.strictEqual(main.m_callbacks.length, 1);
clearInterval(window.__droiddeckKeyboard.timer);
})().catch(e => { console.error(e); process.exit(1); });
"""
(self.dir / "keyboard.js").write_text(agent.KEYBOARD_JS)
(self.dir / "harness.js").write_text(harness)
result = subprocess.run(["node", str(self.dir / "harness.js"), str(self.dir / "keyboard.js")],
capture_output=True, text=True, timeout=20)
self.assertEqual(0, result.returncode, result.stderr)
@staticmethod
def capture(call):
try:
call()
except Exception as e:
return e
class VrFocusTest(unittest.TestCase):
def test_scene_dashboard_and_external_focus_changes(self):
focus = agent.VrSceneFocus()
+75 -4
View File
@@ -45,6 +45,8 @@ class FexTestCase(unittest.TestCase):
"WANTED": str(self.home / ".config/droiddeck/fex-wanted"),
"PRELOADS": str(self.tmp / "preloads"),
"HOST_PRELOAD": str(self.tmp / "ld.so.preload"),
"DEVICE_FONTS": str(self.tmp / "android-fonts"),
"FONT_RULES": str(self.tmp / "66-droiddeck-device-fonts.conf"),
}
patcher = mock.patch.dict(G, patches)
patcher.start()
@@ -69,9 +71,10 @@ class FexTestCase(unittest.TestCase):
self.write(Path(library or self.steam) / "steamapps/appmanifest_3127680.acf", '"AppState" { "installdir" "FEX-Emu" }')
return tool
def runtime(self, version="3.0.20260805.254768", lines=None):
runtime = self.steam / "steamapps/common/SteamLinuxRuntime_sniper"
platform = runtime / ("sniper_platform_" + version)
def runtime(self, version="3.0.20260805.254768", lines=None, app="1628350", folder="SteamLinuxRuntime_sniper",
prefix="sniper_platform_"):
runtime = self.steam / "steamapps/common" / folder
platform = runtime / (prefix + version)
files = platform / "files"
self.write(files / "lib/x86_64-linux-gnu/libc.so.6", elf(62))
self.write(files / "ab/cdef-1.bin", b"blob")
@@ -89,9 +92,16 @@ class FexTestCase(unittest.TestCase):
]
with gzip.open(platform / "usr-mtree.txt.gz", "wt") as out:
out.write("\n".join(mtree) + "\n")
self.write(self.steam / "steamapps/appmanifest_1628350.acf", '"AppState" { "installdir" "SteamLinuxRuntime_sniper" }')
self.write(self.steam / ("steamapps/appmanifest_%s.acf" % app), '"AppState" { "installdir" "%s" }' % folder)
return platform
def steamrt4(self):
return self.runtime("4.0.20260928.262390", app="4183110", folder="SteamLinuxRuntime_4", prefix="steamrt4_platform_")
def proton(self, require):
proton = self.steam / "steamapps/common/Proton - Experimental"
self.write(proton / "toolmanifest.vdf", '"manifest"\n{\n "commandline" "/proton %%verb%%"\n "require_tool_appid" "%s"\n}\n' % require)
return self.write(proton / "proton", "#!/usr/bin/env python3\n", 0o755)
def graphics(self, sniper, libc=b"GLIBC_2.2.5 GLIBC_2.31 GLIBC_2.34 GLIBC_2.41", libstdcxx=b"GLIBCXX_3.4.28 GLIBCXX_3.4.33"):
files = Path(sniper) / "files"
x86 = files / "lib/x86_64-linux-gnu"
@@ -119,6 +129,9 @@ class FexTestCase(unittest.TestCase):
self.write(provided / "gconv/NEW.so", b"new gconv")
self.write(platform / "files/lib/i386-linux-gnu/libc.so.6", b"GLIBC_2.41")
self.write(platform / "files/lib/i386-linux-gnu/ld-linux.so.2", b"new ld32")
for arch in ("x86_64", "i386"):
for name in ("libssl.so.3", "libcrypto.so.3"):
self.write(platform / "files/lib" / (arch + "-linux-gnu") / name, arch.encode() + name.encode())
with gzip.open(platform / "usr-mtree.txt.gz", "wt") as out:
out.write("#mtree\n. type=dir\n")
self.write(self.steam / "steamapps/appmanifest_4183110.acf", '"AppState" { "installdir" "SteamLinuxRuntime_4" }')
@@ -238,6 +251,8 @@ class PrepareTest(FexTestCase):
self.assertEqual((root / "etc/ld.so.preload").read_text(),
"/usr/$LIB/droiddeck/libblsession.so\n/usr/$LIB/droiddeck/libfakeinput.so\n")
self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfakeinput.so").read_bytes(), b"i386libfakeinput.so")
self.assertEqual((root / "etc/asound.conf").read_text(),
"pcm.!default {\n type pulse\n}\nctl.!default {\n type pulse\n}\n")
self.write(self.tmp / "ld.so.preload", "/usr/local/lib/libblsession.so\n")
FEX["install_preloads"](str(root))
self.assertEqual((root / "etc/ld.so.preload").read_text(), "/usr/$LIB/droiddeck/libblsession.so\n")
@@ -253,6 +268,21 @@ class PrepareTest(FexTestCase):
self.assertEqual((root / "lib/i386-linux-gnu/droiddeck/libfaultreport.so").read_bytes(), b"report32")
self.assertEqual((root / "etc/ld.so.preload").read_text(), "/usr/$LIB/droiddeck/libfaultreport.so\n")
def test_device_fonts_reach_the_x86_runtime(self):
root = self.tmp / "root"
conf = root / str(self.tmp / "66-droiddeck-device-fonts.conf").lstrip("/")
rules = '<?xml version="1.0"?><fontconfig>\n<match target="pattern"></match>\n</fontconfig>\n'
self.write(self.tmp / "66-droiddeck-device-fonts.conf", rules)
FEX["install_fonts"](str(root))
self.assertFalse(conf.exists())
(self.tmp / "android-fonts").mkdir()
FEX["install_fonts"](str(root))
self.assertEqual(conf.read_text(), '<?xml version="1.0"?><fontconfig>\n<dir>%s</dir>\n<match target="pattern"></match>\n</fontconfig>\n'
% (self.tmp / "android-fonts"))
(self.tmp / "66-droiddeck-device-fonts.conf").unlink()
FEX["install_fonts"](str(root))
self.assertFalse(conf.exists())
def test_config_turns_thunks_on_only_when_complete(self):
FEX["write_config"]({"host_thunks": "/h", "guest_thunks": "/g", "thunks_db": "/db"}, "/root")
config = json.loads((self.home / ".local/share/droiddeck-fex/config/Config.json").read_text())
@@ -272,6 +302,29 @@ class PrepareTest(FexTestCase):
status = json.loads((self.home / ".local/share/droiddeck-fex/status.json").read_text())
self.assertFalse(status["ready"])
def test_a_missing_steam_runtime_4_is_named(self):
self.fex_tool()
self.runtime()
with mock.patch.dict(G, {"steam_running": lambda: False}):
fex, said = self.quiet(FEX["prepare"], "4183110")
self.assertIsNone(fex)
self.assertIn("Steam Linux Runtime 4.0 (steamrt4, Steam app 4183110)", said)
self.assertNotIn("FEX (Steam app", said)
def test_the_x86_runtime_gets_its_own_steam_client_link(self):
self.fex_tool()
platform = self.runtime()
self.write(self.steam / "linuxarm64/steamclient.so", elf(183))
self.write(self.steam / "linux64/steamclient.so", elf(62))
self.write(self.steam / "linux32/steamclient.so", elf(3))
(self.home / ".steam").mkdir()
os.symlink(self.steam / "linuxarm64", self.home / ".steam/sdk64")
self.quiet(FEX["prepare"])
guest = platform / "files" / str(self.home).lstrip("/") / ".steam"
self.assertEqual(os.readlink(guest / "sdk64"), str(self.steam / "linux64"))
self.assertEqual(os.readlink(guest / "sdk32"), str(self.steam / "linux32"))
self.assertEqual(os.readlink(self.home / ".steam/sdk64"), str(self.steam / "linux64"))
def test_a_ready_install_is_prepared(self):
tool = self.fex_tool()
platform = self.runtime()
@@ -302,6 +355,10 @@ class PrepareTest(FexTestCase):
self.assertEqual((x86 / "ld-linux-x86-64.so.2").read_bytes(), b"new ld")
self.assertEqual((x86 / "gconv/NEW.so").read_bytes(), b"new gconv")
self.assertEqual((root / "lib/i386-linux-gnu/libc.so.6").read_bytes(), b"GLIBC_2.41")
self.assertEqual((x86 / "libssl.so.3").read_bytes(), b"x86_64libssl.so.3")
self.assertEqual((x86 / "libcrypto.so.3").read_bytes(), b"x86_64libcrypto.so.3")
self.assertEqual((root / "lib/i386-linux-gnu/libssl.so.3").read_bytes(), b"i386libssl.so.3")
self.assertEqual((root / "lib/i386-linux-gnu/libcrypto.so.3").read_bytes(), b"i386libcrypto.so.3")
self.assertEqual((x86 / "libSDL2-2.0.so.0").read_bytes(), b"sdl")
self.assertEqual(os.readlink(x86 / "libfoo.so.1"), "libfoo.so.1.2")
self.assertEqual((x86 / "libfoo.so.1").read_bytes(), b"foo")
@@ -528,6 +585,20 @@ class LaunchTest(FexTestCase):
thunks = json.loads((self.home / ".local/share/droiddeck-fex/config/ThunksConfig.json").read_text())
self.assertEqual(thunks, {"ThunksDB": {"GL": 1, "Vulkan": 1}})
def test_host_libc_tunables_stay_on_the_host(self):
guest = FEX["guest_environment"]({"portable": True}, {"GLIBC_TUNABLES": "glibc.pthread.rseq=0"})
self.assertNotIn("GLIBC_TUNABLES", guest)
def test_proton_runs_in_the_runtime_its_manifest_requires(self):
self.fex_tool()
self.runtime()
platform = self.steamrt4()
proton = self.proton("4183110")
with mock.patch("os.execve") as emulated:
self.quiet(FEX["launch"], [str(proton), "waitforexitandrun", "game.exe"], {}, "on")
self.assertEqual(emulated.call_args[0][2]["FEX_ROOTFS"], str(platform / "files"))
self.assertEqual(FEX["required_runtime"](str(self.proton("1391110"))), "1628350")
def test_native_programs_run_directly(self):
program = self.write(self.tmp / "native", elf(183), 0o755)
with mock.patch("os.execvpe") as native, mock.patch("os.execve") as emulated:
+3 -1
View File
@@ -1164,7 +1164,9 @@ class BundleTest(unittest.TestCase):
bundle = steps["Bundle the droiddeck-esync packs"]
self.assertNotIn("if", bundle)
self.assertIn("tools/droiddeck-esync/release.env", bundle["run"])
self.assertEqual(bundle["run"].count('-R "$SYNC_BUNDLE_REPO"'), 2)
self.assertIn('release_url="https://github.com/${SYNC_BUNDLE_REPO}/releases/download/${SYNC_BUNDLE_TAG}"', bundle["run"])
self.assertIn('curl -fsSL --retry 3 -o sync-bundle.tzst "$release_url/$SYNC_BUNDLE_ASSET"', bundle["run"])
self.assertIn('curl -fsSL --retry 3 -o sync-index.json "$release_url/index.json"', bundle["run"])
self.assertIn("sha256sum -c -", bundle["run"])
self.assertNotIn("revoked.txt", bundle["run"])
stage = next(step for step in apk["jobs"]["build"]["steps"] if "overlay/usr/local/bin/droiddeck-*" in step.get("run", ""))
+222 -13
View File
@@ -18,24 +18,44 @@ READER = r"""
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <sys/uio.h>
#include <unistd.h>
int main(void)
static int vector_count;
static ssize_t controller_read(int fd, void *buffer, size_t size)
{
if (!vector_count)
return read(fd, buffer, size);
struct iovec vectors[3] = {
{buffer, sizeof(struct input_event)},
{(char *)buffer + sizeof(struct input_event), 0},
{(char *)buffer + sizeof(struct input_event), size - sizeof(struct input_event)},
};
if (vector_count == 1) {
vectors[0].iov_len = size;
return readv(fd, vectors, 1);
}
return readv(fd, vectors, 3);
}
int main(int argc, char **argv)
{
vector_count = argc > 1 ? (argv[1][0] == '1' ? 1 : 3) : 0;
struct input_event events[64];
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0) {
perror("open");
return 1;
}
while (read(fd, events, sizeof(events)) > 0)
while (controller_read(fd, events, sizeof(events)) > 0)
;
puts("ready");
fflush(stdout);
char go;
if (read(0, &go, 1) != 1)
return 1;
ssize_t got = read(fd, events, sizeof(events));
ssize_t got = controller_read(fd, events, sizeof(events));
for (ssize_t i = 0; i < got / (ssize_t)sizeof(events[0]); i++)
printf("%ld.%06ld %u %u %d\n", (long)events[i].time.tv_sec, (long)events[i].time.tv_usec, events[i].type,
events[i].code, events[i].value);
@@ -65,6 +85,146 @@ int main(void)
return 0;
}
"""
READV_CHECKS = r"""
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
int main(void)
{
struct input_event events[64];
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0)
return 1;
while (read(fd, events, sizeof(events)) > 0)
;
struct iovec vector = {events, sizeof(events)};
if (readv(fd, &vector, 1) != -1 || errno != EAGAIN)
return 2;
if (readv(fd, NULL, 0) != 0)
return 3;
vector.iov_len = 0;
if (readv(fd, &vector, 1) != 0)
return 4;
vector.iov_len = sizeof(struct input_event) - 1;
if (readv(fd, &vector, 1) != -1 || errno != EINVAL)
return 5;
ssize_t (*invoke)(int, const struct iovec *, int) = readv;
if (invoke(fd, NULL, -1) != -1 || errno != EINVAL)
return 6;
if (invoke(fd, NULL, 1025) != -1 || errno != EINVAL)
return 7;
if (invoke(fd, NULL, 1) != -1 || errno != EFAULT)
return 8;
long page = sysconf(_SC_PAGESIZE);
void *area = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (area == MAP_FAILED)
return 10;
struct iovec *boundary = (struct iovec *)((char *)area + page - sizeof(struct iovec));
*boundary = vector;
if (mprotect((char *)area + page, page, PROT_NONE))
return 11;
if (invoke(fd, boundary, 2) != -1 || errno != EFAULT)
return 12;
if (invoke(fd, boundary + 1, 1) != -1 || errno != EFAULT)
return 13;
if (munmap(area, 2 * page))
return 14;
if (invoke(fd, boundary, 1) != -1 || errno != EFAULT)
return 15;
int pipefd[2];
char text[5] = {0};
struct iovec parts[2] = {{text, 1}, {text + 1, 3}};
if (pipe(pipefd) || write(pipefd[1], "test", 4) != 4 ||
readv(pipefd[0], parts, 2) != 4 || strcmp(text, "test"))
return 9;
puts("ok");
return 0;
}
"""
READV_DESTINATION_CHECKS = r"""
#include <errno.h>
#include <fcntl.h>
#include <linux/input.h>
#include <stdio.h>
#include <sys/mman.h>
#include <sys/uio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
struct input_event events[64];
int fd = open("/dev/input/event16", O_RDONLY | O_NONBLOCK);
if (fd < 0)
return 1;
if (argc > 1)
while (read(fd, events, sizeof(events)) > 0)
;
puts("ready");
fflush(stdout);
char go;
if (read(0, &go, 1) != 1)
return 2;
long page = sysconf(_SC_PAGESIZE);
char *area = mmap(NULL, 2 * page, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (area == MAP_FAILED || mprotect(area + page, page, PROT_NONE))
return 3;
struct iovec vector = {area + page, sizeof(struct input_event)};
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
return 4;
if (read(fd, vector.iov_base, vector.iov_len) != -1 || errno != EFAULT)
return 5;
if (mprotect(area, page, PROT_READ))
return 6;
vector.iov_base = area;
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
return 7;
if (mprotect(area, page, PROT_READ | PROT_WRITE) || munmap(area + page, page))
return 8;
vector.iov_base = area + page;
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
return 9;
vector.iov_base = area + page - 1;
if (readv(fd, &vector, 1) != -1 || errno != EFAULT)
return 15;
vector.iov_base = area + page - sizeof(struct input_event);
vector.iov_len = 2 * sizeof(struct input_event);
if (readv(fd, &vector, 1) != sizeof(struct input_event))
return 10;
struct input_event *first = vector.iov_base;
if (first->type != EV_KEY || first->code != BTN_A)
return 11;
struct iovec parts[2] = {{events, sizeof(struct input_event)}, {NULL, sizeof(struct input_event)}};
if (readv(fd, parts, 2) != sizeof(struct input_event))
return 12;
if (events[0].type != (argc > 1 ? EV_ABS : EV_KEY) || events[0].code != (argc > 1 ? ABS_Y : BTN_B))
return 13;
vector.iov_base = events;
vector.iov_len = sizeof(events);
ssize_t got = readv(fd, &vector, 1);
if (got != (argc > 1 ? 1 : 18) * sizeof(struct input_event) ||
events[0].type != (argc > 1 ? EV_SYN : EV_KEY) || events[0].code != (argc > 1 ? SYN_REPORT : BTN_X))
return 14;
munmap(area, page);
puts("ok");
return 0;
}
"""
OVERLAY_READ = r"""
#include <sys/uio.h>
#include <unistd.h>
ssize_t read(int fd, void *buffer, size_t size)
{
struct iovec vector = {buffer, size};
return readv(fd, &vector, 1);
}
"""
def can_build(bits):
@@ -82,15 +242,16 @@ class FakeinputRingTest(unittest.TestCase):
self.tmp = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.tmp, True)
def ring(self):
def ring(self, virtual=True):
hooks = self.tmp / "hooks"
hooks.mkdir()
(hooks / "event16").touch()
ring = bytearray(HEADER + CAPACITY * EVENT + DESCRIPTION)
(hooks / ("event16" if virtual else "event0")).touch()
ring = bytearray(HEADER + CAPACITY * EVENT + (DESCRIPTION if virtual else 0))
struct.pack_into("<IIIIQQQ", ring, 0, RING_MAGIC, 2, EVENT, CAPACITY, 5, 0, 0)
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
path = hooks / ".uinput-event16"
if virtual:
struct.pack_into("<IiHHHHI80s", ring, HEADER + CAPACITY * EVENT, DESCRIPTION_MAGIC, os.getpid(),
3, 0x28de, 0x11ff, 1, 16, b"Microsoft X-Box 360 pad 0")
path = hooks / ".uinput-event16" if virtual else self.tmp / "ring0"
path.write_bytes(bytes(ring))
return hooks, path
@@ -106,11 +267,22 @@ class FakeinputRingTest(unittest.TestCase):
subprocess.run(["gcc", bits, "-o", str(binary), str(self.tmp / (name + ".c"))], check=True)
return library, binary
def read_through(self, bits):
library, reader = self.build(bits, READER, "reader")
hooks, path = self.ring()
def read_through(self, bits, vectors=None, overlay=False, virtual=True, program=READER):
if not virtual:
program = program.replace("event16", "event0")
library, reader = self.build(bits, program, "reader")
hooks, path = self.ring(virtual=virtual)
env = dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks))
process = subprocess.Popen([str(reader)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
if not virtual:
env["FAKE_EVDEV_MEMFD_PATHS"] = "0=" + str(path)
if overlay:
source = self.tmp / "overlay.c"
source.write_text(OVERLAY_READ)
overlay_library = self.tmp / "overlay.so"
subprocess.run(["gcc", bits, "-shared", "-fPIC", "-o", str(overlay_library), str(source)], check=True)
env["LD_PRELOAD"] = str(overlay_library) + ":" + str(library)
command = [str(reader)] + ([str(vectors)] if vectors else [])
process = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, env=env, text=True)
self.addCleanup(process.kill)
self.assertEqual(process.stdout.readline(), "ready\n")
with open(path, "r+b") as ring:
@@ -131,6 +303,43 @@ class FakeinputRingTest(unittest.TestCase):
self.assertEqual(self.read_through("-m64"),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_readv_reads_events_instead_of_the_backing_file(self):
self.assertEqual(self.read_through("-m64", vectors=1),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_readv_reads_the_original_controller_ring(self):
self.assertEqual(self.read_through("-m64", vectors=1, virtual=False),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_an_overlay_read_fallback_to_readv_reads_events_without_recursion(self):
self.assertEqual(self.read_through("-m64", overlay=True),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_readv_reads_event_aligned_vectors_and_skips_empty_ones(self):
self.assertEqual(self.read_through("-m64", vectors=3),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_a_32_bit_guest_reads_the_same_events_with_readv(self):
self.assertEqual(self.read_through("-m32", vectors=1),
"1700000000.250000 1 304 1\n1700000001.250000 3 1 -32768\n1700000002.250000 0 0 0\n")
def test_readv_preserves_nonblocking_errors_and_other_descriptors(self):
library, probe = self.build("-m64", READV_CHECKS, "readv-checks")
hooks, _ = self.ring()
run = subprocess.run([str(probe)], capture_output=True, text=True, timeout=10,
env=dict(os.environ, LD_PRELOAD=str(library), FAKE_EVDEV_DIR=str(hooks)))
self.assertEqual(run.returncode, 0, run.stderr)
self.assertEqual(run.stdout, "ok\n")
def test_readv_keyframes_handle_destination_faults_and_partial_progress(self):
self.assertEqual(self.read_through("-m64", program=READV_DESTINATION_CHECKS), "ok\n")
def test_readv_ring_events_handle_destination_faults_and_partial_progress(self):
self.assertEqual(self.read_through("-m64", vectors=1, program=READV_DESTINATION_CHECKS), "ok\n")
def test_a_32_bit_guest_handles_readv_destination_faults(self):
self.assertEqual(self.read_through("-m32", program=READV_DESTINATION_CHECKS), "ok\n")
def test_an_event_node_rejects_joydev_requests_so_sdl_reads_its_id(self):
library, probe = self.build("-m64", PROBE, "probe")
hooks, _ = self.ring()
+197 -4
View File
@@ -4,6 +4,7 @@ import os
import shutil
from pathlib import Path
import runpy
import shlex
import subprocess
import sys
import tempfile
@@ -43,6 +44,17 @@ class ReadConfigMappingTest(unittest.TestCase):
class GameEnvironmentTest(unittest.TestCase):
def test_optional_xbox_loader_failure_keeps_stock_launch(self):
from unittest.mock import patch
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
calls = []
with patch.dict(os.environ, {}, clear=True), patch('sys.argv', ['droiddeck-game-env', '/stock', 'run']), \
patch('runpy.run_path', side_effect=error), patch('os.execvpe', side_effect=lambda *args: calls.append(args)), \
patch.dict(MODULE['main'].__globals__, load_sync=lambda: None, select_sync=lambda command, env, sync: (command, env)):
MODULE['main']()
self.assertEqual(calls[0][0:2], ('/stock', ['/stock', 'run']))
def test_directaudio_capture_follows_the_session_microphone_setting(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
@@ -83,6 +95,73 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(calls[0][0][1], str(root))
self.assertEqual(calls[0][1]["DROIDDECK_SEED_SCRIPTS"], str(script))
SCRIPT = ('"evaluatorscript" { "0" { "appid" "228980" "compat_installscript" { "run process" { '
'"x64 14.28.29334.0" { "hasrunkey" "HKEY_LOCAL_MACHINE\\\\Software\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2019" '
'"process 1" "%INSTALLDIR%\\\\x64.cmd" "requirement_os" { "Is64BitWindows" "1" } } '
'"Setup" { "process 1" "%INSTALLDIR%\\\\setup.exe" } } } } }')
REDIST = "[Software\\\\Wow6432Node\\\\Valve\\\\Steam\\\\Apps\\\\CommonRedist\\\\vcredist\\\\2019] 1\n\"x64 14.28.29334.0\"=dword:00000001\n"
SETUP = "[Software\\\\Valve\\\\Steam\\\\Apps\\\\228980] 1\n\"Setup\"=dword:00000001\n"
def test_install_script_run_keys_default_to_the_app_key(self):
keys = MODULE["run_keys"](MODULE["read_vdf"](self.SCRIPT))
self.assertEqual(keys, {
("hkey_local_machine\\software\\valve\\steam\\apps\\commonredist\\vcredist\\2019", "x64 14.28.29334.0"),
("hkey_local_machine\\software\\valve\\steam\\apps\\228980", "setup"),
})
with self.assertRaises(ValueError):
MODULE["read_vdf"]('"a" { "b" }')
def test_install_scripts_count_as_done_only_when_recorded_and_still_marked(self):
with tempfile.TemporaryDirectory() as tmp:
script = Path(tmp) / "evaluatorscript_1.vdf"
script.write_text(self.SCRIPT)
prefix = Path(tmp) / "compat/pfx"
env = {"STEAM_COMPAT_DATA_PATH": str(prefix.parent)}
done = MODULE["install_scripts_done"]
self.assertFalse(done([str(script)], env))
prefix.mkdir(parents=True)
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
self.assertFalse(done([str(script)], env))
(prefix / "system.reg").write_text(self.REDIST)
self.assertFalse(done([str(script)], env))
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
self.assertTrue(done([str(script)], env))
script.write_text(self.SCRIPT.replace("x64.cmd", "x64-update.cmd"))
self.assertFalse(done([str(script)], env))
script.write_text('"InstallScript" { "Registry" { "HKEY_LOCAL_MACHINE\\\\Software\\\\Game" { "string" { "Path" "%INSTALLDIR%" } } } }')
MODULE["record_install_scripts"](MODULE["scripts_digest"]([str(script)]), env)
self.assertFalse(done([str(script)], env))
def test_the_evaluator_is_skipped_once_it_finished_the_same_scripts(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "legacycompat").mkdir()
evaluator = root / "legacycompat/iscriptevaluator.exe"
evaluator.write_bytes(b"evaluator")
script = root / "legacycompat/evaluatorscript_1.vdf"
prefix = root / "compatdata/1/pfx"
prefix.mkdir(parents=True)
(prefix / "system.reg").write_text(self.REDIST + self.SETUP)
runs = root / "runs"
proton = root / "proton"
proton.write_text("#!/bin/sh\necho run >> %s\nexit ${EXIT_CODE:-0}\n" % shlex.quote(str(runs)))
proton.chmod(0o755)
def evaluate(exit_code="0"):
script.write_text(self.SCRIPT if exit_code != "changed" else self.SCRIPT.replace("setup.exe", "setup-update.exe"))
env = dict(os.environ, HOME=tmp, STEAM_COMPAT_CLIENT_INSTALL_PATH=str(root),
STEAM_COMPAT_DATA_PATH=str(prefix.parent), EXIT_CODE="0" if exit_code == "changed" else exit_code)
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"), str(proton), "run",
str(evaluator), "legacycompat\\evaluatorscript_1.vdf"],
env=env, text=True, capture_output=True)
return result.returncode, len(runs.read_text().splitlines()) if runs.exists() else 0
self.assertEqual(evaluate("3"), (3, 1))
self.assertFalse((prefix / ".droiddeck-install-scripts").exists())
self.assertEqual(evaluate(), (0, 2))
self.assertEqual(evaluate(), (0, 2))
self.assertEqual(evaluate("changed"), (0, 3))
def test_profile_precedence_and_unset(self):
env = {"KEEP": "inherited", "REMOVE": "inherited", "CUSTOM": "launch option"}
config = {"version": 1, "shared": {"CUSTOM": "shared"}, "games": {"42": {"REMOVE": None, "CUSTOM": "game", "EMPTY": ""}}}
@@ -90,6 +169,17 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(env["REMOVE"], "inherited")
self.assertEqual(MODULE["apply_config"](env, config, "43")["CUSTOM"], "shared")
def test_games_get_their_own_turnip_debug_and_a_game_profile_still_wins(self):
gpu = MODULE["game_gpu"]
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "", "KEEP": "1"}), {"KEEP": "1"})
self.assertEqual(gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": "sysmem"}), {"TU_DEBUG": "sysmem"})
self.assertEqual(gpu({"DROIDDECK_GAME_TU_DEBUG": "nolrz"}), {"TU_DEBUG": "nolrz"})
self.assertEqual(gpu({"TU_DEBUG": "sysmem"}), {"TU_DEBUG": "sysmem"})
config = {"version": 1, "games": {"42": {"TU_DEBUG": "sysmem"}}}
env = gpu({"TU_DEBUG": "sysmem", "DROIDDECK_GAME_TU_DEBUG": ""})
self.assertEqual(MODULE["apply_config"](env, config, "42")["TU_DEBUG"], "sysmem")
self.assertNotIn("TU_DEBUG", MODULE["apply_config"](env, config, "43"))
def test_a_games_wine_sync_choice_also_reaches_its_setup_runs(self):
env = {"BL_SYNC": "1", "BL_SYNC_FALLBACK": "1", "BL_FSYNC_FIRST": "0", "OTHER": "kept"}
config = {"version": 1, "games": {"42": {"BL_SYNC": "0", "BL_FSYNC_FIRST": "1", "PROTON_NO_ESYNC": "1", "FEX_TSOENABLED": "1"}}}
@@ -179,6 +269,75 @@ class GameEnvironmentTest(unittest.TestCase):
(other / "Other.exe").touch()
self.assertEqual(MODULE["engine_fixes"](str(other / "Other.exe"), []), ({}, [], []))
def test_easy_anti_cheat_games_start_offline_only_when_opted_in(self):
with tempfile.TemporaryDirectory() as tmp:
game = Path(tmp) / "ELDEN RING/Game"
(game / "EasyAntiCheat").mkdir(parents=True)
for name in ("start_protected_game.exe", "eldenring.exe"):
(game / name).touch()
(game / "EasyAntiCheat/settings.json").write_text('\ufeff{ "executable" : "eldenring.exe" }', encoding="utf-8")
command = ["proton", "waitforexitandrun", str(game / "start_protected_game.exe"), "-arg"]
offline = MODULE["offline_without_anticheat"]
self.assertEqual(offline(command, {}), command)
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "0"}), command)
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}),
["proton", "waitforexitandrun", str(game / "eldenring.exe"), "-arg"])
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "../../escape.exe" }')
(Path(tmp) / "escape.exe").touch()
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "missing.exe" }')
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "link/escape.exe" }')
outside = Path(tmp) / "outside"
outside.mkdir()
(outside / "escape.exe").touch()
(game / "link").symlink_to(outside, target_is_directory=True)
self.assertEqual(offline(command, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), command)
(game / "EasyAntiCheat/settings.json").write_text('{ "executable" : "eldenring.exe" }')
plain = ["proton", "waitforexitandrun", str(game / "eldenring.exe")]
self.assertEqual(offline(plain, {"DROIDDECK_ANTICHEAT_OFFLINE": "1"}), plain)
self.assertEqual(offline(["proton", "run", command[2]],
{"DROIDDECK_ANTICHEAT_OFFLINE": "1"}),
["proton", "run", command[2]])
def test_easy_anti_cheat_forwarding_through_entrypoint(self):
with tempfile.TemporaryDirectory() as tmp:
home = Path(tmp)
game = home / "ELDEN RING/Game"
(game / "EasyAntiCheat").mkdir(parents=True)
bootstrapper = game / "start_protected_game.exe"
target = game / "eldenring.exe"
bootstrapper.touch()
target.touch()
(game / "EasyAntiCheat/settings.json").write_text(json.dumps({"executable": "eldenring.exe"}))
proton = home / "fake-proton"
proton.write_text("#!" + sys.executable + "\nimport json, sys\nprint(json.dumps(sys.argv[1:]))\n")
proton.chmod(0o755)
config = home / ".config/droiddeck/game-environment.json"
config.parent.mkdir(parents=True)
env = dict(os.environ, HOME=tmp, STEAM_COMPAT_DATA_PATH="/compatdata/42")
env.pop("DROIDDECK_ANTICHEAT_OFFLINE", None)
for setting, expected in (("1", target), ("0", bootstrapper), (None, bootstrapper)):
with self.subTest(setting=setting):
values = {} if setting is None else {"DROIDDECK_ANTICHEAT_OFFLINE": setting}
config.write_text(json.dumps({"version": 1, "games": {"42": values}}))
result = subprocess.run([sys.executable, str(BIN / "droiddeck-game-env"),
str(proton), "waitforexitandrun", str(bootstrapper), "-arg"],
env=env, text=True, capture_output=True, check=True)
self.assertEqual(json.loads(result.stdout.strip()),
["waitforexitandrun", str(expected), "-arg"])
def test_deep_rock_gdk_avoids_the_raytracing_pipeline_crash(self):
game = "/game/FSD/Binaries/WinGDK/FSD-WinGDK-Shipping.exe"
env, extra, notes = MODULE["engine_fixes"](game, [])
self.assertEqual(extra, ["-noraytracing", "-ini:Engine:[/Script/Engine.RendererSettings]:r.RayTracing=False"])
self.assertEqual(env, {})
self.assertTrue(notes)
for choice in ("-raytracing", "-noraytracing"):
self.assertEqual(MODULE["engine_fixes"](game, [choice]), ({}, [], []))
self.assertEqual(MODULE["engine_fixes"]("/game/FSD-Win64-Shipping.exe", []), ({}, [], []))
self.assertEqual(MODULE["engine_fixes"]("/game/Other-WinGDK-Shipping.exe", []), ({}, [], []))
def test_arkham_city_gets_full_x87_precision_over_the_preset(self):
with tempfile.TemporaryDirectory() as tmp:
city = Path(tmp) / "Batman Arkham City GOTY/Binaries/Win32"
@@ -434,6 +593,8 @@ class GameEnvironmentTest(unittest.TestCase):
self.assertEqual(changes, {"42": COMPAT["TOOL"]})
def test_both_proton_wrappers_call_environment_launcher(self):
self.assertIn('bl_directaudio "$depot" "$@"', COMPAT["LAUNCHER_SH"])
self.assertIn('bl_directaudio "$here" "$@"', COMPAT["EXTRA_WRAPPER_SH"] % "proton")
for script in (COMPAT["LAUNCHER_SH"], COMPAT["EXTRA_WRAPPER_SH"] % "proton"):
subprocess.run(["bash", "-n"], input=script, text=True, check=True)
self.assertIn('bl_run ${BL_TASKSET:-} /usr/local/bin/droiddeck-game-env', script)
@@ -849,12 +1010,15 @@ class DirectAudioPrefixTest(unittest.TestCase):
(self.windows / folder).mkdir(parents=True)
self.reg = self.compat / "pfx/user.reg"
def run_setup(self, verb="waitforexitandrun"):
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat))
def run_setup(self, verb="waitforexitandrun", target="game.exe", cwd=None):
script = COMPAT["BL_DIRECTAUDIO_SETUP"] + '\nverb=$2\nbl_directaudio "$1" "$3"\necho "WINEDLLPATH=$WINEDLLPATH"\necho "WINE_AUDIO_DRIVER=${WINE_AUDIO_DRIVER:-}"\n'
steam = self.compat.parent / "Steam"
env = dict(os.environ, BL_DIRECTAUDIO=str(self.sets), STEAM_COMPAT_DATA_PATH=str(self.compat),
STEAM_COMPAT_CLIENT_INSTALL_PATH=str(steam))
env.pop("WINEDLLPATH", None)
env.pop("WINE_AUDIO_DRIVER", None)
return subprocess.run(["bash", "-c", script, "bash", str(self.tool), verb], env=env, capture_output=True, text=True, check=True)
return subprocess.run(["bash", "-c", script, "bash", str(self.tool), verb, target], cwd=cwd, env=env,
capture_output=True, text=True, check=True)
def audio_values(self):
found, current = [], None
@@ -869,6 +1033,35 @@ class DirectAudioPrefixTest(unittest.TestCase):
path = self.windows / folder / "winedirectaudio.drv"
return os.readlink(path) if path.is_symlink() else None
def test_steam_installscript_evaluator_does_not_change_prefix_audio(self):
legacycompat = self.compat.parent / "Steam/legacycompat"
legacycompat.mkdir(parents=True)
(legacycompat / "iscriptevaluator.exe").write_bytes(b"Steam install-script evaluator")
self.reg.write_text("WINE REGISTRY Version 2\n\n#arch=win64\n")
result = self.run_setup(target="iscriptevaluator.exe", cwd=legacycompat)
self.assertIn("DirectAudio skipped for Steam's install-script evaluator", result.stderr)
self.assertIn("WINEDLLPATH=\n", result.stdout)
self.assertIn("WINE_AUDIO_DRIVER=\n", result.stdout)
self.assertEqual(self.reg.read_text(), "WINE REGISTRY Version 2\n\n#arch=win64\n")
self.assertIsNone(self.link("system32"))
self.assertIsNone(self.link("syswow64"))
def test_same_basename_outside_steam_legacycompat_keeps_normal_setup(self):
legacycompat = self.compat.parent / "Steam/legacycompat"
legacycompat.mkdir(parents=True)
(legacycompat / "iscriptevaluator.exe").write_bytes(b"Steam install-script evaluator")
other = self.compat.parent / "other"
other.mkdir()
(other / "iscriptevaluator.exe").write_bytes(b"unrelated executable")
self.reg.write_text("WINE REGISTRY Version 2\n\n#arch=win64\n")
result = self.run_setup(target="iscriptevaluator.exe", cwd=other)
self.assertIn("DirectAudio selected", result.stderr)
self.assertEqual(self.link("system32"), str(self.audio / "lib/wine/aarch64-windows/winedirectaudio.drv"))
self.assertEqual(self.audio_values(), [("[Software\\\\Wine\\\\Drivers]", '"Audio"="directaudio,pulse"')])
def test_non_launch_verbs_preserve_audio_configuration(self):
for verb in ("getcompatpath", "getnativepath", "destroyprefix"):
with self.subTest(verb=verb):
+50 -1
View File
@@ -77,6 +77,7 @@ class SleepHandshakeTest(unittest.TestCase):
GLib.Variant("(ss)", (IFACE, "PreparingForSleep")))[0]
def suspend(self):
(self.dir / "steam-sleep").unlink(missing_ok=True)
self.call(IFACE, "Suspend", GLib.Variant("(b)", (True,)))
self.wait_for(lambda: (self.dir / "steam-sleep").exists())
self.wait_for(lambda: self.signals == [True])
@@ -239,6 +240,7 @@ class FakeAgentCase(unittest.TestCase):
suspend = SleepHandshakeTest.suspend
state = SleepHandshakeTest.state
request_wake = SleepHandshakeTest.request_wake
request_native = SleepHandshakeTest.request_native
def asked(self):
path = self.dir / "agent-calls"
@@ -264,7 +266,7 @@ class AwakeSteamTest(FakeAgentCase):
self.state(token, "paused")
self.request_wake()
self.wait_for(lambda: self.signals == [True, False])
self.assertEqual([], self.asked())
self.assertNotIn("--steam-asleep", self.asked())
@unittest.skipUnless(Gio and os.environ.get("DBUS_SESSION_BUS_ADDRESS"), "requires dbus-run-session and PyGObject")
@@ -276,6 +278,53 @@ class AsleepSteamTest(FakeAgentCase):
self.wait_for(lambda: self.signals == [True, False])
self.assertEqual(["--steam-asleep"], self.asked())
def test_steam_sleep_request_holds_idle_sleep_before_the_host_pauses(self):
token = self.suspend()
self.assertEqual(["--steam-idle-inhibit", "on"], self.asked())
self.state(token, "paused")
self.state(token, "awake")
self.wait_for(lambda: self.signals == [True, False])
self.wait_for(lambda: self.asked()[-1:] == ["off"])
self.assertEqual(["--steam-idle-inhibit", "on", "--steam-idle-suspend-seconds",
"--steam-idle-inhibit", "off"], self.asked())
def test_idle_pause_holds_idle_sleep_without_a_sleep_wake_pair(self):
token = self.request_native("2" * 32 + " idle").split()[0]
self.wait_for(lambda: (self.dir / "steam-native-ready").exists())
self.assertEqual(token, (self.dir / "steam-native-ready").read_text().strip())
self.assertEqual(["--steam-idle-inhibit", "on"], self.asked())
self.state(token, "paused")
self.state(token, "awake")
self.wait_for(lambda: self.asked()[-1:] == ["off"])
self.assertEqual([], self.signals)
self.assertEqual(["--steam-idle-inhibit", "on", "--steam-idle-suspend-seconds",
"--steam-idle-inhibit", "off"], self.asked())
def test_a_failed_release_is_tried_again(self):
failed = self.dir / "release-failed"
(self.dir / "bin/droiddeck-agent").write_text(
"#!/bin/sh\necho \"$@\" >> \"%s\"\n"
"if [ \"$2\" = off ] && [ ! -e \"%s\" ]; then : > \"%s\"; exit 1; fi\nexit 0\n"
% (self.dir / "agent-calls", failed, failed))
token = self.suspend()
self.state(token, "paused")
self.state(token, "awake")
self.wait_for(lambda: self.asked().count("off") == 2)
time.sleep(2.5)
self.assertEqual(["--steam-idle-inhibit", "on", "--steam-idle-suspend-seconds",
"--steam-idle-inhibit", "off", "--steam-idle-inhibit", "off"], self.asked())
def test_a_hold_steam_did_not_confirm_is_still_released(self):
(self.dir / "bin/droiddeck-agent").write_text(
"#!/bin/sh\necho \"$@\" >> \"%s\"\n[ \"$2\" = on ] && exit 1\nexit 0\n" % (self.dir / "agent-calls"))
token = self.suspend()
self.state(token, "paused")
self.state(token, "awake")
self.wait_for(lambda: self.signals == [True, False])
self.wait_for(lambda: self.asked()[-1:] == ["off"])
self.assertEqual(["--steam-idle-inhibit", "on", "--steam-idle-suspend-seconds",
"--steam-idle-inhibit", "off"], self.asked())
class WithNetworkManagerTest(SleepHandshakeTest):
ARGS = ["--with-netmanager"]
+136 -10
View File
@@ -7,6 +7,7 @@ import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
FASTPATH = Path(__file__).resolve().parents[1] / "proot/fastpath/fastpath.c"
# Opens each "<dirfd>\t<flags>\t<path>" case with openat2(RESOLVE_IN_ROOT) as FEX does: first through the kernel's own
# openat2 on argv[1] when it has one, then, with openat2 failing ENOSYS as under proot, through the preload on argv[2].
@@ -84,6 +85,62 @@ int main(int argc, char **argv) {
}
"""
COUNTER = r"""
#define _GNU_SOURCE
#include <dlfcn.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
static int opens, stats, links;
int openat(int dirfd, const char *path, int flags, ...) {
va_list args;
va_start(args, flags);
mode_t mode = va_arg(args, int);
va_end(args);
opens++;
return ((int (*)(int, const char *, int, ...))dlsym(RTLD_NEXT, "openat"))(dirfd, path, flags, mode);
}
int fstatat(int dirfd, const char *path, struct stat *st, int flags) {
stats++;
return ((int (*)(int, const char *, struct stat *, int))dlsym(RTLD_NEXT, "fstatat"))(dirfd, path, st, flags);
}
int fstatat64(int dirfd, const char *path, struct stat64 *st, int flags) {
stats++;
return ((int (*)(int, const char *, struct stat64 *, int))dlsym(RTLD_NEXT, "fstatat64"))(dirfd, path, st, flags);
}
ssize_t readlinkat(int dirfd, const char *path, char *buf, size_t size) {
links++;
return ((ssize_t (*)(int, const char *, char *, size_t))dlsym(RTLD_NEXT, "readlinkat"))(dirfd, path, buf, size);
}
__attribute__((destructor)) static void report(void) {
fprintf(stderr, "calls %d %d %d\n", opens, stats, links);
}
"""
RAW_OPEN = r"""
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <sys/syscall.h>
#include <unistd.h>
int main(int argc, char **argv) {
char text[16] = "";
long fd = syscall(SYS_openat, AT_FDCWD, argv[1], O_RDONLY | O_CLOEXEC, 0);
if (fd < 0 || read((int)fd, text, sizeof(text) - 1) < 0) return 1;
printf("%s\n", text);
return syscall(SYS_openat, AT_FDCWD, argv[2], O_RDONLY | O_CLOEXEC, 0) == -1 ? 0 : 1;
}
"""
O_PATH = getattr(os, "O_PATH", 0o10000000)
# (dirfd: r = the tree, o = "/"), flags, path, expected: a path in the tree, an errno name, or "proc" for a file outside it.
@@ -117,8 +174,17 @@ CASES = [
("o", os.O_RDONLY, "proc/self/status", "proc"),
]
# Only the preload: an absolute link to a path missing in the tree but present outside it, as droiddeck-fex's rootfs has.
HOST_CASES = [
("r", os.O_RDONLY, "lib/x86_64-linux-gnu/libbar.so.2", "host:libbar.so.2"),
("r", os.O_RDONLY, "hostdir/sub/data", "host:sub/data"),
("r", os.O_RDONLY | os.O_DIRECTORY, "hostdir/sub", "host:sub"),
("r", os.O_RDONLY, "etc/alternatives/hn", "etc/hostname"),
("r", os.O_RDONLY, "hostdir/missing", "ENOENT"),
]
def make_tree(root):
def make_tree(root, outside):
for folder in ("usr/lib/x86_64-linux-gnu", "etc/alternatives", "loop", "chain"):
(root / folder).mkdir(parents=True)
(root / "usr/lib/x86_64-linux-gnu/libfoo.so.1.2").write_text("x86")
@@ -129,16 +195,24 @@ def make_tree(root):
"etc/alternatives/hn": "/etc/hostname", "etc/escape": "../../../../../../etc/hostname", "loop/a": "b",
"loop/b": "a", "dirlink": "/usr", "rootlink": "/", "dangling": "/usr/newfile"}
links.update({"chain/l%d" % i: ("l%d" % (i + 1) if i < 41 else "end") for i in range(1, 42)})
links.update({"usr/lib/x86_64-linux-gnu/libbar.so.2": str(outside / "libbar.so.2"), "hostdir": str(outside)})
for link, target in links.items():
os.symlink(target, root / link)
def labels(lines, root):
def make_outside(outside):
(outside / "sub").mkdir(parents=True)
(outside / "libbar.so.2").write_text("host")
(outside / "sub/data").write_text("host")
def labels(lines, root, outside):
inodes = {(os.lstat(root).st_dev, os.lstat(root).st_ino): "."}
for folder, dirs, files in os.walk(root):
for name in dirs + files:
st = os.lstat(os.path.join(folder, name))
inodes[(st.st_dev, st.st_ino)] = os.path.relpath(os.path.join(folder, name), root)
for base, prefix in ((root, ""), (outside, "host:")):
for folder, dirs, files in os.walk(base):
for name in dirs + files:
st = os.lstat(os.path.join(folder, name))
inodes[(st.st_dev, st.st_ino)] = prefix + os.path.relpath(os.path.join(folder, name), base)
out = []
for line in lines:
kind, *values = line.split()
@@ -161,16 +235,50 @@ class Openat2PreloadTest(unittest.TestCase):
source.write_text(PROGRAM)
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "openat2"), str(source), "-ldl"], check=True)
cls.trees = (cls.tmp / "kernel", cls.tmp / "preload")
cls.outside = cls.tmp / "outside"
make_outside(cls.outside)
for tree in cls.trees:
make_tree(tree)
cases = "".join("%s\t%d\t%s\n" % case[:3] for case in CASES)
make_tree(tree, cls.outside)
every = CASES + HOST_CASES
cases = "".join("%s\t%d\t%s\n" % case[:3] for case in every)
result = subprocess.run([str(cls.tmp / "openat2"), *map(str, cls.trees)], input=cases, capture_output=True, text=True,
env=dict(os.environ, LD_PRELOAD=str(cls.lib)), timeout=60)
if result.returncode != 0:
raise AssertionError(result.stdout + result.stderr)
lines = result.stdout.splitlines()
cls.kernel = labels(lines[1:1 + len(CASES)], cls.trees[0]) if lines[0] == "kernel" else None
cls.preload = labels(lines[-len(CASES):], cls.trees[1])
cls.kernel = labels(lines[1:1 + len(CASES)], cls.trees[0], cls.outside) if lines[0] == "kernel" else None
cls.preload = labels(lines[-len(every):], cls.trees[1], cls.outside)
counter = cls.tmp / "counter.c"
counter.write_text(COUNTER)
(cls.tmp / "fp").mkdir()
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-o", str(cls.tmp / "fp/libblfastpath.so"),
str(counter), "-ldl"], check=True)
tree = cls.tmp / "counted"
make_tree(tree, cls.outside)
counted = subprocess.run([str(cls.tmp / "openat2"), str(tree), str(tree)], input=cases, capture_output=True,
text=True, env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so")),
timeout=60)
if counted.returncode != 0:
raise AssertionError(counted.stdout + counted.stderr)
cls.counted = labels(counted.stdout.splitlines()[-len(every):], tree, cls.outside)
cls.calls = [int(n) for n in counted.stderr.split("calls ")[-1].split()]
raw = cls.tmp / "raw_open.c"
raw.write_text(RAW_OPEN)
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-o", str(cls.tmp / "raw_open"), str(raw)], check=True)
cls.raw = subprocess.run([str(cls.tmp / "raw_open"), str(tree / "etc/hostname"), str(tree / "missing")],
capture_output=True, text=True, timeout=60,
env=dict(os.environ, LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "fp/libblfastpath.so")))
(cls.tmp / "real").mkdir()
subprocess.run(["cc", "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-pthread", "-o",
str(cls.tmp / "real/libblfastpath.so"), str(FASTPATH), "-ldl"], check=True)
shutil.copy(cls.tmp / "raw_open", cls.tmp / "FEX")
try:
cls.fex = subprocess.run([str(cls.tmp / "FEX"), str(tree / "etc/hostname"), str(tree / "missing")],
capture_output=True, text=True, timeout=20,
env=dict(os.environ, PROOT_FP_ROOT="/", PROOT_FP_KEY="test",
LD_PRELOAD="%s:%s" % (cls.lib, cls.tmp / "real/libblfastpath.so")))
except subprocess.TimeoutExpired:
cls.fex = None
@classmethod
def tearDownClass(cls):
@@ -181,6 +289,24 @@ class Openat2PreloadTest(unittest.TestCase):
self.assertEqual(got, case[3], case)
self.assertTrue((self.trees[1] / "usr/newfile").exists())
def test_preload_finishes_a_link_to_a_path_only_outside_the_root_there(self):
for case, got in zip(HOST_CASES, self.preload[len(CASES):]):
self.assertEqual(got, case[3], case)
def test_the_walk_asks_the_fast_path_when_it_is_loaded(self):
self.assertEqual(self.counted, self.preload)
self.assertTrue(all(n > 0 for n in self.calls), self.calls)
def test_a_raw_openat_syscall_asks_the_fast_path_too(self):
self.assertEqual(self.raw.returncode, 0, self.raw.stderr)
self.assertEqual(self.raw.stdout, "inside\n")
self.assertEqual(self.raw.stderr.split("calls ")[-1].split(), ["2", "0", "0"])
def test_a_first_raw_openat_in_fex_does_not_wait_on_the_fast_path_starting(self):
self.assertIsNotNone(self.fex, "hung")
self.assertEqual(self.fex.returncode, 0, self.fex.stderr)
self.assertEqual(self.fex.stdout, "inside\n")
def test_the_kernel_agrees(self):
if self.kernel is None:
self.skipTest("this kernel or sandbox has no openat2")
+90
View File
@@ -0,0 +1,90 @@
import os
import subprocess
import tarfile
import tempfile
import unittest
from pathlib import Path
SOURCE = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-pipewire'
class PipeWireHelperTest(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory()
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.lib = self.root / 'lib'
self.runtime = self.root / 'run'
self.lib.mkdir()
self.runtime.mkdir()
self.bundle = self.lib / 'droiddeck-pipewire.tzst'
self.dir = self.lib / 'droiddeck-pipewire'
text = SOURCE.read_text().replace('/usr/local/lib/droiddeck-pipewire', str(self.dir))
self.helper = self.root / 'droiddeck-pipewire'
self.helper.write_text(text)
self.environment = dict(os.environ, XDG_RUNTIME_DIR=str(self.runtime))
def pack(self, daemon_body):
tree = self.root / 'tree'
for name, body in (('pipewire', daemon_body), ('wireplumber', 'exec sleep 30')):
path = tree / 'bin' / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('#!/bin/sh\n' + body + '\n')
path.chmod(0o755)
tar = self.root / 'bundle.tar'
with tarfile.open(tar, 'w') as archive:
archive.add(tree, arcname='.')
subprocess.run(['zstd', '-q', '-f', str(tar), '-o', str(self.bundle)], check=True)
def run_helper(self, *args):
with tempfile.TemporaryFile('w+') as out, tempfile.TemporaryFile('w+') as err:
done = subprocess.run(['sh', str(self.helper), *args], env=self.environment, stdout=out, stderr=err,
text=True, timeout=15)
out.seek(0)
err.seek(0)
return subprocess.CompletedProcess(done.args, done.returncode, out.read(), err.read())
def tearDown(self):
self.run_helper('stop')
def test_env_points_clients_at_the_bundle(self):
out = self.run_helper('env').stdout
for part in ('PIPEWIRE_CONFIG_DIR=%s/share/pipewire', 'PIPEWIRE_MODULE_DIR=%s/lib/pipewire-0.3',
'SPA_PLUGIN_DIR=%s/lib/spa-0.2'):
self.assertIn(part % self.dir, out)
def test_start_waits_for_the_socket_and_stop_ends_both_daemons(self):
socket = self.runtime / 'pipewire-0'
self.pack('python3 -c "import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); '
'import time; time.sleep(30)" "$XDG_RUNTIME_DIR/pipewire-0"')
result = self.run_helper('start')
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue(socket.is_socket())
pids = (self.runtime / 'droiddeck-pipewire/pids').read_text().split()
self.assertEqual(len(pids), 2)
self.run_helper('stop')
for pid in pids:
subprocess.run(['sh', '-c', 'for i in 1 2 3 4 5 6 7 8 9 10; do kill -0 %s 2>/dev/null || exit 0; '
'sleep 0.1; done; exit 1' % pid], check=True)
def test_start_fails_cleanly_when_pipewire_never_listens(self):
self.pack('exec sleep 30')
result = self.run_helper('start')
self.assertNotEqual(result.returncode, 0)
self.assertIn('did not open', result.stderr)
self.assertFalse((self.runtime / 'droiddeck-pipewire/pids').exists())
def test_unchanged_bundle_is_not_unpacked_again(self):
self.pack('exec sleep 30')
self.run_helper('start')
marker = self.dir / 'kept'
marker.write_text('x')
self.run_helper('start')
self.assertTrue(marker.exists())
self.pack('exec sleep 31')
self.run_helper('start')
self.assertFalse(marker.exists())
if __name__ == '__main__':
unittest.main()
+72 -1
View File
@@ -29,6 +29,32 @@ class RuntimeInputsTest(unittest.TestCase):
self.source.parent.mkdir(parents=True)
self.source.write_text('current source')
self.audio(['pactl', 'modules/arm64/module-aaudio-sink.so', 'modules/arm64/module-directaudio-native-sink.so'])
self.packs()
def pack(self, name, files):
stream = io.BytesIO()
with tarfile.open(fileobj=stream, mode='w') as archive:
for rel, content in files.items():
entry = tarfile.TarInfo(rel)
entry.size = len(content)
archive.addfile(entry, io.BytesIO(content))
path = self.root / runtime.PACKS / (name + '.tar.zst')
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(subprocess.run(['zstd', '-q', '-c'], input=stream.getvalue(), capture_output=True, check=True).stdout)
def packs(self):
self.pack('tracking', {library.rsplit('/', 1)[1]: b'library' for library in runtime.PACKED_LIBRARIES})
proot = {}
for name, (pack, rel) in runtime.PACKED_FILES.items():
proot[rel] = (self.root / runtime.outputs(self.root)[name]).read_bytes()
self.pack('proot', proot)
for prefix, name in runtime.PACKED.items():
base = self.root / 'app/src/main' / prefix
self.pack(name, {path.relative_to(base).as_posix(): path.read_bytes() for path in base.rglob('*') if path.is_file()})
@staticmethod
def in_apk(name):
return name not in runtime.PACKED_FILES and not any(name.startswith(prefix) for prefix in runtime.PACKED)
def audio(self, names):
stream = io.BytesIO()
@@ -40,6 +66,11 @@ class RuntimeInputsTest(unittest.TestCase):
path = self.root / 'app/build/prepared-assets/pulseaudio.tzst'
path.write_bytes(subprocess.run(['zstd', '-q', '-c'], input=stream.getvalue(), capture_output=True, check=True).stdout)
def test_an_apk_still_carrying_proot_is_rejected(self):
apk = self.current_apk(self.root / 'bundled.apk', {'lib/arm64-v8a/libproot.so': b'prepared runtime'})
with self.assertRaisesRegex(ValueError, 'proot pack provides'):
runtime.check_apk(apk, self.root)
def test_missing_proot_cannot_be_attested(self):
(self.root / 'app/src/main/jniLibs/arm64-v8a/libproot.so').unlink()
with self.assertRaisesRegex(ValueError, 'libproot.so'):
@@ -82,6 +113,8 @@ class RuntimeInputsTest(unittest.TestCase):
apk = self.root / 'old.apk'
with ZipFile(apk, 'w') as package:
for name, output in data['outputs'].items():
if not self.in_apk(name):
continue
content = b'stale' if name == 'assets/linuxfs/libssbs.so' else (self.root / output['path']).read_bytes()
package.writestr(name, content)
with self.assertRaisesRegex(ValueError, 'stale runtime input'):
@@ -93,9 +126,43 @@ class RuntimeInputsTest(unittest.TestCase):
apk = self.root / 'current.apk'
with ZipFile(apk, 'w') as package:
for name, output in data['outputs'].items():
package.writestr(name, (self.root / output['path']).read_bytes())
if self.in_apk(name):
package.writestr(name, (self.root / output['path']).read_bytes())
runtime.check_apk(apk, self.root)
def current_apk(self, path, extra=None):
runtime.record(self.root)
data = runtime.verify(self.root)
with ZipFile(path, 'w') as package:
for name, output in data['outputs'].items():
if self.in_apk(name):
package.writestr(name, (self.root / output['path']).read_bytes())
for name, content in (extra or {}).items():
package.writestr(name, content)
return path
def test_an_apk_still_carrying_a_packed_tree_is_rejected(self):
apk = self.current_apk(self.root / 'bundled.apk', {'assets/linuxfs/usr/local/lib/droiddeck-xbox/xodus-cli': b'prepared runtime'})
with self.assertRaisesRegex(ValueError, 'xbox pack provides'):
runtime.check_apk(apk, self.root)
def test_an_apk_still_carrying_tracking_libraries_is_rejected(self):
apk = self.current_apk(self.root / 'bundled.apk', {runtime.PACKED_LIBRARIES[0]: b'library'})
with self.assertRaisesRegex(ValueError, 'tracking pack provides'):
runtime.check_apk(apk, self.root)
def test_a_stale_pack_is_rejected(self):
apk = self.current_apk(self.root / 'current.apk')
self.pack('comet', {'comet': b'old build', 'version': b'old'})
with self.assertRaisesRegex(ValueError, 'comet is missing or has a stale'):
runtime.check_apk(apk, self.root)
def test_a_missing_pack_is_rejected(self):
apk = self.current_apk(self.root / 'current.apk')
(self.root / runtime.PACKS / 'xbox.tar.zst').unlink()
with self.assertRaisesRegex(ValueError, 'Missing add-on pack xbox'):
runtime.check_apk(apk, self.root)
def test_windows_manifest_matches_portable_apk_paths(self):
path_type = type(self.root)
original_relative_to = path_type.relative_to
@@ -114,6 +181,8 @@ class RuntimeInputsTest(unittest.TestCase):
apk = self.root / 'portable.apk'
with ZipFile(apk, 'w') as package:
for name, output in data['outputs'].items():
if not self.in_apk(name):
continue
self.assertNotIn('\\', name)
self.assertNotIn('\\', output['path'])
package.writestr(name, (self.root / output['path']).read_bytes())
@@ -125,6 +194,8 @@ class RuntimeInputsTest(unittest.TestCase):
apk = self.root / 'expanded.apk'
with ZipFile(apk, 'w') as package:
for name, output in data['outputs'].items():
if not self.in_apk(name):
continue
content = (self.root / output['path']).read_bytes()
if name.endswith('.gzip'):
name = name.removesuffix('.gzip')
+20
View File
@@ -155,6 +155,26 @@ class SeedRedistsTest(unittest.TestCase):
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
self.assertIn('"x64 14.99.1.0"=dword:00000001', self.reg.read_text())
def test_an_unchanged_registry_is_not_read_again(self):
self.game()
self.run_seed()
self.run_seed()
shim = self.tmp / "bin"
shim.mkdir()
log = self.tmp / "awk.log"
(shim / "awk").write_text('#!/bin/sh\nprintf "%%s\\n" "$*" >> "%s"\nexec %s "$@"\n' % (log, shutil.which("awk")))
(shim / "awk").chmod(0o755)
env = dict(os.environ, DROIDDECK_LIBRARIES="", PATH="%s:%s" % (shim, os.environ["PATH"]))
once = self.reg.read_text()
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
self.assertEqual(once, self.reg.read_text())
self.assertNotIn(str(self.reg), log.read_text() if log.exists() else "")
replaced = self.reg.with_name("system.reg.new")
replaced.write_text("WINE REGISTRY Version 2\n")
os.replace(replaced, self.reg)
subprocess.run(["bash", str(SCRIPT), str(self.steam)], env=env, capture_output=True, text=True, check=True)
self.assertEqual(self.reg.read_text().count('"VCRedist2022"=dword:00000001'), 2)
def test_the_prefix_date_is_kept(self):
os.utime(self.reg, (1_000_000_000, 1_000_000_000))
self.run_seed()
+49
View File
@@ -0,0 +1,49 @@
import os
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
URUNTIME = "/usr/local/lib/droiddeck/uruntime"
def target_case():
match = re.search(r"^ case \$\{target,,\} in\n.*?^ esac\n", SESSION.read_text(), re.M | re.S)
return match.group(0)
class SessionAppImageTest(unittest.TestCase):
def setUp(self):
self.dir = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.dir, True)
self.image = self.dir / "rpcs3.AppImage"
self.image.write_bytes(b"\x7fELF")
self.uruntime = self.dir / "uruntime"
self.uruntime.write_text("#!/bin/sh\n")
self.uruntime.chmod(0o755)
def launch(self, fex=()):
script = ("set -u\n"
"run_program() { printf '%%s\\n' \"TARGET=${TARGET_APPIMAGE:-} EXTRACT=${APPIMAGE_EXTRACT_AND_RUN:-}\" \"$@\"; exit 0; }\n"
"target=%s\nfex=(%s)\nset -- --no-gui\n" % (self.image, " ".join(fex))
+ target_case().replace(URUNTIME, str(self.uruntime)))
env = {k: v for k, v in os.environ.items() if k not in ("TARGET_APPIMAGE", "APPIMAGE_EXTRACT_AND_RUN")}
return subprocess.run(["bash", "-c", script], env=env, capture_output=True, text=True, timeout=30).stdout.splitlines()
def test_an_arm64_image_runs_through_the_shipped_runtime(self):
self.assertEqual(["TARGET=%s EXTRACT=1" % self.image, str(self.uruntime), "--no-gui"], self.launch())
def test_without_the_shipped_runtime_the_image_runs_itself(self):
self.uruntime.unlink()
self.assertEqual(["TARGET= EXTRACT=1", str(self.image), "--no-gui"], self.launch())
def test_an_x86_image_still_starts_under_fex(self):
fex = ("/usr/local/bin/droiddeck-fex", "run", "--mode", "on", "--")
self.assertEqual(["TARGET= EXTRACT=1", *fex, str(self.image), "--no-gui"], self.launch(fex))
if __name__ == "__main__":
unittest.main()
+67
View File
@@ -0,0 +1,67 @@
import os
import re
import shutil
import subprocess
import tempfile
import unittest
from pathlib import Path
SESSION = Path(__file__).resolve().parents[1] / "linuxfs/overlay/usr/local/bin/droiddeck-session"
def run_case():
return re.search(r"^ run\)\n.*?^ ;;\n", SESSION.read_text(), re.M | re.S).group(0)
def steam_display():
return re.search(r"^ steam\)\n(.*?)^ steam_x64=0\n", SESSION.read_text(), re.M | re.S).group(1)
class SessionRunDisplayTest(unittest.TestCase):
def setUp(self):
self.dir = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.dir, True)
self.target = self.dir / "target.sh"
self.target.write_text("printf '%s\\n' \"${WAYLAND_DISPLAY-unset}\" \"${XDG_SESSION_TYPE-unset}\""
" > \"$1\"\n")
def display(self, **env):
base = {k: v for k, v in os.environ.items()
if k not in ("GAMESCOPE_WAYLAND_DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE",
"BL_LAUNCH_DIR")}
seen = self.dir / "seen"
script = ("program_cores() { :; }\nmode=run\ncase $mode in\n" + run_case() + "esac\n"
+ "echo unreachable\n")
run = subprocess.run(["bash", "-c", script, "droiddeck-session", str(self.target), str(seen)],
env={**base, **env}, capture_output=True, text=True, timeout=30)
self.assertEqual(0, run.returncode, run.stderr)
self.assertNotIn("unreachable", run.stdout)
return seen.read_text().splitlines()
def test_programs_under_gamescope_cannot_reach_a_wayland_server(self):
self.assertEqual(["", "x11"], self.display(GAMESCOPE_WAYLAND_DISPLAY="gamescope-0",
WAYLAND_DISPLAY="gamescope-0", XDG_SESSION_TYPE="wayland"))
def test_without_gamescope_the_display_is_left_alone(self):
self.assertEqual(["wayland-0", "wayland"], self.display(WAYLAND_DISPLAY="wayland-0", XDG_SESSION_TYPE="wayland"))
def steam_env(self, **env):
base = {k: v for k, v in os.environ.items()
if k not in ("GAMESCOPE_WAYLAND_DISPLAY", "WAYLAND_DISPLAY", "XDG_SESSION_TYPE")}
script = steam_display() + ('printf "%s\\n" "${WAYLAND_DISPLAY-unset}" "${XDG_SESSION_TYPE-unset}"'
' "${MOZ_SHM_NO_SEALS-unset}" "${MOZ_DISABLE_CONTENT_SANDBOX-unset}"\n')
run = subprocess.run(["bash", "-c", script], env={**base, **env}, capture_output=True, text=True, timeout=30)
self.assertEqual(0, run.returncode, run.stderr)
return run.stdout.splitlines()
def test_steam_games_under_gamescope_cannot_reach_a_wayland_server(self):
self.assertEqual(["", "x11", "1", "1"], self.steam_env(GAMESCOPE_WAYLAND_DISPLAY="gamescope-0",
WAYLAND_DISPLAY="gamescope-0", XDG_SESSION_TYPE="wayland"))
def test_steam_without_gamescope_keeps_the_display(self):
self.assertEqual(["wayland-0", "wayland", "1", "1"],
self.steam_env(WAYLAND_DISPLAY="wayland-0", XDG_SESSION_TYPE="wayland"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,82 @@
import os
from pathlib import Path
import re
import subprocess
import tempfile
import textwrap
import unittest
SESSION = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-session'
SOURCE = SESSION.read_text()
ARM64_BRANCH = SOURCE.index(' else\n step "checking the Steam client (first run')
START = SOURCE.index(' droiddeck-steam-install || steam_setup_failed $?\n', ARM64_BRANCH)
END = SOURCE.index(' step "Steam client ready"\n', START)
HELPER = re.search(r'^steam_setup_failed\(\) \{\n.*?^\}\n', SOURCE, re.M | re.S).group()
INSTALL_BLOCK = HELPER + textwrap.dedent(SOURCE[START:END])
RUN_GAMESCOPE = re.search(r'^run_gamescope\(\) \(\n.*?^\)\n', SOURCE, re.M | re.S).group()
MARKER = '== steam: the Steam client could not be set up'
class SteamClientSetupFailureTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
def installer(self, status):
script = self.root / 'droiddeck-steam-install'
script.write_text('#!/bin/bash\n'
'echo "curl: (35) Recv failure: Connection reset by peer" >&2\n'
'exit ' + str(status) + '\n')
script.chmod(0o755)
def env(self, **extra):
base = {k: v for k, v in os.environ.items() if k != 'BL_STEAM_EXIT_FILE'}
return dict(base, PATH=str(self.root) + os.pathsep + os.environ['PATH'],
XDG_RUNTIME_DIR=str(self.root), **extra)
def run_block(self, status, exit_file=None):
self.installer(status)
extra = {'BL_STEAM_EXIT_FILE': str(exit_file)} if exit_file else {}
return subprocess.run(['bash', '-c', INSTALL_BLOCK + 'echo continued\n'], env=self.env(**extra),
capture_output=True, text=True, timeout=10)
def test_failed_install_reports_its_status_in_the_exit_file(self):
exit_file = self.root / 'exit'
result = self.run_block(1, exit_file)
self.assertEqual(1, result.returncode)
self.assertIn(MARKER + ' (status 1)', result.stdout)
self.assertNotIn('continued', result.stdout)
self.assertEqual('1\n', exit_file.read_text())
def test_failed_install_outside_gamescope_still_exits_with_its_status(self):
result = self.run_block(50)
self.assertEqual(50, result.returncode)
self.assertIn(MARKER + ' (status 50)', result.stdout)
def test_ready_client_continues_without_a_report(self):
exit_file = self.root / 'exit'
result = self.run_block(0, exit_file)
self.assertEqual(0, result.returncode)
self.assertIn('continued', result.stdout)
self.assertNotIn(MARKER, result.stdout)
self.assertFalse(exit_file.exists())
def test_failed_install_survives_successful_compositor_shutdown(self):
self.installer(1)
compositor = self.root / 'gamescope'
compositor.write_text('#!/bin/bash\n"$@"\nexit 0\n')
compositor.chmod(0o755)
child = self.root / 'session-child'
child.write_text('#!/bin/bash\n' + INSTALL_BLOCK + 'exit 0\n')
child.chmod(0o755)
result = subprocess.run(['bash', '-c', RUN_GAMESCOPE + '\nrun_gamescope "$@"', 'session', str(child)],
env=self.env(), capture_output=True, text=True, timeout=10)
self.assertEqual(1, result.returncode)
self.assertIn(MARKER, result.stdout)
self.assertEqual(list(self.root.glob('droiddeck-steam-exit.??????')), [])
if __name__ == '__main__':
unittest.main()
+24 -3
View File
@@ -1,4 +1,4 @@
"""Requested Steam games are handed over as soon as the interface is up; a shortcut is handed over again only if it never took focus."""
"""Retry a dropped shortcut without duplicating a launch that is still preparing its first window."""
import os
from pathlib import Path
import subprocess
@@ -48,14 +48,21 @@ class SteamColdLaunchTest(unittest.TestCase):
sleep = self.bin / "sleep"
sleep.write_text("#!/bin/sh\nprintf '%s\n' \"$@\" >> \"$SLEEP_ARGS\"\n")
sleep.chmod(0o755)
pgrep = self.bin / "pgrep"
pgrep.write_text(
"#!/bin/sh\n"
"printf '%s\\n' \"$@\" > \"$HOME/pgrep-args\"\n"
"n=$(cat \"$HOME/pgrep-count\" 2>/dev/null || echo 0); n=$((n + 1)); echo $n > \"$HOME/pgrep-count\"\n"
"[ \"$n\" -ge \"${RUNNING_AFTER:-999}\" ]\n")
pgrep.chmod(0o755)
self.block = LAUNCH_BLOCK.replace("/usr/local/bin/droiddeck-agent", str(agent))
def run_launch(self, target, focus="769", helper_status=0):
def run_launch(self, target, focus="769", helper_status=0, running_after=999):
env = dict(os.environ, HOME=str(self.root), BL_LAUNCH_DIR=str(self.launch_dir),
PATH=str(self.bin) + os.pathsep + os.environ["PATH"],
AGENT_ARGS=str(self.agent_args), SLEEP_ARGS=str(self.sleep_args),
AGENT_COUNT=str(self.agent_count), AGENT_STATUS=str(helper_status),
FOCUS=focus, FOCUS_COUNT=str(self.focus_count))
FOCUS=focus, FOCUS_COUNT=str(self.focus_count), RUNNING_AFTER=str(running_after))
script = self.block + "\nprintf 'ARG:%s\n' \"$@\"\nwait\n"
url = target if target.startswith("steam://") else "steam://rungameid/" + target
result = subprocess.run(["bash", "-c", script, "cold-launch", url],
@@ -85,6 +92,20 @@ class SteamColdLaunchTest(unittest.TestCase):
self.assertEqual(2, len(self.hand_offs(result)), result.stdout)
self.assertIn("overview status 1", result.stdout)
def test_a_game_still_starting_without_a_window_is_not_launched_twice(self):
result = self.run_launch(SHORTCUT, running_after=1)
self.assertEqual(1, len(self.hand_offs(result)), result.stdout)
self.assertFalse(self.agent_args.exists())
self.assertEqual(["-f", "reaper SteamLaunch AppId=3551182975( |$)"],
(self.root / "pgrep-args").read_text().splitlines())
self.assertIn("already starting", result.stdout)
def test_a_game_starting_during_the_overview_wait_is_not_launched_twice(self):
result = self.run_launch(SHORTCUT, running_after=2)
self.assertEqual(1, len(self.hand_offs(result)), result.stdout)
self.assertTrue(self.agent_args.exists())
self.assertIn("started while waiting", result.stdout)
def test_a_game_that_takes_focus_during_the_overview_wait_is_not_started_twice(self):
focus = " ".join(["769"] * 23) + " 4242"
result = self.run_launch(SHORTCUT, focus=focus, helper_status=0)
+89 -4
View File
@@ -54,6 +54,7 @@ class FakeSocket {
state.authed = dec.decode(h[40][0]) === "secret" && dec.decode(body[1][0]) === "secret";
result = state.authed ? 1 : 5;
} else if (!state.authed) result = 5;
else if (method === "CompatManager.GetCompatTools#1" && ["16", "128"].includes(String(body[1][0]))) result = Number(body[1][0]);
else if (method === "CompatManager.GetCompatTools#1") {
const app = String(body[1] ? body[1][0] : 0n);
for (const name of state.known) { const t = []; lenField(1, enc.encode(name), t); lenField(2, enc.encode(name + " shown"), t); lenField(1, t, out); }
@@ -79,17 +80,19 @@ const install = require("fs").readFileSync(process.argv[4], "utf8");
const before = await c.get(0);
await c.set(0, "droiddeck-proton-11-arm64");
await c.set(42, "");
const after = await c.many(["0", "42", "43"]);
const after = await c.many(["0", "42", "43", "128"]);
const timedOut = await c.many(["0", "16"]).then(() => null, (e) => e.eresult);
await new Promise((r) => setTimeout(r, 10));
console.log(JSON.stringify({ before, after, log: state.log, notify: state.notify, url: state.socket.url }));
console.log(JSON.stringify({ before, after, timedOut, log: state.log, notify: state.notify, url: state.socket.url }));
})().catch((e) => { console.error(e.stack || String(e)); process.exit(1); });
"""
class FakePage:
def __init__(self, mapping, known):
def __init__(self, mapping, known, refused=()):
self.mapping = dict(mapping)
self.known = list(known)
self.refused = set(refused)
self.sets = []
def compat(self, call):
@@ -98,8 +101,10 @@ class FakePage:
if name == "get":
return {"selected": self.mapping.get(str(args[0]), ""), "fallback": "proton_experimental", "tools": self.known}
if name == "many":
return {app: self.mapping.get(app, "") for app in args[0]}
return {app: self.mapping.get(app, "") for app in args[0] if app not in self.refused}
if name == "set":
if str(args[0]) in self.refused:
raise RuntimeError("SpecifyCompatTool %s failed (128)" % args[0])
self.mapping[str(args[0])] = args[1]
self.sets.append((str(args[0]), args[1]))
return True
@@ -202,6 +207,7 @@ assert.deepStrictEqual(calls, [['611670', 'custom args', -1, 100], ['2508200', '
self.assertEqual(out["url"], "ws://127.0.0.1:4242/transportsocket/")
self.assertEqual(out["before"], {"selected": TOOL, "fallback": "proton_experimental", "tools": [TOOL, TOOL_11, "proton_experimental"]})
self.assertEqual(out["after"], {"0": TOOL_11, "42": "", "43": ""})
self.assertEqual(out["timedOut"], 16)
self.assertEqual(out["log"], ["0=" + TOOL_11, "42="])
self.assertEqual(out["notify"], ["1", "2"])
@@ -264,6 +270,21 @@ class ReconcileTest(unittest.TestCase):
self.assertTrue(state["live"])
self.assertEqual(self.helper.installed, ["10", "11"])
def test_an_app_the_client_refuses_is_dropped_instead_of_failing_the_sync(self):
page = FakePage({"0": TOOL, "10": TOOL, "11": "proton_experimental"}, [TOOL, TOOL_11], refused={"1628350"})
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL, "1628350": TOOL}}))
(self.state / "games.json").write_text(json.dumps({"version": 1, "games": {"1628350": {"valve": True, "dir": "Proton 11.0 (ARM64)"}}}))
state = self.reconcile(page)
self.assertEqual(page.sets, [("11", TOOL)])
self.assertEqual(state["auto"], {"10": TOOL, "11": TOOL})
def test_a_refused_apps_native_choice_is_kept(self):
page = FakePage({"0": TOOL, "10": TOOL, "11": TOOL}, [TOOL, TOOL_11], refused={"20"})
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "native_choices": ["20"]}))
state = self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertEqual(state["native_choices"], ["20"])
def test_app_request_moves_the_default_and_followers(self):
page = FakePage({"0": TOOL, "10": TOOL, "11": "GE-Proton11-7"}, [TOOL, TOOL_11])
(self.state / "state.json").write_text(json.dumps({"default": TOOL, "auto": {"10": TOOL}}))
@@ -488,6 +509,70 @@ class ReconcileTest(unittest.TestCase):
self.assertEqual(page.sets, [])
self.assertEqual(state["native_choices"], [app])
def test_clearing_a_tool_picked_in_steam_keeps_the_native_build(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}})
page.known.append(COMPAT["FEX_TOOL"])
page.mapping[app] = COMPAT["FEX_TOOL"]
config = self.steam / "config/config.vdf"
config.write_text(
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
'"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, COMPAT["FEX_TOOL"]))
state = self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertNotIn(app, state["auto"])
page.mapping[app] = ""
state = self.reconcile(page)
self.assertEqual(page.sets, [])
config.write_text(
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
state = self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertEqual(state["native_choices"], [app])
restarted = LIVE["Helper"](str(self.steam), 1)
restarted.page = page
restarted.reconcile()
self.assertEqual(page.sets, [])
def test_a_new_tool_for_a_picked_game_is_kept_before_the_client_writes_its_config(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "picked": ["892970"]})
page.mapping[app] = TOOL_11
with mock.patch.dict(COMPAT, {"native_targets": lambda _root, apps: {app: COMPAT["FEX_TOOL"]} if app in apps else {}}):
state = self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertEqual(page.mapping[app], TOOL_11)
self.assertIn(app, state["picked"])
def test_a_cleared_picked_game_showing_a_stale_inherited_tool_stays_native(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}, "picked": ["892970"]})
page.mapping[app] = "proton"
state = self.reconcile(page)
self.assertEqual(page.sets, [])
self.assertEqual(state["native_choices"], [app])
def test_a_clear_saved_after_the_helper_stopped_is_kept_at_the_next_start(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL, "11": TOOL}})
page.known.append(COMPAT["FEX_TOOL"])
page.mapping[app] = COMPAT["FEX_TOOL"]
config = self.steam / "config/config.vdf"
config.write_text(
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
'"CompatToolMapping" { "0" { "name" "%s" } "%s" { "name" "%s" } } } } } }' % (TOOL, app, COMPAT["FEX_TOOL"]))
state = self.reconcile(page)
self.assertIn(app, state["picked"])
config.write_text(
'"InstallConfigStore" { "Software" { "Valve" { "Steam" { '
'"CompatToolMapping" { "0" { "name" "%s" } } } } } }' % TOOL)
with mock.patch.dict(COMPAT["register_default"].__globals__, {"native_targets": COMPAT["native_targets"]}):
COMPAT["register_default"](str(config), ["10", "11", app], settle=True, directory=str(self.state))
self.assertNotIn(app, COMPAT["read_config_mapping"](str(config)))
state = json.loads((self.state / "state.json").read_text())
self.assertEqual(state["native_choices"], [app])
self.assertNotIn(app, state["picked"])
def test_unmapped_dual_platform_game_gets_the_default_without_a_readable_config(self):
app, page = self.dual_platform_game({"default": TOOL, "auto": {"10": TOOL}, "native_choices": ["11"]})
(self.steam / "config/config.vdf").unlink()
+18
View File
@@ -311,6 +311,24 @@ class ImportsTest(unittest.TestCase):
self.assertFalse((self.steam / 'steamapps/appmanifest_42.acf').exists())
self.assertFalse(os.path.lexists(self.steam / 'steamapps/common/DroidDeck-42'))
def test_imported_game_stays_imported_when_ownership_is_unconfirmed(self):
self.snapshot()
imports.route(self.steam, self.acct, [self.game])
for owned, account in [(False, '123'), (True, '456')]:
self.snapshot(owned, account)
self.assertEqual(([], {str(self.game['appid']): 42}), imports.route(self.steam, self.acct, [self.game]))
self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file())
def test_unlisted_card_library_is_not_another_clients_install(self):
card = self.root / 'card'
(card / 'steamapps').mkdir(parents=True)
(card / 'steamapps/appmanifest_42.acf').write_text('the other client installed it here')
self.snapshot()
with patch.object(imports, 'LIBRARY', str(card)):
self.assertEqual(([], {str(self.game['appid']): 42}), imports.route(self.steam, self.acct, [self.game]))
self.assertTrue((self.steam / 'steamapps/appmanifest_42.acf').is_file())
self.assertEqual(self.folder, (self.steam / 'steamapps/common/DroidDeck-42').resolve())
def test_replaced_game_does_not_inherit_cached_ownership(self):
self.snapshot()
self.exe.write_bytes(b'a different game')
+78
View File
@@ -0,0 +1,78 @@
from pathlib import Path
import os
import subprocess
import tempfile
import unittest
SCRIPT = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin/droiddeck-steam-x64'
REGISTRY = ('"Registry"\n{\n\t"HKCU"\n\t{\n\t\t"Software"\n\t\t{\n\t\t\t"Valve"\n\t\t\t{\n\t\t\t\t"Steam"\n\t\t\t\t{\n'
'\t\t\t\t\t"language"\t\t"english"\n%s\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
CONFIG = ('"InstallConfigStore"\n{\n\t"Software"\n\t{\n\t\t"Valve"\n\t\t{\n\t\t\t"Steam"\n\t\t\t{\n%s'
'\t\t\t\t"CompatToolMapping"\n\t\t\t\t{\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n')
ACCOUNTS = ('\t\t\t\t"Accounts"\n\t\t\t\t{\n\t\t\t\t\t"someone"\n\t\t\t\t\t{\n'
'\t\t\t\t\t\t"SteamID"\t\t"76561198000000001"\n\t\t\t\t\t}\n\t\t\t\t}\n')
def local(token):
entry = '\t\t"abc1"\t\t"%s"\n' % token if token else ''
return '"MachineUserConfigStore"\n{\n\t"ConnectCache"\n\t{\n%s\t}\n}\n' % entry
class X64SignInTest(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.home = Path(self.temp.name)
self.arm = self.home / '.local/share/Steam'
self.x64 = self.home / '.droiddeck-x64/.local/share/Steam'
for root in (self.arm, self.x64):
(root / 'config').mkdir(parents=True)
(self.home / '.steam').mkdir()
(self.home / '.droiddeck-x64/.steam').mkdir(parents=True)
self.write(self.arm / 'local.vdf', local('00ff'))
self.write(self.arm / 'config/loginusers.vdf', '"users"\n{\n}\n')
self.write(self.arm / 'config/config.vdf', CONFIG % ACCOUNTS)
self.write(self.home / '.steam/registry.vdf', REGISTRY % '\t\t\t\t\t"AutoLoginUser"\t\t"someone"\n')
self.write(self.x64 / 'local.vdf', local(None))
self.write(self.x64 / 'config/loginusers.vdf', '"users"\n{\n}\n')
self.write(self.x64 / 'config/config.vdf', CONFIG % '')
self.write(self.home / '.droiddeck-x64/.steam/registry.vdf', REGISTRY % '')
def write(self, path, text):
path.write_text(text)
def sync(self):
env = dict(os.environ, HOME=str(self.home))
env.pop('XDG_DATA_HOME', None)
env.pop('BL_X64_HOME', None)
return subprocess.run(['bash', str(SCRIPT), '--sync-login'], env=env, capture_output=True, text=True, check=True)
def test_a_refused_x64_sign_in_gets_the_token_account_and_auto_login(self):
self.assertIn('sign-in shared from the arm64 client', self.sync().stdout)
self.assertEqual(local('00ff'), (self.x64 / 'local.vdf').read_text())
self.assertIn('"SteamID"\t\t"76561198000000001"', (self.x64 / 'config/config.vdf').read_text())
self.assertIn('"AutoLoginUser"\t\t"someone"', (self.home / '.droiddeck-x64/.steam/registry.vdf').read_text())
def test_an_earlier_copy_still_gains_the_account_and_nothing_repeats(self):
self.sync()
self.write(self.x64 / 'config/config.vdf', CONFIG % '')
self.write(self.home / '.droiddeck-x64/.steam/registry.vdf', REGISTRY % '')
self.assertNotIn('sign-in shared', self.sync().stdout)
self.assertIn('"76561198000000001"', (self.x64 / 'config/config.vdf').read_text())
self.assertIn('"AutoLoginUser"', (self.home / '.droiddeck-x64/.steam/registry.vdf').read_text())
self.sync()
for root in (self.arm, self.x64):
self.assertEqual(1, (root / 'config/config.vdf').read_text().count('"SteamID"'))
self.assertEqual(1, (self.home / '.droiddeck-x64/.steam/registry.vdf').read_text().count('AutoLoginUser'))
def test_a_newer_x64_sign_in_moves_to_arm64(self):
self.write(self.x64 / 'local.vdf', local('11ee'))
os.utime(self.arm / 'local.vdf', (1, 1))
self.assertIn('from the x86-64 client', self.sync().stdout)
self.assertEqual(local('11ee'), (self.arm / 'local.vdf').read_text())
if __name__ == '__main__':
unittest.main()
+38
View File
@@ -210,6 +210,44 @@ class SteamVrHelperTest(unittest.TestCase):
def test_flat_presenter_does_not_enable_the_producer_lease(self):
self.assertIn('present=unset lease=unset', self.lease_log())
def registration(self):
return (self.home / '.config/openvr/openvrpaths.vrpath',
self.home / '.config/openxr/1/active_runtime.json')
def helper_action(self, action):
subprocess.run(['sh', str(self.helper), action], env=self.environment, check=True,
capture_output=True, timeout=5)
def test_runtime_is_registered_only_while_a_session_is_active(self):
vrpath, xr = self.registration()
self.start()
self.assertTrue(vrpath.is_file())
self.assertTrue(xr.is_symlink())
self.helper_action('status')
self.assertTrue(vrpath.is_file())
self.helper_action('stop')
self.assertFalse(vrpath.exists())
self.assertFalse(xr.is_symlink())
def test_idle_status_and_session_start_clear_a_leftover_registration(self):
vrpath, xr = self.registration()
for action in ('status', 'unregister'):
self.start()
(self.runtime / 'droiddeck-steamvr/active').unlink()
self.helper_action(action)
self.assertFalse(vrpath.exists(), action)
self.assertFalse(xr.is_symlink(), action)
def test_unregister_leaves_another_runtime_alone(self):
vrpath, xr = self.registration()
vrpath.parent.mkdir(parents=True)
xr.parent.mkdir(parents=True)
vrpath.write_text('{"runtime": ["/opt/other-runtime"]}')
xr.symlink_to('/opt/monado/openxr_monado.json')
self.helper_action('unregister')
self.assertTrue(vrpath.is_file())
self.assertTrue(xr.is_symlink())
if __name__ == '__main__':
unittest.main()
+130
View File
@@ -226,6 +226,43 @@ class CloudHooks(unittest.TestCase):
self.assertEqual(store.CLOUD_TIMEOUT, asked[1][1])
self.assertEqual('cloud-up', asked[2][0]['op'])
def test_a_first_launch_creates_the_prefix_before_the_cloud_download(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='epic', ident='fa4240e5')
sidecar = json.loads((folder / store.SIDECAR).read_text())
sidecar['epic'] = {'eos': False, 'offline': True}
(folder / store.SIDECAR).write_text(json.dumps(sidecar))
proton = Path(root) / 'proton'
proton.write_text('selected Proton')
compat = Path(root) / 'compatdata/1'
order = []
def run(argv, **kwargs):
order.append(argv)
(compat / 'pfx').mkdir(parents=True)
(compat / 'pfx/user.reg').write_text('WINE REGISTRY Version 2\n')
return __import__('subprocess').CompletedProcess(argv, 0)
env = {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': str(compat), 'BL_STORE_PROTON': str(proton)}
with patch.dict(os.environ, env), patch.object(store.subprocess, 'run', side_effect=run), \
patch.object(store, 'ask', side_effect=lambda channel, request, timeout=5.0: order.append(request) or {'result': 'ok'}):
self.assertEqual(store.STORE_GAME, store.main([str(folder / store.LAUNCHER)]))
self.assertEqual([str(proton), 'run', 'cmd.exe', '/d', '/c', 'exit'], order[0])
self.assertEqual({'op': 'cloud-down', 'store': 'epic', 'id': 'fa4240e5'}, order[-1])
self.assertEqual('present', store.create_prefix(str(compat), str(proton)))
self.assertEqual(2, len(order))
def test_a_prefix_that_is_not_made_leaves_the_deferred_download(self):
with tempfile.TemporaryDirectory() as root:
proton = Path(root) / 'proton'
proton.write_text('selected Proton')
with patch.object(store.subprocess, 'run', return_value=__import__('subprocess').CompletedProcess([], 1)):
self.assertEqual('failed', store.create_prefix(root + '/compatdata/1', str(proton)))
with patch.object(store.subprocess, 'run', side_effect=__import__('subprocess').TimeoutExpired('proton', 1)):
self.assertEqual('timeout', store.create_prefix(root + '/compatdata/1', str(proton)))
self.assertEqual('no-proton', store.create_prefix(root + '/compatdata/1', root + '/missing'))
self.assertEqual('no-proton', store.create_prefix('', str(proton)))
def test_cloud_off_or_amazon_runs_proton_as_before(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='1')
@@ -314,3 +351,96 @@ class GogAchievements(unittest.TestCase):
with patch.object(store, 'COMET_DIR', base), patch.object(store.subprocess, 'run', return_value=__import__('subprocess').CompletedProcess([], 1)):
self.assertEqual('service-unavailable', store.provision_galaxy(str(base / 'compat'), str(base / 'proton')))
self.assertFalse((base / 'compat/pfx/.droiddeck-comet-service').exists())
def gog_script(folder, product, actions):
(folder / ('goggame-%s.script' % product)).write_text(json.dumps({'actions': actions, 'baseProductId': product, 'version': 1}))
def set_registry(**arguments):
return {'install': {'action': 'setRegistry', 'arguments': arguments}, 'name': 'setRegistry'}
class GogRegistry(unittest.TestCase):
def test_the_scripts_registry_values_are_read_with_the_games_paths(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='1454587428')
gog_script(folder, '1454587428', [
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\Bethesda Softworks\\FalloutNV',
valueName='Installed Path', valueData='{app}\\', valueType='string'),
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\GOG.com\\Games\\{productId}',
valueName='buildId', valueData='42', valueType='dword'),
set_registry(root='HKEY_CURRENT_USER', subkey='Software\\Game', valueName='', valueData='AAH/', valueType='binary'),
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\Empty'),
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\Game', valueName='x', valueData='1', valueType='qword'),
set_registry(root='HKEY_LOCAL_MACHINE', subkey='Software\\Game', valueName='x', valueData='{nowhere}', valueType='string'),
set_registry(root='HKEY_USERS', subkey='S-1-5', valueName='x', valueData='1', valueType='string'),
{'install': {'action': 'Execute', 'arguments': {'executable': 'setup.exe'}}},
'nonsense',
])
entries, skipped = store.gog_registry(folder)
app = store.windows_path(str(folder)).replace('\\', '\\\\')
self.assertEqual([
'[HKEY_LOCAL_MACHINE\\Software\\Bethesda Softworks\\FalloutNV]\r\n"Installed Path"="%s\\\\"' % app,
'[HKEY_LOCAL_MACHINE\\Software\\GOG.com\\Games\\1454587428]\r\n"buildId"=dword:0000002a',
'[HKEY_CURRENT_USER\\Software\\Game]\r\n@=hex:00,01,ff',
'[HKEY_LOCAL_MACHINE\\Software\\Empty]',
], entries)
self.assertEqual(3, skipped)
def test_a_game_without_a_script_starts_without_proton(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog')
with patch.object(store.subprocess, 'run') as run:
self.assertEqual('none', store.apply_gog_registry(folder, root + '/compat', root + '/proton'))
run.assert_not_called()
def test_values_are_imported_into_the_32_bit_view_once_until_the_script_changes(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='1454587428')
proton = Path(root) / 'proton'
proton.write_text('selected Proton')
data = Path(root) / 'compat'
action = set_registry(root='HKLM', subkey='Software\\Bethesda Softworks\\FalloutNV',
valueName='Installed Path', valueData='{app}', valueType='string')
gog_script(folder, '1454587428', [action])
imported = []
def run(argv, **kwargs):
self.assertEqual([str(proton), 'run', 'reg.exe', 'import'], argv[:4])
self.assertEqual('/reg:32', argv[5])
raw = Path(argv[4][2:].replace('\\', '/')).read_bytes()
self.assertTrue(raw.startswith(b'\xff\xfe'))
imported.append(raw[2:].decode('utf-16-le'))
(data / 'pfx').mkdir(parents=True, exist_ok=True)
(data / 'pfx/system.reg').write_text('Wine registry')
return __import__('subprocess').CompletedProcess(argv, 0)
with patch.object(store.subprocess, 'run', side_effect=run):
self.assertEqual('written=1', store.apply_gog_registry(folder, str(data), str(proton)))
self.assertTrue(imported[0].startswith('Windows Registry Editor Version 5.00\r\n'))
self.assertIn('[HKEY_LOCAL_MACHINE\\Software\\Bethesda Softworks\\FalloutNV]', imported[0])
self.assertEqual('ready', store.apply_gog_registry(folder, str(data), str(proton)))
self.assertEqual(1, len(imported))
action['install']['arguments']['valueData'] = '{app}\\'
gog_script(folder, '1454587428', [action])
self.assertEqual('written=1', store.apply_gog_registry(folder, str(data), str(proton)))
self.assertEqual(2, len(imported))
def test_a_failed_import_is_tried_again_next_launch(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog', ident='7')
proton = Path(root) / 'proton'
proton.write_text('selected Proton')
gog_script(folder, '7', [set_registry(root='HKLM', subkey='Software\\Game', valueName='a', valueData='b', valueType='string')])
with patch.object(store.subprocess, 'run', return_value=__import__('subprocess').CompletedProcess([], 1)):
self.assertEqual('import-failed', store.apply_gog_registry(folder, root + '/compat', str(proton)))
self.assertFalse((Path(root) / 'compat/pfx' / store.GOG_REGISTRY_MARK).exists())
self.assertEqual('no-proton', store.apply_gog_registry(folder, root + '/compat', root + '/missing'))
def test_every_gog_launch_brings_the_registry_in(self):
with tempfile.TemporaryDirectory() as root:
folder = game(root, store_id='gog')
with patch.dict(os.environ, {'BL_LAUNCH_DIR': root, 'STEAM_COMPAT_DATA_PATH': root + '/compat/', 'BL_STORE_PROTON': '/chosen/proton'}), \
patch.object(store, 'prepare_gog', return_value=False), patch.object(store, 'ask', return_value=None), \
patch.object(store, 'apply_gog_registry', return_value='ready') as apply:
store.main([str(folder / store.LAUNCHER)])
apply.assert_called_once_with(folder, root + '/compat', '/chosen/proton')
+9
View File
@@ -20,6 +20,15 @@ class SysvPreloadTest(unittest.TestCase):
result = subprocess.run([binary], capture_output=True, text=True, timeout=10, env=env)
self.assertIn('PASS: sysv otime', result.stdout, result.stdout + result.stderr)
def test_message_queue_mapping_is_reused_and_removal_wakes_waiters(self):
with tempfile.TemporaryDirectory() as folder:
binary = str(Path(folder) / 'test-sysv-msg')
subprocess.run(['gcc', '-Wall', '-Wextra', '-O2', '-pthread', '-o', binary,
str(Path(__file__).resolve().parent / 'sysv_msg_harness.c'), str(PRELOAD / 'sysv.c')], check=True)
env = dict(os.environ, BL_SYSV_DIR=folder)
result = subprocess.run([binary], capture_output=True, text=True, timeout=20, env=env)
self.assertIn('PASS: sysv msg', result.stdout, result.stdout + result.stderr)
if __name__ == '__main__':
unittest.main()
+227
View File
@@ -0,0 +1,227 @@
import array
import mmap
import os
import socket
import struct
import subprocess
import tempfile
import threading
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
PROTO = ROOT / 'app/src/main/cpp/venc/venc_proto.h'
VENC = ROOT / 'tools/linuxfs/preload/venc.c'
TOUCH = ROOT / 'tools/linuxfs/preload/rptouch.c'
DRIVER = r'''
#include <errno.h>
#include <linux/videodev2.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
int bl_venc_open(const char *path, int flags);
int bl_venc_ioctl(int fd, unsigned long req, void *arg, int *rc);
int bl_venc_mmap(void *addr, size_t len, int prot, int flags, int fd, off_t off,
void *(*real)(void *, size_t, int, int, int, off_t), void **out);
void bl_venc_closed(int fd);
static int fd;
static int call(unsigned long req, void *arg) {
int rc;
if (!bl_venc_ioctl(fd, req, arg, &rc)) return -100;
return rc < 0 ? -errno : 0;
}
int main(void) {
if (bl_venc_open("/dev/video0", 0) != -2) return 2;
fd = bl_venc_open("/dev/video-enc0", 0);
if (fd < 0) return 3;
struct v4l2_capability cap;
if (call(VIDIOC_QUERYCAP, &cap) || !(cap.device_caps & V4L2_CAP_VIDEO_M2M_MPLANE)) return 4;
struct v4l2_format f = { .type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE };
f.fmt.pix_mp.width = 640; f.fmt.pix_mp.height = 360; f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_NV12;
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.plane_fmt[0].sizeimage != 640 * 360 * 3 / 2) return 5;
f = (struct v4l2_format){ .type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
f.fmt.pix_mp.pixelformat = V4L2_PIX_FMT_HEVC;
if (call(VIDIOC_S_FMT, &f) || f.fmt.pix_mp.pixelformat != V4L2_PIX_FMT_HEVC) return 6;
struct v4l2_control c = { V4L2_CID_MPEG_VIDEO_BITRATE, 8000000 };
if (call(VIDIOC_S_CTRL, &c)) return 7;
unsigned types[2] = { V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE, V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE };
unsigned char *maps[2][2];
for (int t = 0; t < 2; t++) {
struct v4l2_requestbuffers r = { .count = 2, .type = types[t], .memory = V4L2_MEMORY_MMAP };
if (call(VIDIOC_REQBUFS, &r) || r.count != 2) return 8;
for (int i = 0; i < 2; i++) {
struct v4l2_plane p;
struct v4l2_buffer b = { .index = i, .type = types[t], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
if (call(VIDIOC_QUERYBUF, &b)) return 9;
void *m;
if (!bl_venc_mmap(NULL, p.length, PROT_READ | PROT_WRITE, MAP_SHARED, fd, p.m.mem_offset, mmap, &m) ||
m == MAP_FAILED) return 10;
maps[t][i] = m;
if (t == 1 && call(VIDIOC_QBUF, &b)) return 11;
}
if (call(VIDIOC_STREAMON, &types[t])) return 12;
}
struct v4l2_plane cp;
struct v4l2_buffer cb = { .type = types[1], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &cp };
if (call(VIDIOC_DQBUF, &cb) != -EAGAIN) return 13;
for (int frame = 0; frame < 3; frame++) {
memset(maps[0][frame % 2], 'a' + frame, 640 * 360);
struct v4l2_plane p = { .bytesused = 640 * 360 * 3 / 2 };
struct v4l2_buffer b = { .index = frame % 2, .type = types[0], .memory = V4L2_MEMORY_MMAP, .length = 1, .m.planes = &p };
b.timestamp.tv_sec = frame;
if (frame == 1) {
struct v4l2_control k = { V4L2_CID_MPEG_VIDEO_FORCE_KEY_FRAME, 1 };
call(VIDIOC_S_CTRL, &k);
}
if (call(VIDIOC_QBUF, &b)) return 14;
if (call(VIDIOC_DQBUF, &cb)) return 15;
printf("%d %u %d %ld %.*s\n", frame, cp.bytesused, !!(cb.flags & V4L2_BUF_FLAG_KEYFRAME),
(long)cb.timestamp.tv_sec, (int)cp.bytesused, maps[1][cb.index]);
if (call(VIDIOC_DQBUF, &b)) return 16;
if (call(VIDIOC_QBUF, &cb)) return 17;
}
bl_venc_closed(fd);
return 0;
}
'''
TOUCH_DRIVER = r'''
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int bl_venc_open(const char *path, int flags);
void bl_venc_closed(int fd);
int XTestFakeMotionEvent(void *dpy, int screen, int x, int y, unsigned long delay);
int XTestFakeButtonEvent(void *dpy, unsigned int button, int press, unsigned long delay);
int XDisplayWidth(void *dpy, int screen) { return 1281; }
int XDisplayHeight(void *dpy, int screen) { return 721; }
int main(void) {
XTestFakeButtonEvent(NULL, 1, 1, 0);
XTestFakeButtonEvent(NULL, 1, 0, 0);
int fd = bl_venc_open("/dev/video-enc0", 0);
if (fd < 0) return 3;
XTestFakeMotionEvent(NULL, 0, 1280, 360, 0);
XTestFakeButtonEvent(NULL, 1, 1, 0);
XTestFakeMotionEvent(NULL, 0, 640, 0, 0);
XTestFakeButtonEvent(NULL, 3, 1, 0);
XTestFakeButtonEvent(NULL, 1, 0, 0);
char marker[512];
snprintf(marker, sizeof marker, "%s/droiddeck-remote-play", getenv("XDG_RUNTIME_DIR"));
if (access(marker, F_OK) != 0) return 4;
pid_t child = fork();
if (child == 0) { bl_venc_closed(fd); _exit(access(marker, F_OK) == 0 ? 0 : 1); }
int status;
waitpid(child, &status, 0);
if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) return 5;
bl_venc_closed(fd);
if (access(marker, F_OK) == 0) return 6;
XTestFakeButtonEvent(NULL, 1, 1, 0);
usleep(200000);
return 0;
}
'''
CONFIG = struct.Struct('<' + 'I' * 12 + 'ii' + 'I' * 4)
FRAME = struct.Struct('<IIIII4xq')
DONE = struct.Struct('<IiII')
class FakeEncoder(threading.Thread):
def __init__(self, path):
super().__init__(daemon=True)
self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
self.listener.bind(path)
self.listener.listen(1)
self.configs, self.frames, self.touches = [], [], []
def run(self):
while True:
try:
conn, _ = self.listener.accept()
except OSError:
return
threading.Thread(target=self.serve, args=(conn,), daemon=True).start()
def serve(self, conn):
outputs = []
while True:
fds = array.array('i')
msg, ancdata, _, _ = conn.recvmsg(256, socket.CMSG_LEN(32 * fds.itemsize))
if not msg:
return
for level, kind, data in ancdata:
if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS:
fds.frombytes(data[:len(data) - len(data) % fds.itemsize])
kind = struct.unpack_from('<I', msg)[0]
if kind == 5:
self.touches.append(struct.unpack('<IIII', msg)[1:])
elif kind == 1:
c = CONFIG.unpack(msg)
self.configs.append(c)
inputs, size = c[14], c[17]
outputs = [mmap.mmap(fd, size) for fd in fds[inputs:]]
for fd in fds:
os.close(fd)
conn.send(DONE.pack(3, 0, 0, 0))
elif kind == 2:
_, _, output, nbytes, key, pts = FRAME.unpack(msg)
self.frames.append((nbytes, key, pts))
payload = b'frame%d' % len(self.frames)
outputs[output][:len(payload)] = payload
conn.send(DONE.pack(3, 0, len(payload), 1 if key or len(self.frames) == 1 else 0))
class VencEmulatorTest(unittest.TestCase):
def test_steam_style_session_round_trips_through_the_app_socket(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
driver = tmp / 'driver.c'
driver.write_text(DRIVER)
binary = tmp / 'driver'
subprocess.run(['cc', '-O1', '-pthread', '-o', str(binary), str(driver), str(VENC), '-ldl'],
check=True)
sock = tmp / 'venc.sock'
server = FakeEncoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock)),
capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stdout + done.stderr)
self.assertEqual(done.stdout.split('\n')[:3],
['0 6 1 0 frame1', '1 6 1 1 frame2', '2 6 0 2 frame3'])
self.assertEqual(len(server.configs), 1)
config = server.configs[0]
self.assertEqual(config[1], 1)
self.assertEqual(config[2:6], (640, 360, 640, 360))
self.assertEqual(config[8], 8000000)
self.assertEqual([f[1] for f in server.frames], [0, 1, 0])
self.assertEqual([f[2] for f in server.frames], [0, 1000000, 2000000])
self.assertTrue(all(f[0] == 640 * 360 * 3 // 2 for f in server.frames))
def test_remote_touch_and_stream_marker_follow_the_streaming_process(self):
with tempfile.TemporaryDirectory() as tmp:
tmp = Path(tmp)
driver = tmp / 'touch.c'
driver.write_text(TOUCH_DRIVER)
binary = tmp / 'touch'
subprocess.run(['cc', '-O1', '-pthread', '-rdynamic', '-o', str(binary), str(driver), str(VENC), str(TOUCH),
'-ldl'], check=True)
sock = tmp / 'venc.sock'
server = FakeEncoder(str(sock))
self.addCleanup(server.listener.close)
server.start()
done = subprocess.run([str(binary)], env=dict(os.environ, BL_VENC_SOCKET=str(sock), XDG_RUNTIME_DIR=str(tmp)),
capture_output=True, text=True, timeout=20)
self.assertEqual(done.returncode, 0, done.stderr)
self.assertEqual(server.touches, [(0, 65535, 32767), (1, 32767, 0), (2, 32767, 0)])
if __name__ == '__main__':
unittest.main()
+108
View File
@@ -0,0 +1,108 @@
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import unittest
PRELOAD = Path(__file__).resolve().parents[1] / "linuxfs/preload"
PROGRAM = r"""
#define _GNU_SOURCE
#include <errno.h>
#include <stdint.h>
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/prctl.h>
#include <sys/uio.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
unsigned char *code = mmap((void *)0xc0000000UL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (sizeof(void *) == 4 && (uintptr_t)code <= 0x7fffffffU) return 3;
unsigned char *data = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
memset(code, 0x90, 4096);
mprotect(code, 4096, PROT_READ | PROT_EXEC);
int ready[2];
if (pipe(ready)) return 2;
pid_t child = fork();
if (child == 0) {
prctl(PR_SET_PDEATHSIG, SIGKILL);
close(ready[0]);
if (write(ready[1], "", 1) != 1) _exit(1);
pause();
_exit(0);
}
char c;
close(ready[1]);
if (read(ready[0], &c, 1) != 1) return 2;
unsigned char patch[4] = {0xB8, 0x78, 0x56, 0x34};
struct iovec mine = {patch, sizeof patch};
struct iovec theirs[2] = {{code, sizeof patch}, {data, sizeof patch}};
for (int i = 0; i < 2; i++) {
ssize_t n = process_vm_writev(child, &mine, 1, &theirs[i], 1, 0);
printf("%s %zd %d", i ? "data" : "code", n, n < 0 ? errno : 0);
unsigned char back[4] = {0};
struct iovec got = {back, sizeof back};
process_vm_readv(child, &got, 1, &theirs[i], 1, 0);
printf(" %s\n", memcmp(back, patch, sizeof patch) ? "old" : "new");
}
struct iovec split[2] = {{patch, 2}, {patch + 2, 2}};
ssize_t n = process_vm_writev(child, split, 2, &theirs[0], 1, 0);
printf("split %zd %d\n", n, n < 0 ? errno : 0);
n = process_vm_writev(child, (const struct iovec *)8, 1, &theirs[0], 1, 0);
printf("invalid %zd %d\n", n, n < 0 ? errno : 0);
kill(child, SIGKILL);
waitpid(child, NULL, 0);
return 0;
}
"""
@unittest.skipUnless(shutil.which("cc") and os.path.exists("/proc/self/mem"), "needs cc and /proc")
class VmWritePreloadTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.tmp = Path(tempfile.mkdtemp())
cls.addClassCleanup(shutil.rmtree, cls.tmp, ignore_errors=True)
source = cls.tmp / "program.c"
source.write_text(PROGRAM)
cls.bits32 = True
for flags, sub in (([], "64"), (["-m32"], "32")):
(cls.tmp / sub).mkdir()
try:
subprocess.run(["cc", *flags, "-O2", "-Wall", "-Werror", "-fPIC", "-shared", "-o",
str(cls.tmp / sub / "libvmwrite.so"), str(PRELOAD / "vmwrite.c"), "-ldl"],
check=True, capture_output=True)
for name in ("wineserver", "game"):
subprocess.run(["cc", *flags, "-O2", "-o", str(cls.tmp / sub / name), str(source)],
check=True, capture_output=True)
except subprocess.CalledProcessError:
if not flags:
raise
cls.bits32 = False
def run_as(self, name, preload=True, bits="64"):
lib = self.tmp / bits / "libvmwrite.so"
env = dict(os.environ, LD_PRELOAD=str(lib)) if preload else {k: v for k, v in os.environ.items() if k != "LD_PRELOAD"}
result = subprocess.run([str(self.tmp / bits / name)], env=env, capture_output=True, text=True, check=True)
return result.stdout.splitlines()
def test_wineserver_writes_a_page_the_kernel_refused(self):
self.assertEqual(self.run_as("wineserver"), ["code 4 0 new", "data 4 0 new", "split -1 14", "invalid -1 14"])
def test_a_32_bit_wineserver_writes_above_2_gib(self):
if not self.bits32:
self.skipTest("needs cc -m32")
self.assertEqual(self.run_as("wineserver", bits="32"), ["code 4 0 new", "data 4 0 new", "split -1 14", "invalid -1 14"])
def test_everyone_else_keeps_the_kernel_answer(self):
for refused in (self.run_as("game"), self.run_as("wineserver", preload=False)):
self.assertEqual(refused, ["code -1 14 old", "data 4 0 new", "split -1 14", "invalid -1 14"])
if __name__ == "__main__":
unittest.main()
+48
View File
@@ -0,0 +1,48 @@
import os
from pathlib import Path
import subprocess
import tempfile
import unittest
class XboxBuildSourceTest(unittest.TestCase):
def test_main_advancing_between_jobs_does_not_change_packaged_source(self):
try:
import yaml
except ImportError:
self.fail('PyYAML is required to execute workflow steps')
workflow = yaml.safe_load((Path(__file__).resolve().parents[2] / '.github/workflows/build.yml').read_text())
jobs = workflow['jobs']
step = lambda job, name: next(s['run'] for s in jobs[job]['steps'] if s.get('name') == name)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
env = dict(os.environ, GIT_AUTHOR_NAME='test', GIT_COMMITTER_NAME='test',
GIT_AUTHOR_EMAIL='test@example.test', GIT_COMMITTER_EMAIL='test@example.test',
GITHUB_STEP_SUMMARY=str(root / 'summary'))
def git(*args, cwd=root):
return subprocess.check_output(['git', *args], cwd=cwd, env=env, stderr=subprocess.DEVNULL, text=True).strip()
git('init', '-q', '-b', 'main')
(root / 'backend').write_text('base')
git('add', '.'); git('commit', '-qm', 'base')
git('switch', '-qc', 'feature')
(root / 'app').write_text('feature')
git('add', '.'); git('commit', '-qm', 'feature')
head = git('rev-parse', 'HEAD')
git('switch', '-q', 'main')
(root / 'backend').write_text('merged backend')
git('commit', '-qam', 'backend changed after branch')
for name in ('xbox', 'apk'):
git('clone', '-q', str(root), str(root / name))
git('checkout', '-q', head, cwd=root / name)
output = root / 'output'
env['GITHUB_OUTPUT'] = str(output)
subprocess.run(['bash', '-c', step('xbox', 'Pin and merge the APK source')], cwd=root / 'xbox', env=env, check=True, capture_output=True)
base = output.read_text().strip().split('=', 1)[1]
tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'xbox')
(root / 'backend').write_text('newer main, after backend build')
git('commit', '-qam', 'main advanced again')
env.update(BUILD_BASE_SHA=base, XBOX_SOURCE_TREE=tree)
subprocess.run(['bash', '-c', step('build', 'Merge onto main, or say what conflicts')], cwd=root / 'apk', env=env, check=True, capture_output=True)
subprocess.run(['bash', '-c', step('build', 'Verify backend and APK source match')], cwd=root / 'apk', env=env, check=True, capture_output=True)
self.assertEqual((root / 'apk/backend').read_text(), 'merged backend')
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'apk'), tree)
+131
View File
@@ -0,0 +1,131 @@
import json
import os
from pathlib import Path
import runpy
import socket
import tempfile
import threading
import unittest
from unittest.mock import patch
BIN = Path(__file__).resolve().parents[1] / 'linuxfs/overlay/usr/local/bin'
xbox = runpy.run_path(str(BIN / 'droiddeck-xbox'))
class XboxLaunchTest(unittest.TestCase):
def test_other_stores_keep_their_existing_launch(self):
with tempfile.TemporaryDirectory() as root:
folder = Path(root)
(folder / '.droiddeck-store.json').write_text(json.dumps({'store': 'gog', 'id': '1'}))
self.assertIsNone(xbox['launch'](['/proton', 'waitforexitandrun', str(folder / 'Game.exe')], {}))
def test_renewal_retries_a_timeout_and_stops_after_rejection(self):
stopped = unittest.mock.Mock()
stopped.wait.side_effect = [False, False, False, AssertionError('renewed a rejected lease')]
ask = unittest.mock.Mock(side_effect=[None, {'ok': True}, {'ok': False}])
xbox['renew_lease'](ask, Path('/channel'), 'GAME', 'lease-1', stopped)
self.assertEqual(ask.call_count, 3)
def test_stopping_a_launch_stops_renewal_without_another_request(self):
stopped = threading.Event()
stopped.set()
ask = unittest.mock.Mock()
xbox['renew_lease'](ask, Path('/channel'), 'GAME', 'lease-1', stopped)
ask.assert_not_called()
def test_missing_store_detector_keeps_stock_launch(self):
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
with self.subTest(error=error), patch('runpy.run_path', side_effect=error):
self.assertIsNone(xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], {}))
def test_launch_uses_prepared_image_and_never_receives_account_credentials(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
runtime = root / 'runtime/windows'
runtime.mkdir(parents=True)
for name in xbox['DLLS']:
(runtime / name).write_bytes(b'MZ')
store = {'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}),
'ask': unittest.mock.Mock(return_value={'ok': True, 'socket': '/service', 'lease': 'lease-1',
'exe': '/private/Game.exe', 'playfab': 'game-token'})}
close = unittest.mock.Mock()
with patch('runpy.run_path', return_value=store), patch.dict(xbox['launch'].__globals__, RUNTIME=runtime.parent), \
patch.dict(xbox['launch'].__globals__, bridge=lambda path: (1234, 'key', close)), \
patch.dict(xbox['launch'].__globals__, wine=unittest.mock.Mock(return_value=7)):
launch = xbox['launch']
self.assertEqual(launch(['/proton', 'waitforexitandrun', '/encrypted/Game.exe'],
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale'}), 7)
wine = launch.__globals__['wine']
self.assertEqual(wine.call_args.args[0], ['/private/Game.exe'])
env = wine.call_args.args[1]
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', env)
self.assertEqual(env['XODUS_XSTS_PLAYFAB'], 'game-token')
close.assert_called_once()
self.assertEqual(store['ask'].call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
def test_bridge_start_failure_still_releases_the_lease(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
runtime = root / 'windows'
runtime.mkdir()
for name in xbox['DLLS']:
(runtime / name).touch()
ask = unittest.mock.Mock(return_value={'ok': True, 'socket': '/service', 'lease': 'lease-1'})
with patch('runpy.run_path', return_value={'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}), 'ask': ask}), \
patch.dict(xbox['launch'].__globals__, RUNTIME=root, bridge=unittest.mock.Mock(side_effect=OSError('bind failed'))):
with self.assertRaises(OSError):
xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], {'BL_LAUNCH_DIR': '/launch'})
self.assertEqual(ask.call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
def test_bridge_authenticates_before_forwarding(self):
with tempfile.TemporaryDirectory() as root:
path = str(Path(root) / 'service.sock')
upstream = socket.socket(socket.AF_UNIX)
upstream.bind(path); upstream.listen(1); upstream.settimeout(3)
received = []
def serve():
connection, _ = upstream.accept()
with connection:
received.append(connection.recv(8))
connection.sendall(b'reply')
worker = threading.Thread(target=serve); worker.start()
port, key, close = xbox['bridge'](path)
try:
with socket.create_connection(('127.0.0.1', port), timeout=2) as denied:
denied.sendall(b'x' * 64)
self.assertEqual(denied.recv(1), b'')
with socket.create_connection(('127.0.0.1', port), timeout=2) as client:
client.sendall(key[:20].encode())
client.sendall(key[20:].encode() + b'request')
self.assertEqual(client.recv(5), b'reply')
worker.join(3)
self.assertFalse(worker.is_alive())
self.assertEqual(received, [b'request'])
finally:
close(); upstream.close()
def test_wine_wrapper_preserves_selected_proton_args_and_prefix_isolation(self):
with tempfile.TemporaryDirectory() as root:
root = Path(root)
prefix = root / 'compat/pfx'
prefix.mkdir(parents=True)
runtime = root / 'runtime/windows'; runtime.mkdir(parents=True)
for name in xbox['DLLS']:
(runtime / name).write_bytes(b'MZ-synthetic')
command = root / 'command.json'
command.write_text(json.dumps(['/selected/proton', 'waitforexitandrun', '/encrypted/Game.exe', '--custom', 'two words']))
env = {'STEAM_COMPAT_DATA_PATH': str(prefix.parent), 'DROIDDECK_XBOX_COMMAND_FILE': str(command),
'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'private-account-channel', 'XODUS_BRIDGE_KEY': 'runtime-key'}
with patch.dict(os.environ, env), patch.dict(xbox['wine'].__globals__, RUNTIME=runtime.parent), patch('subprocess.run') as initialize, patch('subprocess.call', return_value=7) as call:
initialize.return_value.returncode = 0
self.assertEqual(xbox['wine'](['/private-view/Game.exe']), 7)
argv = call.call_args.args[0]
self.assertEqual(argv, ['/selected/proton', 'waitforexitandrun', '/private-view/Game.exe', '--custom', 'two words'])
self.assertIn('xgameruntime=n', call.call_args.kwargs['env']['WINEDLLOVERRIDES'])
self.assertEqual((prefix / 'drive_c/windows/system32/xgameruntime.dll').read_bytes(), b'MZ-synthetic')
initialize.assert_called_once()
for child in (initialize, call):
child_env = child.call_args.kwargs['env']
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', child_env)
self.assertNotIn('DROIDDECK_XBOX_COMMAND_FILE', child_env)
self.assertEqual(child_env['XODUS_BRIDGE_KEY'], 'runtime-key')
+147 -53
View File
@@ -30,6 +30,7 @@
#include "handcam_shm.h"
#include "hand_skeleton.h"
#include "index_pose.h"
#include "pad_controller_config.h"
#include "joycon_shm.h"
#include "presenter.h"
#include "spatial_tracking.h"
@@ -1027,45 +1028,57 @@ public:
pose_.qWorldFromDriverRotation.w = pose_.qDriverFromHeadRotation.w = pose_.qRotation.w = 1;
}
void SetProfile(PadProfile profile) { profile_ = profile; }
EVRInitError Activate(uint32_t id) override {
id_ = id;
PropertyContainerHandle_t c = VRProperties()->TrackedDeviceToPropertyContainer(id_);
XrTrackingFile tracking;
DroidDeckXrTracking packet{};
xrMode_ = tracking.Read(&packet) && XrTrackingFile::Fresh(packet);
VRProperties()->SetStringProperty(c, Prop_ModelNumber_String, xrMode_ ? "DroidDeck Quest Touch" : "DroidDeck Pad Hand");
VRProperties()->SetStringProperty(c, Prop_ManufacturerName_String, xrMode_ ? "Meta" : "DroidDeck");
const PadProfile profile = xrMode_ ? PadProfile::Touch : profile_;
touch_ = profile == PadProfile::Touch;
index_ = profile == PadProfile::Index;
const char *model = touch_ ? "DroidDeck Quest Touch" : index_ ? "DroidDeck Index Hand" : "DroidDeck Pad Hand";
VRProperties()->SetStringProperty(c, Prop_ModelNumber_String, model);
VRProperties()->SetStringProperty(c, Prop_ManufacturerName_String, touch_ ? "Meta" : index_ ? "Valve" : "DroidDeck");
VRProperties()->SetStringProperty(c, Prop_TrackingSystemName_String, "droiddeck");
VRProperties()->SetStringProperty(c, Prop_RenderModelName_String, xrMode_ ?
VRProperties()->SetStringProperty(c, Prop_RenderModelName_String, touch_ ?
(right_ ? "oculus_quest_plus_controller_right" : "oculus_quest_plus_controller_left") :
(right_ ? "{indexcontroller}valve_controller_knu_1_0_right" : "{indexcontroller}valve_controller_knu_1_0_left"));
VRProperties()->SetStringProperty(c, Prop_ControllerType_String, xrMode_ ? "oculus_touch" : "vive_controller");
VRProperties()->SetStringProperty(c, Prop_InputProfilePath_String, xrMode_ ?
"{oculus}/input/touch_profile.json" : "{htc}/input/vive_controller_profile.json");
VRProperties()->SetStringProperty(c, Prop_ControllerType_String, touch_ ? "oculus_touch" : index_ ? "knuckles" : "vive_controller");
VRProperties()->SetStringProperty(c, Prop_InputProfilePath_String, touch_ ? "{oculus}/input/touch_profile.json" :
index_ ? "{indexcontroller}/input/index_controller_profile.json" : "{htc}/input/vive_controller_profile.json");
VRProperties()->SetInt32Property(c, Prop_ControllerRoleHint_Int32,
right_ ? TrackedControllerRole_RightHand : TrackedControllerRole_LeftHand);
VRProperties()->SetInt32Property(c, Prop_DeviceClass_Int32, TrackedDeviceClass_Controller);
auto in = VRDriverInput();
const bool stick = touch_ || index_;
const char *stickPath = touch_ ? "/input/joystick" : "/input/thumbstick";
const auto path = [](const char *base, const char *leaf) { return std::string(base) + leaf; };
in->CreateBooleanComponent(c, "/input/system/click", &system_);
in->CreateBooleanComponent(c, "/input/application_menu/click", &menu_);
in->CreateBooleanComponent(c, "/input/grip/click", &grip_);
if (!index_) in->CreateBooleanComponent(c, "/input/application_menu/click", &menu_);
in->CreateBooleanComponent(c, stick ? "/input/grip/touch" : "/input/grip/click", &grip_);
in->CreateBooleanComponent(c, "/input/trigger/click", &triggerClick_);
in->CreateScalarComponent(c, "/input/trigger/value", &trigger_, VRScalarType_Absolute, VRScalarUnits_NormalizedOneSided);
in->CreateScalarComponent(c, xrMode_ ? "/input/joystick/x" : "/input/trackpad/x", &padX_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
in->CreateScalarComponent(c, xrMode_ ? "/input/joystick/y" : "/input/trackpad/y", &padY_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
in->CreateBooleanComponent(c, xrMode_ ? "/input/joystick/click" : "/input/trackpad/click", &padClick_);
in->CreateBooleanComponent(c, xrMode_ ? "/input/joystick/touch" : "/input/trackpad/touch", &padTouch_);
if (xrMode_) {
const char *axisBase = stick ? stickPath : "/input/trackpad";
in->CreateScalarComponent(c, path(axisBase, "/x").c_str(), &padX_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
in->CreateScalarComponent(c, path(axisBase, "/y").c_str(), &padY_, VRScalarType_Absolute, VRScalarUnits_NormalizedTwoSided);
in->CreateBooleanComponent(c, path(axisBase, "/click").c_str(), &padClick_);
in->CreateBooleanComponent(c, path(axisBase, "/touch").c_str(), &padTouch_);
if (stick) {
const bool letters = touch_ && !right_;
in->CreateScalarComponent(c, "/input/grip/value", &gripValue_, VRScalarType_Absolute, VRScalarUnits_NormalizedOneSided);
if (index_) in->CreateScalarComponent(c, "/input/grip/force", &gripForce_, VRScalarType_Absolute, VRScalarUnits_NormalizedOneSided);
in->CreateBooleanComponent(c, "/input/trigger/touch", &triggerTouch_);
in->CreateBooleanComponent(c, right_ ? "/input/a/click" : "/input/x/click", &primaryClick_);
in->CreateBooleanComponent(c, right_ ? "/input/b/click" : "/input/y/click", &secondaryClick_);
in->CreateBooleanComponent(c, right_ ? "/input/a/touch" : "/input/x/touch", &primaryTouch_);
in->CreateBooleanComponent(c, right_ ? "/input/b/touch" : "/input/y/touch", &secondaryTouch_);
in->CreateBooleanComponent(c, "/input/thumbrest/touch", &thumbrestTouch_);
in->CreateBooleanComponent(c, letters ? "/input/x/click" : "/input/a/click", &primaryClick_);
in->CreateBooleanComponent(c, letters ? "/input/y/click" : "/input/b/click", &secondaryClick_);
in->CreateBooleanComponent(c, letters ? "/input/x/touch" : "/input/a/touch", &primaryTouch_);
in->CreateBooleanComponent(c, letters ? "/input/y/touch" : "/input/b/touch", &secondaryTouch_);
if (touch_) in->CreateBooleanComponent(c, "/input/thumbrest/touch", &thumbrestTouch_);
}
in->CreateHapticComponent(c, "/output/haptic", &haptic_);
Log("%s hand activated (%s)", right_ ? "right" : "left", xrMode_ ? "Quest Touch" : "game pad");
Log("%s hand activated (%s)", right_ ? "right" : "left", xrMode_ ? "Quest Touch" : model);
return VRInitError_None;
}
void Deactivate() override { ClearInputs(); id_ = k_unTrackedDeviceIndexInvalid; }
@@ -1085,11 +1098,14 @@ public:
if (id_ == k_unTrackedDeviceIndexInvalid) return;
auto in = VRDriverInput();
EVRInputError error = VRInputError_None;
for (VRInputComponentHandle_t h : {system_, menu_, grip_, triggerClick_, padClick_, padTouch_}) {
for (VRInputComponentHandle_t h : {system_, menu_, grip_, triggerClick_, padClick_, padTouch_, triggerTouch_,
primaryClick_, secondaryClick_, primaryTouch_, secondaryTouch_}) {
if (!h) continue;
const auto result = in->UpdateBooleanComponent(h, false, 0);
if (result != VRInputError_None) error = result;
}
for (VRInputComponentHandle_t h : {trigger_, padX_, padY_}) {
for (VRInputComponentHandle_t h : {trigger_, padX_, padY_, gripValue_, gripForce_}) {
if (!h) continue;
const auto result = in->UpdateScalarComponent(h, 0.0f, 0);
if (result != VRInputError_None) error = result;
}
@@ -1183,16 +1199,14 @@ public:
p.result = valid ? TrackingResult_Running_OK : TrackingResult_Running_OutOfRange;
auto in = VRDriverInput();
const uint32_t b = pad ? pad->buttons : 0;
in->UpdateBooleanComponent(system_, right_ && (b & PAD_GUIDE), 0);
in->UpdateBooleanComponent(menu_, (b & (right_ ? PAD_START : PAD_SELECT)) != 0, 0);
const auto gripError = in->UpdateBooleanComponent(grip_, opticalInputs_.grip, 0);
if (gripValue_) in->UpdateScalarComponent(gripValue_, opticalInputs_.grip ? 1.0f : 0.0f, 0);
const auto clickError = in->UpdateBooleanComponent(triggerClick_, opticalInputs_.click, 0);
const auto triggerError = in->UpdateScalarComponent(trigger_, opticalInputs_.trigger, 0);
if (triggerTouch_) in->UpdateBooleanComponent(triggerTouch_, opticalInputs_.trigger > 0.05f, 0);
const float x = pad ? pad->axes[right_ ? 2 : 0]/32767.0f : 0;
const float y = pad ? -pad->axes[right_ ? 3 : 1]/32767.0f : 0;
in->UpdateScalarComponent(padX_, x, 0); in->UpdateScalarComponent(padY_, y, 0);
in->UpdateBooleanComponent(padTouch_, x*x+y*y > 0.01f || (b & (right_ ? PAD_A : PAD_X)), 0);
in->UpdateBooleanComponent(padClick_, (b & (right_ ? (PAD_A|PAD_R3) : PAD_X)) != 0, 0);
UpdatePadButtons(b, x, y, true);
LogOpticalInputs(hand, inputValid, valid, now, connection, origin, inputEpochs, gripError, clickError, triggerError);
pose_ = p;
VRServerDriverHost()->TrackedDevicePoseUpdated(id_, p, sizeof(p));
@@ -1251,19 +1265,42 @@ public:
auto in = VRDriverInput();
const uint32_t b = pad->buttons;
const float trig = pad->axes[right_ ? 4 : 5] / 255.0f;
const bool touch = !sticksMoveHands && stickX * stickX + stickY * stickY > 0.01f;
in->UpdateBooleanComponent(system_, right_ && (b & PAD_GUIDE), 0);
in->UpdateBooleanComponent(menu_, (b & (right_ ? PAD_START : PAD_SELECT)) != 0, 0);
in->UpdateBooleanComponent(grip_, (b & (right_ ? PAD_RB : PAD_LB)) != 0, 0);
const bool grip = (b & (right_ ? PAD_RB : PAD_LB)) != 0;
in->UpdateScalarComponent(trigger_, trig, 0);
in->UpdateBooleanComponent(triggerClick_, trig > 0.6f, 0);
in->UpdateScalarComponent(padX_, touch ? stickX : 0.0f, 0);
in->UpdateScalarComponent(padY_, touch ? stickY : 0.0f, 0);
in->UpdateBooleanComponent(padTouch_, touch || (b & (right_ ? PAD_A : PAD_X)), 0);
in->UpdateBooleanComponent(padClick_, (b & (right_ ? (PAD_A | PAD_R3) : PAD_X)) != 0, 0);
if (triggerTouch_) in->UpdateBooleanComponent(triggerTouch_, trig > 0.05f, 0);
in->UpdateBooleanComponent(grip_, grip, 0);
if (gripValue_) in->UpdateScalarComponent(gripValue_, grip ? 1.0f : 0.0f, 0);
if (gripForce_) in->UpdateScalarComponent(gripForce_, grip ? 1.0f : 0.0f, 0);
UpdatePadButtons(b, stickX, stickY, !sticksMoveHands);
}
private:
// Face buttons, menus and the stick, for both the game pad and optical hands.
void UpdatePadButtons(uint32_t b, float stickX, float stickY, bool stickToGame) {
auto in = VRDriverInput();
const bool touch = stickToGame && stickX * stickX + stickY * stickY > 0.01f;
in->UpdateBooleanComponent(system_, right_ && (b & PAD_GUIDE), 0);
in->UpdateScalarComponent(padX_, touch ? stickX : 0.0f, 0);
in->UpdateScalarComponent(padY_, touch ? stickY : 0.0f, 0);
if (!touch_ && !index_) {
in->UpdateBooleanComponent(menu_, (b & (right_ ? PAD_START : PAD_SELECT)) != 0, 0);
in->UpdateBooleanComponent(padTouch_, touch || (b & (right_ ? PAD_A : PAD_X)), 0);
in->UpdateBooleanComponent(padClick_, (b & (right_ ? (PAD_A | PAD_R3) : PAD_X)) != 0, 0);
return;
}
// Touch and Index: face buttons are their own inputs and the stick is a thumbstick.
const bool primary = b & (right_ ? PAD_A : PAD_X), secondary = b & (right_ ? PAD_B : PAD_Y);
const bool both = (b & PAD_L3) && (b & PAD_R3);
if (menu_) in->UpdateBooleanComponent(menu_, !right_ && (b & (PAD_START | PAD_SELECT)), 0);
in->UpdateBooleanComponent(primaryClick_, primary, 0);
in->UpdateBooleanComponent(secondaryClick_, secondary, 0);
in->UpdateBooleanComponent(primaryTouch_, primary, 0);
in->UpdateBooleanComponent(secondaryTouch_, secondary, 0);
in->UpdateBooleanComponent(padTouch_, touch, 0);
in->UpdateBooleanComponent(padClick_, !both && (b & (right_ ? PAD_R3 : PAD_L3)), 0);
}
void LogOpticalInputs(const dd_spatial_hand &hand, bool inputValid, bool poseValid, int64_t now,
uint64_t connection, uint64_t origin, uint16_t inputEpochs, EVRInputError gripError,
EVRInputError clickError, EVRInputError triggerError) {
@@ -1297,14 +1334,15 @@ private:
static constexpr int16_t kGrabTrigger = 153;
static constexpr float kStickDeadzone = 0.12f, kHandRangeX = 0.40f, kHandRangeUp = 0.50f, kHandRangeDown = 0.30f, kHandSmoothing = 0.05f, kHandPivot = 0.45f;
bool right_;
bool xrMode_ = false;
bool xrMode_ = false, touch_ = false, index_ = false;
PadProfile profile_ = PadProfile::Index;
uint32_t id_ = k_unTrackedDeviceIndexInvalid;
DriverPose_t pose_ = {};
float pull_ = 0.0f, handX_ = 0.0f, handY_ = 0.0f;
std::chrono::steady_clock::time_point lastUpdate_ = std::chrono::steady_clock::now();
VRInputComponentHandle_t system_ = 0, menu_ = 0, grip_ = 0, triggerClick_ = 0, trigger_ = 0, padX_ = 0, padY_ = 0,
padClick_ = 0, padTouch_ = 0, haptic_ = 0;
VRInputComponentHandle_t gripValue_ = 0, triggerTouch_ = 0, primaryClick_ = 0, secondaryClick_ = 0,
VRInputComponentHandle_t gripValue_ = 0, gripForce_ = 0, triggerTouch_ = 0, primaryClick_ = 0, secondaryClick_ = 0,
primaryTouch_ = 0, secondaryTouch_ = 0, thumbrestTouch_ = 0;
};
@@ -1552,9 +1590,9 @@ private:
if (fresh) PublishChaperone(xr);
DriverPose_t head = GetPose();
VRServerDriverHost()->TrackedDevicePoseUpdated(id_, head, sizeof(head));
for (int hand = 0; hand < 2; hand++) if (hands_[hand]) {
for (int hand = 0; hand < 2; hand++) if (CardboardController *pad = ActiveHand(hand)) {
DroidDeckXrHand state = fresh ? xr.hands[hand] : DroidDeckXrHand{};
hands_[hand]->UpdateXr(state, fresh ? xr.predicted_ns : 0);
pad->UpdateXr(state, fresh ? xr.predicted_ns : 0);
}
VRDriverInput()->UpdateBooleanComponent(proximity_, fresh, 0);
std::this_thread::sleep_for(std::chrono::milliseconds(2));
@@ -1594,9 +1632,10 @@ private:
VRServerDriverHost()->TrackedDevicePoseUpdated(id_, head, sizeof(DriverPose_t));
const bool lumaJoyCons = (spatial.flags & DD_SPATIAL_ACTIVE) && (spatial.flags & DD_SPATIAL_JOYCONS);
const bool optical = !lumaJoyCons && (spatial.flags & DD_SPATIAL_ACTIVE) && (spatial.flags & DD_SPATIAL_HANDS);
if (!optical && havePad && (pad.buttons & PAD_L3) && !(lastPad_.buttons & PAD_L3)) {
sticksMoveHands_ = !sticksMoveHands_;
Log("sticks now move %s", sticksMoveHands_ ? "the hands" : "in the game");
const uint32_t chord = PAD_L3 | PAD_R3;
if (!optical && havePad && (pad.buttons & chord) == chord && (lastPad_.buttons & chord) != chord) {
sticksMoveHands_.store(!sticksMoveHands_.load());
Log("sticks now move %s", sticksMoveHands_.load() ? "the hands" : "in the game");
}
const float dt = std::min(std::chrono::duration<float>(now - lastReach_).count(), 0.1f);
lastReach_ = now;
@@ -1638,7 +1677,7 @@ private:
if (joyCon || bare) wantHand_[side] = true;
const bool covered = handControllers_[side] && handControllers_[side]->Update(joyCon, bare, head.qRotation, nowNs,
lumaJoyCons ? &spatial : nullptr);
CardboardController *hand = hands_[side];
CardboardController *hand = ActiveHand(side);
if (!hand) continue;
if (otherControllers_ || covered || bare || lumaJoyCons) {
if (!padHandOff_[side]) hand->Disconnect();
@@ -1650,7 +1689,7 @@ private:
havePad ? &pad : nullptr, SpatialNow(), spatial.connection, spatial.origin,
uint16_t(spatial.input_epochs >> (side*16)),
spatial.flags & DD_SPATIAL_STEADY_AIM ? &spatial.head : nullptr);
else hand->Update(head, havePad ? &pad : nullptr, sticksMoveHands_, reach_);
else hand->Update(head, havePad ? &pad : nullptr, sticksMoveHands_.load(), reach_);
}
if (havePad) lastPad_ = pad;
lastSent = now;
@@ -1713,6 +1752,18 @@ private:
PropertyContainerHandle_t container_ = k_ulInvalidPropertyContainer;
public:
void SetHands(CardboardController *left, CardboardController *right) { hands_[0] = left; hands_[1] = right; }
void SetSticksMoveHands(bool on) { sticksMoveHands_ = on; }
// Called only from the pose thread: a replaced pair is disconnected there, so it never races an update.
CardboardController *ActiveHand(int side) {
CardboardController *wanted = hands_[side].load();
if (wanted != active_[side]) {
if (active_[side]) active_[side]->Disconnect();
active_[side] = wanted;
padHandOff_[side] = false;
}
return wanted;
}
void SetHandControllers(HandController *left, HandController *right) { handControllers_[0] = left; handControllers_[1] = right; }
bool WantsHand(int side) const { return wantHand_[side].load(); }
@@ -1729,12 +1780,13 @@ private:
PadState lastPad_;
VRInputComponentHandle_t proximity_ = 0;
bool worn_ = true;
bool sticksMoveHands_ = true;
std::atomic<bool> sticksMoveHands_{false};
float reach_ = 0.0f;
std::chrono::steady_clock::time_point lastReach_ = std::chrono::steady_clock::now();
std::chrono::steady_clock::time_point lastScan_{};
bool otherControllers_ = false;
CardboardController *hands_[2] = {nullptr, nullptr};
std::atomic<CardboardController *> hands_[2] = {nullptr, nullptr};
CardboardController *active_[2] = {nullptr, nullptr};
bool padHandOff_[2] = {false, false};
ShmFile<droiddeck_joycon> joyConFile_{kJoyConPath, DROIDDECK_JOYCON_MAGIC, DROIDDECK_JOYCON_VERSION, "Joy-Con"};
uint32_t lastJoyConSeq_ = 0;
@@ -1767,11 +1819,8 @@ public:
Log("DroidDeck Cardboard driver loaded");
if (!VRServerDriverHost()->TrackedDeviceAdded("droiddeck-cardboard-hmd", TrackedDeviceClass_HMD, &hmd_))
Log("TrackedDeviceAdded failed");
if (VRSettings()->GetBool(kSettingsSection, "gamepadControllers")) {
VRServerDriverHost()->TrackedDeviceAdded("droiddeck-pad-left", TrackedDeviceClass_Controller, &left_);
VRServerDriverHost()->TrackedDeviceAdded("droiddeck-pad-right", TrackedDeviceClass_Controller, &right_);
hmd_.SetHands(&left_, &right_);
}
padsEnabled_ = VRSettings()->GetBool(kSettingsSection, "gamepadControllers");
ApplyPadConfig(true);
hmd_.SetHandControllers(&handLeft_, &handRight_);
return VRInitError_None;
}
@@ -1782,6 +1831,11 @@ public:
}
const char *const *GetInterfaceVersions() override { return k_InterfaceVersions; }
void RunFrame() override {
const auto now = std::chrono::steady_clock::now();
if (now - lastConfigCheck_ > std::chrono::seconds(1)) {
lastConfigCheck_ = now;
ApplyPadConfig(false);
}
for (int side = 0; side < 2; side++) {
if (handAdded_[side] || !hmd_.WantsHand(side)) continue;
handAdded_[side] = true;
@@ -1803,9 +1857,11 @@ public:
if (!h.componentHandle) continue;
if (h.componentHandle == handLeft_.Haptic()) SendRumble(DROIDDECK_JOYCON_RUMBLE_SLOT, h);
else if (h.componentHandle == handRight_.Haptic()) SendRumble(DROIDDECK_JOYCON_RUMBLE_SLOT + 1, h);
else if (h.componentHandle == left_.Haptic() || h.componentHandle == right_.Haptic()) {
if (left_.XrMode()) SendHaptic(h.componentHandle == right_.Haptic() ? 1 : 0, h);
else for (int p = 0; p < kPadProfiles; p++) {
if (!padAdded_[p] || (h.componentHandle != pads_[p][0].Haptic() && h.componentHandle != pads_[p][1].Haptic())) continue;
if (pads_[p][0].XrMode()) SendHaptic(h.componentHandle == pads_[p][1].Haptic() ? 1 : 0, h);
else SendRumble(0, h);
break;
}
}
}
@@ -1852,8 +1908,46 @@ private:
target.frequency = std::max(pulse.fFrequency, 0.f);
__atomic_store_n(&haptics_->seq, (sequence | 1u) + 1u, __ATOMIC_RELEASE);
}
// SteamVR fixes a device's input profile when it activates, so each type gets its own pair,
// added the first time it is chosen; devices cannot be removed, only disconnected.
void ApplyPadConfig(bool initial) {
// The file is a few bytes, so compare what it says; two quick writes can share an mtime.
const PadControllerConfig pads = read_pad_controller_config("/run/droiddeck/" DROIDDECK_VR_CONTROLLERS_FILE);
if (!initial && pads.profile == configProfile_ && pads.sticksMoveHands == configSticks_) return;
configProfile_ = pads.profile;
if (initial || pads.sticksMoveHands != configSticks_) hmd_.SetSticksMoveHands(pads.sticksMoveHands);
configSticks_ = pads.sticksMoveHands;
const PadProfile profile = padsEnabled_ ? pads.profile : PadProfile::Off;
if (!initial && profile == profile_) return;
profile_ = profile;
Log("game pad hands: %s, sticks start in %s", pad_profile_name(profile), pads.sticksMoveHands ? "the hands" : "the game");
if (profile == PadProfile::Off) { hmd_.SetHands(nullptr, nullptr); return; }
const int p = int(profile) - 1;
if (!padAdded_[p]) {
static const char *const kNames[kPadProfiles][2] = {
{"droiddeck-pad-left", "droiddeck-pad-right"},
{"droiddeck-pad-touch-left", "droiddeck-pad-touch-right"},
{"droiddeck-pad-vive-left", "droiddeck-pad-vive-right"},
};
for (int side = 0; side < 2; side++) {
pads_[p][side].SetProfile(profile);
VRServerDriverHost()->TrackedDeviceAdded(kNames[p][side], TrackedDeviceClass_Controller, &pads_[p][side]);
}
padAdded_[p] = true;
}
hmd_.SetHands(&pads_[p][0], &pads_[p][1]);
}
static constexpr int kPadProfiles = 3;
CardboardHmd hmd_;
CardboardController left_{false}, right_{true};
CardboardController pads_[kPadProfiles][2] = {{CardboardController(false), CardboardController(true)},
{CardboardController(false), CardboardController(true)},
{CardboardController(false), CardboardController(true)}};
bool padAdded_[kPadProfiles] = {false, false, false};
bool padsEnabled_ = true, configSticks_ = false;
PadProfile profile_ = PadProfile::Off;
PadProfile configProfile_ = PadProfile::Index;
std::chrono::steady_clock::time_point lastConfigCheck_{};
HandController handLeft_{false}, handRight_{true};
bool handAdded_[2] = {false, false};
};
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include <cstdio>
#include <cstring>
#define DROIDDECK_VR_CONTROLLERS_FILE "droiddeck-vr-controllers"
enum class PadProfile { Off, Index, Touch, Vive };
struct PadControllerConfig {
PadProfile profile = PadProfile::Index;
bool sticksMoveHands = false;
};
// One key=value per line, written by the app before SteamVR starts.
inline PadControllerConfig pad_controller_config(const char *text) {
PadControllerConfig config;
if (!text) return config;
for (const char *line = text; *line;) {
const char *end = std::strchr(line, '\n');
const size_t length = end ? size_t(end - line) : std::strlen(line);
const auto is = [&](const char *expected) {
return std::strlen(expected) == length && !std::strncmp(line, expected, length);
};
if (is("emulate=off")) config.profile = PadProfile::Off;
else if (is("emulate=index")) config.profile = PadProfile::Index;
else if (is("emulate=touch")) config.profile = PadProfile::Touch;
else if (is("emulate=vive")) config.profile = PadProfile::Vive;
else if (is("sticks=hands")) config.sticksMoveHands = true;
else if (is("sticks=game")) config.sticksMoveHands = false;
if (!end) break;
line = end + 1;
}
return config;
}
inline PadControllerConfig read_pad_controller_config(const char *path) {
char text[256] = {};
if (FILE *f = std::fopen(path, "r")) {
const size_t n = std::fread(text, 1, sizeof(text) - 1, f);
text[n] = 0;
std::fclose(f);
}
return pad_controller_config(text);
}
inline const char *pad_profile_name(PadProfile profile) {
switch (profile) {
case PadProfile::Off: return "off";
case PadProfile::Index: return "Index";
case PadProfile::Touch: return "Quest Touch";
case PadProfile::Vive: return "Vive";
}
return "?";
}
@@ -80,6 +80,7 @@ int main() {
Context context;
VRDriverContext() = &context;
CardboardController controller(false);
controller.SetProfile(PadProfile::Vive);
assert(controller.Activate(1) == VRInitError_None);
const auto gripHandle=context.input.handles.at("/input/grip/click");
const auto clickHandle=context.input.handles.at("/input/trigger/click");
@@ -260,4 +261,46 @@ int main() {
joyCon.Update(nullptr, false, {1,0,0,0}, now, &spatial);
assert(!joyCon.GetPose().deviceIsConnected && context.input.values.at(joyTrigger) == 0);
puts("PASS: optical controller recovery and Luma Joy-Con camera, fallback, head loss and origin changes");
for (const PadProfile profile : {PadProfile::Index, PadProfile::Touch}) {
auto &padContext = context;
padContext.input.handles.clear();
CardboardController pad(true);
pad.SetProfile(profile);
assert(pad.Activate(2) == VRInitError_None);
const auto &h = padContext.input.handles;
const std::string stick = profile == PadProfile::Touch ? "/input/joystick" : "/input/thumbstick";
assert(!h.count("/input/trackpad/x") && h.count("/input/b/click") && h.count("/input/grip/value"));
assert(h.count("/input/application_menu/click") == (profile == PadProfile::Touch));
DriverPose_t head{};
head.qRotation.w = 1;
PadState state{};
state.buttons = PAD_A | PAD_RB;
state.axes[2] = 32767;
state.axes[4] = 255;
pad.Update(head, &state, false, 0);
const auto value = [&](const std::string &name) { return padContext.input.values.at(h.at(name)); };
assert(value("/input/a/click") == 1 && value("/input/b/click") == 0);
assert(value(stick + "/x") == 1 && value(stick + "/touch") == 1 && value(stick + "/click") == 0);
assert(value("/input/grip/value") == 1 && value("/input/trigger/value") == 1);
pad.Update(head, &state, true, 0);
assert(value(stick + "/x") == 0);
state = {};
state.buttons = PAD_R3;
pad.Update(head, &state, false, 0);
assert(value(stick + "/click") == 1);
state.buttons = PAD_L3 | PAD_R3;
pad.Update(head, &state, false, 0);
assert(value(stick + "/click") == 0);
dd_spatial_hand optical{};
state = {};
state.buttons = PAD_A;
pad.UpdateOptical(optical, false, &state, 1000000000, 1, 1);
assert(value("/input/a/click") == 1 && value(stick + "/click") == 0 && value(stick + "/touch") == 0);
state.buttons = PAD_B | PAD_R3;
pad.UpdateOptical(optical, false, &state, 1000000001, 1, 1);
assert(value("/input/b/click") == 1 && value("/input/a/click") == 0 && value(stick + "/click") == 1);
assert(!padContext.input.values.count(0));
}
puts("PASS: game pad hands as Index and Quest Touch thumbstick controllers");
}
@@ -0,0 +1,19 @@
#include "../src/pad_controller_config.h"
#include <cassert>
#include <cstdio>
int main() {
auto config = pad_controller_config(nullptr);
assert(config.profile == PadProfile::Index && !config.sticksMoveHands);
config = pad_controller_config("emulate=touch\nsticks=hands\n");
assert(config.profile == PadProfile::Touch && config.sticksMoveHands);
config = pad_controller_config("emulate=off");
assert(config.profile == PadProfile::Off);
config = pad_controller_config("emulate=vive\nsticks=game");
assert(config.profile == PadProfile::Vive && !config.sticksMoveHands);
config = pad_controller_config("emulate=offline\nsticks=handsome\n");
assert(config.profile == PadProfile::Index && !config.sticksMoveHands);
assert(read_pad_controller_config("/nonexistent/droiddeck").profile == PadProfile::Index);
std::puts("pad controller config ok");
return 0;
}
+502
View File
@@ -0,0 +1,502 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Xodus Nexus contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+23
View File
@@ -0,0 +1,23 @@
The MIT License
Copyright (c) 2012, 2014, 2015, 2016 Tatsuhiro Tsujikawa
Copyright (c) 2012, 2014, 2015, 2016 nghttp2 contributors
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+103
View File
@@ -0,0 +1,103 @@
# Xbox backend for DroidDeck
DroidDeck uses the Nexus backend protocol with a native Linux AArch64 CLI and
service. It does not install the Nexus desktop launcher or x86 Linux Wine.
`backend.lock.json` pins Xodus, the Nexus commit, Rust, and the ordered patch
checksums. `runtime.lock.json` pins the Nexus Windows runtime release and each
extracted PE DLL. `prepare.py` verifies both source revisions and all Nexus patch
checksums before applying the local transport, launch and library patches.
`droiddeck-library-subscriptions.patch` queries fresh subscription membership
alongside product entitlements using the same Store session, account and market.
Android can validate a Game Pass child's parent plan when that plan is absent
from the product response. A failed membership query fails the refresh and
preserves the previous library. Empty membership results add no plan evidence;
valid plans already present in the product response retain their existing checks.
Build on AArch64 Ubuntu 24.04 with Rust from the lock, a C/C++ compiler, OpenSSL
development headers, pkg-config, protoc, CMake, Git, Python 3 and xz:
```sh
bash tools/xbox/build.sh
```
On macOS, `bash tools/xbox/build-local.sh` uses an AArch64 Ubuntu container.
`tools/build_local.sh` includes this step and caches it by recipe inputs. CI
builds the same recipe on `ubuntu-24.04-arm` and transfers the result to the APK
job. Cache hits still download that build's Xbox artifact before APK assembly.
The build runs account-free CLI, credential and streaming tests. It retains the
patched backend source archive and the checksum-verified runtime source archive
in the build cache and publishes both in CI's `xbox-corresponding-source`
artifact; distribute corresponding sources with published binaries.
`droiddeck-credentials.patch` replaces Linux Secret Service with a bounded,
Android abstract socket restricted to the backend process started by the host. The Android host encrypts every persistent
write using its existing Keystore cipher, verifies backend read-backs, and
rejects writes when Keystore is unavailable. No token values enter process
arguments, external storage, application logs or a plaintext credential file.
Account-generation invalidation prevents a signed-out child's later writes from
restoring credentials. Each backend gets its own socket. The host checks the peer UID, the PRoot tracer
owned by its live child, and an executable mapping of the backend file with a matching inode and
SHA-256 against the APK asset. PRoot's loader can occupy `/proc/<pid>/exe`, so
authentication checks the mapped backend image instead. A socket name alone grants no credential operations, including to another
copy of Xodus started by the guest.
Licensed launch-view preparation runs in an Android-owned Xodus child, which
never starts Wine or a game. Steam and DroidDeck launch paths can request
preparation for an installed Xbox title during a live session with an Xbox
account. The reply contains a random launch lease, a materialized executable
path, a game-service socket and the existing PlayFab game token; it contains no
account credential endpoint.
Leases bind product, account and session, expire without heartbeats, and release
idempotently. Cancellation, session stop and account changes revoke leases;
closing the child's stdin lets it remove its private view. Suspension preserves
live leases.
The Proton initialization and game processes do not inherit the raw credential
channel or command-file environment variables. The authenticated GDK bridge
remains available to the game. Like the other stores, games share DroidDeck's
Linux environment and Android UID. The process checks close the direct
credential-socket route; they do not isolate writable runtime files, prevent
same-UID process tampering, or provide a sandbox against malicious games.
Microsoft sign-in uses Nexus's private stdio protocol in an isolated Android
WebView process. Its page bridge is restricted to the allowed Microsoft/Xbox
HTTPS origins and the main frame; it has no credential-store or launcher API.
Cookies and page storage are cleared for each attempt. This protocol requires
an embedded host for CloudExperienceHost messages; opening its URL in an ordinary
Android browser does not complete it. Passkey behavior needs device testing.
`droiddeck-launch-view.patch` materializes all licensed encrypted images,
including DLLs, in a private temporary directory. Original package files remain
encrypted, and the temporary view is removed after the Wine child exits. Wine
receives normal files with no Xodus FD-map requirement. This costs temporary
storage proportional to the encrypted images. The app keeps the account service
alive for the session; an authenticated loopback bridge carries GDK requests.
Wine's builtin PE marker makes `WINEDLLOVERRIDES=n` reject the Nexus modules.
The extractor verifies their original hashes, then changes only that 16-byte DOS
stub marker to `DroidDeck native`; code, imports and exports stay unchanged. This
lets ARM64EC Wine load the AMD64 modules through its normal native DLL path.
Only each Xbox game's prefix receives these Windows modules. Existing
Steam games and other store prefixes retain their selected runtimes.
Cloud saves and in-game identity use the reused XGameRuntime/service interfaces;
those are game-dependent. Entitlements distinguish purchases from Game Pass
access, and the backend performs a fresh license check for downloads and launch.
The store lists PC MSIXVC games only. It does not emulate Xbox consoles or add
support for UWP/APPX packages. Update / verify refreshes an installed package through the normal licensed
streaming path. Manage content resolves manifest-related licensed PC DLC into
separate content roots and checks its parent identity after download. These
flows still require game/account validation; runtime API presence does not
establish that they work on Thor.
Upstream contribution restrictions are respected: these are launcher, storage,
build and file-lifecycle adapters in DroidDeck, not submitted reverse-engineering
contributions to Xodus.
Sources and licenses:
- Xodus: https://github.com/xodus-gaming/xodus (GPL-3.0, `LICENSE.xodus`).
- Nexus patches: https://github.com/domsvoboda/xodus-nexus (MIT, `LICENSE.nexus`).
- XGameRuntime/Wine modules: the exact source archive is identified in
`runtime.lock.json` (LGPL-2.1, `LICENSE.LGPL-2.1`).
- `libnghttp2.dll`: nghttp2, MIT; its license is retained in the runtime source
archive and is packaged as `LICENSE.nghttp2`.
+109
View File
@@ -0,0 +1,109 @@
{
"schema": 1,
"version": "0.2.8",
"repository": "https://github.com/xodus-gaming/xodus.git",
"commit": "53ea781dcd073e31d7ea68e894134e9c959bff04",
"rust": "1.99.0",
"cargoLockSha256": "2259b343e00dadc263018beb7664b12e9d58a0b73bff502ad566f5f8619ce28a",
"patchId": "linux-run-v24",
"compatibility": "linux-run-v18",
"patches": [
{
"file": "xodus-linux-run.patch",
"sha256": "68f260ec2c6e9264c47ed1a650868511f5412a756725d4000a865804f4712e8b"
},
{
"file": "xodus-offline-mirror.patch",
"sha256": "c865fc2559c43a5b3eb2bc841035c076eae5c42a90fe488f90514384aa916986"
},
{
"file": "xodus-account-status.patch",
"sha256": "e2a718d16957733d140891fcdd26cc8cb3db0636307e6ff6e9ffbfa41a2d393c"
},
{
"file": "xodus-streaming-cache-flush.patch",
"sha256": "4dd7a129ab9b3aac74d46f926efe26f163741d50fe2853a07f292240ab522b05"
},
{
"file": "xodus-launch-chain.patch",
"sha256": "22dfbfc5cec911091351bb2d648f4b16bd274aa276ee4524be738a357c8b219a"
},
{
"file": "xodus-memfd-path.patch",
"sha256": "905cfda813f0a434a2c13fd2db973385f0311cbec5c86bc3549737a7838f49fd"
},
{
"file": "xodus-real-launch-images.patch",
"sha256": "95fc642e3adfa50414648e40df6ee94262964f5eea0f3762a34765f56d7824b7"
},
{
"file": "xodus-store-license.patch",
"sha256": "99a89821e15ba144126515b5e8ec70b0673caf694d9295f16cd6661564b7c579"
},
{
"file": "xodus-store-updates.patch",
"sha256": "554e3849122c8cd3c64c7f5904ac06931a088bc8fb4c522ec2c55b972b72ea8e"
},
{
"file": "xodus-streaming-progress.patch",
"sha256": "b5e22d8eb595502776c4d6f2a5451403647e31754fc6358bc4f338cab72642a0"
},
{
"file": "xodus-case-insensitive-paths.patch",
"sha256": "53dbfd6f734db100fff958e4a311155cad2cb374db456f73544ad76e3799ac8d"
},
{
"file": "xodus-account-profile.patch",
"sha256": "135166ff0cf9f95af92dad6fd1c958b6c57e939fbb5b398b5a603b730541554a"
},
{
"file": "xodus-subscription-login.patch",
"sha256": "6c3f32c905039948b3ff95a0ceaba9b2a09a9417606653bce9b741c8bba43eb0"
},
{
"file": "xodus-external-auth.patch",
"sha256": "0a22d5a84d328780e6f13ac07f8e1db6359ec70139ad4262e4c1ee988973e20e"
},
{
"file": "xodus-keyring-activation.patch",
"sha256": "8c71928e0b365f4770532ef968322450f1ebab3a1199e7a10d894119c48c925e"
},
{
"file": "xodus-package-selection.patch",
"sha256": "7507cb0535cd914d3607e7940d5e17b949d106d0b89c139b84372a1ee1732c54"
},
{
"file": "xodus-package-metadata.patch",
"sha256": "43fccfbb2ea2a9809e7f0b3d9e2f506213e6245d3bbd4c1c631149a67bb2d661"
},
{
"file": "xodus-license-sku.patch",
"sha256": "b7c93b6ead7120c5b2af3616e80c0dadf56326a8bc81a2526a5e1f2700f58e20"
},
{
"file": "xodus-keyring-credentials.patch",
"sha256": "8b354f95b864ffd7eadb02f0d54eb1361bb92fde14ff8696fabfea5c43d03811"
},
{
"file": "xodus-library-resilience.patch",
"sha256": "0136157efe8a1419f91243c496656c4d043422e126c40e4a552e769c53de3545"
},
{
"file": "xodus-game-activity.patch",
"sha256": "89bfd422f951515dd393eb479901ff9613441c627d139918c233a19ec21f1e06"
},
{
"file": "xodus-achievements.patch",
"sha256": "55e4b56b943f491da4c9836a5d6655417ed63ab6383576a8e0f153ec986039b0"
},
{
"file": "xodus-session-recovery.patch",
"sha256": "fa67d768214247a5955716b9691616b45330ebda504703bf372fdda2252b0831"
},
{
"file": "xodus-content-response.patch",
"sha256": "e9997951526cfa08e3dd8c5fc4c383bf630e7ab8992d9e211acee40fdc6422a4"
}
],
"nexusCommit": "396e7fb8fe0e5f00d956091195c614b8a0732ab1"
}
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env bash
set -euo pipefail
repo=$(cd "$(dirname "$0")/../.." && pwd)
cache=${DROIDDECK_XBOX_CACHE:-"${HOME}/.cache/droiddeck-xbox-build"}
mkdir -p "$cache"
docker run --rm --platform linux/arm64 -v "$repo:/src" -v "$cache:/work" -w /src \
-e CARGO_HOME=/work/cargo -e RUSTUP_HOME=/work/rustup -e XBOX_BUILD_DIR=/work/build ubuntu:24.04 bash -lc '
set -euo pipefail
apt-get update -qq
DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends \
build-essential pkg-config libssl-dev protobuf-compiler cmake curl git ca-certificates xz-utils python3 >/dev/null
export PATH=/work/cargo/bin:$PATH
if ! command -v rustup >/dev/null; then
version=$(python3 -c '\''import json;print(json.load(open("tools/xbox/backend.lock.json"))["rust"])'\'')
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain "$version"
fi
bash tools/xbox/build.sh
'
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env bash
set -euo pipefail
repo=$(cd "$(dirname "$0")/../.." && pwd)
cache=${XBOX_BUILD_DIR:-"$repo/app/build/xbox"}
out=${1:-"$repo/app/src/main/assets/linuxfs/usr/local/lib/droiddeck-xbox"}
mkdir -p "$cache" "$out"
source_dir=$(python3 "$repo/tools/xbox/prepare.py" "$cache")
rust_version=$(python3 -c 'import json,sys;print(json.load(open(sys.argv[1]))["rust"])' "$repo/tools/xbox/backend.lock.json")
export RUSTUP_TOOLCHAIN=$rust_version
export CARGO_TARGET_DIR=${CARGO_TARGET_DIR:-"$cache/target"}
rustup target add aarch64-unknown-linux-gnu
export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=${CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER:-aarch64-linux-gnu-gcc}
if [[ $(uname -m) = aarch64 ]]; then export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=cc; fi
cd "$source_dir"
cargo build --locked --release --no-default-features --target aarch64-unknown-linux-gnu -p xodus-cli -p xodus-service
if [[ $(uname -m) = aarch64 ]]; then
cargo test --locked --release --no-default-features --target aarch64-unknown-linux-gnu -p xodus-cli
cargo test --locked --release --no-default-features --target aarch64-unknown-linux-gnu -p xodus credential_
cargo test --locked --release --no-default-features --target aarch64-unknown-linux-gnu -p msixvc streaming_
fi
for binary in xodus-cli xodus-service; do
install -m755 "$CARGO_TARGET_DIR/aarch64-unknown-linux-gnu/release/$binary" "$out/$binary"
done
python3 "$repo/tools/xbox/runtime.py" "$cache/runtime" "$out/windows"
install -m644 "$repo/tools/xbox/LICENSE.xodus" "$out/LICENSE.xodus"
install -m644 "$repo/tools/xbox/LICENSE.nexus" "$out/LICENSE.nexus"
install -m644 "$repo/tools/xbox/LICENSE.LGPL-2.1" "$out/LICENSE.LGPL-2.1"
install -m644 "$repo/tools/xbox/LICENSE.nghttp2" "$out/LICENSE.nghttp2"
cp "$repo/tools/xbox/"*.lock.json "$out/"
python3 - "$out" "$repo/tools/xbox/droiddeck-credentials.patch" <<'PY'
import hashlib,json,pathlib,sys
out=pathlib.Path(sys.argv[1])
files={str(p.relative_to(out)):hashlib.sha256(p.read_bytes()).hexdigest() for p in out.rglob('*') if p.is_file() and p.name!='version'}
files['credentialPatch']=hashlib.sha256(pathlib.Path(sys.argv[2]).read_bytes()).hexdigest()
(out/'version').write_text(hashlib.sha256(json.dumps(files,sort_keys=True).encode()).hexdigest()+'\n')
PY
tar -cJf "$cache/xodus-droiddeck-source.tar.xz" --exclude=.git --exclude=target -C "$source_dir" . -C "$repo" tools/xbox
+154
View File
@@ -0,0 +1,154 @@
--- a/crates/xodus/src/secrets.rs
+++ b/crates/xodus/src/secrets.rs
@@ -1,73 +1,14 @@
-pub static SERVICE_NAME: &str = "Xodus Service";
+use crate::tokens::{backend::KeychainBackend, store::{TokenBackend, TokenStoreError}};
pub fn init_secrets() -> Result<(), keyring_core::Error> {
- #[cfg(feature = "key-chain-file")]
- {
- let store = keyring_core::sample::Store::new_with_backing(
- secrets_backing_file()
- .to_str()
- .expect("Invalid secrets backing path"),
- )?;
- keyring_core::set_default_store(store);
- }
-
- #[cfg(not(feature = "key-chain-file"))]
- {
- #[cfg(target_os = "linux")]
- {
- activate_desktop_keyring();
- keyring_core::set_default_store(dbus_secret_service_keyring_store::Store::new()?);
- }
-
- #[cfg(target_os = "macos")]
- {
- keyring_core::set_default_store(apple_native_keyring_store::keychain::Store::new()?);
- }
-
- #[cfg(not(any(target_os = "linux", target_os = "macos")))]
- {
- let store = keyring_core::sample::Store::new_with_configuration(
- &std::collections::HashMap::from([("persist", "true")]),
- )?;
- keyring_core::set_default_store(store);
- }
- }
-
+ if std::env::var_os("DROIDDECK_XBOX_CREDENTIAL_SOCKET").is_none() { return Err(keyring_core::Error::NoEntry); }
Ok(())
}
-
-// Some KDE installations advertise ksecretd only under its compatibility
-// activation name. Respect an existing/default Secret Service provider first.
-// This starts a packaged user service, never installs or configures a keyring.
-#[cfg(all(target_os = "linux", not(feature = "key-chain-file")))]
-fn activate_desktop_keyring() {
- use dbus::blocking::Connection;
- use std::time::Duration;
- let Ok(connection) = Connection::new_session() else { return; };
- let bus = connection.with_proxy("org.freedesktop.DBus", "/org/freedesktop/DBus", Duration::from_secs(3));
- let Ok((owned,)): Result<(bool,), _> = bus.method_call("org.freedesktop.DBus", "NameHasOwner", ("org.freedesktop.secrets",)) else { return; };
- if owned { return; }
- let Ok((names,)): Result<(Vec<String>,), _> = bus.method_call("org.freedesktop.DBus", "ListActivatableNames", ()) else { return; };
- if names.iter().any(|name| name == "org.freedesktop.secrets") { return; }
- if names.iter().any(|name| name == "org.kde.secretservicecompat") {
- // On failure, Store::new below still returns the genuine keyring error.
- let _: Result<(u32,), _> = bus.method_call("org.freedesktop.DBus", "StartServiceByName", ("org.kde.secretservicecompat", 0u32));
- }
+pub struct Entry(String);
+pub fn get_entry(user: &str) -> Result<Entry, keyring_core::Error> { Ok(Entry(user.into())) }
+impl Entry {
+ pub fn get_secret(&self) -> Result<Vec<u8>, TokenStoreError> { KeychainBackend.get(&self.0)?.ok_or(TokenStoreError::NotFound) }
+ pub fn set_secret(&self, value: &[u8]) -> Result<(), TokenStoreError> { KeychainBackend.set(&self.0, value) }
+ pub fn delete_credential(&self) -> Result<(), TokenStoreError> { KeychainBackend.remove(&self.0) }
}
-
-pub fn get_entry(user: &str) -> Result<keyring_core::Entry, keyring_core::Error> {
- keyring_core::Entry::new(SERVICE_NAME, user)
-}
-
-pub fn destroy_secrets() {
- keyring_core::unset_default_store();
-}
-
-#[cfg(feature = "key-chain-file")]
-fn secrets_backing_file() -> std::path::PathBuf {
- std::env::var_os("HOME")
- .or_else(|| std::env::var_os("USERPROFILE"))
- .map(std::path::PathBuf::from)
- .unwrap_or_else(std::env::temp_dir)
- .join(".xodus-keyring.ron")
-}
+pub fn destroy_secrets() {}
--- a/crates/xodus/src/tokens/backend/keychain.rs
+++ b/crates/xodus/src/tokens/backend/keychain.rs
@@ -1,22 +1,43 @@
use crate::tokens::store::{TokenBackend, TokenStoreError};
+use serde_json::{Value, json};
+use std::io::{BufRead, Read, Write};
+use std::os::linux::net::SocketAddrExt;
+use std::os::unix::net::{SocketAddr, UnixStream};
+use std::time::Duration;
pub struct KeychainBackend;
+fn request(value: Value) -> Result<Value, TokenStoreError> {
+ let name = std::env::var("DROIDDECK_XBOX_CREDENTIAL_SOCKET")
+ .map_err(|_| std::io::Error::other("Android credential host is unavailable"))?;
+ let address = SocketAddr::from_abstract_name(name)?;
+ let mut stream = UnixStream::connect_addr(&address)?;
+ stream.set_read_timeout(Some(Duration::from_secs(10)))?;
+ stream.set_write_timeout(Some(Duration::from_secs(10)))?;
+ serde_json::to_writer(&mut stream, &value)?;
+ stream.write_all(b"\n")?;
+ let mut bytes = Vec::new();
+ std::io::BufReader::new(stream).take(2_097_153).read_until(b'\n', &mut bytes)?;
+ if bytes.len() > 2_097_152 || bytes.last() != Some(&b'\n') {
+ return Err(std::io::Error::other("Invalid Android credential response").into());
+ }
+ let response: Value = serde_json::from_slice(&bytes)?;
+ if response["ok"] != true { return Err(std::io::Error::other("Android credential storage unavailable").into()); }
+ Ok(response)
+}
+
impl TokenBackend for KeychainBackend {
fn get(&self, key: &str) -> Result<Option<Vec<u8>>, TokenStoreError> {
- let entry = crate::secrets::get_entry(key)?;
- match entry.get_secret() {
- Ok(bytes) => Ok(Some(bytes)),
- Err(keyring_core::Error::NoEntry) => Ok(None),
- Err(e) => Err(e.into()),
- }
+ let response = request(json!({"op":"get", "key":key}))?;
+ if response["value"].is_null() { return Ok(None); }
+ Ok(Some(serde_json::from_value(response["value"].clone())?))
}
-
fn set(&self, key: &str, value: &[u8]) -> Result<(), TokenStoreError> {
- Ok(crate::secrets::get_entry(key)?.set_secret(value)?)
+ request(json!({"op":"set", "key":key, "value":value}))?;
+ Ok(())
}
-
fn remove(&self, key: &str) -> Result<(), TokenStoreError> {
- Ok(crate::secrets::get_entry(key)?.delete_credential()?)
+ request(json!({"op":"remove", "key":key}))?;
+ Ok(())
}
}
--- a/crates/xodus/Cargo.toml
+++ b/crates/xodus/Cargo.toml
@@ -43,8 +43,8 @@
smbios-lib = "0.9.4"
[target.'cfg(target_os = "linux")'.dependencies]
-dbus = "=0.9.12"
-dbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-openssl"]}
+dbus = { version = "=0.9.12", optional = true }
+dbus-secret-service-keyring-store = { version = "1.0.1", features = ["crypto-openssl"], optional = true}
[target.'cfg(target_os = "macos")'.dependencies]
apple-native-keyring-store = { version = "1.0.2", features = ["keychain"]}
+106
View File
@@ -0,0 +1,106 @@
--- a/crates/xodus-cli/src/commands/run.rs
+++ b/crates/xodus-cli/src/commands/run.rs
@@ -77,6 +77,7 @@
launch_image: &Path,
materialize_chain: bool,
) -> (String, String) {
+ if materialize_chain { return (String::new(), String::new()); }
let source_nt = source.to_string_lossy().replace('/', "\\");
let source_nt = source_nt.trim_end_matches('\\');
let mirror_unix = mirror_nt_prefix.map(|prefix| prefix.replace('\\', "/"));
@@ -200,9 +201,7 @@
let entry_path = checked_relative_path(entry_suffix)?;
let mut decrypted = HashMap::new();
for (name, fd) in fds {
- if name.to_ascii_lowercase().ends_with(".exe") || checked_relative_path(name)? == entry_path {
- decrypted.insert(checked_relative_path(name)?, *fd);
- }
+ decrypted.insert(checked_relative_path(name)?, *fd);
}
if !decrypted.contains_key(&entry_path) {
return Err(std::io::Error::new(
@@ -222,11 +221,8 @@
}
}
let decrypted_files: HashSet<PathBuf> = decrypted.keys().cloned().collect();
- let parent = source_root.parent().unwrap_or_else(|| Path::new("/tmp"));
- let mirror = Builder::new()
- .prefix(".xodus-chain-")
- .tempdir_in(parent)
- .or_else(|_| Builder::new().prefix("xodus-chain-").tempdir())?;
+ let mirror = Builder::new().prefix("droiddeck-xbox-")
+ .permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700)).tempdir()?;
populate_launch_view(
source_root,
mirror.path(),
@@ -667,21 +663,15 @@
use std::os::fd::AsRawFd;
#[test]
- fn full_launch_view_uses_real_executables_and_preserves_encrypted_dll_maps() {
+ fn full_launch_view_needs_no_inherited_descriptor_maps() {
let entry = String::from("\\Launcher.exe");
let child = String::from("\\Bin\\Child.ExE");
let dll = String::from("\\Bin\\Encrypted.dll");
let files = [(&entry, 10), (&child, 11), (&dll, 12)];
let (nt, unix) = launch_file_maps(&files, Path::new("/package"), Some("\\view"),
&entry, 10, Path::new("/view/Launcher.exe"), true);
- assert!(nt.contains("10:\\??\\Z:\\package\\Launcher.exe"));
- assert!(unix.contains("10:/package/Launcher.exe"));
- assert!(!nt.contains("\\view\\Launcher.exe"));
- assert!(!nt.contains("\\view\\Bin\\Child.ExE"));
- assert!(!unix.contains("/view/Launcher.exe"));
- assert!(!unix.contains("/view/Bin/Child.ExE"));
- assert!(nt.contains("12:\\??\\Z:\\view\\Bin\\Encrypted.dll"));
- assert!(unix.contains("12:/view/Bin/Encrypted.dll"));
+ assert!(nt.is_empty());
+ assert!(unix.is_empty());
}
#[test]
@@ -778,6 +768,25 @@
.is_symlink());
assert_eq!(std::fs::read(source.join("Dungeons.exe")).unwrap(), b"encrypted launcher");
assert_eq!(std::fs::read(nested.join("Shipping.exe")).unwrap(), b"encrypted child");
+ }
+
+ #[test]
+ fn launch_view_materializes_encrypted_dlls_in_private_storage() {
+ let root = tempfile::tempdir().unwrap();
+ std::fs::write(root.path().join("Game.exe"), b"encrypted").unwrap();
+ std::fs::write(root.path().join("Secret.dll"), b"encrypted-dll").unwrap();
+ let mut image = tempfile::tempfile().unwrap();
+ image.write_all(&fake_pe()).unwrap();
+ let exe = String::from("Game.exe");
+ let dll = String::from("Secret.dll");
+ let files = [(&exe, image.as_raw_fd()), (&dll, image.as_raw_fd())];
+ let (view, _, count, _) = create_launch_chain_mirror(root.path(), &exe, &files).unwrap();
+ assert_eq!(count, 2);
+ assert_eq!(std::fs::read(view.path().join("Secret.dll")).unwrap(), fake_pe());
+ assert!(!view.path().join("Secret.dll").is_symlink());
+ assert_eq!(std::fs::read(root.path().join("Secret.dll")).unwrap(), b"encrypted-dll");
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(std::fs::metadata(view.path()).unwrap().permissions().mode() & 0o077, 0);
}
#[test]
--- a/crates/xodus-cli/src/commands/run.rs
+++ b/crates/xodus-cli/src/commands/run.rs
@@ -618 +618,17 @@
+ if wine == "droiddeck:prepare" {
+ use std::io::Write;
+ if !materialize_chain { return ExitCode::FAILURE; }
+ let ready = serde_json::json!({
+ "exe": stub_path,
+ "playfab": playfab_auth_header(client, tokens).await,
+ });
+ println!("DROIDDECK_LAUNCH_V1 {}", ready);
+ let _ = std::io::stdout().flush();
+ let mut release = String::new();
+ let _ = std::io::stdin().read_line(&mut release);
+ drop(launch_mirror);
+ cleanup().await;
+ return ExitCode::SUCCESS;
+ }
+
let mut command = Command::new(wine);
@@ -0,0 +1,95 @@
--- a/crates/xodus-cli/src/commands/library.rs
+++ b/crates/xodus-cli/src/commands/library.rs
@@ -96,6 +96,48 @@
eprintln!("NEXUS_LIBRARY_DIAGNOSTIC_V1 {stage} {status} {count}");
}
+const SUBSCRIPTION_PLANS: &[&str] = &[
+ "CFQ7TTC0KGQ8", "CFQ7TTC0KHS0", "CFQ7TTC0P85B",
+ "CFQ7TTC0K5DJ", "CFQ7TTC0K6L8", "CFQ7TTC10QFD",
+];
+
+fn subscription_rows(body: &Value) -> Result<Vec<Value>, &'static str> {
+ let rows = body["entitlements"].as_object().ok_or("subscriptions-shape")?;
+ if rows.len() > SUBSCRIPTION_PLANS.len() { return Err("subscriptions-count"); }
+ let mut plans = Vec::new();
+ for (id, row) in rows {
+ if !SUBSCRIPTION_PLANS.contains(&id.as_str()) { return Err("subscriptions-product"); }
+ let status = row["status"].as_str().ok_or("subscriptions-status")?;
+ if status != "Active" { continue; }
+ let expiry = row["endDate"].as_str().filter(|s| s.len() < 50)
+ .filter(|s| chrono::DateTime::parse_from_rfc3339(s).is_ok()).ok_or("subscriptions-expiry")?;
+ plans.push(json!({"productId":id,"status":status,"endDate":expiry}));
+ }
+ Ok(plans)
+}
+
+async fn subscriptions(client: &reqwest::Client, ticket: &str, market: &str) -> Result<Vec<Value>, &'static str> {
+ let url = format!("https://beige.xboxservices.com/PCGAFD/entitlements/subscriptions?market={market}&language=en-US&appVersion=0.2.3");
+ let cv = format!("{}.0", STANDARD_NO_PAD.encode(uuid::Uuid::new_v4().as_bytes()));
+ let mut response = client.post(url)
+ .header("Authorization", ticket).header("X-MS-API-Version", "1.1")
+ .header("Calling-App-Name", "Xodus-Nexus").header("MS-CV", cv)
+ .json(&json!({"productIds":SUBSCRIPTION_PLANS}))
+ .send().await.map_err(|_| "subscriptions-request")?;
+ if !response.status().is_success() {
+ diagnostic("subscriptions-http", response.status().as_u16(), 0);
+ return Err("subscriptions-http");
+ }
+ if response.content_length().is_some_and(|n| n > 262_144) { return Err("subscriptions-size"); }
+ let mut bytes = Vec::new();
+ while let Some(chunk) = response.chunk().await.map_err(|_| "subscriptions-read")? {
+ if bytes.len() + chunk.len() > 262_144 { return Err("subscriptions-size"); }
+ bytes.extend_from_slice(&chunk);
+ }
+ let body: Value = serde_json::from_slice(&bytes).map_err(|_| "subscriptions-json")?;
+ subscription_rows(&body)
+}
+
async fn query(tokens: &TokenManager, market: &str) -> Result<Value, &'static str> {
if market.len() != 2 || !market.bytes().all(|b| b.is_ascii_uppercase()) {
return Err("market");
@@ -155,6 +197,7 @@
let page: Value = serde_json::from_slice(&bytes).map_err(|_| "entitlements-json")?;
all.add(&page)?;
if continuation.is_none() {
+ let subscriptions = subscriptions(&client, &ticket, market).await?;
if tokens.get_user().map_err(|_| "account-check")?.username != account {
return Err("account-changed");
}
@@ -162,7 +205,7 @@
for (reason, count) in &all.reasons { diagnostic(reason, 0, *count); }
diagnostic(if all.skipped > 0 { "partial" } else { "complete" }, 0, all.skipped);
return Ok(json!({"schema":1,"account":account,"market":market,
- "checkedAt":chrono::Utc::now().to_rfc3339(),"skippedEntitlements":all.skipped,
+ "checkedAt":chrono::Utc::now().to_rfc3339(),"skippedEntitlements":all.skipped,"subscriptions":subscriptions,
"entitlements":all.entries.into_values().collect::<Vec<_>>()}));
}
}
@@ -200,6 +243,26 @@
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn subscription_membership_is_separate_from_product_entitlements() {
+ let body = json!({"entitlements":{"CFQ7TTC0KGQ8":{
+ "status":"Active","endDate":"2099-01-01T00:00:00Z","autoRenew":true,"private":"not-output"}}});
+ assert_eq!(subscription_rows(&body).unwrap(), vec![json!({"productId":"CFQ7TTC0KGQ8",
+ "status":"Active","endDate":"2099-01-01T00:00:00Z"})]);
+ assert!(subscription_rows(&json!({"entitlements":{}})).unwrap().is_empty());
+ assert!(subscription_rows(&json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":"Expired"}}})).unwrap().is_empty());
+ }
+
+ #[test]
+ fn malformed_membership_is_an_error_not_an_empty_subscription_list() {
+ for body in [json!({}), json!({"entitlements":[]}),
+ json!({"entitlements":{"unknown":{"status":"Active"}}}),
+ json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":true}}}),
+ json!({"entitlements":{"CFQ7TTC0KGQ8":{"status":"Active","endDate":"invalid"}}})] {
+ assert!(subscription_rows(&body).is_err());
+ }
+ }
+
const A: &str = "9AAAAAAAAAAA";
const B: &str = "9BBBBBBBBBBB";
const C: &str = "9CCCCCCCCCCC";
+37
View File
@@ -0,0 +1,37 @@
#!/usr/bin/env python3
"""Reproduce the pinned Nexus source and DroidDeck credential transport."""
import hashlib
import json
from pathlib import Path
import subprocess
import sys
recipe = Path(__file__).resolve().parent
cache = Path(sys.argv[1]).resolve()
lock = json.loads((recipe / 'backend.lock.json').read_text())
local_patches = ['droiddeck-credentials.patch', 'droiddeck-launch-view.patch', 'droiddeck-library-subscriptions.patch']
identity = hashlib.sha256((recipe / 'backend.lock.json').read_bytes() + b''.join((recipe / name).read_bytes() for name in local_patches)).hexdigest()
source = cache / ('source-' + identity[:16])
if not (source / '.prepared').is_file():
if source.exists():
raise RuntimeError('Incomplete Xbox source directory; inspect it before retrying: ' + str(source))
source.mkdir(parents=True)
nexus = cache / ('nexus-' + lock['nexusCommit'])
for directory, remote, commit in ((source, lock['repository'], lock['commit']),
(nexus, 'https://github.com/domsvoboda/xodus-nexus.git', lock['nexusCommit'])):
directory.mkdir(parents=True, exist_ok=True)
if not (directory / '.git').is_dir():
subprocess.run(['git', 'init', '-q', str(directory)], check=True)
subprocess.run(['git', '-C', str(directory), 'fetch', '-q', '--depth', '1', remote, commit], check=True)
subprocess.run(['git', '-C', str(directory), 'checkout', '-q', '--detach', 'FETCH_HEAD'], check=True)
assert subprocess.check_output(['git', '-C', str(directory), 'rev-parse', 'HEAD'], text=True).strip() == commit
assert hashlib.sha256((source / 'Cargo.lock').read_bytes()).hexdigest() == lock['cargoLockSha256']
for patch in lock['patches']:
file = nexus / 'assets' / patch['file']
assert hashlib.sha256(file.read_bytes()).hexdigest() == patch['sha256']
subprocess.run(['git', '-C', str(source), 'apply', str(file)], check=True)
for name in local_patches:
subprocess.run(['git', '-C', str(source), 'apply', str(recipe / name)], check=True)
(source / '.prepared').write_text(identity + '\n')
assert (source / '.prepared').read_text().strip() == identity
print(source)
+23
View File
@@ -0,0 +1,23 @@
#include <windows.h>
#include <stdio.h>
int main(void)
{
setvbuf(stdout, NULL, _IONBF, 0);
const char *modules[] = { "xgameruntime.dll", "winhttp.dll", "windows.web.dll", "twinapi.appcore.dll" };
int failed = 0;
for (unsigned i = 0; i < sizeof(modules) / sizeof(modules[0]); i++)
{
printf("loading %s\n", modules[i]);
HMODULE module = LoadLibraryA(modules[i]);
printf("%s loaded=%u error=%lu\n", modules[i], module != NULL, module ? 0ul : GetLastError());
if (!module) failed = 1;
if (module && i == 0)
{
FARPROC entry = GetProcAddress(module, "InitializeApiImplEx2");
printf("InitializeApiImplEx2 present=%u\n", entry != NULL);
if (!entry) failed = 1;
}
}
return failed;
}
+17
View File
@@ -0,0 +1,17 @@
{
"repository": "domsvoboda/xodus-nexus",
"tag": "runtime-11.0-20261018-gf291f544",
"archive": "xodus-nexus-runtime-11.0-20261018-gf291f544-x86_64.tar.xz",
"sha512": "8e16634dc4d75ead4b7f48712624e107cfdc29a31a2da1b32624af25a6e3e8938636a6701e076a9dee08eb0c5b36b549342598313971f5fceb5de1e483c43578",
"source": {
"name": "xodus-nexus-runtime-11.0-20261018-gf291f544-source.tar.xz",
"sha256": "58b5d35d23b61f73f771b733fde43ea75096fe8b60f2ddc660949af3d8d87baf"
},
"dlls": {
"twinapi.appcore.dll": "c203bbd707d521c68719b42a0a81db2b4838cc41be83fc76bfd87bf33e507336",
"windows.web.dll": "1a510c73ca31475b163692337d3cf37fef3381078df9729662095fc92b2e4e83",
"libnghttp2.dll": "2b171eba9296b207fe6016560e5381bc6e7405f3ad5ee5cd4add316358204ec0",
"xgameruntime.dll": "060120e0ec6bccfbab516128315a0658b11d3e316f62a917c653daf1a1dd3e05",
"winhttp.dll": "81e1da7a731d83fbd24dbe2fa2ecb8f155bd477a9f9b6f4cc3932063cc326c27"
}
}
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Extract only pinned Windows GDK modules; Linux Wine stays ARM64."""
import hashlib
import json
from pathlib import Path
import shutil
import sys
import tarfile
import urllib.request
recipe = Path(__file__).resolve().parent
lock = json.loads((recipe / 'runtime.lock.json').read_text())
cache = Path(sys.argv[1]); output = Path(sys.argv[2])
cache.mkdir(parents=True, exist_ok=True)
output.mkdir(parents=True, exist_ok=True)
url = 'https://github.com/' + lock['repository'] + '/releases/download/' + lock['tag'] + '/'
def download(name, expected, algorithm):
target = cache / name
def matches():
if not target.is_file():
return False
digest = hashlib.new(algorithm)
with target.open('rb') as file:
for block in iter(lambda: file.read(1024 * 1024), b''):
digest.update(block)
return digest.hexdigest() == expected
if not matches():
part = target.with_suffix(target.suffix + '.part')
with urllib.request.urlopen(url + name, timeout=90) as response, part.open('wb') as file:
shutil.copyfileobj(response, file)
part.replace(target)
if not matches():
raise RuntimeError('Xbox runtime checksum mismatch: ' + name)
return target
archive = download(lock['archive'], lock['sha512'], 'sha512')
# Keep corresponding source available beside the build cache for redistribution.
source = lock['source']
download(source['name'], source['sha256'], 'sha256')
remaining = set(lock['dlls'])
with tarfile.open(archive) as tar:
for member in tar:
name = Path(member.name).name
if '/files/lib/wine/x86_64-windows/' not in member.name or name not in remaining:
continue
if not member.isfile() or member.size > 32 * 1024 * 1024:
raise RuntimeError('Invalid Xbox Windows runtime module')
data = tar.extractfile(member).read()
if hashlib.sha256(data).hexdigest() != lock['dlls'][name] or data[:2] != b'MZ':
raise RuntimeError('Xbox Windows runtime module checksum mismatch')
# Wine rejects builtin-tagged PE files when WINEDLLOVERRIDES selects native.
# These standalone Windows modules must use the native x64 loader on ARM64EC.
if data[64:80] == b'Wine builtin DLL':
data = data[:64] + b'DroidDeck native' + data[80:]
(output / name).write_bytes(data)
remaining.remove(name)
if remaining:
raise RuntimeError('Missing Xbox runtime modules')