mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-22 14:26:00 +00:00
Expanded Fastpaths for proot and increased performance up to 57% (#494)
* perf: fast path resolves links, /proc and glue as proot does, and answers uname, isatty and passwd
The fast path handed back to proot whatever crossed a symlink, /proc or a directory proot
only shows as glue, which is most of what Steam and Wine ask. It now walks a path the way
proot's canonicalize() does, so those calls stay in-process:
- links are followed in guest terms and their text detranslated as detranslate_path() does,
including readlink into a buffer the kernel cut short and /proc's exe, cwd and fd links;
- a binding proot dropped at start is dropped here too, glue above a binding is ENOENT, and a
last component proot cannot stat is left to the kernel;
- pipe and socket dirfds are ENOTDIR, rmdir("dir/") removes dir, and "." and ".." go to proot;
- a blocking accept() with a connection already waiting no longer goes to proot.
Also answered: uname() and gethostname() (proot's utsname never changes), isatty() (glibc
2.43 asks with TCGETS2, which proot rewrites) and getpwnam/getpwuid when nsswitch.conf
sends passwd to files first and the entry is there (Xwayland asks for every client).
equiv.py, equiv2.py and equiv3.py match line for line with and without the fast path
(222, 507 and 924 lines). Per call on the RedMagic: realpath 240 us -> 1.0 us,
realpath /proc/self/fd/N 408 -> 9.9, getpwuid 41.5 -> 4.6, uname 28 -> 0.006.
* perf: LD_AUDIT module skips library lookups proot would fail
ld.so looks each library up along the game's search path, and Proton puts the game's
directory, Steam's runtime and video directories and its own library directories ahead of
/usr/lib: 72% of ld.so's opens in an Among Us launch failed, each a round trip to proot.
libblaudit.so answers la_objsearch() for a candidate proot would certainly fail with ENOENT
(its directory walked as canonicalize() walks it, the name or a directory on the way missing).
It has no libc and maps the fast path's trampoline itself. Each lookup's first candidate is
still opened, since a skipped one fails with ld.so's errno as it stands, and the default
directories are never skipped, so dlerror() reads the same. droiddeck-proton and the extra
wrapper add it to LD_AUDIT when the fast path is on.
* perf: droiddeck-proton checks a tool's components with one sha256sum
Each program the launcher starts pays a dozen traced library lookups under the game's search
path before it does anything. One sha256sum over every listed file replaces one per file;
the check itself is unchanged.
* perf: build a locale archive for C.UTF-8
Every program loads the locale LANG names before main(). glibc ships C.UTF-8 as a directory
it looks for once per category under two spellings, before reading gconv's module lists:
about 30 opens, each a stop in proot, in every process of the session. droiddeck-session
builds /usr/lib/locale/locale-archive (and gconv's cache) once per glibc package, so that is
one open.
localedef names a finished archive by hard link, which Android refuses; with
DROIDDECK_LINK_RENAME=1 libblsession turns a refused link into a rename that will not replace
an existing name.
* perf: library beat starts its helpers only when what they read changed
Every 15 s the session ran droiddeck-seed-redists (some forty programs under proot) and, when
a library directory had changed, steam-compatibility: a burst of thousands of proot stops each
quarter minute, game loads included. The seeder now runs when a library changed or a prefix
(or Proton's template for them) is unmarked, the compat pass when a manifest, depot, tool or
config.vdf changed, both checked from bash without starting anything, and each every five
minutes regardless. The seeder reads its stamp and the time without a subshell each.
* perf: fakeinput opens pad.log on its first line
Every process the library is loaded in opened the session's pad.log at start, a stop in proot
on shared storage, and most never write to it. The file is now opened when there is a line to
write.
* docs: the fast path as it ships, the audit module and measured launch times
* fix: a game the app launches after an idle spell comes to the front
The Steam client brings a game it launched forward only while it counts someone as present,
which it reads from gamescope's input counter. A game the app launched after four or more
minutes without a touch started, mapped its window, and stayed behind the library page until
the next input (device: Palworld, Stardew Valley, Fallout: New Vegas, Mortal Kombat X; the same
on main). The session now watches a requested launch, and when the game's window is focusable
but the interface keeps focus for two polls, counts one input on gamescope's counter, as a key
would. Nothing changes for a launch the client already brings forward.
This commit is contained in:
1 parent
a5fd64f9f2
commit
fb8361b197
14 files changed
+2875
-245
No files matched your search
@@ -0,0 +1,259 @@
|
||||
"""Fast path equivalence, part two: symlinked directories (Wine's dosdevices), "..", trailing
|
||||
slashes, realpath/getcwd, the write family, Unix sockets, xattrs, statfs, inotify and fstat.
|
||||
|
||||
Run under proot with and without the fast path (run-device.sh fpoff / fastpath) and diff the
|
||||
output: every line must match. Builds its own tree under /root/fx and /mnt/droiddeck-sd/fx.
|
||||
"""
|
||||
import ctypes
|
||||
import errno
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import sys
|
||||
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
libc.realpath.restype = ctypes.c_char_p
|
||||
libc.realpath.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
|
||||
libc.getcwd.restype = ctypes.c_char_p
|
||||
libc.getcwd.argtypes = [ctypes.c_char_p, ctypes.c_size_t]
|
||||
libc.get_nprocs.restype = ctypes.c_int
|
||||
|
||||
FX = "/root/fx"
|
||||
SD = "/mnt/droiddeck-sd/fx"
|
||||
|
||||
|
||||
def setup():
|
||||
for d in (FX, SD):
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
os.makedirs(FX + "/pfx/drive_c/windows/system32")
|
||||
os.makedirs(FX + "/pfx/dosdevices")
|
||||
os.makedirs(FX + "/real/sub/deeper")
|
||||
os.makedirs(SD + "/data/inner")
|
||||
with open(FX + "/pfx/drive_c/windows/system32/kernel32.dll", "w") as f:
|
||||
f.write("MZ" * 10)
|
||||
with open(FX + "/real/sub/file.txt", "w") as f:
|
||||
f.write("hello")
|
||||
with open(SD + "/data/inner/asset.pak", "w") as f:
|
||||
f.write("pak" * 7)
|
||||
os.symlink("../drive_c", FX + "/pfx/dosdevices/c:")
|
||||
os.symlink("/", FX + "/pfx/dosdevices/z:")
|
||||
os.symlink(SD + "/data", FX + "/pfx/dosdevices/d:")
|
||||
os.symlink("real/sub", FX + "/rel-dir")
|
||||
os.symlink(FX + "/real", FX + "/abs-dir")
|
||||
os.symlink("rel-dir", FX + "/chain1")
|
||||
os.symlink("chain1", FX + "/chain2")
|
||||
os.symlink("nowhere", FX + "/dangling")
|
||||
os.symlink("loop-b", FX + "/loop-a")
|
||||
os.symlink("loop-a", FX + "/loop-b")
|
||||
os.symlink("rel-dir/file.txt", FX + "/file-link")
|
||||
os.symlink("../fx/real/sub/../sub/deeper", FX + "/dotdot-link")
|
||||
os.symlink("/etc", FX + "/etc-link")
|
||||
os.symlink("/proc/self", FX + "/proc-link")
|
||||
os.symlink("/dev/null", FX + "/null-link")
|
||||
os.symlink("../../../root/fx/real", SD + "/back-to-root")
|
||||
|
||||
|
||||
PATHS = [
|
||||
"pfx/dosdevices/c:/windows/system32/kernel32.dll",
|
||||
"pfx/dosdevices/c:/windows/system32/KERNEL32.DLL",
|
||||
"pfx/dosdevices/c:/windows/system32",
|
||||
"pfx/dosdevices/c:/windows/system32/",
|
||||
"pfx/dosdevices/c:/windows/system32/kernel32.dll/",
|
||||
"pfx/dosdevices/z:/root/fx/real/sub/file.txt",
|
||||
"pfx/dosdevices/z:/etc/os-release",
|
||||
"pfx/dosdevices/z:/mnt/droiddeck-sd/fx/data/inner/asset.pak",
|
||||
"pfx/dosdevices/z:/proc/self/status",
|
||||
"pfx/dosdevices/z:/nope/x",
|
||||
"pfx/dosdevices/d:/inner/asset.pak",
|
||||
"pfx/dosdevices/d:/inner/missing.pak",
|
||||
"pfx/dosdevices/d:/../back-to-root/sub/file.txt",
|
||||
"pfx/dosdevices/c:/../dosdevices/c:/windows",
|
||||
"rel-dir/file.txt",
|
||||
"rel-dir/../sub/file.txt",
|
||||
"rel-dir/..",
|
||||
"abs-dir/sub/deeper",
|
||||
"chain2/file.txt",
|
||||
"chain2",
|
||||
"chain2/",
|
||||
"dangling",
|
||||
"dangling/x",
|
||||
"loop-a",
|
||||
"loop-a/x",
|
||||
"file-link",
|
||||
"file-link/",
|
||||
"dotdot-link",
|
||||
"etc-link/os-release",
|
||||
"proc-link/status",
|
||||
"null-link",
|
||||
"real/sub/./file.txt",
|
||||
"real//sub///file.txt",
|
||||
"real/sub/file.txt/../file.txt",
|
||||
"nope",
|
||||
"nope/deeper",
|
||||
".",
|
||||
"..",
|
||||
"../fx/real",
|
||||
]
|
||||
|
||||
|
||||
def call(fn):
|
||||
try:
|
||||
return repr(fn())
|
||||
except OSError as e:
|
||||
return "E" + errno.errorcode.get(e.errno, str(e.errno))
|
||||
|
||||
|
||||
def realpath(p):
|
||||
ctypes.set_errno(0)
|
||||
r = libc.realpath(p.encode(), None)
|
||||
if r is None:
|
||||
return "E" + errno.errorcode.get(ctypes.get_errno(), "?")
|
||||
return r.decode()
|
||||
|
||||
|
||||
def mode_of(s):
|
||||
return (stat.S_IFMT(s.st_mode), s.st_size if stat.S_ISREG(s.st_mode) else 0)
|
||||
|
||||
|
||||
def probe(p):
|
||||
out = [
|
||||
"stat=" + call(lambda: mode_of(os.stat(p))),
|
||||
"lstat=" + call(lambda: mode_of(os.lstat(p))),
|
||||
"readlink=" + call(lambda: os.readlink(p)),
|
||||
"read=" + call(lambda: open(p, "rb").read(8)),
|
||||
"list=" + call(lambda: sorted(os.listdir(p))[:5]),
|
||||
"access=" + call(lambda: (os.access(p, os.R_OK), os.access(p, os.W_OK, effective_ids=True))),
|
||||
"realpath=" + realpath(p),
|
||||
"nofollow=" + call(lambda: os.close(os.open(p, os.O_RDONLY | os.O_NOFOLLOW))),
|
||||
"statvfs=" + call(lambda: (lambda v: (v.f_bsize, v.f_frsize, v.f_namemax, v.f_flag, v.f_fsid, v.f_files > 0))(os.statvfs(p))),
|
||||
"xattr=" + call(lambda: os.getxattr(p, "user.DOSATTRIB")),
|
||||
"lxattr=" + call(lambda: len(os.listxattr(p, follow_symlinks=False)) >= 0),
|
||||
]
|
||||
return " ".join(out)
|
||||
|
||||
|
||||
def writes(base):
|
||||
out = []
|
||||
w = base + "/w"
|
||||
t = lambda label, fn: out.append(f" {label}: {call(fn)}")
|
||||
t("mkdir", lambda: os.mkdir(w))
|
||||
t("mkdir again", lambda: os.mkdir(w))
|
||||
t("mkdir under file", lambda: os.mkdir(base + "/real/sub/file.txt/x"))
|
||||
t("mkdir missing parent", lambda: os.mkdir(w + "/a/b"))
|
||||
t("create", lambda: os.close(os.open(w + "/f", os.O_CREAT | os.O_WRONLY, 0o640)))
|
||||
t("excl existing", lambda: os.open(w + "/f", os.O_CREAT | os.O_EXCL | os.O_WRONLY))
|
||||
t("symlink", lambda: os.symlink("f", w + "/lf"))
|
||||
t("symlink exists", lambda: os.symlink("f", w + "/lf"))
|
||||
t("create through link", lambda: os.close(os.open(w + "/lf", os.O_CREAT | os.O_WRONLY)))
|
||||
t("dangling create", lambda: (os.symlink("made-by-link", w + "/dl"), os.close(os.open(w + "/dl", os.O_CREAT | os.O_WRONLY)), os.path.lexists(w + "/made-by-link"))[2])
|
||||
t("excl through link", lambda: os.open(w + "/lf", os.O_CREAT | os.O_EXCL | os.O_WRONLY))
|
||||
t("chmod", lambda: (os.chmod(w + "/lf", 0o600), oct(os.stat(w + "/f").st_mode & 0o777))[1])
|
||||
t("utime", lambda: (os.utime(w + "/f", (1000, 2000)), os.stat(w + "/f").st_mtime)[1])
|
||||
t("utime link nofollow", lambda: os.utime(w + "/lf", (3, 4), follow_symlinks=False))
|
||||
t("futimens", lambda: (lambda fd: (os.utime(fd, (5, 6)), os.close(fd)))(os.open(w + "/f", os.O_RDONLY)))
|
||||
t("truncate", lambda: (os.truncate(w + "/lf", 7), os.stat(w + "/f").st_size)[1])
|
||||
t("rename file", lambda: os.rename(w + "/f", w + "/g"))
|
||||
t("rename missing", lambda: os.rename(w + "/f", w + "/h"))
|
||||
t("rename link", lambda: os.rename(w + "/lf", w + "/lg"))
|
||||
t("readlink renamed", lambda: os.readlink(w + "/lg"))
|
||||
t("replace", lambda: (open(w + "/tmp", "w").write("new"), os.replace(w + "/tmp", w + "/g"), open(w + "/g").read())[2])
|
||||
t("rename dir", lambda: (os.mkdir(w + "/d1"), os.rename(w + "/d1", w + "/d2"))[1])
|
||||
t("rename trailing", lambda: os.rename(w + "/d2/", w + "/d3"))
|
||||
t("unlink", lambda: os.unlink(w + "/g"))
|
||||
t("unlink missing", lambda: os.unlink(w + "/g"))
|
||||
t("unlink dir", lambda: os.unlink(w + "/d3"))
|
||||
t("unlink trailing", lambda: os.unlink(w + "/lg/"))
|
||||
t("rmdir nonempty", lambda: os.rmdir(w))
|
||||
t("rmdir file", lambda: os.rmdir(w + "/lg"))
|
||||
t("unlink link", lambda: os.unlink(w + "/lg"))
|
||||
t("rmdir", lambda: os.rmdir(w + "/d3"))
|
||||
t("listing", lambda: sorted(os.listdir(w)))
|
||||
for name in os.listdir(w):
|
||||
call(lambda: os.unlink(w + "/" + name))
|
||||
t("rmdir done", lambda: os.rmdir(w))
|
||||
return out
|
||||
|
||||
|
||||
def sockets(base):
|
||||
out = []
|
||||
path = base + "/s.sock"
|
||||
try:
|
||||
os.unlink(path)
|
||||
except OSError:
|
||||
pass
|
||||
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
out.append(" bind " + call(lambda: srv.bind(path)))
|
||||
if not os.path.exists(path):
|
||||
# adb's shell may not create sockets under /data/local/tmp; the app can.
|
||||
srv.close()
|
||||
return out
|
||||
out.append(" name " + call(lambda: srv.getsockname()))
|
||||
out.append(" listen " + call(lambda: srv.listen(1)))
|
||||
out.append(" is socket " + call(lambda: stat.S_ISSOCK(os.stat(path).st_mode)))
|
||||
cli = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
out.append(" connect " + call(lambda: cli.connect(path)))
|
||||
conn, _ = srv.accept()
|
||||
out.append(" peer " + call(lambda: cli.getpeername()))
|
||||
cli.sendall(b"ping")
|
||||
out.append(" recv " + call(lambda: conn.recv(4)))
|
||||
srv.setblocking(False)
|
||||
out.append(" accept none " + call(lambda: srv.accept()))
|
||||
for s in (conn, cli, srv):
|
||||
s.close()
|
||||
out.append(" connect missing " + call(lambda: socket.socket(socket.AF_UNIX).connect(base + "/nope.sock")))
|
||||
a = socket.socket(socket.AF_UNIX)
|
||||
out.append(" abstract " + call(lambda: (a.bind("\0fp-equiv"), a.getsockname())[1]))
|
||||
a.close()
|
||||
os.unlink(path)
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
setup()
|
||||
for cwd in [FX, "/", FX + "/pfx/dosdevices/c:/windows", FX + "/chain2", SD + "/data", "/mnt/droiddeck-sd"]:
|
||||
print("== cwd", cwd, call(lambda: os.chdir(cwd)), "getcwd", call(os.getcwd), "libc", libc.getcwd(None, 0))
|
||||
for p in PATHS:
|
||||
print(" ", p, probe(p))
|
||||
d = os.open(".", os.O_RDONLY)
|
||||
for p in PATHS[:12]:
|
||||
print(" at", p, call(lambda: mode_of(os.stat(p, dir_fd=d))), call(lambda: mode_of(os.stat(p, dir_fd=d, follow_symlinks=False))))
|
||||
print(" fstat", call(lambda: stat.S_IFMT(os.fstat(d).st_mode)))
|
||||
os.close(d)
|
||||
for base in (FX, SD, FX + "/pfx/dosdevices/d:", FX + "/chain2"):
|
||||
os.chdir("/")
|
||||
print("== writes in", base)
|
||||
print("\n".join(writes(base)))
|
||||
print("== sockets in", base)
|
||||
print("\n".join(sockets(base)))
|
||||
os.chdir(FX)
|
||||
print("== relative writes")
|
||||
print("\n".join(writes(".")))
|
||||
print("== moved cwd")
|
||||
os.mkdir(FX + "/mv1")
|
||||
os.chdir(FX + "/mv1")
|
||||
os.rename(FX + "/mv1", FX + "/mv2")
|
||||
print(" getcwd", call(os.getcwd), libc.getcwd(None, 0))
|
||||
print(" rel stat", call(lambda: mode_of(os.stat("."))))
|
||||
os.chdir(FX)
|
||||
os.rmdir(FX + "/mv2")
|
||||
print("== deleted cwd")
|
||||
os.mkdir(FX + "/gone")
|
||||
os.chdir(FX + "/gone")
|
||||
os.rmdir(FX + "/gone")
|
||||
print(" getcwd", call(os.getcwd))
|
||||
os.chdir(FX)
|
||||
print("== inotify")
|
||||
lib_in = libc.inotify_init1(0)
|
||||
for p in (FX + "/chain2", FX + "/pfx/dosdevices/c:/windows", FX + "/dangling", FX + "/nope"):
|
||||
ctypes.set_errno(0)
|
||||
w = libc.inotify_add_watch(lib_in, p.encode(), 0x100 | 0x200)
|
||||
print(" ", p, "ok" if w >= 0 else "E" + errno.errorcode.get(ctypes.get_errno(), "?"))
|
||||
os.close(lib_in)
|
||||
print("== cpus", libc.get_nprocs() == os.cpu_count(), os.cpu_count() > 0)
|
||||
for d in (FX, SD):
|
||||
shutil.rmtree(d, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,509 @@
|
||||
"""Fast path equivalence, part three: /proc (self, fd and exe links, readlink as proot answers it,
|
||||
realpath through it, opening through fd links), link text naming host paths, creating in
|
||||
directories whose host path is long, glue above a binding proot cannot look into, files the
|
||||
caller may not stat, trailing slashes, shm_open, accept, passwd lookups and the _FORTIFY_SOURCE
|
||||
entry points.
|
||||
|
||||
Run under proot with and without the fast path (run-device.sh fpoff / fastpath) and diff the
|
||||
output: every line must match. The rig's rootfs is ROOT; run-device.sh binds /cache/fp/perf and
|
||||
SHARED at /opt/fpx.
|
||||
"""
|
||||
import ctypes
|
||||
import errno
|
||||
import os
|
||||
import shutil
|
||||
import socket
|
||||
import stat
|
||||
import sys
|
||||
|
||||
ROOT = "/data/local/tmp/dd/mini"
|
||||
SHARED = "/data/local/tmp/dd/fpx"
|
||||
FX = "/root/fx3"
|
||||
DEEP = FX + "/a-directory-name-long-enough/to-push-the-host-path/past-what-sun-path-holds/and-then-some"
|
||||
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
libc.realpath.restype = ctypes.c_char_p
|
||||
libc.realpath.argtypes = [ctypes.c_char_p, ctypes.c_char_p]
|
||||
libc.readlink.restype = ctypes.c_ssize_t
|
||||
libc.readlink.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_size_t]
|
||||
libc.__readlink_chk.restype = ctypes.c_ssize_t
|
||||
libc.__readlink_chk.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_size_t]
|
||||
libc.__readlinkat_chk.restype = ctypes.c_ssize_t
|
||||
libc.__readlinkat_chk.argtypes = [ctypes.c_int, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_size_t]
|
||||
libc.__getcwd_chk.restype = ctypes.c_char_p
|
||||
libc.__getcwd_chk.argtypes = [ctypes.c_char_p, ctypes.c_size_t, ctypes.c_size_t]
|
||||
libc.shm_open.restype = ctypes.c_int
|
||||
libc.shm_open.argtypes = [ctypes.c_char_p, ctypes.c_int, ctypes.c_uint]
|
||||
libc.shm_unlink.restype = ctypes.c_int
|
||||
libc.shm_unlink.argtypes = [ctypes.c_char_p]
|
||||
|
||||
|
||||
def norm(s):
|
||||
return str(s).replace(str(os.getpid()), "PID").replace(str(ctypes.CDLL(None).gettid()), "TID")
|
||||
|
||||
|
||||
def err():
|
||||
return "E" + errno.errorcode.get(ctypes.get_errno(), "?")
|
||||
|
||||
|
||||
def call(fn):
|
||||
try:
|
||||
return norm(repr(fn()))
|
||||
except OSError as e:
|
||||
return "E" + errno.errorcode.get(e.errno, str(e.errno))
|
||||
|
||||
|
||||
def realpath(p):
|
||||
ctypes.set_errno(0)
|
||||
r = libc.realpath(p.encode(), None)
|
||||
return err() if r is None else norm(r.decode())
|
||||
|
||||
|
||||
def raw_readlink(p, size, chk=False):
|
||||
buf = ctypes.create_string_buffer(b"#" * (size + 2), size + 2)
|
||||
ctypes.set_errno(0)
|
||||
n = libc.__readlink_chk(p.encode(), buf, size, size + 2) if chk else libc.readlink(p.encode(), buf, size)
|
||||
if n < 0:
|
||||
return err()
|
||||
return norm((n, buf.raw[: min(n + 1, size)]))
|
||||
|
||||
|
||||
def mode_of(s):
|
||||
return (stat.S_IFMT(s.st_mode), s.st_size if stat.S_ISREG(s.st_mode) else 0)
|
||||
|
||||
|
||||
def opened(p):
|
||||
def go():
|
||||
fd = os.open(p, os.O_RDONLY)
|
||||
try:
|
||||
return mode_of(os.fstat(fd))
|
||||
finally:
|
||||
os.close(fd)
|
||||
return f"open={call(go)} stat={call(lambda: mode_of(os.stat(p)))}"
|
||||
|
||||
|
||||
def links(p):
|
||||
sizes = [1, 5, 4096]
|
||||
try:
|
||||
whole = len(os.readlink(p))
|
||||
sizes += [whole - 1, whole, whole + 1, whole + 2]
|
||||
except OSError:
|
||||
pass
|
||||
out = [f"readlink={call(lambda: os.readlink(p))}", f"realpath={realpath(p)}",
|
||||
f"stat={call(lambda: mode_of(os.stat(p)))}", f"lstat={call(lambda: stat.S_IFMT(os.lstat(p).st_mode))}"]
|
||||
out += [f"buf{n}={raw_readlink(p, n)}" for n in sizes if n > 0]
|
||||
out.append(f"chk={raw_readlink(p, 64, True)}")
|
||||
return " ".join(out)
|
||||
|
||||
|
||||
def proc_section():
|
||||
print("== /proc")
|
||||
os.makedirs(FX + "/dir", exist_ok=True)
|
||||
open(FX + "/file", "w").write("x")
|
||||
open(FX + "/doomed", "w").write("x")
|
||||
held = {
|
||||
"rootfs file": os.open(FX + "/file", os.O_RDONLY),
|
||||
"rootfs dir": os.open(FX + "/dir", os.O_RDONLY),
|
||||
"bound file": os.open("/proc/version", os.O_RDONLY),
|
||||
"sdcard": os.open("/sdcard", os.O_RDONLY),
|
||||
"shared bind": os.open("/mnt/droiddeck-sd", os.O_RDONLY),
|
||||
"dev null": os.open("/dev/null", os.O_RDONLY),
|
||||
"deleted": os.open(FX + "/doomed", os.O_RDONLY),
|
||||
"outside": os.open("/data/local/tmp", os.O_RDONLY),
|
||||
}
|
||||
os.unlink(FX + "/doomed")
|
||||
r, w = os.pipe()
|
||||
held["pipe"] = r
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
|
||||
held["socket"] = s.fileno()
|
||||
for label, fd in held.items():
|
||||
for p in (f"/proc/self/fd/{fd}", f"/proc/{os.getpid()}/fd/{fd}", f"/proc/thread-self/fd/{fd}"):
|
||||
print(" ", label, norm(p), links(p))
|
||||
d = os.open("/proc/self/fd", os.O_RDONLY)
|
||||
print(" ", label, "at", call(lambda: os.readlink(str(fd), dir_fd=d)))
|
||||
os.close(d)
|
||||
for p in ("/proc/self/exe", f"/proc/{os.getpid()}/exe", "/proc/self/cwd", "/proc/self/root", "/proc/self",
|
||||
"/proc/thread-self", "/proc/self/task", "/proc/1/exe", "/proc/self/ns/mnt", "/proc/nope/exe",
|
||||
"/proc/self/fd/9999", "/proc/self/fd/", "/proc/self/fd/foo"):
|
||||
print(" ", norm(p), links(p))
|
||||
for p in ("/proc/self/cwd/file", "/proc/self/cwd/../fx3/dir", "/proc/self/exe/x", "/proc/self/fd/../status",
|
||||
"/proc/self/./status", "/proc/self/task/../status", "/proc/thread-self/status", "/proc/self/root/etc"):
|
||||
print(" ", norm(p), "realpath", realpath(p), "stat", call(lambda: mode_of(os.stat(p))))
|
||||
for p in ("/proc/self/status", "/proc/version", "/proc/loadavg", "/proc/self/cmdline", "/proc/meminfo"):
|
||||
print(" ", p, "first", call(lambda: open(p, "rb").read(5)), "access", call(lambda: os.access(p, os.R_OK)))
|
||||
print(" fd count", call(lambda: len(os.listdir("/proc/self/fd")) > 3))
|
||||
for label, fd in list(held.items()) + [("write end", w)]:
|
||||
for p in (f"/proc/self/fd/{fd}", f"/proc/{os.getpid()}/fd/{fd}", f"/proc/thread-self/fd/{fd}"):
|
||||
print(" ", label, "through", norm(p), opened(p), "access", call(lambda: os.access(p, os.R_OK)),
|
||||
"nofollow", call(lambda: os.close(os.open(p, os.O_RDONLY | os.O_NOFOLLOW))),
|
||||
"below", call(lambda: mode_of(os.stat(p + "/file"))), "slash", call(lambda: mode_of(os.stat(p + "/"))))
|
||||
for p in ("/proc/mounts", "/proc/net", "/proc/net/unix", "/proc/self/cwd/file", f"/proc/{os.getpid()}/cwd/dir",
|
||||
"/proc/self/root/etc/os-release", "/proc/self/exe", "/proc/1/fd/0", "/proc/1/fd/0/x", "/proc/1/cwd",
|
||||
"/proc/1/environ", "/proc/self/task"):
|
||||
print(" ", norm(p), opened(p), "access", call(lambda: os.access(p, os.F_OK)),
|
||||
"lstat", call(lambda: stat.S_IFMT(os.lstat(p).st_mode)))
|
||||
print(" mtab-like", call(lambda: (os.symlink("/proc/self/mounts", FX + "/mtab"), open(FX + "/mtab").read(4))[1]))
|
||||
for fd in list(held.values()) + [w]:
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
s.detach()
|
||||
|
||||
|
||||
def host_text_section():
|
||||
print("== link text naming host paths")
|
||||
cases = {
|
||||
"in-root": ROOT + "/etc/os-release",
|
||||
"root itself": ROOT,
|
||||
"bound sdcard": "/sdcard/Download",
|
||||
"shared bind": "/data/local/tmp/dd/tmp",
|
||||
"outside": "/data/local/tmp",
|
||||
"relative": "../fx3/file",
|
||||
}
|
||||
for label, text in cases.items():
|
||||
link = FX + "/ht-" + label.replace(" ", "-")
|
||||
os.symlink(text, link)
|
||||
print(" ", label, links(link), "read", call(lambda: open(link, "rb").read(4)))
|
||||
|
||||
|
||||
def shared_section():
|
||||
print("== link text across bindings")
|
||||
os.makedirs(SHARED + "/sub", exist_ok=True)
|
||||
open(SHARED + "/target", "w").write("shared")
|
||||
os.makedirs("/data/local/tmp/dd/fpy", exist_ok=True)
|
||||
cases = [
|
||||
("/opt/fpx/l-same", SHARED + "/target"),
|
||||
("/opt/fpx/l-itself", SHARED),
|
||||
("/opt/fpx/l-sub", SHARED + "/sub"),
|
||||
("/opt/fpx/l-other-bind", "/data/local/tmp/dd/fpy"),
|
||||
("/opt/fpx/l-rootfs", ROOT + "/etc/os-release"),
|
||||
("/opt/fpx/l-rel", "target"),
|
||||
("/opt/fpx/l-guest", "/opt/fpx/target"),
|
||||
("/data/local/tmp/dd/fpy/l-into-shared", SHARED + "/target"),
|
||||
("/data/local/tmp/dd/fpy/l-rootfs", ROOT + "/etc/os-release"),
|
||||
("/data/local/tmp/dd/fpy/l-root", ROOT),
|
||||
(FX + "/l-shared", SHARED + "/target"),
|
||||
(FX + "/l-shared-guest", "/opt/fpx/target"),
|
||||
]
|
||||
for link, text in cases:
|
||||
try:
|
||||
os.unlink(link)
|
||||
except OSError:
|
||||
pass
|
||||
os.symlink(text, link)
|
||||
print(" ", link, links(link), opened(link), "via", call(lambda: mode_of(os.stat(link + "/"))),
|
||||
"below", call(lambda: mode_of(os.stat(link + "/target"))))
|
||||
shutil.rmtree("/data/local/tmp/dd/fpy", ignore_errors=True)
|
||||
for name in os.listdir(SHARED):
|
||||
if name.startswith("l-"):
|
||||
os.unlink(SHARED + "/" + name)
|
||||
|
||||
|
||||
def unseen_section():
|
||||
print("== files the caller may not stat")
|
||||
for p in ("/proc/1/fd/0", "/proc/1/fd/0/x", "/proc/1/fd", "/proc/1/environ", "/proc/1/mem", "/proc/1/fdinfo/0",
|
||||
"/proc/sys/vm/overcommit_memory", "/proc/1/task/1/fd/0"):
|
||||
print(" ", p, "stat", call(lambda: mode_of(os.stat(p))), "lstat", call(lambda: stat.S_IFMT(os.lstat(p).st_mode)),
|
||||
"access", call(lambda: os.access(p, os.R_OK)), "open", call(lambda: os.close(os.open(p, os.O_RDONLY))),
|
||||
"xattr", call(lambda: os.listxattr(p)), "chmod", call(lambda: os.chmod(p, 0o600)),
|
||||
"utime", call(lambda: os.utime(p)), "unlink", call(lambda: os.unlink(p)), "mkdir", call(lambda: os.mkdir(p)),
|
||||
"readlink", call(lambda: os.readlink(p)), "realpath", realpath(p))
|
||||
|
||||
|
||||
def slash_section():
|
||||
print("== trailing slashes")
|
||||
os.makedirs(FX + "/sl/dir", exist_ok=True)
|
||||
open(FX + "/sl/file", "w").write("x")
|
||||
os.symlink("dir", FX + "/sl/ldir")
|
||||
os.symlink("file", FX + "/sl/lfile")
|
||||
os.symlink("nowhere", FX + "/sl/ldangling")
|
||||
for name in ("missing", "dir", "file", "ldir", "lfile", "ldangling", "missing/deeper", "file/deeper"):
|
||||
p = FX + "/sl/" + name + "/"
|
||||
print(" ", name + "/", "stat", call(lambda: mode_of(os.stat(p))), "lstat", call(lambda: stat.S_IFMT(os.lstat(p).st_mode)),
|
||||
"access", call(lambda: os.access(p, os.F_OK)), "open", call(lambda: os.close(os.open(p, os.O_RDONLY))),
|
||||
"realpath", realpath(p))
|
||||
t = lambda label, fn: print(f" {label}: {call(fn)}")
|
||||
t("create missing/", lambda: os.close(os.open(FX + "/sl/new/", os.O_CREAT | os.O_WRONLY, 0o644)))
|
||||
t("create dir/", lambda: os.close(os.open(FX + "/sl/dir/", os.O_CREAT | os.O_WRONLY, 0o644)))
|
||||
t("mkdir new/", lambda: os.mkdir(FX + "/sl/made/"))
|
||||
t("made", lambda: mode_of(os.stat(FX + "/sl/made")))
|
||||
t("mkdir file/", lambda: os.mkdir(FX + "/sl/file/"))
|
||||
t("rmdir made/", lambda: os.rmdir(FX + "/sl/made/"))
|
||||
t("unlink file/", lambda: os.unlink(FX + "/sl/file/"))
|
||||
s = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
t("bind sock/", lambda: s.bind(FX + "/sl/sock/"))
|
||||
t("connect missing/", lambda: s.connect(FX + "/sl/missing/"))
|
||||
s.close()
|
||||
for name in ("empty", "empty2", "full/inner"):
|
||||
os.makedirs(FX + "/sl/" + name, exist_ok=True)
|
||||
os.chdir(FX + "/sl/empty")
|
||||
for p in (".", "./", "..", "../empty/.", "../empty/..", "../empty2/"):
|
||||
t(f"rmdir {p}", lambda: os.rmdir(p))
|
||||
t(f"unlink {p}", lambda: os.unlink(p))
|
||||
os.chdir(FX)
|
||||
for name in ("ldir/", "lfile/", "file/", "missing/", "full/", "full//", "empty//", "full/inner/../"):
|
||||
t(f"rmdir {name}", lambda: os.rmdir(FX + "/sl/" + name))
|
||||
r, w = os.pipe()
|
||||
t("stat at a pipe", lambda: os.stat("x", dir_fd=r))
|
||||
t("access at a pipe", lambda: os.access("x", os.F_OK, dir_fd=r))
|
||||
t("open at a pipe", lambda: os.open("x", os.O_RDONLY, dir_fd=r))
|
||||
t("mkdir at a pipe", lambda: os.mkdir("x", dir_fd=r))
|
||||
t("readlink at a pipe", lambda: os.readlink("x", dir_fd=r))
|
||||
os.close(r)
|
||||
os.close(w)
|
||||
t("listing", lambda: sorted(os.listdir(FX + "/sl")))
|
||||
os.symlink("/usr/local/lib/directaudio/linux-wine11/lib/wine/aarch64-windows/winedirectaudio.drv", FX + "/sl/long")
|
||||
os.symlink(ROOT + "/usr/local/lib/directaudio/linux-wine11/lib/wine/aarch64-windows/x.drv", FX + "/sl/longhost")
|
||||
os.symlink(ROOT + "x/y", FX + "/sl/rootprefix")
|
||||
for name in ("long", "longhost", "rootprefix"):
|
||||
p = FX + "/sl/" + name
|
||||
print(" ", name, " ".join(f"{n}:{raw_readlink(p, n)}" for n in (1, 2, len(ROOT), len(ROOT) + 1, len(ROOT) + 2, 30, 64, 128)))
|
||||
|
||||
|
||||
def accept_section():
|
||||
print("== accept")
|
||||
path = "\0fp-equiv3-listener"
|
||||
srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
srv.bind(path)
|
||||
srv.listen(4)
|
||||
named = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
named.bind("\0fp-equiv3-client")
|
||||
named.connect(path)
|
||||
plain = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
plain.connect(path)
|
||||
for label in ("named", "plain"):
|
||||
c, addr = srv.accept()
|
||||
print(" ", label, "blocking", srv.getblocking(), "addr", repr(addr), "name", repr(c.getsockname()),
|
||||
"peer", call(c.getpeername))
|
||||
c.close()
|
||||
srv.setblocking(False)
|
||||
print(" none waiting", call(srv.accept))
|
||||
for x in (srv, named, plain):
|
||||
x.close()
|
||||
|
||||
|
||||
def deep_section():
|
||||
print("== long host paths")
|
||||
os.makedirs(DEEP)
|
||||
t = lambda label, fn: print(f" {label}: {call(fn)}")
|
||||
t("stat missing", lambda: os.stat(DEEP + "/missing.dll"))
|
||||
t("access missing", lambda: os.access(DEEP + "/missing.dll", os.F_OK))
|
||||
t("create", lambda: os.close(os.open(DEEP + "/new", os.O_CREAT | os.O_WRONLY, 0o644)))
|
||||
t("mkdir", lambda: os.mkdir(DEEP + "/sub"))
|
||||
t("symlink", lambda: os.symlink("new", DEEP + "/sub/link"))
|
||||
t("stat through", lambda: mode_of(os.stat(DEEP + "/sub/link")))
|
||||
t("readlink", lambda: os.readlink(DEEP + "/sub/link"))
|
||||
t("rename", lambda: os.rename(DEEP + "/new", DEEP + "/renamed"))
|
||||
t("unlink missing", lambda: os.unlink(DEEP + "/new"))
|
||||
t("unlink", lambda: os.unlink(DEEP + "/renamed"))
|
||||
t("realpath", lambda: realpath(DEEP + "/sub/../sub/link"))
|
||||
t("listing", lambda: sorted(os.listdir(DEEP)))
|
||||
|
||||
|
||||
def glue_section():
|
||||
print("== glue above a binding")
|
||||
for p in ("/cache", "/cache/fp", "/cache/fp/perf", "/cache/fp/other", "/cache/other", "/cache/fp/perf/x",
|
||||
"/cache/fp/.", "/cache/fp/..", "/cache/fp/../fp/perf", "/cache/fp/./perf", "/cache/fp/", "/cache/fp/perf/",
|
||||
"/sys/class/..", "/sys/class/../class", "/proc/self/..", "/opt/fpx/.."):
|
||||
print(" ", p, "stat", call(lambda: mode_of(os.stat(p))), "read", call(lambda: open(p, "rb").read(4)),
|
||||
"realpath", realpath(p))
|
||||
|
||||
|
||||
def shm_section():
|
||||
print("== shm_open")
|
||||
|
||||
def shm(name, flags, mode=0o600):
|
||||
ctypes.set_errno(0)
|
||||
fd = libc.shm_open(name, flags, mode)
|
||||
if fd < 0:
|
||||
return err()
|
||||
st = os.fstat(fd)
|
||||
os.close(fd)
|
||||
return (stat.S_IFMT(st.st_mode), oct(st.st_mode & 0o777), st.st_size)
|
||||
|
||||
def unlink(name):
|
||||
ctypes.set_errno(0)
|
||||
return "ok" if libc.shm_unlink(name) == 0 else err()
|
||||
|
||||
os.makedirs("/dev/shm/fp-dir", exist_ok=True)
|
||||
rw, creat, excl = os.O_RDWR, os.O_CREAT, os.O_EXCL
|
||||
for label, args in [("create", (b"/fp-eq", rw | creat)), ("again", (b"fp-eq", rw)), ("excl", (b"/fp-eq", rw | creat | excl)),
|
||||
("slashes", (b"///fp-eq", os.O_RDONLY)), ("missing", (b"/fp-none", rw)), ("empty", (b"", rw)),
|
||||
("only slash", (b"/", rw)), ("inner slash", (b"/a/b", rw | creat)), ("dir", (b"fp-dir", os.O_RDONLY)),
|
||||
("long", (b"x" * 300, rw | creat))]:
|
||||
print(" ", label, shm(*args))
|
||||
print(" unlink", unlink(b"/fp-eq"), "again", unlink(b"/fp-eq"), "bad", unlink(b"a/b"), "dir", unlink(b"fp-dir"))
|
||||
os.rmdir("/dev/shm/fp-dir")
|
||||
|
||||
|
||||
def uname_section():
|
||||
print("== uname")
|
||||
print(" uname", tuple(os.uname()), "again", tuple(os.uname()) == tuple(os.uname()))
|
||||
print(" hostname", socket.gethostname())
|
||||
for n in (0, 1, 4, 64, 65, 300):
|
||||
buf = ctypes.create_string_buffer(b"#" * (n + 1), n + 1)
|
||||
ctypes.set_errno(0)
|
||||
r = libc.gethostname(buf, n)
|
||||
print(f" gethostname {n}", r, err() if r else "", buf.raw[: n + 1])
|
||||
sys.stdout.flush()
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
print(" child", tuple(os.uname()) == tuple(os.uname()), socket.gethostname(), flush=True)
|
||||
os._exit(0)
|
||||
os.waitpid(pid, 0)
|
||||
|
||||
|
||||
def isatty_section():
|
||||
print("== isatty")
|
||||
libc.isatty.argtypes = [ctypes.c_int]
|
||||
r, w = os.pipe()
|
||||
fds = {"pipe": r, "dev null": os.open("/dev/null", os.O_RDONLY), "file": os.open("/etc/os-release", os.O_RDONLY),
|
||||
"dir": os.open("/", os.O_RDONLY), "socket": socket.socket().detach(), "closed": 999, "negative": -1}
|
||||
try:
|
||||
m, sl = os.openpty()
|
||||
fds.update({"pty master": m, "pty slave": sl})
|
||||
except OSError as e:
|
||||
print(" openpty", errno.errorcode.get(e.errno))
|
||||
for label, fd in fds.items():
|
||||
ctypes.set_errno(0)
|
||||
print(" ", label, libc.isatty(fd), err(), "os", call(lambda: os.isatty(fd)))
|
||||
for fd in fds.values():
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
os.close(w)
|
||||
|
||||
|
||||
PASSWD = """# comment
|
||||
|
||||
root:x:0:0:root:/root:/bin/bash
|
||||
alice:x:1000:1000:Alice A,,,:/home/alice:/bin/sh
|
||||
bob:*:1001:100::/home/bob:
|
||||
"""
|
||||
PASSWD_VARIANTS = {
|
||||
"plain": ("passwd: files systemd\ngroup: files\n", PASSWD),
|
||||
"extra colon": ("passwd: files systemd\n", PASSWD + "carol:x:1002:1002::/home/carol:/bin/sh:extra\n"),
|
||||
"bad uid": ("passwd: files\n", "bad:x:abc:1::/:/bin/sh\n" + PASSWD + "dave:x:1003:1003::/:/bin/sh"),
|
||||
"big uid": ("passwd: files\n", PASSWD + "eve:x:0010:4294967296::/:/bin/sh\n"),
|
||||
"compat": ("passwd: files\n", "+@staff\n-bob\n" + PASSWD),
|
||||
"leading space": ("passwd: files\n", " root:x:0:0:root:/root:/bin/bash\n" + PASSWD),
|
||||
"duplicate": ("passwd: files\n", "alice:x:1001:1:dup:/:/bin/false\n" + PASSWD),
|
||||
"cr": ("passwd: files\n", PASSWD.replace("\n", "\r\n")),
|
||||
"action": ("passwd: files [NOTFOUND=return] systemd\n", PASSWD),
|
||||
"files second": ("passwd: systemd files\n", PASSWD),
|
||||
"comment": ("passwd: files # local\n", PASSWD),
|
||||
"none": ("group: files\n", PASSWD),
|
||||
"two lines": ("passwd: files\npasswd: systemd\n", PASSWD),
|
||||
}
|
||||
|
||||
|
||||
class Passwd(ctypes.Structure):
|
||||
_fields_ = [("name", ctypes.c_char_p), ("passwd", ctypes.c_char_p), ("uid", ctypes.c_uint),
|
||||
("gid", ctypes.c_uint), ("gecos", ctypes.c_char_p), ("dir", ctypes.c_char_p),
|
||||
("shell", ctypes.c_char_p)]
|
||||
|
||||
|
||||
def lookup(fn):
|
||||
try:
|
||||
return repr(tuple(fn()))
|
||||
except (KeyError, OSError) as e:
|
||||
return type(e).__name__
|
||||
|
||||
|
||||
def show_pw(p):
|
||||
return "NULL" if not p else repr(tuple(getattr(p.contents, f) for f, _ in Passwd._fields_))
|
||||
|
||||
|
||||
def passwd_probe():
|
||||
import pwd
|
||||
libc.getpwnam.restype = libc.getpwuid.restype = ctypes.POINTER(Passwd)
|
||||
libc.getpwnam.argtypes = [ctypes.c_char_p]
|
||||
libc.getpwuid.argtypes = [ctypes.c_uint]
|
||||
names = ["root", "alice", "bob", "carol", "dave", "eve", "nobody", "+@staff", "-bob", ""]
|
||||
uids = [0, 10, 100, 1000, 1001, 1002, 1003, 65534, 4294967295]
|
||||
for n in names:
|
||||
ctypes.set_errno(0)
|
||||
r = libc.getpwnam(n.encode())
|
||||
print(f" getpwnam {n!r}", show_pw(r), err(), lookup(lambda: pwd.getpwnam(n)) if n else "")
|
||||
for u in uids:
|
||||
ctypes.set_errno(0)
|
||||
r = libc.getpwuid(u)
|
||||
print(f" getpwuid {u}", show_pw(r), err(), lookup(lambda: pwd.getpwuid(u)))
|
||||
a = libc.getpwnam(b"root")
|
||||
b = libc.getpwnam(b"alice")
|
||||
print(" static reused", bool(a) and bool(b) and ctypes.addressof(a.contents) == ctypes.addressof(b.contents),
|
||||
show_pw(a))
|
||||
for fn, key in ((libc.getpwnam_r, b"alice"), (libc.getpwuid_r, 1000), (libc.getpwnam_r, b"nobody")):
|
||||
for size in (1, 8, 40, 46, 47, 48, 49, 50, 64, 1024):
|
||||
pw, res, buf = Passwd(), ctypes.POINTER(Passwd)(), ctypes.create_string_buffer(size)
|
||||
ctypes.set_errno(0)
|
||||
r = fn(key, ctypes.byref(pw), buf, size, ctypes.byref(res))
|
||||
print(f" {fn.__name__} {key!r} {size}", errno.errorcode.get(r, r), err(), show_pw(res))
|
||||
sys.stdout.flush()
|
||||
|
||||
|
||||
def passwd_section():
|
||||
print("== passwd")
|
||||
saved = {}
|
||||
for f in ("/etc/passwd", "/etc/nsswitch.conf"):
|
||||
try:
|
||||
saved[f] = open(f).read()
|
||||
except OSError:
|
||||
saved[f] = None
|
||||
try:
|
||||
for label, (conf, passwd) in PASSWD_VARIANTS.items():
|
||||
print(" ", label, flush=True)
|
||||
open("/etc/nsswitch.conf", "w").write(conf)
|
||||
open("/etc/passwd", "w").write(passwd)
|
||||
pid = os.fork()
|
||||
if pid == 0:
|
||||
os.execv(sys.executable, [sys.executable, __file__, "passwd"])
|
||||
os.waitpid(pid, 0)
|
||||
finally:
|
||||
for f, text in saved.items():
|
||||
if text is None:
|
||||
os.unlink(f)
|
||||
else:
|
||||
open(f, "w").write(text)
|
||||
|
||||
|
||||
def fortify_section():
|
||||
print("== fortify")
|
||||
os.chdir(FX + "/dir")
|
||||
buf = ctypes.create_string_buffer(256)
|
||||
ctypes.set_errno(0)
|
||||
r = libc.__getcwd_chk(buf, 256, 256)
|
||||
print(" getcwd_chk", norm(r.decode()) if r else err())
|
||||
ctypes.set_errno(0)
|
||||
r = libc.__getcwd_chk(buf, 4, 256)
|
||||
print(" getcwd_chk small", norm(r.decode()) if r else err())
|
||||
d = os.open(FX, os.O_RDONLY)
|
||||
print(" readlinkat_chk", libc.__readlinkat_chk(d, b"mtab", buf, 256, 256), norm(buf.value))
|
||||
os.close(d)
|
||||
os.chdir("/")
|
||||
|
||||
|
||||
def main():
|
||||
shutil.rmtree(FX, ignore_errors=True)
|
||||
os.makedirs(FX)
|
||||
os.chdir(FX)
|
||||
proc_section()
|
||||
host_text_section()
|
||||
shared_section()
|
||||
unseen_section()
|
||||
slash_section()
|
||||
accept_section()
|
||||
deep_section()
|
||||
glue_section()
|
||||
shm_section()
|
||||
uname_section()
|
||||
isatty_section()
|
||||
passwd_section()
|
||||
fortify_section()
|
||||
shutil.rmtree(FX, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
passwd_probe() if sys.argv[1:] == ["passwd"] else main()
|
||||
@@ -0,0 +1,119 @@
|
||||
/* The calls the fast path took over from proot, timed: run under fpoff and fastpath and compare.
|
||||
* Usage: fpbench <scratch dir in the guest> [iterations]. Builds a Wine-like prefix there. */
|
||||
#define _GNU_SOURCE
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <pwd.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/statvfs.h>
|
||||
#include <sys/un.h>
|
||||
#include <sys/utsname.h>
|
||||
#include <sys/xattr.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static double now(void) {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
return t.tv_sec * 1e9 + t.tv_nsec;
|
||||
}
|
||||
|
||||
#define BENCH(name, n, body) \
|
||||
do { \
|
||||
for (int _w = 0; _w < (n) / 10 + 1; _w++) { body; } \
|
||||
double _t0 = now(); \
|
||||
for (int _i = 0; _i < (n); _i++) { body; } \
|
||||
printf("%-34s %10.0f ns\n", name, (now() - _t0) / (n)); \
|
||||
fflush(stdout); \
|
||||
} while (0)
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
const char *d = argc > 1 ? argv[1] : "/root/fpb";
|
||||
int n = argc > 2 ? atoi(argv[2]) : 5000;
|
||||
char p[PATH_MAX], q[2 * PATH_MAX], f[PATH_MAX], dos[PATH_MAX], buf[PATH_MAX];
|
||||
struct stat st;
|
||||
const char *dirs[] = {"", "/pfx", "/pfx/drive_c", "/pfx/drive_c/windows", "/pfx/drive_c/windows/system32", "/pfx/dosdevices"};
|
||||
for (size_t i = 0; i < sizeof dirs / sizeof *dirs; i++) {
|
||||
snprintf(p, sizeof p, "%s%s", d, dirs[i]);
|
||||
mkdir(p, 0755);
|
||||
}
|
||||
snprintf(p, sizeof p, "%s/pfx/drive_c/windows/system32/kernel32.dll", d);
|
||||
close(open(p, O_CREAT | O_WRONLY, 0644));
|
||||
snprintf(p, sizeof p, "%s/pfx/dosdevices/c:", d);
|
||||
unlink(p);
|
||||
if (symlink("../drive_c", p) != 0) return 1;
|
||||
snprintf(p, sizeof p, "%s/pfx/dosdevices/z:", d);
|
||||
unlink(p);
|
||||
if (symlink("/", p) != 0) return 1;
|
||||
snprintf(dos, sizeof dos, "%s/pfx/dosdevices/c:/windows/system32/kernel32.dll", d);
|
||||
snprintf(f, sizeof f, "%s/pfx/drive_c/windows/system32/kernel32.dll", d);
|
||||
snprintf(q, sizeof q, "%s/pfx/dosdevices/z:%s", d, f);
|
||||
|
||||
BENCH("stat plain path", n, stat(f, &st));
|
||||
BENCH("stat through c: link", n, stat(dos, &st));
|
||||
BENCH("stat through z: link", n, stat(q, &st));
|
||||
BENCH("open+close through c:", n, close(open(dos, O_RDONLY)));
|
||||
BENCH("stat missing through c:", n, stat("/root/fpb/pfx/dosdevices/c:/windows/nope.dll", &st));
|
||||
BENCH("realpath through c:", n, if (!realpath(dos, buf)) return 1);
|
||||
BENCH("realpath plain", n, if (!realpath(f, buf)) return 1);
|
||||
BENCH("getcwd", n, if (!getcwd(buf, sizeof buf)) return 1);
|
||||
BENCH("fstat", n, { int fd = open(f, O_RDONLY); fstat(fd, &st); close(fd); });
|
||||
BENCH("faccessat AT_EACCESS", n, (void)!faccessat(AT_FDCWD, f, R_OK, AT_EACCESS));
|
||||
BENCH("getxattr through c:", n, getxattr(dos, "user.DOSATTRIB", buf, sizeof buf));
|
||||
BENCH("statvfs", n, { struct statvfs v; statvfs(f, &v); });
|
||||
snprintf(p, sizeof p, "%s/w", d);
|
||||
snprintf(q, sizeof q, "%s/w2", d);
|
||||
BENCH("mkdir+rmdir", n / 2, { mkdir(p, 0755); rmdir(p); });
|
||||
BENCH("create+rename+unlink", n / 2, { close(open(p, O_CREAT | O_WRONLY, 0644)); rename(p, q); unlink(q); });
|
||||
BENCH("symlink+unlink", n / 2, { (void)!symlink("x", p); unlink(p); });
|
||||
BENCH("utimensat", n, utimensat(AT_FDCWD, f, NULL, 0));
|
||||
BENCH("sysconf NPROCESSORS_ONLN", n, sysconf(_SC_NPROCESSORS_ONLN));
|
||||
int held = open(f, O_RDONLY);
|
||||
char fdlink[64];
|
||||
snprintf(fdlink, sizeof fdlink, "/proc/self/fd/%d", held);
|
||||
BENCH("readlink /proc/self/fd/N", n, (void)!readlink(fdlink, buf, sizeof buf));
|
||||
BENCH("realpath /proc/self/fd/N", n, if (!realpath(fdlink, buf)) return 1);
|
||||
BENCH("realpath /proc/self/exe", n, if (!realpath("/proc/self/exe", buf)) return 1);
|
||||
BENCH("open+close /proc/self/fd/N", n, close(open(fdlink, O_RDONLY)));
|
||||
BENCH("open+close /proc/mounts", n / 4, close(open("/proc/mounts", O_RDONLY)));
|
||||
BENCH("access /proc/1/fd/0 (EACCES)", n, (void)!access("/proc/1/fd/0", F_OK));
|
||||
snprintf(p, sizeof p, "%s/pfx/drive_c/windows/nope/", d);
|
||||
BENCH("stat missing dir/", n, stat(p, &st));
|
||||
BENCH("open+close /proc/self/status", n, close(open("/proc/self/status", O_RDONLY)));
|
||||
close(held);
|
||||
BENCH("shm_open+close", n, close(shm_open("/fpbench", O_RDWR | O_CREAT, 0600)));
|
||||
shm_unlink("/fpbench");
|
||||
snprintf(p, sizeof p, "%s/pfx/drive_c/windows/system32/a-name-long-enough-to-push-the-host-path-past-sun_path.dll", d);
|
||||
BENCH("stat missing, long host path", n, stat(p, &st));
|
||||
BENCH("create+unlink, long host path", n / 2, { close(open(p, O_CREAT | O_WRONLY, 0644)); unlink(p); });
|
||||
{
|
||||
int l = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
struct sockaddr_un a = { .sun_family = AF_UNIX };
|
||||
memcpy(a.sun_path, "\0fpbench-listener", 18);
|
||||
if (bind(l, (struct sockaddr *)&a, sizeof a) != 0 || listen(l, 64) != 0) { perror("listener"); return 1; }
|
||||
BENCH("connect+accept unix (blocking)", n / 4, {
|
||||
int c = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
connect(c, (struct sockaddr *)&a, sizeof a);
|
||||
close(accept(l, NULL, NULL));
|
||||
close(c);
|
||||
});
|
||||
close(l);
|
||||
}
|
||||
BENCH("connect abstract unix", n / 4, {
|
||||
int s = socket(AF_UNIX, SOCK_STREAM, 0);
|
||||
struct sockaddr_un a = { .sun_family = AF_UNIX };
|
||||
memcpy(a.sun_path, "\0fpbench-none", 13);
|
||||
connect(s, (struct sockaddr *)&a, offsetof(struct sockaddr_un, sun_path) + 13);
|
||||
close(s);
|
||||
});
|
||||
BENCH("getpwuid", n / 4, getpwuid(0));
|
||||
BENCH("uname", n, { struct utsname u; uname(&u); });
|
||||
BENCH("isatty", n, isatty(0));
|
||||
return 0;
|
||||
}
|
||||
@@ -13,7 +13,7 @@ D=/data/local/tmp/dd
|
||||
V=$1; shift
|
||||
U=$(id -u)
|
||||
REL="\\Linux\\DroidDeck\\$(uname -r)\\$(uname -v)\\aarch64\\localdomain\\-1\\"
|
||||
BINDS="-b /dev -b /proc -b /sys -b /dev/urandom:/dev/random -b /proc/self/fd:/dev/fd -b /proc/self/fd/0:/dev/stdin -b /proc/self/fd/1:/dev/stdout -b /proc/self/fd/2:/dev/stderr -b $D/tmp:/dev/shm -b $D -b /sdcard -b /data/local/tmp/dd/mini/etc/os-release:/proc/version -b $D/mini/etc/os-release:/proc/loadavg -b $D/mini/etc/os-release:/proc/uptime -b /sys/class/thermal/thermal_zone0/temp:/sys/class/thermal/thermal_zone28/temp -b $D/tmp:/mnt/droiddeck-sd -b $D/tmp:/mnt/droiddeck"
|
||||
BINDS="-b /dev -b /proc -b /sys -b /dev/urandom:/dev/random -b /proc/self/fd:/dev/fd -b /proc/self/fd/0:/dev/stdin -b /proc/self/fd/1:/dev/stdout -b /proc/self/fd/2:/dev/stderr -b $D/tmp:/dev/shm -b $D -b /sdcard -b /data/local/tmp/dd/mini/etc/os-release:/proc/version -b $D/mini/etc/os-release:/proc/loadavg -b $D/mini/etc/os-release:/proc/uptime -b /sys/class/thermal/thermal_zone0/temp:/sys/class/thermal/thermal_zone28/temp -b $D/tmp:/mnt/droiddeck-sd -b $D/tmp:/mnt/droiddeck -b /cache -b $D/mini/etc/os-release:/cache/fp/perf -b $D/fpx:/opt/fpx"
|
||||
export PROOT_TMP_DIR=$D/tmp
|
||||
case $V in
|
||||
patched) export PROOT_LOADER=$D/loader; exec $D/proot --kill-on-exit --kernel-release="$REL" -i $U:$U -r $D/mini -w /root $BINDS /usr/bin/env -i HOME=/root PATH=/usr/bin LANG=C.UTF-8 "$@" ;;
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
/*
|
||||
* libblaudit: an LD_AUDIT module that keeps ld.so from asking proot about libraries that are not
|
||||
* there. ld.so finds a library by trying to open it in each directory of its search path in turn,
|
||||
* and under proot every one of those opens is a round trip through the tracer. A game's environment
|
||||
* puts the game's own directory, Steam's runtime and video directories and Proton's library
|
||||
* directories ahead of /usr/lib, so most of the opens of every Wine process fail.
|
||||
*
|
||||
* la_objsearch() is asked about each candidate before ld.so opens it. One that provably does not
|
||||
* exist - its parent directory is reached through no symlink, so proot would walk the same path,
|
||||
* and the name itself is missing there - is skipped. Everything else is left to ld.so, which then
|
||||
* behaves exactly as it would have.
|
||||
*
|
||||
* Built without libc: an audit module is loaded into a link namespace of its own, and a libc there
|
||||
* would be searched for along that same path. Its calls go through the trampoline page of
|
||||
* libblfastpath.so, mapped here first (libblfastpath finds it in place), and only in a process traced
|
||||
* by the proot the environment describes (PROOT_FP_KEY, as libblfastpath checks it).
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <link.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <time.h>
|
||||
|
||||
#define FP_STUB_ADDR 0xffff00000UL /* as in fastpath.c */
|
||||
#define FP_STUB_SIZE 4096UL
|
||||
#define MAX_BINDS 256
|
||||
#define PATH 4096
|
||||
#define VERIFIED 32
|
||||
#define TTL_NS 2000000000LL
|
||||
|
||||
typedef long (*stub_fn)(long, long, long, long, long, long, long);
|
||||
static stub_fn sys;
|
||||
|
||||
static long sc(long nr, long a, long b, long c, long d) { return sys(nr, a, b, c, d, 0, 0); }
|
||||
|
||||
/* A syscall of its own, before the trampoline exists: only mmap, mprotect and munmap, which proot
|
||||
* does not stop. */
|
||||
static long raw(long nr, long a, long b, long c, long d) {
|
||||
register long x8 __asm__("x8") = nr;
|
||||
register long x0 __asm__("x0") = a;
|
||||
register long x1 __asm__("x1") = b;
|
||||
register long x2 __asm__("x2") = c;
|
||||
register long x3 __asm__("x3") = d;
|
||||
register long x4 __asm__("x4") = -1;
|
||||
register long x5 __asm__("x5") = 0;
|
||||
__asm__ volatile("svc #0" : "+r"(x0) : "r"(x8), "r"(x1), "r"(x2), "r"(x3), "r"(x4), "r"(x5) : "memory");
|
||||
return x0;
|
||||
}
|
||||
|
||||
/* What __builtin___clear_cache does on aarch64, without libgcc. */
|
||||
static void sync_code(char *b, char *e) {
|
||||
for (char *p = b; p < e; p += 4) __asm__ volatile("dc cvau, %0" : : "r"(p) : "memory");
|
||||
__asm__ volatile("dsb ish" : : : "memory");
|
||||
for (char *p = b; p < e; p += 4) __asm__ volatile("ic ivau, %0" : : "r"(p) : "memory");
|
||||
__asm__ volatile("dsb ish\n\tisb" : : : "memory");
|
||||
}
|
||||
|
||||
static size_t len_of(const char *s) {
|
||||
size_t n = 0;
|
||||
while (s[n]) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
static int same(const char *a, const char *b, size_t n) {
|
||||
for (size_t i = 0; i < n; i++)
|
||||
if (a[i] != b[i]) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void copy(char *d, const char *s, size_t n) {
|
||||
for (size_t i = 0; i < n; i++) d[i] = s[i];
|
||||
}
|
||||
|
||||
static int under(const char *path, const char *dir, size_t dlen) {
|
||||
return same(path, dir, dlen) && (path[dlen] == 0 || path[dlen] == '/');
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- setup */
|
||||
|
||||
static char env[65536], tracer_env[32768];
|
||||
static size_t env_len;
|
||||
static const char *root;
|
||||
static size_t rootlen;
|
||||
static char root_canon[PATH];
|
||||
struct bind { const char *host; size_t hlen; const char *guest; size_t glen; int state; char canon[PATH]; };
|
||||
static struct bind binds[MAX_BINDS];
|
||||
static int nbinds;
|
||||
static int ready;
|
||||
|
||||
static long slurp(const char *path, char *buf, size_t size) {
|
||||
long fd = sc(SYS_openat, AT_FDCWD, (long)path, O_RDONLY | O_CLOEXEC, 0);
|
||||
if (fd < 0) return -1;
|
||||
size_t have = 0;
|
||||
for (long r; have < size - 1 && (r = sc(SYS_read, fd, (long)buf + have, size - 1 - have, 0)) > 0;) have += r;
|
||||
sc(SYS_close, fd, 0, 0, 0);
|
||||
buf[have] = 0;
|
||||
return (long)have;
|
||||
}
|
||||
|
||||
static const char *var(const char *buf, size_t len, const char *name) {
|
||||
size_t n = len_of(name);
|
||||
for (size_t i = 0; i < len; i += len_of(buf + i) + 1)
|
||||
if (same(buf + i, name, n) && buf[i + n] == '=') return buf + i + n + 1;
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/* The canonical form of a host path, as proot's realpath() made it; 0 when it has none. */
|
||||
static int canonical(const char *path, char *out) {
|
||||
long fd = sc(SYS_openat, AT_FDCWD, (long)path, O_PATH | O_CLOEXEC, 0);
|
||||
if (fd < 0) return 0;
|
||||
char link[40] = "/proc/self/fd/";
|
||||
char digits[20];
|
||||
int nd = 0;
|
||||
for (long v = fd; nd == 0 || v; v /= 10) digits[nd++] = '0' + v % 10;
|
||||
for (int i = 0; i < nd; i++) link[14 + i] = digits[nd - 1 - i];
|
||||
link[14 + nd] = 0;
|
||||
long n = sc(SYS_readlinkat, AT_FDCWD, (long)link, (long)out, PATH - 1);
|
||||
sc(SYS_close, fd, 0, 0, 0);
|
||||
if (n <= 0 || out[0] != '/') return 0;
|
||||
out[n] = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int traced_by_match(const char *key) {
|
||||
char status[4096], path[48] = "/proc/";
|
||||
long n = slurp("/proc/self/status", status, sizeof status);
|
||||
const char *line = NULL;
|
||||
for (long i = 0; n > 0 && i < n; i++)
|
||||
if (status[i] == '\n' && same(status + i + 1, "TracerPid:", 10)) { line = status + i + 11; break; }
|
||||
if (!line) return 0;
|
||||
while (*line == ' ' || *line == '\t') line++;
|
||||
size_t d = 0;
|
||||
while (line[d] >= '0' && line[d] <= '9' && d < 16) d++;
|
||||
if (d == 0 || (d == 1 && line[0] == '0')) return 0;
|
||||
copy(path + 6, line, d);
|
||||
copy(path + 6 + d, "/environ", 9);
|
||||
long have = slurp(path, tracer_env, sizeof tracer_env);
|
||||
if (have <= 0 || var(tracer_env, have, "PROOT_NO_SECCOMP")) return 0;
|
||||
const char *theirs = var(tracer_env, have, "PROOT_FASTPATH");
|
||||
return theirs && len_of(theirs) == len_of(key) && same(theirs, key, len_of(key));
|
||||
}
|
||||
|
||||
static void setup(void) {
|
||||
long p = raw(SYS_mmap, FP_STUB_ADDR, FP_STUB_SIZE, PROT_READ | PROT_WRITE,
|
||||
MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED_NOREPLACE);
|
||||
/* Loaded before anything else maps, so whatever is already there is not the trampoline. */
|
||||
if (p != (long)FP_STUB_ADDR) {
|
||||
if (p > 0) raw(SYS_munmap, p, FP_STUB_SIZE, 0, 0);
|
||||
return;
|
||||
}
|
||||
static const uint32_t code[] = {
|
||||
0xAA0003E8, 0xAA0103E0, 0xAA0203E1, 0xAA0303E2, 0xAA0403E3, 0xAA0503E4, 0xAA0603E5,
|
||||
0xD4000001, 0xD65F03C0, /* mov x8,x0; mov x0..x5,x1..x6; svc #0; ret */
|
||||
};
|
||||
copy((char *)p, (const char *)code, sizeof code);
|
||||
sync_code((char *)p, (char *)p + sizeof code);
|
||||
if (raw(SYS_mprotect, FP_STUB_ADDR, FP_STUB_SIZE, PROT_READ | PROT_EXEC, 0) != 0) {
|
||||
raw(SYS_munmap, FP_STUB_ADDR, FP_STUB_SIZE, 0, 0);
|
||||
return;
|
||||
}
|
||||
sys = (stub_fn)FP_STUB_ADDR;
|
||||
long n = slurp("/proc/self/environ", env, sizeof env);
|
||||
if (n <= 0 || (size_t)n >= sizeof env - 1) return;
|
||||
env_len = n;
|
||||
const char *key = var(env, env_len, "PROOT_FP_KEY"), *b = var(env, env_len, "PROOT_FP_BINDS");
|
||||
root = var(env, env_len, "PROOT_FP_ROOT");
|
||||
if (!key || !*key || !root || !*root || var(env, env_len, "PROOT_FP_OFF") || !traced_by_match(key)) return;
|
||||
if (!canonical(root, root_canon)) return;
|
||||
root = root_canon;
|
||||
rootlen = len_of(root);
|
||||
if (rootlen <= 1) return;
|
||||
/* "host[:guest]|..." taken apart in place; a list this cannot hold leaves everything to ld.so. */
|
||||
for (char *s = (char *)b; s && *s;) {
|
||||
if (nbinds == MAX_BINDS) return;
|
||||
char *end = s;
|
||||
while (*end && *end != '|') end++;
|
||||
char *colon = s;
|
||||
while (colon < end && *colon != ':') colon++;
|
||||
struct bind *bd = &binds[nbinds];
|
||||
bd->host = s;
|
||||
bd->hlen = colon - s;
|
||||
bd->guest = colon < end ? colon + 1 : s;
|
||||
bd->glen = colon < end ? (size_t)(end - colon - 1) : bd->hlen;
|
||||
if (bd->guest[0] == '/' && bd->glen > 1 && bd->hlen > 0) nbinds++;
|
||||
int last = *end == 0;
|
||||
*end = 0;
|
||||
if (colon < end) *colon = 0;
|
||||
if (last) break;
|
||||
s = end + 1;
|
||||
}
|
||||
ready = 1;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- lookups */
|
||||
|
||||
/* The host path proot binds there, as it canonicalised it: NULL for one it dropped (or /proc/self). */
|
||||
static const char *bind_host(struct bind *bd) {
|
||||
if (!bd->state) {
|
||||
bd->state = under(bd->host, "/proc/self", 10) || !canonical(bd->host, bd->canon) ? 2 : 1;
|
||||
}
|
||||
return bd->state == 1 ? bd->canon : NULL;
|
||||
}
|
||||
|
||||
static long long now(void) {
|
||||
struct timespec ts;
|
||||
if (sc(SYS_clock_gettime, CLOCK_MONOTONIC_COARSE, (long)&ts, 0, 0) != 0) return 0;
|
||||
return ts.tv_sec * 1000000000LL + ts.tv_nsec;
|
||||
}
|
||||
|
||||
/* The host path proot gives a canonical guest path: under the longest binding over it (the last of
|
||||
* two for the same path), else the rootfs. 0 for a binding proot dropped, or no room. */
|
||||
static int to_host(const char *g, char *host, int *bound) {
|
||||
size_t n = len_of(g);
|
||||
struct bind *bd = NULL;
|
||||
for (int i = 0; i < nbinds; i++)
|
||||
if (under(g, binds[i].guest, binds[i].glen) && (!bd || binds[i].glen >= bd->glen)) bd = &binds[i];
|
||||
const char *base = root, *rest = g;
|
||||
if (bd) {
|
||||
base = bind_host(bd);
|
||||
if (!base) return 0;
|
||||
rest = g + bd->glen;
|
||||
} else if (n == 1) {
|
||||
rest = "";
|
||||
}
|
||||
size_t blen = len_of(base), rlen = len_of(rest);
|
||||
if (blen + rlen >= PATH) return 0;
|
||||
copy(host, base, blen);
|
||||
copy(host + blen, rest, rlen + 1);
|
||||
*bound = bd != NULL;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Under a directory proot or the kernel answers for in its own way. */
|
||||
static int special(const char *g) {
|
||||
return under(g, "/proc", 5) || under(g, "/dev", 4) || under(g, "/sys", 4);
|
||||
}
|
||||
|
||||
/* A guest path proot only shows as glue, or one with a binding below it. */
|
||||
static int above_binding(const char *g) {
|
||||
size_t n = len_of(g);
|
||||
for (int i = 0; i < nbinds; i++)
|
||||
if (binds[i].glen > n && under(binds[i].guest, g, n)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* The canonical guest path of the directory `g`, walked as canonicalize() walks it: a symlink in the
|
||||
* rootfs is followed in guest terms, its text losing the rootfs prefix as detranslate_path() has it.
|
||||
* -1 when a component is missing, so proot fails the path with ENOENT. Anything this cannot follow
|
||||
* exactly (a link inside a binding, glue, a component not a directory) gives 0.
|
||||
*/
|
||||
static int canonical_dir(const char *g, char *out) {
|
||||
char path[PATH], next[PATH], host[PATH], text[PATH];
|
||||
char st_buf[256] __attribute__((aligned(16)));
|
||||
struct stat *st = (struct stat *)st_buf;
|
||||
size_t glen = len_of(g), olen = 0;
|
||||
int links = 0, bound;
|
||||
if (glen >= PATH) return 0;
|
||||
copy(path, g, glen + 1);
|
||||
out[0] = '/';
|
||||
out[1] = 0;
|
||||
for (char *c = path;;) {
|
||||
while (*c == '/') c++;
|
||||
if (!*c) break;
|
||||
char *e = c;
|
||||
while (*e && *e != '/') e++;
|
||||
size_t n = e - c;
|
||||
if (n == 1 && c[0] == '.') { c = e; continue; }
|
||||
if (n == 2 && c[0] == '.' && c[1] == '.') {
|
||||
while (olen > 0 && out[olen] != '/') olen--;
|
||||
out[olen ? olen : 1] = 0;
|
||||
c = e;
|
||||
continue;
|
||||
}
|
||||
if (olen + n + 2 >= PATH) return 0;
|
||||
out[olen] = '/';
|
||||
copy(out + olen + 1, c, n);
|
||||
out[olen + 1 + n] = 0;
|
||||
if (!to_host(out, host, &bound)) return 0;
|
||||
long r = sc(SYS_newfstatat, AT_FDCWD, (long)host, (long)st, AT_SYMLINK_NOFOLLOW);
|
||||
if (r == -ENOENT && !special(out) && !above_binding(out)) return -1;
|
||||
if (r != 0) return 0;
|
||||
if (S_ISDIR(st->st_mode)) {
|
||||
olen += 1 + n;
|
||||
c = e;
|
||||
continue;
|
||||
}
|
||||
if (!S_ISLNK(st->st_mode) || bound || ++links > 16) return 0;
|
||||
long t = sc(SYS_readlinkat, AT_FDCWD, (long)host, (long)text, PATH - 1);
|
||||
if (t <= 0 || t >= PATH - 1) return 0;
|
||||
text[t] = 0;
|
||||
const char *guest_text = text;
|
||||
if (under(text, root, rootlen)) guest_text = text[rootlen] ? text + rootlen : "/";
|
||||
size_t tl = len_of(guest_text), rest = len_of(e);
|
||||
if (tl + rest + 1 >= PATH) return 0;
|
||||
copy(next, guest_text, tl);
|
||||
copy(next + tl, e, rest + 1);
|
||||
copy(path, next, tl + rest + 1);
|
||||
c = path;
|
||||
if (guest_text[0] == '/') olen = 0;
|
||||
out[olen ? olen : 1] = 0;
|
||||
}
|
||||
if (olen == 0) out[1] = 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static struct { char dir[PATH]; char canon[PATH]; long long at; } known[VERIFIED];
|
||||
static int next_slot;
|
||||
|
||||
/* canonical_dir(), remembered for a while: ld.so looks in the same few directories for every
|
||||
* library. */
|
||||
static int known_dir(const char *g, char *out) {
|
||||
size_t n = len_of(g);
|
||||
long long t = now();
|
||||
for (int i = 0; i < VERIFIED; i++)
|
||||
if (known[i].at && t - known[i].at < TTL_NS && same(known[i].dir, g, n + 1)) {
|
||||
copy(out, known[i].canon, len_of(known[i].canon) + 1);
|
||||
return 1;
|
||||
}
|
||||
int r = canonical_dir(g, out);
|
||||
if (r != 1) return r;
|
||||
copy(known[next_slot].dir, g, n + 1);
|
||||
copy(known[next_slot].canon, out, len_of(out) + 1);
|
||||
known[next_slot].at = t;
|
||||
next_slot = (next_slot + 1) % VERIFIED;
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* The guest path certainly names nothing: its directory is one proot reaches the same way, and the
|
||||
* name is missing there. */
|
||||
static int missing(const char *g) {
|
||||
char dir[PATH], cand[PATH], host[PATH];
|
||||
size_t n = len_of(g);
|
||||
if (g[0] != '/' || n < 2 || n >= PATH - 1) return 0;
|
||||
size_t slash = n;
|
||||
while (slash > 0 && g[slash - 1] != '/') slash--;
|
||||
const char *name = g + slash;
|
||||
size_t nl = n - slash;
|
||||
if (nl == 0 || (nl == 1 && name[0] == '.') || (nl == 2 && name[0] == '.' && name[1] == '.')) return 0;
|
||||
copy(dir, g, slash);
|
||||
dir[slash > 1 ? slash - 1 : 1] = 0;
|
||||
int known_as = known_dir(dir, cand);
|
||||
if (known_as != 1) return known_as < 0;
|
||||
size_t cl = len_of(cand);
|
||||
if (cl + nl + 2 >= PATH) return 0;
|
||||
if (cl > 1) cand[cl++] = '/';
|
||||
copy(cand + cl, name, nl + 1);
|
||||
int bound;
|
||||
if (special(cand) || above_binding(cand) || !to_host(cand, host, &bound))
|
||||
return 0;
|
||||
char st[256] __attribute__((aligned(16)));
|
||||
return sc(SYS_newfstatat, AT_FDCWD, (long)host, (long)st, AT_SYMLINK_NOFOLLOW) == -ENOENT;
|
||||
}
|
||||
|
||||
unsigned int la_version(unsigned int version) {
|
||||
(void)version;
|
||||
setup();
|
||||
return LAV_CURRENT;
|
||||
}
|
||||
|
||||
/*
|
||||
* A candidate skipped here is one whose open "failed" with ld.so's errno as it stands, and ld.so
|
||||
* gives up on the whole search path unless that is ENOENT or EACCES. So each lookup's first
|
||||
* candidate is always opened for real: once that has failed, errno says so, and nothing ld.so
|
||||
* does between candidates changes it unless the search ends anyway. The default directories are
|
||||
* left alone too: what ld.so meets there is what it reports when a library is nowhere.
|
||||
*/
|
||||
static int tried;
|
||||
|
||||
char *la_objsearch(const char *name, uintptr_t *cookie, unsigned int flag) {
|
||||
(void)cookie;
|
||||
if (flag == LA_SER_ORIG) {
|
||||
tried = 0;
|
||||
return (char *)name;
|
||||
}
|
||||
if (!ready || !tried || flag == LA_SER_DEFAULT || !missing(name)) {
|
||||
tried = 1;
|
||||
return (char *)name;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
+1423
-216
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user