Repository navigation
feat: a real USB port in the guest through Termux:API - #2
Merged
Merged
Conversation
The guest now gets /dev/bus/usb/BBB/DDD for libusb programs and /dev/ttyUSB0 for serial programs, backed by the real descriptor that Termux:API opened. Nothing is simulated at the transfer level; only the node name is virtual, because proot cannot call mknod. - lib/lfa-usb-node.c: freestanding preload that duplicates the inherited usbfs fd on open(), reports SYSFS_MAGIC for /sys so libudev accepts the syspath, stubs the udev hotplug monitor, and forwards DTR/RTS ioctls. Built with -nostdlib (no DT_NEEDED) for glibc, musl and bionic; an aarch64 object is bundled and lib/build-usb-shim.sh rebuilds it. - lib/usb-desc.py: raw descriptor reader plus a sysfs writer that fills the device, configuration, interface and endpoint files usbutils and libusb walk, from the real descriptors. - lib/lfa-usb-tty.py: bulk-endpoint-to-pty bridge for CDC-ACM, CP210x and CH340, with baud polling and line-state merging so esptool auto-reset reaches the board. - lfa usb attach/tty: descriptor pass, sysfs bind, LFA_USB_MAP, preload, placeholder nodes with a manifest so disable removes them again. - lfa usb flash now installs and runs esptool inside the guest and maps probe/write/verify/erase/read to the v4 or v5 spelling. - lsusb helper hands over to the distribution's usbutils when a mapped session is active. - fix: a failing advisory update check (curl timeout 28) aborted the interactive installer through set -e before the menu. - docs/USB.md rewritten; README, architecture, incompatibilities, changelog, test report and tracker updated. Host suite: PASS=784 FAIL=0.
- rename the multi-select scratch array so it cannot collide with the string variable of the same name in lfa_usb_print_changes - disable SC2046 as well as SC2086 for the pd_login_flags word list - assign and export LFA_USB_PD_FLAGS separately in the three sessions - use CDPATH='' in lib/build-usb-shim.sh
- a working `termux-usb -l` now counts as proof that Termux:API is installed: `pm list packages` cannot see other apps on Android 11+, so the old text told the user to install an app they already had - report host mode as "not advertised" instead of "no" when the feature list has no android.hardware.usb.host entry (common on Vivo/Oppo builds that still support OTG) - the lsusb/lfa-usb helpers honor an explicit LFA_USB_BRIDGE instead of falling back to /tmp/lfa-usb, which could read a stale directory - tests: hidden-pm status checks, docs and counts (787)
`lfa usb scan` returned to the prompt without a word when it could not decide which distribution to use (more than one installed and no instance remembered). It now: - reuses the instance saved by `lfa usb enable`, so plain `lfa usb scan` works with several distros installed - prints "Choose a distribution: lfa usb <command> -i NAME" with the installed list, or names the saved instance that disappeared - reports a failed helper copy (usb-desc.py / the callback) instead of returning 1 silently Tests cover the saved-but-missing instance path. Suite: 790 checks.
`lfa usb attach` wrapped the session in `lfa_android_timeout 0`, which ran `timeout 0 termux-usb ...`. GNU timeout puts the command in its own process group, so the guest shell became a background job: interactive reads either stopped (SIGTTIN) or failed with EIO, and `lfa usb attach` looked wedged even though `-- true` worked. Zero already means "no limit", so run the command directly. Adds a regression test that a zero timeout never invokes timeout while real timeouts still do.
`termux-usb` runs the -e callback inside `OUTPUT="$(...)"`, so the guest's stdout was captured by the Termux script and only printed when the session exited. A shell still got its prompt (stderr) and echoed typing, but every command looked silent; the earlier trace only appeared at the end. In the callback, when stdout is not a tty but stderr still is, point stdout at the terminal. Interactive sessions now behave normally and the guest sees a tty on stdout. Redirecting both streams (`lfa usb attach -- cmd > log 2>&1`) still captures everything. Adds a pty regression test for both branches.
proot-distro v5+ binds the host /dev over the rootfs /dev, so the placeholder created at <rootfs>/dev/bus/usb/BBB/DDD was never visible: `ls -l /dev/bus/usb/001/002` said No such file or directory, and a program that stats the path before opening it gave up early. perpare_nodes now also writes the node into a Termux-side shadow tree, and attach/tty pass it to the guest as `--bind=<shadow>/dev/bus/usb:/dev/bus/usb`. Custom binds are appended after proot-distro's default binds, so this one wins. The rootfs placeholder stays for proot-distro versions that do not bind /dev. Adds checks for the shadow node and the bind argument.
proot-distro v5 removes LD_PRELOAD from the environment it passes to
proot (`child_env.pop("LD_PRELOAD", None)`), so the session ran without
the udev stubs. libusb then failed at init with
libusb: error [linux_udev_start_event_monitor] could not initialize udev monitor
unable to initialize libusb: -99
and the real usbutils lsusb never touched the synthetic sysfs.
The generated attach/tty guest scripts now export LD_PRELOAD themselves,
after proot has started, where that filter cannot reach. The session
shell, lsusb, libusb programs and the tty bridge all inherit it.
Adds checks that both generated scripts carry the export.
The guest profile written by real-feel.sh unsets every LD_PRELOAD to hide Termux variables, so an interactive session (`bash -l`) lost the usbfs shim right after starting. libusb then failed with -99 again, even though the session script exported the preload. The profile now keeps LD_PRELOAD when LFA_USB_MAP is set (a live USB session) and still drops any other one, which would be a Termux/bionic object the guest cannot load. Adds checks for both branches.
libudev scans /sys/bus and /sys/class before it looks at /sys/bus/usb/devices. On Android /sys is not readable for an app, so udev_enumerate_scan_devices() returned EACCES and libusb reported an empty device list; lsusb exited silently even though the descriptors and the node were present. Bind a small readable /sys/bus (with just our usb/devices tree) and an empty /sys/class for the session. The synthetic subsystem links are now absolute: proot resolves a relative "../../../../bus/usb" against the host path of the bind source, where it dangles. Verified with libusb 1.0.27 against the real descriptors: one device, descriptor rc 0.
The fake proot-distro logs to $HOME/pd-calls.log, but the attach session runs with the guest user's HOME, so those lines land elsewhere. The session's own log carries the fake's argv echo; assert against it.
Termux:API can hand the device over with FD_CLOEXEC, so the descriptor was open in the session shell but closed in every child. `os.dup(7)` returned EBADF, the node open fell through to the placeholder file, and control transfers failed with ENOTTY (device qualifier, status) even though descriptors still came from sysfs. The generated attach/tty scripts now duplicate the descriptor without the flag and rewrite LFA_USB_MAP to the new number; the login profile keeps TERMUX_USB_FD in a USB session instead of stripping it with the other Termux variables. The preload also stops masking dup() failures as EBADF. Rebuilt the bundled aarch64 shim.
printf turns %% into a literal %, so the script gets ${VAR%=*}, which
strips the fd suffix exactly the same way.
bash's "{var}<&N" redirection allocates the target with F_DUPFD_CLOEXEC on
some builds, so the duplicate looked fine in the session shell (FD=10) and
was still closed in every child: lfa-usb desc got EBADF and libusb could
not open the node, while descriptors kept coming from sysfs.
Use a plain redirection onto a free high fd instead (dup2() always clears
close-on-exec), rewrite LFA_USB_MAP to the new number, and print whether a
child really inherited it so a silent EBADF cannot hide again.
The previous round added three checks but bumped 806 to 808; the real total was 809 (808 passed, 1 failed). This commit's extra check makes it 810.
The session's login shell marks inherited descriptors close-on-exec, so the device fd stayed in bash and disappeared in every child. lsusb then opened the placeholder file (`Couldn't open device`, control transfers ENOTTY) and lfa-usb desc got EBADF, while descriptors still came from sysfs - which is why the dump looked almost right. Reproduced outside the guest: `bash -l -i` keeps fd 10 and its children do not, while `bash -i` and `bash -l -c` keep it. The preload now clears FD_CLOEXEC on the mapped fds (and the tty fd) inside execve, so the first child inherits a plain descriptor and nothing re-sets the flag. Rebuilt the bundled aarch64 shim; added a regression check that sets FD_CLOEXEC and then execs /bin/sh.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this does
Gives the Linux guest a real userspace USB port instead of the old
descriptor-only
lfa usb exec:lfa usb attach→/dev/bus/usb/BBB/DDD+ a/sys/bus/usb/devicestree,so unmodified
lsusb, PyUSB, dfu-util and friends work.lfa usb tty→/dev/ttyUSB0for serial tools.lfa usb flash→esptoolinstalled and run inside the distribution,no more
nrflashdelegation.Nothing is faked at the transfer level. Termux:API opens the real usbfs
descriptor; every
ioctl/read/writeafterwards goes to the kernel.Only the node name is virtual, because proot cannot call
mknod.How it works
termux-usb -E -eputs the real fd inTERMUX_USB_FD; fds survivefork/exec, so proot's guest sees the same descriptor.
lib/usb-desc.py --sysfswrites device/configuration/interface/endpointfiles from the real descriptors; the session binds that tree over
/sys/bus/usb/devices.lib/lfa-usb-node.c(preload) duplicates the inherited fd onopen()ofthe node path, reports
SYSFS_MAGICfor/sys(libudev rejects syspathselsewhere), and replaces the udev hotplug monitor with an idle pipe.
It is
-nostdlib(noDT_NEEDED) so one build per architecture works onglibc, musl and bionic; aarch64 is bundled.
lib/lfa-usb-tty.pyclaims the bulk endpoints and exposes a pty as/dev/ttyUSB0for CDC-ACM, CP210x and CH340, forwarding baud changes andDTR/RTS so esptool's auto-reset sequence reaches the board.
Verification
PASS=784 FAIL=0(./tests/test-all.sh), including newchecks for the preload map (open/read/write, unmapped path, DTR/RTS
forwarding), the sysfs tree, the tty session and the esptool wrapper.
libusb/lsusbenumerated the synthetic tree bound over
/systhrough the preload:strings, interface class, endpoint address and packet size all came from
the real descriptors.
tests/usb-tty-plumbing.py) runs the real serialbridge against a socketpair and relays bytes through the pty both ways.
Not verified yet
Real hardware. Needs a phone with an OTG adapter:
lfa usb attach+lsusb -v,lfa usb tty, then a board flash.docs/USB.mdanddocs/TEST-REPORT.mdsay so rather than claiming it.Limits
usbhid,usb-storage, USB audio) still do not attach;this is a userspace port.
lfa usb watchpolls.lsusb -tis empty because the tree has no host-controller root hub.Also fixed
A failing advisory update check (e.g.
curlexit 28 on a timeout) abortedthe interactive installer through
set -ebefore the menu. It is nowguarded, with a stub-curl regression test (this was the intermittent L2
pty-test failure).