#!/usr/bin/env dub
/+ dub.sdl:
name "android-research-exec-route"
targetPath "build"
buildType "checked" {
buildOptions "optimize" "inline" "debugInfo"
}
+/
// ci: run-always
/**
* Model of the exec routes open to an app that targets API >= 29, where the
* kernel refuses execve() of files in the app's writable data directory.
* Evidence for ../index.md#how-it-works and ../index.md#extent-of-the-workaround.
*
* `rewrite` mirrors termux-exec's decision (termux-play-store/termux-exec
* 47633d5df2db3dfea34cef568c6c82a7ba8dcc2e, src/termux-exec.c `execve`): an
* ELF or shebang target under the app's data directory becomes
* `/system/bin/linker64 <target> …`. `route` adds what the rewrite cannot
* express: Bionic's linker loads only Bionic-dynamic ELFs, so static and
* glibc executables need a loader shipped as an APK native library (the Play
* build's `libproot-loader.so`).
*
* The cases are synthetic headers, so the output is the same on every host.
* Pass a file path to classify a real ELF or script instead.
*/
module (module) exec_routeModel of the exec routes open to an app that targets API >= 29, where the
kernel refuses execve() of files in the app's writable data directory.
Evidence for ../index.md#how-it-works and ../index.md#extent-of-the-workaround.
rewrite mirrors termux-exec's decision (termux-play-store/termux-exec
47633d5df2db3dfea34cef568c6c82a7ba8dcc2e, src/termux-exec.c execve): an
ELF or shebang target under the app's data directory becomes
/system/bin/linker64 <target> …. route adds what the rewrite cannot
express: Bionic's linker loads only Bionic-dynamic ELFs, so static and
glibc executables need a loader shipped as an APK native library (the Play
build's libproot-loader.so).
The cases are synthetic headers, so the output is the same on every host.
Pass a file path to classify a real ELF or script instead.
exec_route;
import (package) stdstd.(module) std.algorithmThis package implements generic algorithms oriented towards the processing of
sequences. Sequences processed by these functions define range-based
interfaces. See also Reference on ranges and
tutorial on ranges.
Algorithms are categorized into the following submodules:
Submodule Functions
| Searching |
all
any
balancedParens
boyerMooreFinder
canFind
commonPrefix
count
countUntil
endsWith
find
findAdjacent
findAmong
findSkip
findSplit
findSplitAfter
findSplitBefore
minCount
maxCount
minElement
maxElement
minIndex
maxIndex
minPos
maxPos
skipOver
startsWith
until
|
| Comparison |
among
castSwitch
clamp
cmp
either
equal
isPermutation
isSameLength
levenshteinDistance
levenshteinDistanceAndPath
max
min
mismatch
predSwitch
|
| Iteration |
cache
cacheBidirectional
chunkBy
cumulativeFold
each
filter
filterBidirectional
fold
group
joiner
map
mean
permutations
reduce
splitWhen
splitter
substitute
sum
uniq
|
| Sorting |
completeSort
isPartitioned
isSorted
isStrictlyMonotonic
ordered
strictlyOrdered
makeIndex
merge
multiSort
nextEvenPermutation
nextPermutation
nthPermutation
partialSort
partition
partition3
schwartzSort
sort
topN
topNCopy
topNIndex
|
| Set operations (setops) |
cartesianProduct
largestPartialIntersection
largestPartialIntersectionWeighted
multiwayMerge
multiwayUnion
setDifference
setIntersection
setSymmetricDifference
|
| Mutation |
bringToFront
copy
fill
initializeAll
move
moveAll
moveSome
moveEmplace
moveEmplaceAll
moveEmplaceSome
remove
reverse
strip
stripLeft
stripRight
swap
swapRanges
uninitializedFill
|
Many functions in this package are parameterized with a predicate.
The predicate may be any suitable callable type
(a function, a delegate, a functor, or a lambda), or a
compile-time string. The string may consist of any legal D
expression that uses the symbol a (for unary functions) or the
symbols a and b (for binary functions). These names will NOT
interfere with other homonym symbols in user code because they are
evaluated in a different context. The default for all binary
comparison predicates is "a == b" for unordered operations and
"a < b" for ordered operations.
Example
int[] a = ...;
static bool greater(int a, int b)
{
return a > b;
}
sort!greater(a); // predicate as alias
sort!((a, b) => a > b)(a); // predicate as a lambda.
sort!"a > b"(a); // predicate as string
// (no ambiguity with array name)
sort(a); // no predicate, "a < b" is implicit
Source
std/algorithm/package.d
algorithm : (alias template) exec_route.canFind = std.algorithm.searching.canFind(alias pred = "a == b")Convenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
canFind, (alias template) exec_route.startsWith = std.algorithm.searching.startsWith(alias pred = (a, b) => a == b, Range, Needles...)(Range doesThisStart, Needles withOneOfThese) if (isInputRange!Range && (Needles.length > 1) && allSatisfy!(canTestStartsWith!(pred, Range), Needles))Checks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith;
import (package) stdstd.(module) std.arrayFunctions and types that manipulate built-in arrays and associative arrays.
This module provides all kinds of functions to create, manipulate or convert arrays:
Function Name Description
| array |
Returns a copy of the input in a newly allocated dynamic array.
|
| appender |
Returns a new Appender or RefAppender initialized with a given array.
|
| assocArray |
Returns a newly allocated associative array from a range/ranges of keys and values.
|
| byPair |
Construct a range iterating over an associative array by key/value tuples.
|
| insertInPlace |
Inserts into an existing array at a given position.
|
| join |
Concatenates a range of ranges into one array.
|
| minimallyInitializedArray |
Returns a new array of type T.
|
| replace |
Returns a new array with all occurrences of a certain subrange replaced.
|
| replaceFirst |
Returns a new array with the first occurrence of a certain subrange replaced.
|
| replaceInPlace |
Replaces all occurrences of a certain subrange and puts the result into a given array.
|
| replaceInto |
Replaces all occurrences of a certain subrange and puts the result into an output range.
|
| replaceLast |
Returns a new array with the last occurrence of a certain subrange replaced.
|
| replaceSlice |
Returns a new array with a given slice replaced.
|
| replicate |
Creates a new array out of several copies of an input array or range.
|
| sameHead |
Checks if the initial segments of two arrays refer to the same
place in memory.
|
| sameTail |
Checks if the final segments of two arrays refer to the same place
in memory.
|
| split |
Eagerly split a range or string into an array.
|
| staticArray |
Creates a new static array from given data.
|
| uninitializedArray |
Returns a new array of type T without initializing its elements.
|
Source
std/array.d
array : (alias template) exec_route.join = std.array.join(RoR, R)(RoR ror, R sep) if (isInputRange!RoR && isInputRange!(Unqual!(ElementType!RoR)) && isInputRange!R && (is(immutable(ElementType!(ElementType!RoR)) == immutable(ElementType!R)) || isSomeChar!(ElementType!(ElementType!RoR)) && isSomeChar!(ElementType!R)))Eagerly concatenates all of the ranges in ror together (with the GC)
into one array using sep as the separator if present.
join;
import (package) stdstd.(module) std.fileUtilities for manipulating files and scanning directories. Functions
in this module handle files as a unit, e.g., read or write one file
at a time. For opening files and manipulating them via handles refer
to module std.stdio.
Category Functions General exists isDir isFile isSymlink rename thisExePath Directories chdir dirEntries getcwd mkdir mkdirRecurse rmdir rmdirRecurse tempDir Files append copy read readText remove slurp write Symlinks symlink readLink Attributes attrIsDir attrIsFile attrIsSymlink getAttributes getLinkAttributes getSize setAttributes Timestamp getTimes getTimesWin setTimes timeLastModified timeLastAccessed timeStatusChanged Other DirEntry FileException PreserveAttributes SpanMode getAvailableDiskSpace
Source
std/file.d
file : (alias template) exec_route.read = std.file.read(R)(R name, size_t upTo = size_t.max) if (isSomeFiniteCharInputRange!R && !isConvertibleToString!R)Read entire contents of file name and returns it as an untyped
array. If the file size is larger than upTo, only upTo
bytes are read.
read;
import (package) stdstd.(module) std.stdioCategory Symbols File handles _popen File isFileHandle openNetwork stderr stdin stdout Reading chunks lines readf readfln readln Writing toFile write writef writefln writeln Misc KeepTerminator LockType StdioException
Standard I/O functions that extend core.stdc.stdio. core.stdc.stdio
is publically imported when importing std.stdio.
There are three layers of I/O:
The lowest layer is the operating system layer. The two main schemes are Windows and Posix.
C's stdio.h which unifies the two operating system schemes.
std.stdio, this module, unifies the various stdio.h implementations into
a high level package for D programs.
Source
std/stdio.d
stdio : (alias template) exec_route.writefln = std.stdio.writefln(alias fmt, A...)(A args) if (isSomeString!(typeof(fmt)))Equivalent to writef(fmt, args, '\n').
writefln, (alias template) exec_route.writeln = std.stdio.writeln(T...)(T args)Equivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln;
import (package) stdstd.(module) std.stringString handling functions.
Category Functions Searching column indexOf indexOfAny indexOfNeither lastIndexOf lastIndexOfAny lastIndexOfNeither Comparison isNumeric Mutation capitalize Pruning and Filling center chomp chompPrefix chop detabber detab entab entabber leftJustify outdent rightJustify strip stripLeft stripRight wrap Substitution abbrev soundex soundexer succ tr translate Miscellaneous assumeUTF fromStringz lineSplitter representation splitLines toStringz Objects of types string, wstring, and dstring are value types and cannot be mutated element-by-element. For using mutation during building strings, use char[], wchar[], or dchar[]. The xxxstring types are preferable because they don't exhibit undesired aliasing, thus making code more robust.
The following functions are publicly imported:
Module Functions Publicly imported functions std.algorithm cmp, std,algorithm,comparison count, std,algorithm,searching endsWith, std,algorithm,searching startsWith, std,algorithm,searching std.array join, std,array replace, std,array replaceInPlace, std,array split, std,array empty, std,array std.format format, std,format sformat, std,format std.uni icmp, std,uni toLower, std,uni toLowerInPlace, std,uni toUpper, std,uni toUpperInPlace, std,uni There is a rich set of functions for string handling defined in other modules. Functions related to Unicode and ASCII are found in std.uni and std.ascii, respectively. Other functions that have a wider generality than just strings can be found in std.algorithm and std.range.
Source
std/string.d
string : (alias template) exec_route.indexOf = std.string.indexOf(Range)(Range s, dchar c, CaseSensitive cs = Yes.caseSensitive) if (isInputRange!Range && isSomeChar!(ElementType!Range) && !isSomeString!Range)Searches for a character in a string or range.
indexOf, (alias template) exec_route.strip = std.string.strip(Range)(Range str) if (isSomeString!Range || isRandomAccessRange!Range && hasLength!Range && hasSlicing!Range && !isConvertibleToString!Range && isSomeChar!(ElementEncodingType!Range))Strips both leading and trailing whitespace (as defined by
isWhite) or as specified in the second argument.
strip;
enum (constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir = "/data/data/com.termux/files";
enum (constant) string exec_route.prefix = "/data/data/com.termux/files/usr"prefix = (constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir ~ "/usr";
enum (constant) string exec_route.nativeLibDir = "/data/app/~~x/com.termux-y/lib/arm64"nativeLibDir = "/data/app/~~x/com.termux-y/lib/arm64";
enum (constant) string exec_route.linker = "/system/bin/linker64"linker = "/system/bin/linker64";
enum (enum) exec_route.KindKind { (enum value) exec_route.Kind.bionicDynamic = 0bionicDynamic, (enum value) exec_route.Kind.glibcDynamic = 1glibcDynamic, (enum value) exec_route.Kind.staticElf = 2staticElf, (enum value) exec_route.Kind.shebang = 3shebang, (enum value) exec_route.Kind.other = 4other }
struct (struct) exec_route.HeaderHeader
{
(enum) exec_route.KindKind (field) exec_route.Kind exec_route.Header.kindkind;
(alias) object.string = stringstring (field) string exec_route.Header.interpreterPT_INTERP, or the shebang interpreter
interpreter; /// PT_INTERP, or the shebang interpreter
(alias) object.string = stringstring (field) string exec_route.Header.interpreterArgthe optional single shebang argument
interpreterArg; /// the optional single shebang argument
}
(struct) exec_route.HeaderHeader exec_route.Header exec_route.inspect(const(ubyte)[] bytes)inspect(const(ubyte)[] (parameter) const(ubyte)[] bytesbytes)
{
if ((parameter) const(ubyte)[] bytesbytes.(field) ulong const(ubyte)[].lengthlength >= 64 && (parameter) const(ubyte)[] bytesbytes[0 .. 4] == [0x7f, 'E', 'L', 'F'])
{
const (local variable) const(string) interpinterp = string exec_route.ptInterp(const(ubyte)[] b)The PT_INTERP of a 64-bit little-endian ELF, or null when there is none.
ptInterp((parameter) const(ubyte)[] bytesbytes);
if ((local variable) const(string) interpinterp is null)
return (struct) exec_route.HeaderHeader((enum) exec_route.KindKind.(enum value) exec_route.Kind.staticElf = 2staticElf);
return (struct) exec_route.HeaderHeader((local variable) const(string) interpinterp.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith("/system/bin/linker") ? (enum) exec_route.KindKind.(enum value) exec_route.Kind.bionicDynamic = 0bionicDynamic : (enum) exec_route.KindKind.(enum value) exec_route.Kind.glibcDynamic = 1glibcDynamic, (local variable) const(string) interpinterp);
}
if ((parameter) const(ubyte)[] bytesbytes.(field) ulong const(ubyte)[].lengthlength > 2 && (parameter) const(ubyte)[] bytesbytes[0 .. 2] == "#!")
{
auto (local variable) const(char)[] lineline = cast(const(char)[]) (parameter) const(ubyte)[] bytesbytes[2 .. $];
const (local variable) const(long) nlnl = (local variable) const(char)[] lineline.long std.string.indexOf!char(scope const(char)[] s, dchar c, std.typecons.Flag!"caseSensitive" cs = Flag.yes) pure nothrow @nogc @safeSearches for a character in a string or range.
indexOf('\n');
if ((local variable) const(long) nlnl < 0)
return (struct) exec_route.HeaderHeader((enum) exec_route.KindKind.(enum value) exec_route.Kind.other = 4other);
(local variable) const(char)[] lineline = (local variable) const(char)[] lineline[0 .. (local variable) const(long) nlnl].const(char)[] std.string.strip!(const(char)[])(const(char)[] str) pure nothrow @nogc @safeStrips both leading and trailing whitespace (as defined by
isWhite) or as specified in the second argument.
Examples
import std.uni : lineSep, paraSep;
assert(strip(" hello world ") ==
"hello world");
assert(strip("\n\t\v\rhello world\n\t\v\r") ==
"hello world");
assert(strip("hello world") ==
"hello world");
assert(strip([lineSep] ~ "hello world" ~ [lineSep]) ==
"hello world");
assert(strip([paraSep] ~ "hello world" ~ [paraSep]) ==
"hello world");
strip;
const (local variable) const(long) spacespace = (local variable) const(char)[] lineline.long std.string.indexOf!char(scope const(char)[] s, dchar c, std.typecons.Flag!"caseSensitive" cs = Flag.yes) pure nothrow @nogc @safeSearches for a character in a string or range.
indexOf(' ');
if ((local variable) const(long) spacespace < 0)
return (struct) exec_route.HeaderHeader((enum) exec_route.KindKind.(enum value) exec_route.Kind.shebang = 3shebang, (local variable) const(char)[] lineline.string object.idup!(const(char))(const(char)[] a) pure nothrow @property @safeProvide the .idup array property, which creates an immutable duplicate.
idup);
return (struct) exec_route.HeaderHeader((enum) exec_route.KindKind.(enum value) exec_route.Kind.shebang = 3shebang, (local variable) const(char)[] lineline[0 .. (local variable) const(long) spacespace].string object.idup!(const(char))(const(char)[] a) pure nothrow @property @safeProvide the .idup array property, which creates an immutable duplicate.
idup, (local variable) const(char)[] lineline[(local variable) const(long) spacespace + 1 .. $].const(char)[] std.string.strip!(const(char)[])(const(char)[] str) pure nothrow @nogc @safeStrips both leading and trailing whitespace (as defined by
isWhite) or as specified in the second argument.
Examples
import std.uni : lineSep, paraSep;
assert(strip(" hello world ") ==
"hello world");
assert(strip("\n\t\v\rhello world\n\t\v\r") ==
"hello world");
assert(strip("hello world") ==
"hello world");
assert(strip([lineSep] ~ "hello world" ~ [lineSep]) ==
"hello world");
assert(strip([paraSep] ~ "hello world" ~ [paraSep]) ==
"hello world");
strip.string object.idup!(const(char))(const(char)[] a) pure nothrow @property @safeProvide the .idup array property, which creates an immutable duplicate.
idup);
}
return (struct) exec_route.HeaderHeader((enum) exec_route.KindKind.(enum value) exec_route.Kind.other = 4other);
}
/// The PT_INTERP of a 64-bit little-endian ELF, or null when there is none.
(alias) object.string = stringstring string exec_route.ptInterp(const(ubyte)[] b)The PT_INTERP of a 64-bit little-endian ELF, or null when there is none.
ptInterp(const(ubyte)[] (parameter) const(ubyte)[] bb)
{
ulong ulong exec_route.ptInterp.at(ulong off, ulong n) pure nothrow @nogc @safeat((alias) object.size_t = ulongsize_t (parameter) ulong offoff, (alias) object.size_t = ulongsize_t (parameter) ulong nn)
{
ulong (local variable) ulong vv;
foreach ((local variable) ulong ii; 0 .. (parameter) ulong nn)
(local variable) ulong vv |= cast(ulong) (parameter) const(ubyte)[] bb[(parameter) ulong offoff + (local variable) ulong ii] << (8 * (local variable) ulong ii);
return (local variable) ulong vv;
}
const (local variable) const(ulong) tabletable = cast((alias) object.size_t = ulongsize_t) ulong exec_route.ptInterp.at(ulong off, ulong n) pure nothrow @nogc @safeat(32, 8);
const (local variable) const(ulong) stridestride = cast((alias) object.size_t = ulongsize_t) ulong exec_route.ptInterp.at(ulong off, ulong n) pure nothrow @nogc @safeat(54, 2);
foreach ((local variable) ulong ii; 0 .. ulong exec_route.ptInterp.at(ulong off, ulong n) pure nothrow @nogc @safeat(56, 2))
{
const (local variable) const(ulong) entryentry = (local variable) const(ulong) tabletable + cast((alias) object.size_t = ulongsize_t) (local variable) ulong ii * (local variable) const(ulong) stridestride;
if ((local variable) const(ulong) entryentry + 56 > (parameter) const(ubyte)[] bb.(field) ulong const(ubyte)[].lengthlength || ulong exec_route.ptInterp.at(ulong off, ulong n) pure nothrow @nogc @safeat((local variable) const(ulong) entryentry, 4) != 3) // PT_INTERP
continue;
const (local variable) const(ulong) offoff = cast((alias) object.size_t = ulongsize_t) ulong exec_route.ptInterp.at(ulong off, ulong n) pure nothrow @nogc @safeat((local variable) const(ulong) entryentry + 8, 8);
const (local variable) const(ulong) lenlen = cast((alias) object.size_t = ulongsize_t) ulong exec_route.ptInterp.at(ulong off, ulong n) pure nothrow @nogc @safeat((local variable) const(ulong) entryentry + 32, 8);
return cast((alias) object.string = stringstring) (parameter) const(ubyte)[] bb[(local variable) const(ulong) offoff .. (local variable) const(ulong) offoff + (local variable) const(ulong) lenlen - 1].immutable(ubyte)[] object.idup!(const(ubyte))(const(ubyte)[] a) pure nothrow @property @safeProvide the .idup array property, which creates an immutable duplicate.
idup;
}
return null;
}
/// termux-exec's `/bin/x` and `/usr/bin/x` → `$PREFIX/bin/x` shebang rewrite.
(alias) object.string = stringstring string exec_route.rewriteBin(string path)termux-exec's /bin/x and /usr/bin/x → $PREFIX/bin/x shebang rewrite.
rewriteBin((alias) object.string = stringstring (parameter) string pathpath)
{
foreach ((parameter) string headhead; ["/bin/", "/usr/bin/"])
if ((parameter) string pathpath.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith((local variable) string headhead))
return (constant) string exec_route.prefix = "/data/data/com.termux/files/usr"prefix ~ "/bin/" ~ (parameter) string pathpath[(local variable) string headhead.(field) ulong string.lengthlength .. $];
return (parameter) string pathpath;
}
/// The execve() termux-exec issues for `path` with `argv`.
(alias) object.string = stringstring[] string[] exec_route.rewrite(string path, exec_route.Header h, string[] argv)The execve() termux-exec issues for path with argv.
rewrite((alias) object.string = stringstring (parameter) string pathpath, (struct) exec_route.HeaderHeader (parameter) exec_route.Header hh, (alias) object.string = stringstring[] (parameter) string[] argvargv)
{
const (local variable) const(string) targettarget = (parameter) exec_route.Header hh.(field) exec_route.Kind exec_route.Header.kindkind == (enum) exec_route.KindKind.(enum value) exec_route.Kind.shebang = 3shebang ? string exec_route.rewriteBin(string path)termux-exec's /bin/x and /usr/bin/x → $PREFIX/bin/x shebang rewrite.
rewriteBin((parameter) exec_route.Header hh.(field) string exec_route.Header.interpreterPT_INTERP, or the shebang interpreter
interpreter) : (parameter) string pathpath;
if (!(local variable) const(string) targettarget.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith((constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir))
return [(local variable) const(string) targettarget] ~ (parameter) string[] argvargv; // outside the data dir: exec as-is, LD_PRELOAD stripped
(alias) object.string = stringstring[] (local variable) string[] resultresult = [(constant) string exec_route.linker = "/system/bin/linker64"linker, (parameter) string[] argvargv[0], (local variable) const(string) targettarget];
if ((parameter) exec_route.Header hh.(field) exec_route.Kind exec_route.Header.kindkind == (enum) exec_route.KindKind.(enum value) exec_route.Kind.shebang = 3shebang)
(local variable) string[] resultresult ~= ((parameter) exec_route.Header hh.(field) string exec_route.Header.interpreterArgthe optional single shebang argument
interpreterArg.(field) ulong string.lengthlength ? [(parameter) exec_route.Header hh.(field) string exec_route.Header.interpreterArgthe optional single shebang argument
interpreterArg] : []) ~ (parameter) string pathpath;
return (local variable) string[] resultresult ~ (parameter) string[] argvargv[1 .. $];
}
/// What actually runs once the kernel executes the rewritten command.
(alias) object.string = stringstring string exec_route.route(string path, exec_route.Header h)What actually runs once the kernel executes the rewritten command.
route((alias) object.string = stringstring (parameter) string pathpath, (struct) exec_route.HeaderHeader (parameter) exec_route.Header hh)
{
if ((parameter) string pathpath.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith((constant) string exec_route.nativeLibDir = "/data/app/~~x/com.termux-y/lib/arm64"nativeLibDir))
return "direct execve: APK native library (apk_data_file), allowed";
if (!(parameter) string pathpath.bool std.algorithm.searching.startsWith!("a == b", string, string)(string doesThisStart, string withThis) pure nothrow @nogc @safeChecks whether the given
input range starts with (one
of) the given needle(s) or, if no needles are given,
if its front element fulfils predicate pred.
For more information about pred see find.
startsWith((constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir) && (parameter) exec_route.Header hh.(field) exec_route.Kind exec_route.Header.kindkind != (enum) exec_route.KindKind.(enum value) exec_route.Kind.shebang = 3shebang)
return "direct execve: system file, allowed";
final switch ((parameter) exec_route.Header hh.(field) exec_route.Kind exec_route.Header.kindkind)
{
case (enum) exec_route.KindKind.(enum value) exec_route.Kind.bionicDynamic = 0bionicDynamic:
return "linker64 maps it with mmap(PROT_EXEC): works";
case (enum) exec_route.KindKind.(enum value) exec_route.Kind.shebang = 3shebang:
return "linker64 runs the rewritten interpreter: works if it is Bionic-dynamic";
case (enum) exec_route.KindKind.(enum value) exec_route.Kind.staticElf = 2staticElf:
return "linker64 cannot load it: needs a loader in the APK (PRoot) or nativeLibraryDir";
case (enum) exec_route.KindKind.(enum value) exec_route.Kind.glibcDynamic = 1glibcDynamic:
return "linker64 cannot link glibc: needs PRoot's APK loader to map " ~ (parameter) exec_route.Header hh.(field) string exec_route.Header.interpreterPT_INTERP, or the shebang interpreter
interpreter;
case (enum) exec_route.KindKind.(enum value) exec_route.Kind.other = 4other:
return "ENOEXEC";
}
}
/// A minimal 64-bit AArch64 ELF header, with a PT_INTERP when `interp` is set.
ubyte[] ubyte[] exec_route.elf(string interp)A minimal 64-bit AArch64 ELF header, with a PT_INTERP when interp is set.
elf((alias) object.string = stringstring (parameter) string interpinterp)
{
auto (local variable) ubyte[] bb = new ubyte[](64 + 56 + (parameter) string interpinterp.(field) ulong string.lengthlength + 1);
(local variable) ubyte[] bb[0 .. 4] = [0x7f, 'E', 'L', 'F'];
(local variable) ubyte[] bb[4] = 2; // ELFCLASS64
(local variable) ubyte[] bb[5] = 1; // little-endian
(local variable) ubyte[] bb[16] = (parameter) string interpinterp.(field) ulong string.lengthlength ? 3 : 2; // ET_DYN : ET_EXEC
(local variable) ubyte[] bb[18] = 183; // EM_AARCH64
(local variable) ubyte[] bb[32] = 64; // e_phoff
(local variable) ubyte[] bb[54] = 56; // e_phentsize
(local variable) ubyte[] bb[56] = (parameter) string interpinterp.(field) ulong string.lengthlength ? 1 : 0; // e_phnum
if ((parameter) string interpinterp.(field) ulong string.lengthlength)
{
(local variable) ubyte[] bb[64] = 3; // PT_INTERP
(local variable) ubyte[] bb[72] = 120; // p_offset
(local variable) ubyte[] bb[96] = cast(ubyte)((parameter) string interpinterp.(field) ulong string.lengthlength + 1); // p_filesz
(local variable) ubyte[] bb[120 .. 120 + (parameter) string interpinterp.(field) ulong string.lengthlength] = cast(const(ubyte)[]) (parameter) string interpinterp;
}
return (local variable) ubyte[] bb;
}
void void exec_route.show(string path, const(ubyte)[] bytes, string[] argv)show((alias) object.string = stringstring (parameter) string pathpath, const(ubyte)[] (parameter) const(ubyte)[] bytesbytes, (alias) object.string = stringstring[] (parameter) string[] argvargv)
{
const (local variable) const(exec_route.Header) hh = exec_route.Header exec_route.inspect(const(ubyte)[] bytes)inspect((parameter) const(ubyte)[] bytesbytes);
void std.stdio.writefln!(char, string, const(exec_route.Kind))(in char[] fmt, string __param_1, const(exec_route.Kind) __param_2) @safeEquivalent to writef(fmt, args, '\n').
writefln("%s (%s)", (parameter) string pathpath, (local variable) const(exec_route.Header) hh.(field) exec_route.Kind exec_route.Header.kindkind);
void std.stdio.writefln!(char, string)(in char[] fmt, string __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln(" execve: %s", string[] exec_route.rewrite(string path, exec_route.Header h, string[] argv)The execve() termux-exec issues for path with argv.
rewrite((parameter) string pathpath, (local variable) const(exec_route.Header) hh, (parameter) string[] argvargv).string std.array.join!(string[], string)(string[] ror, string sep) pure nothrow @safeEagerly concatenates all of the ranges in ror together (with the GC)
into one array using sep as the separator if present.
join(" "));
void std.stdio.writefln!(char, string)(in char[] fmt, string __param_1) @safeEquivalent to writef(fmt, args, '\n').
writefln(" result: %s", string exec_route.route(string path, exec_route.Header h)What actually runs once the kernel executes the rewritten command.
route((parameter) string pathpath, (local variable) const(exec_route.Header) hh));
}
void void D main(string[] args)main((alias) object.string = stringstring[] (parameter) string[] argsargs)
{
if ((parameter) string[] argsargs.(field) ulong string[].lengthlength > 1)
return void exec_route.show(string path, const(ubyte)[] bytes, string[] argv)show((parameter) string[] argsargs[1], cast(ubyte[]) void[] std.file.read!string(string name, ulong upTo = 18446744073709551615LU) @safeRead entire contents of file name and returns it as an untyped
array. If the file size is larger than upTo, only upTo
bytes are read.
Examples
import std.utf : byChar;
scope(exit)
{
assert(exists(deleteme));
remove(deleteme);
}
std.file.write(deleteme, "1234"); // deleteme is the name of a temporary file
assert(read(deleteme, 2) == "12");
assert(read(deleteme.byChar) == "1234");
assert((cast(const(ubyte)[])read(deleteme)).length == 4);
read((parameter) string[] argsargs[1]), [(parameter) string[] argsargs[1]]);
const (local variable) const(string) glibcLdglibcLd = "/nix/store/00000000000000000000000000000000-glibc-2.40/lib/ld-linux-aarch64.so.1";
void exec_route.show(string path, const(ubyte)[] bytes, string[] argv)show((constant) string exec_route.prefix = "/data/data/com.termux/files/usr"prefix ~ "/bin/ls", ubyte[] exec_route.elf(string interp)A minimal 64-bit AArch64 ELF header, with a PT_INTERP when interp is set.
elf((constant) string exec_route.linker = "/system/bin/linker64"linker), ["ls", "-l"]);
void exec_route.show(string path, const(ubyte)[] bytes, string[] argv)show((constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir ~ "/home/hello.py", cast(const(ubyte)[]) "#!/usr/bin/env python3\n", ["./hello.py"]);
void exec_route.show(string path, const(ubyte)[] bytes, string[] argv)show("/system/bin/toybox", ubyte[] exec_route.elf(string interp)A minimal 64-bit AArch64 ELF header, with a PT_INTERP when interp is set.
elf((constant) string exec_route.linker = "/system/bin/linker64"linker), ["toybox", "uname"]);
void exec_route.show(string path, const(ubyte)[] bytes, string[] argv)show((constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir ~ "/home/zig-out/bin/app", ubyte[] exec_route.elf(string interp)A minimal 64-bit AArch64 ELF header, with a PT_INTERP when interp is set.
elf(""), ["app"]);
void exec_route.show(string path, const(ubyte)[] bytes, string[] argv)show((constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir ~ "/nix/store/0-hello/bin/hello", ubyte[] exec_route.elf(string interp)A minimal 64-bit AArch64 ELF header, with a PT_INTERP when interp is set.
elf((local variable) const(string) glibcLdglibcLd), ["hello"]);
void exec_route.show(string path, const(ubyte)[] bytes, string[] argv)show((constant) string exec_route.nativeLibDir = "/data/app/~~x/com.termux-y/lib/arm64"nativeLibDir ~ "/libproot-loader.so", ubyte[] exec_route.elf(string interp)A minimal 64-bit AArch64 ELF header, with a PT_INTERP when interp is set.
elf(""), ["loader"]);
// The rewrite is self-consistent: the kernel only ever sees linker64 for
// data-dir targets, and the target path survives as linker64's argv[1].
const (local variable) const(string[]) lsls = string[] exec_route.rewrite(string path, exec_route.Header h, string[] argv)The execve() termux-exec issues for path with argv.
rewrite((constant) string exec_route.prefix = "/data/data/com.termux/files/usr"prefix ~ "/bin/ls", exec_route.Header exec_route.inspect(const(ubyte)[] bytes)inspect(ubyte[] exec_route.elf(string interp)A minimal 64-bit AArch64 ELF header, with a PT_INTERP when interp is set.
elf((constant) string exec_route.linker = "/system/bin/linker64"linker)), ["ls"]);
assert((local variable) const(string[]) lsls == [(constant) string exec_route.linker = "/system/bin/linker64"linker, "ls", (constant) string exec_route.prefix = "/data/data/com.termux/files/usr"prefix ~ "/bin/ls"]);
// termux-exec does not inspect PT_INTERP: a static target is still handed
// to linker64, which is why static binaries fail rather than run directly.
const (local variable) const(string[]) zigzig = string[] exec_route.rewrite(string path, exec_route.Header h, string[] argv)The execve() termux-exec issues for path with argv.
rewrite((constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir ~ "/x", exec_route.Header exec_route.inspect(const(ubyte)[] bytes)inspect(ubyte[] exec_route.elf(string interp)A minimal 64-bit AArch64 ELF header, with a PT_INTERP when interp is set.
elf("")), ["x"]);
assert((local variable) const(string[]) zigzig[0] == (constant) string exec_route.linker = "/system/bin/linker64"linker && (local variable) const(string[]) zigzig.bool std.algorithm.searching.canFind!().canFind!(const(string)[], string)(const(string)[] haystack, scope string needle) pure nothrow @nogc @safeConvenience function. Like find, but only returns whether or not the search
was successful.
For more information about pred see find.
Examples
const arr = [0, 1, 2, 3];
assert(canFind(arr, 2));
assert(!canFind(arr, 4));
// find one of several needles
assert(arr.canFind(3, 2));
assert(arr.canFind(3, 2) == 2); // second needle found
assert(arr.canFind([1, 3], 2) == 2);
assert(canFind(arr, [1, 2], [2, 3]));
assert(canFind(arr, [1, 2], [2, 3]) == 1);
assert(canFind(arr, [1, 7], [2, 3]));
assert(canFind(arr, [1, 7], [2, 3]) == 2);
assert(!canFind(arr, [1, 3], [2, 4]));
assert(canFind(arr, [1, 3], [2, 4]) == 0);
Example using a custom predicate.
Note that the needle appears as the second argument of the predicate.
auto words = [
"apple",
"beeswax",
"cardboard"
];
assert(!canFind(words, "bees"));
assert( canFind!((string elem, string needle) => elem.startsWith(needle))(words, "bees"));
Search for multiple items in an array of items (search for needles in an array of haystacks)
string s1 = "aaa111aaa";
string s2 = "aaa222aaa";
string s3 = "aaa333aaa";
string s4 = "aaa444aaa";
const hay = [s1, s2, s3, s4];
assert(hay.canFind!(e => e.canFind("111", "222")));
canFind((constant) string exec_route.dataDir = "/data/data/com.termux/files"dataDir ~ "/x"));
void std.stdio.writeln!string(string __param_0) @safeEquivalent to write(args, '\n'). Calling writeln without
arguments is valid and just prints a newline to the standard
output.
Example
Reads stdin and writes it to stdout with an argument
counter.
import std.stdio;
void main()
{
string line;
for (size_t count = 0; (line = readln) !is null; count++)
{
writeln("Input ", count, ": ", line);
}
}
writeln("Only the APK's native-library directory is directly executable from the app.");
}