Make clean-clone OS rebuilds autonomous
A fresh clone can now bootstrap a complete armv7 rootfs, apply the Bananarchy overlay, regenerate boot artifacts, and produce a flashable image without local build artifacts. - Add a shared package list and Docker-based rootfs bootstrap, wired into rebuild-image.sh and chroot-shell.sh. - Add offline rebuild preflight checks and prebuilt-to-overlay artifact synchronization. - Vendor the patched EDL client and provision host flashing dependencies. - Remove the hardcoded credential from the power menu helper. - Refresh documentation and changelog for the autonomous workflow.
This commit is contained in:
1 parent
a9b72700ac
commit
0ab9367e28
31 files changed
+3809
-181
No files matched your search
@@ -6,6 +6,7 @@
|
||||
/edl
|
||||
/venv
|
||||
/.venv
|
||||
/.flash-deps
|
||||
/work
|
||||
/build
|
||||
/dist
|
||||
|
||||
@@ -25,9 +25,11 @@ It uses a pure **X11 (`Xlibre` + `sxmo-de-dwm`)** stack (no Wayland) with **Adre
|
||||
- `overlay/rootfs/`: system configuration overlay applied over the target rootfs (kept in sync with `prebuilt/`).
|
||||
- `prebuilt/`: cross-compiled `armv7` binaries and kernel modules (`sxmo-x11`, `fcitx5-t9`, `xlibre`, `kernel-6.12.1-msm8916`, `bantam`, `games`, `gsocket`).
|
||||
- `devices/` & `patches/`: device trees (`.dts`/`.dtb`), MIPI-DBI panel init sequences, and upstream patch sets.
|
||||
- `vendor/edl/`: vendored, patched EDL client library (MIT) used by `flash-edl.py`; a local `edl/` checkout or `BANANARCHY_EDL_DIR` overrides it.
|
||||
- `scripts/rootfs-packages.txt`: single source of truth for the `armv7` rootfs package set, read by both `bootstrap-rootfs.sh` and `rebuild-image.sh`.
|
||||
|
||||
## 3. Build and image generation commands
|
||||
All cross-compilation scripts run inside rootless Docker (`alpine:3.24` `armv7` sysroot) and automatically update both `prebuilt/` and `overlay/rootfs/`:
|
||||
All cross-compilation scripts run inside rootless Docker (`alpine:3.24` `armv7` sysroot) and write to `prebuilt/`; `rebuild-image.sh` mirrors those artifacts into `overlay/rootfs/`:
|
||||
- `./scripts/build-sxmo-x11.sh` — builds `libneoui.so`, `st`, `dmenu.so`, `dwm`, `dwm-plugin`, `bananarchy-verify-passcode`, `bananarchy-melody`, `sxmo_vibrate`, and all C++ `.so` plugins (`locker`, `passcode`, `xdrawer`, `dialer`, `calllog`, `callscreen`, `contacts`, `sms`, `files`, `camera`, `themes`, `modem`, `networks`, `ringtones`, `wallpapers`, `music`, `sip`, `email`, `irc`, `tox`, `smallweb`, `webarchy`, `gps`, `privacy`, `engmenu`).
|
||||
- `./scripts/build-gsocket.sh` — fetches and cross-compiles `gsocket` (`gs-netcat`, `gsocket`, `gs-sftp`, `gs-mount`, `blitz`) for `armv7`.
|
||||
- `./scripts/build-dmenu.sh` — rebuilds only `dmenu.so`, `stest`, `dmenu_path`, and `dmenu_run`.
|
||||
@@ -38,9 +40,13 @@ All cross-compilation scripts run inside rootless Docker (`alpine:3.24` `armv7`
|
||||
- `./scripts/build-bantam.sh` — fetches and cross-compiles the `bantam` AI agent.
|
||||
- `./scripts/generate-artwork.py` — regenerates wallpapers, splashes, and icons from `artwork/icon-large.png`.
|
||||
- `./scripts/version.sh [--print | target_rootfs]` — computes the date-based release version (`<year-letter><MM><DD>` with `2026 = a`) and substitutes `@BANANARCHY_VERSION@` in `etc/os-release`, `etc/issue`, and `etc/motd` (invoked automatically during overlay application and image builds).
|
||||
- `./chroot-shell.sh` — opens an `armv7` container shell to manage packages in `rootfs/` (`pkg-add`, `pkg-del`, `pkg-search`).
|
||||
- `./rebuild-image.sh <device> [--mkinitfs]` — applies `overlay/rootfs/` + `prebuilt/` into `rootfs/` and produces flashable images in `images/`.
|
||||
- `sudo ./flash-edl.sh [device]` — flashes `lk2nd` and the system image over Qualcomm USB EDL (`05c6:9008`).
|
||||
- `./chroot-shell.sh` — opens an `armv7` container shell to manage packages in `rootfs/` (`pkg-add`, `pkg-del`, `pkg-search`); bootstraps `rootfs/` first if needed.
|
||||
- `./rebuild-image.sh <device> [--mkinitfs]` — verifies the clone, syncs `prebuilt/` into `overlay/rootfs/`, bootstraps `rootfs/` from scratch when missing, applies the overlay, and produces flashable images in `images/`.
|
||||
- `./scripts/bootstrap-rootfs.sh [rootfs-dir] [device] [--force|--check]` — creates a complete `armv7` rootfs from `scripts/rootfs-packages.txt` inside rootless Docker; idempotent via `etc/bananarchy/rootfs-bootstrap.done`.
|
||||
- `./scripts/check-rebuild.sh` — offline preflight for a clean clone (syntax, package list, plugin artifacts, overlay sync, ignored local agent config, Docker, version helper).
|
||||
- `./scripts/sync-prebuilt-overlay.sh [--check]` — mirrors `prebuilt/` artifacts into `overlay/rootfs/`; `--check` only reports drift.
|
||||
- `./scripts/bootstrap-flash-deps.sh` — installs `pyusb` and `pyserial` into the gitignored `.flash-deps/` directory for `flash-edl.py`.
|
||||
- `sudo ./flash-edl.sh [device]` — flashes `lk2nd` and the system image over Qualcomm USB EDL (`05c6:9008`), using the vendored `vendor/edl/` library and auto-installed host dependencies.
|
||||
|
||||
## 4. Coding and architecture conventions
|
||||
- **Indentation**: always use 2-space indentation in C, C++, Python, Yabasic, and shell scripts (tabs only in Makefiles and TSV files).
|
||||
@@ -48,4 +54,6 @@ All cross-compilation scripts run inside rootless Docker (`alpine:3.24` `armv7`
|
||||
- **Unified theming**: never hardcode UI colors or font sizes in `dwm`, `dmenu`, `st`, or any DWM plugin. Read colors and proportional font sizes from `PluginTheme` (`src/neoui/neoui.h` / `src/dwm-plugins/theme.h`) / `.Xresources` (`theme.*`), and handle `RELOAD_THEME` on the plugin FIFO.
|
||||
- **Zero-lag plugin model**: phone UI apps must run as preloaded resident daemons (`--preload`) guarded by `/tmp/dwm_plugin_<name>.lock`, sleeping at 0% CPU on `poll()` over `ConnectionNumber(dpy)` and `/tmp/dwm_plugin_<name>.fifo`, and rendering into an offscreen `Pixmap` (`240x296` at `X=0, Y=24`) copied with `XCopyArea` to prevent flicker.
|
||||
- **Documentation**: keep `README.md`, `MANUAL.md`, `SDK.md`, and `CHANGELOG.md` synchronized with any new user-facing features, SDK functions, or keybindings, and do not leave third-party `.md` files inside `src/` or `edl/`.
|
||||
- **Artifact sources**: `prebuilt/` is the single source of truth for compiled artifacts and `scripts/rootfs-packages.txt` for the `armv7` package set. Never edit `overlay/rootfs/` copies of binaries by hand; run `./scripts/sync-prebuilt-overlay.sh` after changing `prebuilt/`.
|
||||
- **Local agent config**: `.bantam.cfg` is a local, gitignored credential file. Never read, edit, commit, or unignore it; `scripts/check-rebuild.sh` verifies that its ignore rule stays in place.
|
||||
- **Sentence case**: always use sentence case in subheadings and list items across all documentation files (`README.md`, `MANUAL.md`, `SDK.md`, `CHANGELOG.md`, `AGENTS.md`).
|
||||
@@ -9,6 +9,20 @@ Release versions follow the `<year-letter><MM><DD>` format (where `2026` is `a`,
|
||||
|
||||
---
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Autonomous rebuild from a clean clone
|
||||
- Added `scripts/rootfs-packages.txt` as the single source of truth for the `armv7` package set, shared by `scripts/bootstrap-rootfs.sh` and `rebuild-image.sh`.
|
||||
- Added `scripts/bootstrap-rootfs.sh` and `scripts/bootstrap-rootfs-container.sh` to create a complete `armv7` rootfs from scratch inside rootless Docker, including system accounts, OpenRC runlevels, base configuration, the overlay, prebuilt kernel modules, and an idempotency marker at `etc/bananarchy/rootfs-bootstrap.done`.
|
||||
- Wired the bootstrap into `rebuild-image.sh` and `chroot-shell.sh`, so a fresh clone builds a flashable image with a single command and no manual `rootfs/` preparation.
|
||||
- Added `scripts/check-rebuild.sh` as an offline preflight (syntax, package list, plugin artifacts, overlay sync, ignored local agent config, Docker, version helper) and `scripts/sync-prebuilt-overlay.sh` to keep `overlay/rootfs/` mirrored from the authoritative `prebuilt/` artifacts.
|
||||
- Vendored the patched EDL client library under `vendor/edl/` (MIT) and made `flash-edl.py` fall back to it, so flashing works from a clean clone without a manual `edl/` checkout; `flash-edl.sh` now installs `pyusb` and `pyserial` into the gitignored `.flash-deps/` directory automatically.
|
||||
- Removed the hardcoded default password from `overlay/rootfs/usr/bin/sxmo_power.sh`; the polkit fallback now delegates authorization to the session's own agent, and the default credentials are configurable via `BANANARCHY_USER_PASSWORD`.
|
||||
- Fixed `mkinitfs` prerequisites for rootfs builds without pmbootstrap: `/usr/sbin/losetup`, `/usr/share/deviceinfo/deviceinfo`, and `/dev/null` are now created by the bootstrap and overlay.
|
||||
- Reconciled the DWM plugin count (26) across `README.md` and corrected the `doas` wording in `MANUAL.md`; documented the clean-clone rebuild and flashing workflow in `README.md`, `MANUAL.md`, and `AGENTS.md`.
|
||||
|
||||
---
|
||||
|
||||
## Build `a1105` — codename `vendetta` (2026-11-05)
|
||||
|
||||
### New features and improvements
|
||||
|
||||
@@ -422,7 +422,8 @@ Three native X11 games (`/usr/bin/snake`, `/usr/bin/tetris`, and `/usr/bin/scoun
|
||||
## 4. Default credentials, USB SSH, and Bantam AI agent
|
||||
|
||||
- **Username**: `user`
|
||||
- **Password**: `147147` (`doas` and `sudo` enabled, with passwordless `doas` configured for `wheel` in `/etc/doas.d/50-sxmo.conf`)
|
||||
- **Password**: `147147` (`doas` and `sudo` enabled; `/etc/doas.d/50-sxmo.conf` requires a password for general `wheel` use and grants targeted passwordless rules for system actions)
|
||||
- **Changing the default password**: set `BANANARCHY_USER_PASSWORD` before bootstrapping a rootfs, or change it on the device with `passwd` or the passcode configurator. The power menu no longer contains any hardcoded credential.
|
||||
- **USB networking SSH**:
|
||||
```bash
|
||||
ssh user@172.16.42.1
|
||||
@@ -575,3 +576,33 @@ The **Xlibre** display server (`modesetting_drv.so`) uses **Glamor + DRI3 + GLX
|
||||
bananarchy-gps watch 2 # continuously poll GPS fix and satellite telemetry every 2s
|
||||
bananarchy-gps disable # stop standalone GNSS engine to save power
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Rebuilding the OS from a clean clone
|
||||
|
||||
A fresh `git clone` is enough to produce a flashable image. Docker, Python 3, and network access are the only host requirements; no pre-existing `rootfs/`, `images/`, or EDL checkout is needed.
|
||||
|
||||
```bash
|
||||
./scripts/check-rebuild.sh # optional offline preflight
|
||||
./rebuild-image.sh nokia-argon # builds images/bananarchy-nokia-argon.img
|
||||
```
|
||||
|
||||
`rebuild-image.sh` runs the following steps automatically:
|
||||
|
||||
1. Verifies shell and Python syntax, the `armv7` package list, plugin artifacts, overlay sync, and the ignored local agent config (`scripts/check-rebuild.sh`).
|
||||
2. Mirrors `prebuilt/` into `overlay/rootfs/` (`scripts/sync-prebuilt-overlay.sh`).
|
||||
3. Creates a complete `armv7` rootfs from `scripts/rootfs-packages.txt` when `rootfs/` is missing or stale (`scripts/bootstrap-rootfs.sh`), including system accounts, OpenRC runlevels, base configuration, the overlay, and prebuilt kernel modules.
|
||||
4. Applies the overlay, regenerates the initramfs with `mkinitfs`, and assembles the partitioned MBR image in `images/`.
|
||||
|
||||
Useful overrides and helpers:
|
||||
|
||||
```bash
|
||||
ROOTFS_DIR=/path/to/rootfs IMAGES_DIR=/path/to/images ./rebuild-image.sh nokia-sparkler
|
||||
BANANARCHY_USER_PASSWORD=1234 ./scripts/bootstrap-rootfs.sh --force
|
||||
./scripts/bootstrap-rootfs.sh --check # report whether bootstrapping is needed
|
||||
./chroot-shell.sh # bootstraps rootfs/ before opening a shell
|
||||
sudo ./flash-edl.sh nokia-argon # uses vendor/edl/ and auto-installs host deps
|
||||
```
|
||||
|
||||
The bootstrap is idempotent: an up-to-date rootfs is left untouched. `prebuilt/` is the single source of truth for compiled artifacts, and `scripts/rootfs-packages.txt` is the single source of truth for the package set. The patched EDL client library is vendored under `vendor/edl/` (MIT), so flashing works from a clean clone without a manual download; `flash-edl.sh` installs `pyusb` and `pyserial` into the gitignored `.flash-deps/` directory when needed.
|
||||
@@ -21,7 +21,7 @@
|
||||
- **Pure X11 graphical stack with GPU acceleration**: cross-compiled **Xlibre** (`X11Libre/xserver`) display server offloading 2D/3D screen rendering to the **Adreno 304 GPU** via **Glamor, DRI3, GLX, and Mesa Freedreno (`FD304`, OpenGL 3.1 / OpenGL ES 3.0)** over `panel-mipi-dbi` KMSRO, paired with a customized **Sxmo (`sxmo-de-dwm`)** window manager (`240x320` vertical stack layout, native `ParentRelative` desktop clock and softkey bar without Conky overhead, `< 2 ms` slider/key wake latency, and zero Wayland overhead).
|
||||
|
||||
### Keypad-first user experience and native DWM plugins
|
||||
Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs a suite of 25 preloaded C/C++ plugins inside DWM that sleep at 0% CPU and open in `< 2 ms`:
|
||||
Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs a suite of 26 preloaded C/C++ plugins inside DWM that sleep at 0% CPU and open in `< 2 ms`:
|
||||
- **System and context menus (`dmenu`)**: instant full-screen 10-line vertical menus with live T9 filtering, built-in submenus, and hardware toggles.
|
||||
- **Passcode-based fullscreen phone locker (`xlocker`), GUI passcode configurator (`xpasscode`), and Duress Mode**: zero-bypass `240x320` fullscreen numeric passcode lock screen verified against the current user's system shadow password (`/usr/bin/bananarchy-verify-passcode`), blocking all desktop, menu, drawer, terminal, and power actions while locked and automatically handing off the display only during incoming calls. Includes a NeoUI **Passcode Configurator (`xpasscode` / `passcode.so`)** in `Config -> Passcode` to change the real Linux user password (`user`, any numeric length `>= 4` digits) and configure a separate **Duress Passcode**. Entering the duress passcode on the lock screen switches the session into **Duress Mode** (`/tmp/duress_home` blank profile with no contacts, SMS, call logs, or personal files, microSD unmounted and disabled, `xfiles` clamped to the profile directory, Passcode/Privacy Center/Tox/IRC/SIP/`st` terminal hidden and blocked, `*#06#` displaying a session-persistent random Luhn-valid IMEI derived from the device's TAC, and theme/wallpaper locked to `NordFrost.xth` and `nordic-peaks.png` until poweroff or reboot).
|
||||
- **Privacy Center (`xprivacy` / `privacy` / `privacy.so`) and `/usr/bin/bananarchy-privacy-ctl`**: 5-tab NeoUI privacy and tunneling control center (`1:Tor`, `2:Warp`, `3:OVPN`, `4:GS`, `5:WG`, hidden and disabled in Duress Mode) with zero background CPU or battery consumption when services are turned off:
|
||||
@@ -89,7 +89,7 @@ bananarchy/
|
||||
│ ├── sxmo-dwm/ # Patched sxmo-dwm (240x320 bstack, Pango bar, softkey bar, and plugin API)
|
||||
│ ├── dwm-plugins/ # DWM plugins (locker, passcode, dialer, calllog, callscreen, contacts, sms,
|
||||
│ │ # files, camera, themes, modem, networks, ringtones, wallpapers, music, sip,
|
||||
│ │ # email, irc, tox, smallweb, webarchy, gps, privacy) and runner
|
||||
│ │ # email, irc, tox, smallweb, webarchy, gps, privacy, engmenu) and runner
|
||||
│ ├── xdrawer/ # XDrawer global phone controls DWM plugin (xdrawer.so / xdrawer)
|
||||
│ ├── sxmo-dmenu/ # Resident DWM menu plugin (dmenu.so) and client (dmenu / xdmenu)
|
||||
│ ├── sxmo-st/ # Patched sxmo-st terminal with HarfBuzz Fira Code ligatures and XIM
|
||||
@@ -100,14 +100,40 @@ bananarchy/
|
||||
│ ├── leds-msm8905-torch/ # Kernel driver for SY7807 torch LED, WCD codec init, and PON shutdown
|
||||
│ └── msm8905-cam/ # Kernel V4L2 driver for GC2395/GC2385/GC2365 2MP rear camera (/dev/video0)
|
||||
├── overlay/rootfs/ # System configuration overlay applied over the target rootfs
|
||||
├── prebuilt/ # Pre-compiled armv7 binaries and kernel modules
|
||||
└── scripts/ # Cross-compilation, artwork generation, version, and overlay scripts
|
||||
├── prebuilt/ # Pre-compiled armv7 binaries and kernel modules (single source of truth)
|
||||
├── vendor/edl/ # Vendored, patched EDL client library (MIT) used by flash-edl.py
|
||||
└── scripts/ # Cross-compilation, bootstrap, verification, version, and overlay scripts
|
||||
# rootfs-packages.txt: single source of truth for the armv7 package set
|
||||
# bootstrap-rootfs.sh: builds a complete rootfs from a clean clone
|
||||
# check-rebuild.sh: offline rebuild preflight
|
||||
# sync-prebuilt-overlay.sh: mirrors prebuilt/ into overlay/rootfs/
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Build and customization workflow
|
||||
|
||||
### 0. Rebuild from a clean clone (autonomous)
|
||||
|
||||
A fresh `git clone` contains everything required to produce a flashable image. Docker, Python 3, and network access are the only host requirements:
|
||||
|
||||
```bash
|
||||
./scripts/check-rebuild.sh # optional offline preflight
|
||||
./rebuild-image.sh nokia-argon # bootstraps rootfs/, then builds images/
|
||||
```
|
||||
|
||||
`rebuild-image.sh` performs the whole pipeline without manual preparation:
|
||||
|
||||
1. Runs `scripts/check-rebuild.sh` to validate shell and Python syntax, the package list, plugin artifacts, overlay sync, and the ignored local agent config.
|
||||
2. Mirrors `prebuilt/` into `overlay/rootfs/` with `scripts/sync-prebuilt-overlay.sh` so the tracked overlay snapshot never drifts.
|
||||
3. Creates a complete `armv7` rootfs from `scripts/rootfs-packages.txt` when `rootfs/` is missing or stale, using `scripts/bootstrap-rootfs.sh` (rootless Docker, Alpine `edge` and postmarketOS `v26.06` repositories, and the trusted keys in `keys/`).
|
||||
4. Applies the overlay and prebuilt artifacts, regenerates the initramfs, and writes `images/bananarchy-<device>.img`.
|
||||
|
||||
The bootstrap is idempotent and safe to re-run; `./chroot-shell.sh` uses it too. Override `ROOTFS_DIR`, `IMAGES_DIR`, or `BANANARCHY_USER_PASSWORD` to change the defaults. Run `./scripts/bootstrap-rootfs.sh --check` to report whether a rootfs needs bootstrapping, or `--force` to rebuild its configuration.
|
||||
|
||||
All cross-compilation scripts write to `prebuilt/`, which is the single source of truth for compiled artifacts. After running any `build-*.sh` script, `rebuild-image.sh` automatically refreshes the matching files in `overlay/rootfs/`.
|
||||
|
||||
### 1. Regenerate artwork assets
|
||||
### 1. Regenerate artwork assets
|
||||
Whenever `artwork/icon-large.png` is updated, regenerate all icons, `240x320` wallpapers, and animated boot splashes:
|
||||
```bash
|
||||
@@ -120,7 +146,7 @@ All components are pre-compiled in `prebuilt/` and `overlay/rootfs/`, and can be
|
||||
# Rebuild cross-compiled Xlibre (X11Libre/xserver) + Glamor/GLX + libinput/fbdev DDX drivers
|
||||
./scripts/build-xlibre.sh
|
||||
|
||||
# Rebuild patched sxmo-st, sxmo-dmenu, sxmo-dwm, and all 22 C++ DWM plugins
|
||||
# Rebuild patched sxmo-st, sxmo-dmenu, sxmo-dwm, and all 26 DWM plugins
|
||||
./scripts/build-sxmo-x11.sh
|
||||
|
||||
# Rebuild standalone X11 games and emulators (snake, tetris, scoundrel, gambatte, remedy)
|
||||
@@ -165,6 +191,9 @@ Output images are written to `images/`:
|
||||
```bash
|
||||
sudo ./flash-edl.sh nokia-argon
|
||||
```
|
||||
|
||||
The patched EDL client library is vendored under `vendor/edl/` (MIT), so a clean clone flashes without any manual download. `flash-edl.sh` also installs `pyusb` and `pyserial` into the gitignored `.flash-deps/` directory when the host lacks them; set `BANANARCHY_EDL_DIR` to use a different library checkout.
|
||||
|
||||
See [MANUAL.md](MANUAL.md) for complete EDL, Fastboot, and microSD installation instructions, keypad navigation shortcuts, and the multi-mode T9 reference.
|
||||
|
||||
## Credits
|
||||
|
||||
+8
-3
@@ -4,12 +4,14 @@ set -eu
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
if [ -n "${ROOTFS_DIR:-}" ]; then
|
||||
ROOTFS_HOST="$(realpath "$ROOTFS_DIR")"
|
||||
ROOTFS_PATH="$ROOTFS_DIR"
|
||||
elif [ -d "$SCRIPT_DIR/rootfs-sxmo" ]; then
|
||||
ROOTFS_HOST="$(realpath "$SCRIPT_DIR/rootfs-sxmo")"
|
||||
ROOTFS_PATH="$SCRIPT_DIR/rootfs-sxmo"
|
||||
else
|
||||
ROOTFS_HOST="$(realpath "$SCRIPT_DIR/rootfs")"
|
||||
ROOTFS_PATH="$SCRIPT_DIR/rootfs"
|
||||
fi
|
||||
mkdir -p "$ROOTFS_PATH"
|
||||
ROOTFS_HOST="$(realpath "$ROOTFS_PATH")"
|
||||
BANANARCHY_DIR="$SCRIPT_DIR"
|
||||
|
||||
if [ "${1:-}" = "sxmo" ]; then
|
||||
@@ -20,6 +22,9 @@ if [ "$#" -eq 0 ]; then
|
||||
set -- /bin/sh
|
||||
fi
|
||||
|
||||
# Ensure the armv7 rootfs exists and is complete before opening a shell.
|
||||
"$BANANARCHY_DIR/scripts/bootstrap-rootfs.sh" "$ROOTFS_HOST"
|
||||
|
||||
exec docker run --rm -it --network=host \
|
||||
-e HOST_UID="$(id -u)" \
|
||||
-e HOST_GID="$(id -g)" \
|
||||
|
||||
+14
-3
@@ -11,11 +11,22 @@ import usb.core
|
||||
import usb.util
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, os.path.join(BASE_DIR, "edl"))
|
||||
DEFAULT_USER_PASSWORD = os.environ.get("BANANARCHY_USER_PASSWORD", "147147")
|
||||
|
||||
# The EDL client library is vendored under vendor/edl so a clean clone can
|
||||
# flash without any manual download. A local edl/ checkout takes precedence
|
||||
# for development, and BANANARCHY_EDL_DIR overrides both.
|
||||
EDL_DIR = os.environ.get("BANANARCHY_EDL_DIR", "")
|
||||
if not EDL_DIR:
|
||||
local_edl = os.path.join(BASE_DIR, "edl")
|
||||
vendor_edl = os.path.join(BASE_DIR, "vendor", "edl")
|
||||
EDL_DIR = local_edl if os.path.isfile(os.path.join(local_edl, "Library", "usb.py")) else vendor_edl
|
||||
if not os.path.isfile(os.path.join(EDL_DIR, "Library", "usb.py")):
|
||||
sys.exit("Error: the EDL client library is missing from " + EDL_DIR)
|
||||
sys.path.insert(0, EDL_DIR)
|
||||
|
||||
from Library.usb import usb_class
|
||||
from Library.gpt import gpt
|
||||
from Library.sahara import qualcomm_sahara
|
||||
from Library.firehose import qualcomm_firehose, xmlparser
|
||||
|
||||
|
||||
@@ -569,7 +580,7 @@ def main():
|
||||
print(" BANANARCHY EDL FLASHING COMPLETED SUCCESSFULLY")
|
||||
print("============================================================")
|
||||
print(" The phone will now boot via lk2nd into Bananarchy Linux (Sxmo).")
|
||||
print(" Default login: user / 147147 | USB SSH: ssh user@172.16.42.1")
|
||||
print(" Default login: user / " + DEFAULT_USER_PASSWORD + " | USB SSH: ssh user@172.16.42.1")
|
||||
print("============================================================")
|
||||
|
||||
|
||||
|
||||
+16
-1
@@ -4,6 +4,21 @@ set -eu
|
||||
BASE_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
PYTHON_BIN="${PYTHON_BIN:-python3}"
|
||||
FLASHER_PY="$BASE_DIR/flash-edl.py"
|
||||
FLASH_DEPS="$BASE_DIR/.flash-deps"
|
||||
|
||||
if [ -d "$FLASH_DEPS" ]; then
|
||||
PYTHONPATH="$FLASH_DEPS${PYTHONPATH:+:$PYTHONPATH}"
|
||||
export PYTHONPATH
|
||||
fi
|
||||
|
||||
# flash-edl.py imports pyusb at startup, so ensure it is available before
|
||||
# even handling --help or elevating privileges.
|
||||
if ! "$PYTHON_BIN" -c 'import usb.core' >/dev/null 2>&1; then
|
||||
echo "[*] Preparing host flashing dependencies..."
|
||||
"$BASE_DIR/scripts/bootstrap-flash-deps.sh"
|
||||
PYTHONPATH="$FLASH_DEPS${PYTHONPATH:+:$PYTHONPATH}"
|
||||
export PYTHONPATH
|
||||
fi
|
||||
|
||||
for arg in "$@"; do
|
||||
if [ "$arg" = "-h" ] || [ "$arg" = "--help" ]; then
|
||||
@@ -14,7 +29,7 @@ done
|
||||
if [ "$(id -u)" -ne 0 ]; then
|
||||
if command -v sudo >/dev/null 2>&1; then
|
||||
echo "[*] Elevating privileges via sudo for raw USB EDL (05c6:9008) access..."
|
||||
exec sudo "$0" "$@"
|
||||
exec sudo env PYTHONPATH="${PYTHONPATH:-}" "$0" "$@"
|
||||
else
|
||||
echo "[!] Warning: Not running as root and 'sudo' not found. Continuing..."
|
||||
fi
|
||||
|
||||
@@ -13,64 +13,16 @@ usage() {
|
||||
|
||||
run_polkit_login1() {
|
||||
method="$1"
|
||||
python3 - "$method" <<'PYEOF' >/dev/null 2>&1
|
||||
import os, pty, select, sys, time
|
||||
method = sys.argv[1]
|
||||
ppid = os.getpid()
|
||||
if method == "Reboot":
|
||||
acts = [
|
||||
"org.freedesktop.login1.reboot",
|
||||
"org.freedesktop.login1.reboot-multiple-sessions",
|
||||
"org.freedesktop.login1.reboot-ignore-inhibit",
|
||||
]
|
||||
else:
|
||||
acts = [
|
||||
"org.freedesktop.login1.power-off",
|
||||
"org.freedesktop.login1.power-off-multiple-sessions",
|
||||
"org.freedesktop.login1.power-off-ignore-inhibit",
|
||||
]
|
||||
for act in acts:
|
||||
cmd = (
|
||||
f"pkttyagent --process {ppid} & AG=$!; sleep 0.25; "
|
||||
f"pkcheck --action-id {act} --process {ppid} -u >/dev/null 2>&1; "
|
||||
f"RC=$?; kill $AG 2>/dev/null || true; exit $RC"
|
||||
)
|
||||
pid, fd = pty.fork()
|
||||
if pid == 0:
|
||||
os.execlp("sh", "sh", "-c", cmd)
|
||||
t0 = time.time()
|
||||
buf = b""
|
||||
while time.time() - t0 < 5.0:
|
||||
r, _, _ = select.select([fd], [], [], 0.2)
|
||||
if r:
|
||||
try:
|
||||
d = os.read(fd, 1024)
|
||||
if not d:
|
||||
break
|
||||
buf += d
|
||||
if b"assword:" in buf or b"password:" in buf.lower():
|
||||
buf = b""
|
||||
os.write(fd, b"147147\n")
|
||||
except OSError:
|
||||
break
|
||||
try:
|
||||
os.close(fd)
|
||||
except OSError:
|
||||
pass
|
||||
os.waitpid(pid, 0)
|
||||
os.execlp(
|
||||
"busctl",
|
||||
"busctl",
|
||||
"call",
|
||||
"--allow-interactive-authorization=true",
|
||||
"org.freedesktop.login1",
|
||||
"/org/freedesktop/login1",
|
||||
"org.freedesktop.login1.Manager",
|
||||
method,
|
||||
"b",
|
||||
"true",
|
||||
)
|
||||
PYEOF
|
||||
# Let the session's own polkit agent handle authorization. Never feed a
|
||||
# hardcoded password: the doas/sudo rules above cover unattended power
|
||||
# actions, and a real agent prompt is used when interactive auth is needed.
|
||||
busctl call \
|
||||
--allow-interactive-authorization=true \
|
||||
org.freedesktop.login1 \
|
||||
/org/freedesktop/login1 \
|
||||
org.freedesktop.login1.Manager \
|
||||
"$method" \
|
||||
b true >/dev/null 2>&1
|
||||
}
|
||||
|
||||
run_priv_power() {
|
||||
|
||||
+15
-106
@@ -6,12 +6,14 @@ set -eu
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
|
||||
if [ -n "${ROOTFS_DIR:-}" ]; then
|
||||
ROOTFS_HOST="$(realpath "$ROOTFS_DIR")"
|
||||
ROOTFS_PATH="$ROOTFS_DIR"
|
||||
elif [ -d "$SCRIPT_DIR/rootfs-sxmo" ]; then
|
||||
ROOTFS_HOST="$(realpath "$SCRIPT_DIR/rootfs-sxmo")"
|
||||
ROOTFS_PATH="$SCRIPT_DIR/rootfs-sxmo"
|
||||
else
|
||||
ROOTFS_HOST="$(realpath "$SCRIPT_DIR/rootfs")"
|
||||
ROOTFS_PATH="$SCRIPT_DIR/rootfs"
|
||||
fi
|
||||
mkdir -p "$ROOTFS_PATH"
|
||||
ROOTFS_HOST="$(realpath "$ROOTFS_PATH")"
|
||||
|
||||
mkdir -p "${IMAGES_DIR:-$SCRIPT_DIR/images}"
|
||||
IMAGES_HOST="$(realpath "${IMAGES_DIR:-$SCRIPT_DIR/images}")"
|
||||
@@ -103,6 +105,15 @@ ensure_prebuilt_artifacts() {
|
||||
|
||||
ensure_prebuilt_artifacts
|
||||
|
||||
# prebuilt/ is the single source of truth for compiled artifacts.
|
||||
"$BANANARCHY_DIR/scripts/sync-prebuilt-overlay.sh"
|
||||
|
||||
# Verify that this clone can rebuild before touching any rootfs data.
|
||||
"$BANANARCHY_DIR/scripts/check-rebuild.sh"
|
||||
|
||||
# Create a complete armv7 rootfs from scratch when it is missing or stale.
|
||||
"$BANANARCHY_DIR/scripts/bootstrap-rootfs.sh" "$ROOTFS_HOST" "$TARGET_DEVICE"
|
||||
|
||||
docker run --rm -v "$ROOTFS_HOST:/rootfs" alpine:3.24 chown -R "$(id -u):$(id -g)" /rootfs
|
||||
|
||||
if [ -x "$BANANARCHY_DIR/scripts/apply-bananarchy-overlay.sh" ]; then
|
||||
@@ -161,109 +172,7 @@ EOF
|
||||
mkdir -p "$ROOTFS/etc/apk/keys"
|
||||
cp /bananarchy/keys/* "$ROOTFS/etc/apk/keys/" 2>/dev/null || true
|
||||
|
||||
REQUIRED_PKGS="
|
||||
adwaita-icon-theme
|
||||
alpine-base
|
||||
alsa-utils
|
||||
bash
|
||||
bc
|
||||
brightnessctl
|
||||
clickclack
|
||||
coreutils
|
||||
doas
|
||||
ed
|
||||
evtest
|
||||
fcitx5
|
||||
fcitx5-gtk3
|
||||
font-droid
|
||||
font-droid-nonlatin
|
||||
font-fira-code
|
||||
font-noto
|
||||
font-noto-emoji
|
||||
font-twemoji
|
||||
frotz
|
||||
g++
|
||||
gcc
|
||||
git
|
||||
gst-libav
|
||||
gst-plugins-bad
|
||||
gst-plugins-good
|
||||
harfbuzz
|
||||
htop
|
||||
i2c-tools
|
||||
imv
|
||||
ip6tables
|
||||
iproute2
|
||||
iptables
|
||||
janet
|
||||
janet-dev
|
||||
jpm
|
||||
lang
|
||||
less
|
||||
libwpe
|
||||
libwpebackend-fdo
|
||||
libxcvt
|
||||
libxft
|
||||
libxinerama
|
||||
libxtst
|
||||
linux-postmarketos-qcom-msm8916
|
||||
lua5.4
|
||||
lua5.4-dev
|
||||
lua5.5
|
||||
lua5.5-dev
|
||||
make
|
||||
mandoc
|
||||
mesa-demos
|
||||
mesa-utils
|
||||
modemmanager
|
||||
musl-dev
|
||||
nano
|
||||
openssh
|
||||
openssh-server-pam
|
||||
openvpn
|
||||
perl
|
||||
perl-io-socket-ssl
|
||||
postmarketos-artwork-wallpapers
|
||||
postmarketos-base
|
||||
postmarketos-base-nofde
|
||||
postmarketos-base-ui
|
||||
postmarketos-base-ui-audio-backend-pipewire
|
||||
postmarketos-base-ui-wifi-wpa_supplicant
|
||||
postmarketos-ui-sxmo-de-dwm
|
||||
postmarketos-ui-sxmo-de-dwm-openrc
|
||||
qmi-utils
|
||||
rlwrap
|
||||
scrot
|
||||
setxkbmap
|
||||
sfeed
|
||||
soc-qcom-msm8909
|
||||
soc-qcom-msm8909-modem
|
||||
soc-qcom-msm8909-modem-openrc
|
||||
soc-qcom-msm8916
|
||||
soc-qcom-msm8916-rproc
|
||||
soc-qcom-msm8916-rproc-openrc
|
||||
soc-qcom-msm8916-ucm
|
||||
sqlite
|
||||
sqlite-tcl
|
||||
sudo-rs
|
||||
tcl
|
||||
tcl-lib
|
||||
tcl-tls
|
||||
tor
|
||||
ttyescape
|
||||
v4l-utils
|
||||
w3m
|
||||
webkit2gtk-4.1
|
||||
wireguard-tools
|
||||
wireguard-tools-wg
|
||||
wireguard-tools-wg-quick
|
||||
xf86-input-libinput
|
||||
xf86-video-fbdev
|
||||
yabasic
|
||||
yabasic-doc
|
||||
zram-init
|
||||
zram-init-openrc
|
||||
"
|
||||
REQUIRED_PKGS="$(grep -v "^[[:space:]]*#" /bananarchy/scripts/rootfs-packages.txt | grep -v "^[[:space:]]*$" | tr "\n" " ")"
|
||||
|
||||
MISSING_PKGS=""
|
||||
INSTALLED_DB="$ROOTFS/lib/apk/db/installed"
|
||||
|
||||
@@ -307,6 +307,12 @@ ln -sf /usr/share/xsessions/sxmo.desktop "$TARGET_ROOTFS/var/lib/tinydm/default-
|
||||
echo "[4/4] Installing deviceinfo for $DEVICE ($DTB_FILE)..."
|
||||
if [ -f "$BASE_DIR/devices/$DEVICE_DIR/$DEVICEINFO_FILE" ]; then
|
||||
cp -a "$BASE_DIR/devices/$DEVICE_DIR/$DEVICEINFO_FILE" "$TARGET_ROOTFS/etc/deviceinfo"
|
||||
# mkinitfs sources /usr/share/deviceinfo/deviceinfo; pmbootstrap normally
|
||||
# creates this link, so recreate it for rootfs builds done without it.
|
||||
mkdir -p "$TARGET_ROOTFS/usr/share/deviceinfo"
|
||||
cp -a "$BASE_DIR/devices/$DEVICE_DIR/$DEVICEINFO_FILE" \
|
||||
"$TARGET_ROOTFS/usr/share/deviceinfo/device-$DEVICE"
|
||||
ln -sf "device-$DEVICE" "$TARGET_ROOTFS/usr/share/deviceinfo/deviceinfo"
|
||||
fi
|
||||
if [ -f "$TARGET_ROOTFS/boot/extlinux/extlinux.conf" ]; then
|
||||
sed -i "s|^[[:space:]]*fdt .*|\tfdt /$DTB_FILE|" "$TARGET_ROOTFS/boot/extlinux/extlinux.conf"
|
||||
|
||||
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
# Install the host Python dependencies needed by flash-edl.py into a
|
||||
# repository-local directory, so a clean clone can flash autonomously.
|
||||
set -eu
|
||||
|
||||
BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PYTHON_BIN="${PYTHON_BIN:-python3}"
|
||||
TARGET="$BASE_DIR/.flash-deps"
|
||||
|
||||
if "$PYTHON_BIN" -c 'import usb.core, serial' >/dev/null 2>&1; then
|
||||
echo "[flash-deps] pyusb and pyserial are already available."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if ! "$PYTHON_BIN" -m pip --version >/dev/null 2>&1; then
|
||||
echo "Error: python3 pip is required to install flashing dependencies." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[flash-deps] Installing pyusb and pyserial into $TARGET..."
|
||||
mkdir -p "$TARGET"
|
||||
"$PYTHON_BIN" -m pip install --disable-pip-version-check --no-input \
|
||||
--target "$TARGET" pyusb pyserial
|
||||
echo "[flash-deps] Done."
|
||||
Executable
+240
@@ -0,0 +1,240 @@
|
||||
#!/bin/sh
|
||||
# Bananarchy rootfs bootstrap, container side.
|
||||
# Runs inside alpine:3.24 with the target rootfs mounted at /rootfs and the
|
||||
# repository mounted read-only at /bananarchy. Invoked by bootstrap-rootfs.sh.
|
||||
set -eu
|
||||
|
||||
ROOTFS="/rootfs"
|
||||
REPO="/bananarchy"
|
||||
PKGS_FILE="$REPO/scripts/rootfs-packages.txt"
|
||||
DEVICE="${TARGET_DEVICE:-nokia-argon}"
|
||||
PASSWORD="${BANANARCHY_USER_PASSWORD:-147147}"
|
||||
HOST_UID="${HOST_UID:-0}"
|
||||
HOST_GID="${HOST_GID:-0}"
|
||||
BOOTSTRAP_VERSION="${BOOTSTRAP_VERSION:-1}"
|
||||
PKG_HASH="${PKG_HASH:-unknown}"
|
||||
|
||||
echo "============================================================"
|
||||
echo "Bootstrapping Bananarchy armv7 rootfs for $DEVICE"
|
||||
echo "============================================================"
|
||||
|
||||
echo "[1/8] Configuring apk repositories and trusted keys..."
|
||||
cat > /etc/apk/repositories <<EOF
|
||||
https://mirror.nura.eco/postmarketos/v26.06
|
||||
https://dl-cdn.alpinelinux.org/alpine/edge/main
|
||||
https://dl-cdn.alpinelinux.org/alpine/edge/community
|
||||
https://dl-cdn.alpinelinux.org/alpine/edge/testing
|
||||
EOF
|
||||
mkdir -p /etc/apk/keys
|
||||
cp "$REPO"/keys/*.rsa.pub /etc/apk/keys/
|
||||
|
||||
mkdir -p "$ROOTFS/etc/apk/keys" "$ROOTFS/lib/apk/db" "$ROOTFS/var/cache/apk"
|
||||
cp /etc/apk/repositories "$ROOTFS/etc/apk/repositories"
|
||||
cp "$REPO"/keys/*.rsa.pub "$ROOTFS/etc/apk/keys/"
|
||||
|
||||
echo "[2/8] Installing host helper tools..."
|
||||
apk add --no-cache python3 kmod openssl >/dev/null
|
||||
|
||||
echo "[3/8] Installing the Bananarchy armv7 package set..."
|
||||
PKGS="$(grep -v '^[[:space:]]*#' "$PKGS_FILE" | grep -v '^[[:space:]]*$' | tr '\n' ' ')"
|
||||
if [ ! -f "$ROOTFS/lib/apk/db/installed" ]; then
|
||||
# shellcheck disable=SC2086
|
||||
apk --root "$ROOTFS" --arch armv7 add --initdb --no-scripts $PKGS >/dev/null
|
||||
else
|
||||
# An existing rootfs only needs newly added packages, not a full reinstall.
|
||||
# shellcheck disable=SC2086
|
||||
apk --root "$ROOTFS" --arch armv7 add --no-scripts $PKGS >/dev/null
|
||||
fi
|
||||
ln -sf lua5.5 "$ROOTFS/usr/bin/lua"
|
||||
ln -sf luac5.5 "$ROOTFS/usr/bin/luac"
|
||||
|
||||
echo "[4/8] Creating system accounts and default credentials..."
|
||||
PW_HASH="$(openssl passwd -6 -salt bananarchy "$PASSWORD")"
|
||||
python3 - "$ROOTFS" "$PW_HASH" <<'PYEOF'
|
||||
import os
|
||||
import sys
|
||||
|
||||
root = sys.argv[1]
|
||||
pw_hash = sys.argv[2]
|
||||
|
||||
|
||||
def load(name):
|
||||
path = os.path.join(root, "etc", name)
|
||||
with open(path, "r") as handle:
|
||||
return [line.rstrip("\n") for line in handle if line.strip()]
|
||||
|
||||
|
||||
def store(name, rows):
|
||||
path = os.path.join(root, "etc", name)
|
||||
with open(path, "w") as handle:
|
||||
handle.write("\n".join(rows) + "\n")
|
||||
|
||||
|
||||
passwd = load("passwd")
|
||||
group = load("group")
|
||||
shadow = load("shadow")
|
||||
|
||||
system_users = [
|
||||
"klogd:x:100:101:klogd:/dev/null:/sbin/nologin",
|
||||
"chrony:x:101:102:chrony:/dev/null:/sbin/nologin",
|
||||
"messagebus:x:102:103:messagebus:/dev/null:/sbin/nologin",
|
||||
"dnsmasq:x:103:104:dnsmasq:/dev/null:/sbin/nologin",
|
||||
"geoclue:x:104:105::/var/lib/geoclue:/sbin/nologin",
|
||||
"polkitd:x:105:110:polkitd:/var/empty:/sbin/nologin",
|
||||
"colord:x:106:111:colord:/var/lib/colord:/sbin/nologin",
|
||||
"greetd:x:107:112:greetd:/var/lib/greetd:/sbin/nologin",
|
||||
"openvpn:x:108:113:OpenVPN:/dev/null:/sbin/nologin",
|
||||
"tor:x:109:114:tor:/var/lib/tor:/sbin/nologin",
|
||||
"user:x:10000:10000::/home/user:/bin/ash",
|
||||
]
|
||||
for entry in system_users:
|
||||
name = entry.split(":")[0]
|
||||
if not any(row.startswith(name + ":") for row in passwd):
|
||||
passwd.append(entry)
|
||||
|
||||
system_groups = [
|
||||
"avahi:x:86:avahi",
|
||||
"klogd:x:101:klogd",
|
||||
"chrony:x:102:chrony",
|
||||
"messagebus:x:103:messagebus",
|
||||
"dnsmasq:x:104:dnsmasq",
|
||||
"geoclue:x:105:geoclue",
|
||||
"plugdev:x:106:user",
|
||||
"pipewire:x:107:user",
|
||||
"seat:x:108:user",
|
||||
"feedbackd:x:109:user",
|
||||
"polkitd:x:110:polkitd",
|
||||
"colord:x:111:colord",
|
||||
"greetd:x:112:greetd",
|
||||
"openvpn:x:113:openvpn",
|
||||
"tor:x:114:tor",
|
||||
"user:x:10000:",
|
||||
]
|
||||
for entry in system_groups:
|
||||
name = entry.split(":")[0]
|
||||
if not any(row.startswith(name + ":") for row in group):
|
||||
group.append(entry)
|
||||
|
||||
member_groups = (
|
||||
"wheel", "audio", "input", "netdev", "plugdev", "video", "seat",
|
||||
"feedbackd", "dialout", "tty", "pipewire",
|
||||
)
|
||||
for index, row in enumerate(group):
|
||||
fields = row.split(":")
|
||||
if fields[0] not in member_groups:
|
||||
continue
|
||||
members = [item for item in fields[3].split(",") if item]
|
||||
if "user" not in members:
|
||||
members.append("user")
|
||||
fields[3] = ",".join(members)
|
||||
group[index] = ":".join(fields)
|
||||
|
||||
for entry in system_users:
|
||||
name = entry.split(":")[0]
|
||||
if name == "user":
|
||||
continue
|
||||
if not any(row.startswith(name + ":") for row in shadow):
|
||||
shadow.append(name + ":!:::::::")
|
||||
|
||||
if not any(row.startswith("user:") for row in shadow):
|
||||
shadow.append("user:" + pw_hash + ":::::::")
|
||||
for index, row in enumerate(shadow):
|
||||
if row.startswith("root:"):
|
||||
fields = row.split(":")
|
||||
if len(fields) > 1 and fields[1] == "":
|
||||
fields[1] = pw_hash
|
||||
shadow[index] = ":".join(fields)
|
||||
|
||||
store("passwd", passwd)
|
||||
store("group", group)
|
||||
store("shadow", shadow)
|
||||
PYEOF
|
||||
mkdir -p "$ROOTFS/home/user" "$ROOTFS/etc/bananarchy"
|
||||
chown -R 10000:10000 "$ROOTFS/home/user"
|
||||
chown 0:42 "$ROOTFS/etc/shadow"
|
||||
chmod 640 "$ROOTFS/etc/shadow"
|
||||
chown 0:0 "$ROOTFS/etc/bananarchy"
|
||||
chmod 0700 "$ROOTFS/etc/bananarchy"
|
||||
|
||||
echo "[5/8] Writing base system configuration..."
|
||||
printf '%s\n' "nokia-argon" > "$ROOTFS/etc/hostname"
|
||||
cat > "$ROOTFS/etc/hosts" <<EOF
|
||||
127.0.0.1 nokia-argon localhost.localdomain localhost
|
||||
::1 localhost ipv6-localhost ipv6-loopback
|
||||
fe00::0 ipv6-localnet
|
||||
ff00::0 ipv6-mcastprefix
|
||||
ff02::1 ipv6-allnodes
|
||||
ff02::2 ipv6-allrouters
|
||||
ff02::3 ipv6-allhosts
|
||||
EOF
|
||||
printf '%s\n' "LANG=C.UTF-8" > "$ROOTFS/etc/locale.conf"
|
||||
if [ -f "$ROOTFS/usr/share/zoneinfo/UTC" ]; then
|
||||
cp "$ROOTFS/usr/share/zoneinfo/UTC" "$ROOTFS/etc/localtime"
|
||||
touch "$ROOTFS/etc/apk/interactive"
|
||||
mkdir -p "$ROOTFS/run/openrc" "$ROOTFS/dev/pts" "$ROOTFS/dev/shm"
|
||||
touch "$ROOTFS/run/openrc/shutdowntime"
|
||||
# mkinitfs and boot-deploy run in a chroot and need /dev/null; devtmpfs
|
||||
# replaces these placeholders on the device at boot time.
|
||||
: > "$ROOTFS/dev/null"
|
||||
chmod 666 "$ROOTFS/dev/null"
|
||||
# mkinitfs expects losetup under /usr/sbin; the util-linux package only
|
||||
# installs it under /sbin when package scripts are skipped.
|
||||
if [ -e "$ROOTFS/sbin/losetup" ] && [ ! -e "$ROOTFS/usr/sbin/losetup" ]; then
|
||||
ln -sf /sbin/losetup "$ROOTFS/usr/sbin/losetup"
|
||||
fi
|
||||
tr -d '-' < /proc/sys/kernel/random/uuid > "$ROOTFS/etc/machine-id"
|
||||
printf '\n' >> "$ROOTFS/etc/machine-id"
|
||||
fi
|
||||
mkdir -p "$ROOTFS/etc/sysctl.d"
|
||||
cat > "$ROOTFS/etc/sysctl.d/90-nokia-argon-lowram.conf" <<EOF
|
||||
vm.swappiness = 180
|
||||
vm.page-cluster = 0
|
||||
vm.vfs_cache_pressure = 150
|
||||
vm.min_free_kbytes = 16384
|
||||
EOF
|
||||
mkdir -p "$ROOTFS/etc/sudoers.d" "$ROOTFS/etc/doas.d"
|
||||
cat > "$ROOTFS/etc/sudoers.d/wheel" <<EOF
|
||||
%wheel ALL=(ALL:ALL) ALL
|
||||
EOF
|
||||
chmod 440 "$ROOTFS/etc/sudoers.d/wheel"
|
||||
rm -f "$ROOTFS/etc/doas.d/wheel.conf"
|
||||
touch "$ROOTFS/etc/apk/interactive"
|
||||
mkdir -p "$ROOTFS/run/openrc"
|
||||
touch "$ROOTFS/run/openrc/shutdowntime"
|
||||
|
||||
echo "[6/8] Enabling OpenRC runlevels..."
|
||||
mkdir -p "$ROOTFS/etc/runlevels/sysinit" "$ROOTFS/etc/runlevels/boot" \
|
||||
"$ROOTFS/etc/runlevels/default" "$ROOTFS/etc/runlevels/shutdown"
|
||||
enable_service() {
|
||||
runlevel="$1"
|
||||
service="$2"
|
||||
if [ -e "$ROOTFS/etc/init.d/$service" ]; then
|
||||
ln -sf "/etc/init.d/$service" "$ROOTFS/etc/runlevels/$runlevel/$service"
|
||||
fi
|
||||
}
|
||||
for svc in devfs dmesg msm-firmware-loader udev udev-trigger udev-settle; do
|
||||
enable_service sysinit "$svc"
|
||||
done
|
||||
for svc in bootmisc hostname modules msm-firmware-loader-unpack osclock \
|
||||
swclock-offset-boot sysctl tmpfs; do
|
||||
enable_service boot "$svc"
|
||||
done
|
||||
for svc in bluetooth cgroups chronyd dbus elogind kill-plymouth local \
|
||||
modemmanager msm8909-modem-wwan-port msm-modem-uim-selection networkmanager \
|
||||
postmarketos-zram-swap q6voiced rfkill rmtfs sshd tinydm udev-postmount \
|
||||
wpa_supplicant; do
|
||||
enable_service default "$svc"
|
||||
done
|
||||
for svc in killprocs mount-ro savecache swclock-offset-shutdown; do
|
||||
enable_service shutdown "$svc"
|
||||
done
|
||||
rm -f "$ROOTFS/etc/runlevels/boot/hwclock"
|
||||
|
||||
echo "[7/8] Applying the Bananarchy overlay and prebuilt artifacts..."
|
||||
"$REPO/scripts/apply-bananarchy-overlay.sh" "$ROOTFS" "$DEVICE"
|
||||
depmod -b "$ROOTFS" 6.12.1-msm8916
|
||||
|
||||
echo "[8/8] Finalizing rootfs ownership and bootstrap marker..."
|
||||
printf '%s:%s\n' "$BOOTSTRAP_VERSION" "$PKG_HASH" > "$ROOTFS/etc/bananarchy/rootfs-bootstrap.done"
|
||||
chown -R "$HOST_UID:$HOST_GID" "$ROOTFS"
|
||||
echo "Bananarchy rootfs bootstrap completed for $DEVICE."
|
||||
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/bin/sh
|
||||
# Autonomously create a complete armv7 Bananarchy rootfs from the repository.
|
||||
# Safe to run repeatedly: an up-to-date rootfs is left untouched.
|
||||
set -eu
|
||||
|
||||
BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
PKGS_FILE="$BASE_DIR/scripts/rootfs-packages.txt"
|
||||
CONTAINER_SCRIPT="$BASE_DIR/scripts/bootstrap-rootfs-container.sh"
|
||||
BOOTSTRAP_VERSION="1"
|
||||
MARKER_REL="etc/bananarchy/rootfs-bootstrap.done"
|
||||
|
||||
ROOTFS_DIR="${ROOTFS_DIR:-$BASE_DIR/rootfs}"
|
||||
TARGET_DEVICE="nokia-argon"
|
||||
FORCE=0
|
||||
CHECK_ONLY=0
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--force|-f)
|
||||
FORCE=1
|
||||
;;
|
||||
--check|-c)
|
||||
CHECK_ONLY=1
|
||||
;;
|
||||
nokia-argon|nokia-beatles|nokia-tough|nokia-sparkler|nokia-leo)
|
||||
TARGET_DEVICE="$arg"
|
||||
;;
|
||||
*)
|
||||
if [ -z "${ROOTFS_DIR_SET:-}" ]; then
|
||||
ROOTFS_DIR="$arg"
|
||||
ROOTFS_DIR_SET=1
|
||||
else
|
||||
echo "Usage: $0 [rootfs-dir] [device] [--force|--check]" >&2
|
||||
exit 1
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [ ! -f "$PKGS_FILE" ] || [ ! -f "$CONTAINER_SCRIPT" ]; then
|
||||
echo "Error: bootstrap inputs are missing from $BASE_DIR/scripts." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$ROOTFS_DIR"
|
||||
ROOTFS_HOST="$(realpath "$ROOTFS_DIR")"
|
||||
PKG_HASH="$(sha256sum "$PKGS_FILE" | awk '{print $1}')"
|
||||
EXPECTED="$BOOTSTRAP_VERSION:$PKG_HASH"
|
||||
MARKER="$ROOTFS_HOST/$MARKER_REL"
|
||||
|
||||
if [ "$FORCE" -eq 0 ] && [ -f "$MARKER" ] && [ "$(cat "$MARKER")" = "$EXPECTED" ]; then
|
||||
echo "[bootstrap] Rootfs is already complete: $ROOTFS_HOST"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "$CHECK_ONLY" -eq 1 ]; then
|
||||
echo "[bootstrap] Rootfs needs bootstrapping: $ROOTFS_HOST"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "Error: Docker is required to bootstrap the armv7 rootfs." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[bootstrap] Building a complete rootfs at $ROOTFS_HOST for $TARGET_DEVICE..."
|
||||
exec docker run --rm --network=host \
|
||||
-e HOST_UID="$(id -u)" \
|
||||
-e HOST_GID="$(id -g)" \
|
||||
-e TARGET_DEVICE="$TARGET_DEVICE" \
|
||||
-e BANANARCHY_USER_PASSWORD="${BANANARCHY_USER_PASSWORD:-147147}" \
|
||||
-e BOOTSTRAP_VERSION="$BOOTSTRAP_VERSION" \
|
||||
-e PKG_HASH="$PKG_HASH" \
|
||||
-v "$ROOTFS_HOST:/rootfs" \
|
||||
-v "$BASE_DIR:/bananarchy:ro" \
|
||||
alpine:3.24 sh -eu /bananarchy/scripts/bootstrap-rootfs-container.sh
|
||||
Executable
+101
@@ -0,0 +1,101 @@
|
||||
#!/bin/sh
|
||||
# Fast offline preflight: verify that a clean clone can rebuild Bananarchy.
|
||||
set -eu
|
||||
|
||||
BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
FAILURES=0
|
||||
|
||||
fail() {
|
||||
echo "FAIL: $1"
|
||||
FAILURES=$((FAILURES + 1))
|
||||
}
|
||||
|
||||
echo "[check] Shell syntax..."
|
||||
for script in "$BASE_DIR"/*.sh "$BASE_DIR"/scripts/*.sh; do
|
||||
if ! sh -n "$script" 2>/dev/null; then
|
||||
fail "shell syntax: $script"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "[check] Python syntax..."
|
||||
python3 - "$BASE_DIR" <<'PYEOF' || exit 1
|
||||
import ast
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
|
||||
base = sys.argv[1]
|
||||
paths = sorted(glob.glob(os.path.join(base, "scripts", "*.py")) +
|
||||
glob.glob(os.path.join(base, "*.py")) +
|
||||
glob.glob(os.path.join(base, "vendor", "edl", "*.py")) +
|
||||
glob.glob(os.path.join(base, "vendor", "edl", "Library", "*.py")))
|
||||
for path in paths:
|
||||
with open(path, "r", encoding="utf-8", errors="replace") as handle:
|
||||
try:
|
||||
ast.parse(handle.read(), filename=path)
|
||||
except SyntaxError as exc:
|
||||
print("FAIL: python syntax: %s: %s" % (path, exc))
|
||||
sys.exit(1)
|
||||
print(" %d Python file(s) parsed" % len(paths))
|
||||
PYEOF
|
||||
|
||||
echo "[check] Rootfs package list..."
|
||||
PKGS_FILE="$BASE_DIR/scripts/rootfs-packages.txt"
|
||||
if [ ! -f "$PKGS_FILE" ]; then
|
||||
fail "missing $PKGS_FILE"
|
||||
else
|
||||
PKG_COUNT="$(grep -v '^[[:space:]]*#' "$PKGS_FILE" | grep -cv '^[[:space:]]*$' || true)"
|
||||
if [ "$PKG_COUNT" -lt 100 ]; then
|
||||
fail "package list has only $PKG_COUNT entries"
|
||||
else
|
||||
echo " $PKG_COUNT packages"
|
||||
fi
|
||||
fi
|
||||
|
||||
echo "[check] Vendored EDL client library..."
|
||||
for module in usb gpt sahara firehose utils; do
|
||||
if [ ! -f "$BASE_DIR/vendor/edl/Library/$module.py" ]; then
|
||||
fail "missing vendor/edl/Library/$module.py"
|
||||
fi
|
||||
done
|
||||
if [ ! -f "$BASE_DIR/vendor/edl/LICENSE" ]; then
|
||||
fail "missing vendor/edl/LICENSE"
|
||||
fi
|
||||
|
||||
echo "[check] Plugin artifacts..."
|
||||
for source in "$BASE_DIR"/src/dwm-plugins/*_plugin.cpp; do
|
||||
name="$(basename "$source" _plugin.cpp)"
|
||||
if [ ! -f "$BASE_DIR/prebuilt/sxmo-x11/usr/lib/dwm/plugins/$name.so" ]; then
|
||||
fail "missing prebuilt plugin: $name.so"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "[check] Overlay artifact sync..."
|
||||
if ! "$BASE_DIR/scripts/sync-prebuilt-overlay.sh" --check; then
|
||||
fail "overlay/rootfs artifacts differ from prebuilt/"
|
||||
fi
|
||||
|
||||
echo "[check] Local agent config stays ignored..."
|
||||
if [ -d "$BASE_DIR/.git" ]; then
|
||||
if ! git -C "$BASE_DIR" check-ignore -q .bantam.cfg; then
|
||||
fail ".bantam.cfg is no longer gitignored"
|
||||
fi
|
||||
elif ! grep -qxF '.bantam.cfg' "$BASE_DIR/.gitignore"; then
|
||||
fail ".bantam.cfg ignore rule is missing"
|
||||
fi
|
||||
|
||||
echo "[check] Docker availability..."
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
fail "docker is not installed"
|
||||
fi
|
||||
|
||||
echo "[check] Version helper..."
|
||||
if ! "$BASE_DIR/scripts/version.sh" --print >/dev/null 2>&1; then
|
||||
fail "scripts/version.sh --print failed"
|
||||
fi
|
||||
|
||||
if [ "$FAILURES" -ne 0 ]; then
|
||||
echo "[check] $FAILURES check(s) failed."
|
||||
exit 1
|
||||
fi
|
||||
echo "[check] All rebuild preflight checks passed."
|
||||
@@ -1,4 +1,8 @@
|
||||
#!/bin/sh
|
||||
# Legacy pmbootstrap-era rootfs configurator (Wayland/Sway based).
|
||||
# Superseded by scripts/bootstrap-rootfs.sh, which builds a complete X11
|
||||
# rootfs from scratch. Kept only for historical reference; do not use it for
|
||||
# new builds.
|
||||
set -eu
|
||||
|
||||
BANANARCHY_DIR="${BANANARCHY_DIR:-/bananarchy}"
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# Bananarchy armv7 rootfs package set.
|
||||
# Single source of truth for scripts/bootstrap-rootfs.sh and rebuild-image.sh.
|
||||
# One package per line; lines starting with '#' and blank lines are ignored.
|
||||
# Keep this list synchronized with the packages used by the overlay and plugins.
|
||||
adwaita-icon-theme
|
||||
alpine-base
|
||||
alsa-utils
|
||||
bash
|
||||
bc
|
||||
brightnessctl
|
||||
clickclack
|
||||
coreutils
|
||||
doas
|
||||
ed
|
||||
evtest
|
||||
fcitx5
|
||||
fcitx5-gtk3
|
||||
font-droid
|
||||
font-droid-nonlatin
|
||||
font-fira-code
|
||||
font-noto
|
||||
font-noto-emoji
|
||||
font-twemoji
|
||||
frotz
|
||||
g++
|
||||
gcc
|
||||
git
|
||||
gst-libav
|
||||
gst-plugins-bad
|
||||
gst-plugins-good
|
||||
harfbuzz
|
||||
htop
|
||||
i2c-tools
|
||||
imv
|
||||
ip6tables
|
||||
iproute2
|
||||
iptables
|
||||
janet
|
||||
janet-dev
|
||||
jpm
|
||||
lang
|
||||
less
|
||||
libwpe
|
||||
libwpebackend-fdo
|
||||
libxcvt
|
||||
libxft
|
||||
libxinerama
|
||||
libxtst
|
||||
linux-postmarketos-qcom-msm8916
|
||||
lua5.4
|
||||
lua5.4-dev
|
||||
lua5.5
|
||||
lua5.5-dev
|
||||
make
|
||||
mandoc
|
||||
mesa-demos
|
||||
mesa-utils
|
||||
modemmanager
|
||||
musl-dev
|
||||
nano
|
||||
openssh
|
||||
openssh-server-pam
|
||||
openvpn
|
||||
perl
|
||||
perl-io-socket-ssl
|
||||
postmarketos-artwork-wallpapers
|
||||
postmarketos-base
|
||||
postmarketos-base-nofde
|
||||
postmarketos-base-ui
|
||||
postmarketos-base-ui-audio-backend-pipewire
|
||||
postmarketos-base-ui-wifi-wpa_supplicant
|
||||
postmarketos-ui-sxmo-de-dwm
|
||||
postmarketos-ui-sxmo-de-dwm-openrc
|
||||
qmi-utils
|
||||
rlwrap
|
||||
scrot
|
||||
setxkbmap
|
||||
sfeed
|
||||
soc-qcom-msm8909
|
||||
soc-qcom-msm8909-modem
|
||||
soc-qcom-msm8909-modem-openrc
|
||||
soc-qcom-msm8916
|
||||
soc-qcom-msm8916-rproc
|
||||
soc-qcom-msm8916-rproc-openrc
|
||||
soc-qcom-msm8916-ucm
|
||||
sqlite
|
||||
sqlite-tcl
|
||||
sudo-rs
|
||||
tcl
|
||||
tcl-lib
|
||||
tcl-tls
|
||||
tor
|
||||
ttyescape
|
||||
v4l-utils
|
||||
w3m
|
||||
webkit2gtk-4.1
|
||||
wireguard-tools
|
||||
wireguard-tools-wg
|
||||
wireguard-tools-wg-quick
|
||||
xf86-input-libinput
|
||||
xf86-video-fbdev
|
||||
yabasic
|
||||
yabasic-doc
|
||||
zram-init
|
||||
zram-init-openrc
|
||||
Executable
+83
@@ -0,0 +1,83 @@
|
||||
#!/bin/sh
|
||||
# Keep the tracked overlay/rootfs snapshot in sync with prebuilt/ artifacts.
|
||||
# prebuilt/ is the single source of truth; this script mirrors every artifact
|
||||
# that also exists in overlay/rootfs back into the overlay.
|
||||
set -eu
|
||||
|
||||
BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
CHECK_ONLY=0
|
||||
|
||||
for arg in "$@"; do
|
||||
case "$arg" in
|
||||
--check|-c)
|
||||
CHECK_ONLY=1
|
||||
;;
|
||||
*)
|
||||
echo "Usage: $0 [--check]" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
python3 - "$BASE_DIR" "$CHECK_ONLY" <<'PYEOF'
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
base = sys.argv[1]
|
||||
check_only = sys.argv[2] == "1"
|
||||
prebuilt_root = os.path.join(base, "prebuilt")
|
||||
overlay_root = os.path.join(base, "overlay", "rootfs")
|
||||
|
||||
|
||||
def digest(path):
|
||||
with open(path, "rb") as handle:
|
||||
return hashlib.sha256(handle.read()).hexdigest()
|
||||
|
||||
|
||||
def regular_files(root):
|
||||
result = []
|
||||
for parent, _, names in os.walk(root):
|
||||
for name in names:
|
||||
path = os.path.join(parent, name)
|
||||
if not os.path.islink(path) and os.path.isfile(path):
|
||||
result.append(path)
|
||||
return result
|
||||
|
||||
|
||||
by_name = {}
|
||||
for path in regular_files(prebuilt_root):
|
||||
by_name.setdefault(os.path.basename(path), []).append(path)
|
||||
|
||||
drift = []
|
||||
matched = 0
|
||||
for target in regular_files(overlay_root):
|
||||
rel = os.path.relpath(target, overlay_root)
|
||||
candidates = by_name.get(os.path.basename(target), [])
|
||||
source = None
|
||||
for candidate in candidates:
|
||||
stripped = os.path.relpath(candidate, prebuilt_root).split(os.sep, 1)[-1]
|
||||
if stripped == rel:
|
||||
source = candidate
|
||||
break
|
||||
if source is None and candidates:
|
||||
source = candidates[0]
|
||||
if source is None:
|
||||
continue
|
||||
matched += 1
|
||||
if digest(source) == digest(target):
|
||||
continue
|
||||
drift.append((source, target))
|
||||
if not check_only:
|
||||
shutil.copy2(source, target)
|
||||
|
||||
if check_only:
|
||||
for source, target in drift:
|
||||
print("out of sync: " + os.path.relpath(target, base))
|
||||
print("artifact drift: %d of %d mirrored file(s)" % (len(drift), matched))
|
||||
sys.exit(1 if drift else 0)
|
||||
|
||||
print("synced %d artifact(s) into overlay/rootfs; %d already in sync" % (
|
||||
len(drift), matched - len(drift)))
|
||||
PYEOF
|
||||
Vendored
+658
@@ -0,0 +1,658 @@
|
||||
--------------------------------------------------------------------------------
|
||||
# These rules refer: https://developer.android.com/studio/run/device.html
|
||||
# and include many suggestions from Arch Linux, GitHub and other Communities.
|
||||
# Latest version can be found at: https://github.com/M0Rf30/android-udev-rules
|
||||
|
||||
# Skip this section below if this device is not connected by USB
|
||||
SUBSYSTEM!="usb", GOTO="android_usb_rules_end"
|
||||
|
||||
LABEL="android_universal_rule"
|
||||
ENV{ID_USB_INTERFACES}!="*:ff420?:*", GOTO="android_usb_rules_begin"
|
||||
ACTION=="add", SUBSYSTEM=="usb", ENV{DEVTYPE}=="usb_device", ENV{ID_USB_INTERFACES}=="*:ff420?:*", MODE="0660", GROUP="adbusers", SYMLINK+="android/$env{ID_SERIAL_SHORT}"
|
||||
|
||||
LABEL="android_usb_rules_begin"
|
||||
# Devices listed here in android_usb_rules_{begin...end} are connected by USB
|
||||
# Acer
|
||||
ATTR{idVendor}!="0502", GOTO="not_Acer"
|
||||
ENV{adb_user}="yes"
|
||||
# Iconia Tab A1-830
|
||||
ATTR{idProduct}=="3604", ENV{adb_adbfast}="yes"
|
||||
# Iconia Tab A500
|
||||
ATTR{idProduct}=="3325", ENV{adb_adbfast}="yes"
|
||||
# Liquid (3202=normal,3203=debug)
|
||||
ATTR{idProduct}=="3203", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Acer"
|
||||
|
||||
# Actions Semiconductor Co., Ltd
|
||||
ATTR{idVendor}=="10d6", ENV{adb_user}="yes"
|
||||
# Denver TAD 70111
|
||||
ATTR{idProduct}=="0c02", SYMLINK+="android_adb"
|
||||
|
||||
# ADVANCE
|
||||
ATTR{idVendor}=="0a5c", ENV{adb_user}="yes"
|
||||
# S5
|
||||
ATTR{idProduct}=="e681", SYMLINK+="android_adb"
|
||||
|
||||
# Amazon Lab126
|
||||
ATTR{idVendor}=="1949", ENV{adb_user}="yes"
|
||||
# Amazon Kindle Fire
|
||||
ATTR{idProduct}=="0006", ENV{adb_adbfast}="yes"
|
||||
|
||||
# Archos
|
||||
ATTR{idVendor}!="0e79", GOTO="not_Archos"
|
||||
ENV{adb_user}="yes"
|
||||
# 43
|
||||
ATTR{idProduct}=="1417", ENV{adb_adbfast}="yes"
|
||||
# 101
|
||||
ATTR{idProduct}=="1411", ENV{adb_adbfast}="yes"
|
||||
# 101 xs
|
||||
ATTR{idProduct}=="1549", ENV{adb_adbfast}="yes"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Archos"
|
||||
|
||||
# ASUSTeK
|
||||
ATTR{idVendor}!="0b05", GOTO="not_Asus"
|
||||
# False positive - accessory
|
||||
ATTR{idProduct}=="1???", GOTO="android_usb_rules_end"
|
||||
ENV{adb_user}="yes"
|
||||
# Zenphone 2 (ZE500CL) (7770=adb 7773=mtp,adb 7777=ptp,adb 7775=rndis,adb,mass_storage 5F03=mtp,adb,pclink,mass_storage 5F07=ptp,adb,pclink 5F05=rndis,adb,pclink,mass_storage
|
||||
ATTR{idProduct}=="7770", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="7773", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="7777", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="7775", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="5F03", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="5F07", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="5F05", SYMLINK+="android_adb"
|
||||
# Zenphone 4 (581f=mtp,adb 583f=rndis,adb)
|
||||
ATTR{idProduct}=="581f", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="583f", SYMLINK+="android_adb"
|
||||
# Zenphone 5 (4c90=normal,4c91=debug,4daf=Fastboot)
|
||||
ATTR{idProduct}=="4c91", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4daf", SYMLINK+="android_fastboot"
|
||||
# Tegra APX
|
||||
ATTR{idProduct}=="7030"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Asus"
|
||||
|
||||
# Azpen Onda
|
||||
ATTR{idVendor}=="1f3a", ENV{adb_user}="yes"
|
||||
|
||||
# BQ
|
||||
ATTR{idVendor}!="2a47", GOTO="not_BQ"
|
||||
ENV{adb_user}="yes"
|
||||
# Aquaris 4.5
|
||||
ATTR{idProduct}=="0c02", ENV{adb_adbfast}="yes"
|
||||
ATTR{idProduct}=="2008", ENV{adb_adbfast}="yes"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_BQ"
|
||||
|
||||
# Dell
|
||||
ATTR{idVendor}=="413c", ENV{adb_user}="yes"
|
||||
|
||||
# Essential
|
||||
ATTR{idVendor}!="2e17", GOTO="not_Essential"
|
||||
ENV{adb_user}="yes"
|
||||
# Essential PH-1
|
||||
ATTR{idProduct}=="c009", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="c030", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Essential"
|
||||
|
||||
# Fairphone 2
|
||||
ATTR{idVendor}=="2ae5", ENV{adb_user}="yes"
|
||||
|
||||
# Foxconn
|
||||
ATTR{idVendor}=="0489", ENV{adb_user}="yes"
|
||||
# Commtiva Z71, Geeksphone One
|
||||
ATTR{idVendor}=="0489", ATTR{idProduct}=="c001", SYMLINK+="android_adb"
|
||||
|
||||
# Fujitsu/Fujitsu Toshiba
|
||||
ATTR{idVendor}=="04c5", ENV{adb_user}="yes"
|
||||
|
||||
# Fuzhou Rockchip Electronics
|
||||
ATTR{idVendor}=="2207", ENV{adb_user}="yes"
|
||||
# Mediacom Smartpad 715i
|
||||
ATTR{idVendor}=="2207", ATTR{idProduct}=="0000", SYMLINK+="android_adb"
|
||||
# Ubislate 7Ci
|
||||
ATTR{idVendor}=="2207", ATTR{idProduct}=="0010", SYMLINK+="android_adb"
|
||||
|
||||
# Garmin-Asus
|
||||
ATTR{idVendor}=="091e", ENV{adb_user}="yes"
|
||||
|
||||
# Google
|
||||
ATTR{idVendor}!="18d1", GOTO="not_Google"
|
||||
ENV{adb_user}="yes"
|
||||
# Nexus, Pixel, Pixel XL, Pixel 2, Pixel 2XL (4ee2=mtp,adb 4ee4=rndis,adb 4ee6=ptp,adb 4ee7=adb 4ee9=midi,adb 2d01=accessory,adb 2d03=audio_source,adb 2d05=accessory,audio_source,adb)
|
||||
# See https://android.googlesource.com/device/google/wahoo/+/master/init.hardware.usb.rc
|
||||
ATTR{idProduct}=="4ee2", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4ee4", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4ee6", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4ee7", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4ee9", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="2d01", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="2d03", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="2d05", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4ee0", SYMLINK+="android_fastboot"
|
||||
# Nexus 7
|
||||
ATTR{idProduct}=="4e42", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4e40", SYMLINK+="android_fastboot"
|
||||
# Nexus 5, Nexus 10
|
||||
ATTR{idProduct}=="4ee1", ENV{adb_adbfast}="yes"
|
||||
# Nexus S (4e22=mass_storage,adb 4e24=rndis,adb)
|
||||
# See https://android.googlesource.com/device/samsung/crespo/+/android-4.1.2_r2.1/init.herring.usb.rc
|
||||
ATTR{idProduct}=="4e22", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4e24", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="4e20", SYMLINK+="android_fastboot"
|
||||
# Galaxy Nexus
|
||||
ATTR{idProduct}=="4e30", ENV{adb_adbfast}="yes"
|
||||
# Nexus One (4e11=normal,4e12=debug,0fff=debug)
|
||||
ATTR{idProduct}=="4e12", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="0fff", SYMLINK+="android_fastboot"
|
||||
# Generic and unspecified debug interface
|
||||
ATTR{idProduct}=="d00d", SYMLINK+="android_fastboot"
|
||||
# Pico i.MX7 Dual Development Board
|
||||
ATTR{idProduct}=="4ee7", SYMLINK+="android_adb"
|
||||
# Include: Samsung Galaxy Nexus (GSM)
|
||||
ATTR{idProduct}=="4e30", SYMLINK+="android_fastboot"
|
||||
# Recovery adb entry for Nexus Family (orig d001, OP3 has 18d1:d002)
|
||||
ATTR{idProduct}=="d00?", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Google"
|
||||
|
||||
# Haier
|
||||
ATTR{idVendor}=="201e", ENV{adb_user}="yes"
|
||||
|
||||
# Hisense
|
||||
ATTR{idVendor}=="109b", ENV{adb_user}="yes"
|
||||
|
||||
# Honeywell/Foxconn
|
||||
ATTR{idVendor}!="0c2e", GOTO="not_Honeywell"
|
||||
ENV{adb_user}="yes"
|
||||
# D70e
|
||||
ATTR{idProduct}=="0ba3", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Honeywell"
|
||||
|
||||
# HTC
|
||||
ATTR{idVendor}!="0bb4", GOTO="not_HTC"
|
||||
ENV{adb_user}="yes"
|
||||
# fastboot mode enabled
|
||||
ATTR{idProduct}=="0fff", ENV{adb_adbfast}="yes", GOTO="android_usb_rule_match"
|
||||
# ChaCha
|
||||
ATTR{idProduct}=="0cb2", ENV{adb_adbfast}="yes"
|
||||
# Desire (Bravo)
|
||||
ATTR{idProduct}=="0c87", SYMLINK+="android_adb"
|
||||
# Desire HD
|
||||
ATTR{idProduct}=="0ca2", SYMLINK+="android_adb"
|
||||
# Desire S (Saga)
|
||||
ATTR{idProduct}=="0cab", SYMLINK+="android_adb"
|
||||
# Desire Z
|
||||
ATTR{idProduct}=="0c91", ENV{adb_adbfast}="yes"
|
||||
# Evo Shift
|
||||
ATTR{idProduct}=="0ca5", SYMLINK+="android_adb"
|
||||
# G1
|
||||
ATTR{idProduct}=="0c01", ENV{adb_adbfast}="yes"
|
||||
# HD2
|
||||
ATTR{idProduct}=="0c02", ENV{adb_adbfast}="yes"
|
||||
# Hero H2000
|
||||
ATTR{idProduct}=="0001", ENV{adb_adbfast}="yes"
|
||||
# Hero (GSM), Desire
|
||||
ATTR{idProduct}=="0c99", SYMLINK+="android_adb"
|
||||
# Hero (CDMA)
|
||||
ATTR{idProduct}=="0c9a", SYMLINK+="android_adb"
|
||||
# Incredible
|
||||
ATTR{idProduct}=="0c9e", SYMLINK+="android_adb"
|
||||
# Incredible rev 0002
|
||||
ATTR{idProduct}=="0c8d", SYMLINK+="android_adb"
|
||||
# MyTouch 4G
|
||||
ATTR{idProduct}=="0c96", SYMLINK+="android_adb"
|
||||
# One (m7) && One (m8)
|
||||
ATTR{idProduct}=="0c93"
|
||||
# Sensation
|
||||
ATTR{idProduct}=="0f87", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="0ff0", SYMLINK+="android_fastboot"
|
||||
# One V
|
||||
ATTR{idProduct}=="0ce5", SYMLINK+="android_adb"
|
||||
# One X
|
||||
ATTR{idProduct}=="0cd6", SYMLINK+="android_adb"
|
||||
# Slide
|
||||
ATTR{idProduct}=="0e03", SYMLINK+="android_adb"
|
||||
# Tatoo, Dream, ADP1, G1, Magic
|
||||
ATTR{idProduct}=="0c01"
|
||||
ATTR{idProduct}=="0c02", ENV{adb_adbfast}="yes"
|
||||
# Vision
|
||||
ATTR{idProduct}=="0c91", SYMLINK+="android_adb"
|
||||
# Wildfire
|
||||
ATTR{idProduct}=="0c8b", ENV{adb_adbfast}="yes"
|
||||
# Wildfire S
|
||||
ATTR{idProduct}=="0c86", ENV{adb_adbfast}="yes"
|
||||
# Zopo ZP900, Fairphone
|
||||
ATTR{idProduct}=="0c03", ENV{adb_adbfast}="yes"
|
||||
# Zopo C2
|
||||
ATTR{idProduct}=="2008", SYMLINK+="libmtp-%k", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_HTC"
|
||||
|
||||
# Huawei
|
||||
ATTR{idVendor}!="12d1", GOTO="not_Huawei"
|
||||
ENV{adb_user}="yes"
|
||||
# IDEOS
|
||||
ATTR{idProduct}=="1038", ENV{adb_adbfast}="yes"
|
||||
# U8850 Vision
|
||||
ATTR{idProduct}=="1021", ENV{adb_adbfast}="yes"
|
||||
# HiKey adb
|
||||
ATTR{idProduct}=="1057", SYMLINK+="android_adb"
|
||||
# HiKey usbnet
|
||||
ATTR{idProduct}=="1050", SYMLINK+="android_adb"
|
||||
# Honor 6
|
||||
ATTR{idProduct}=="103a", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="1051", SYMLINK+="libmtp-%k", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1"
|
||||
# MediaPad M2-A01L
|
||||
ATTR{idProduct}=="1052", SYMLINK+="android_adb"
|
||||
# Huawei Watch
|
||||
ATTR{idProduct}=="1c2c", SYMLINK+="android_adb"
|
||||
# Mate 9
|
||||
ATTR{idProduct}=="107e", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Huawei"
|
||||
|
||||
# Intel
|
||||
# Geeksphone Revolution
|
||||
ATTR{idVendor}=="8087", ATTR{idProduct}=="0a16", SYMLINK+="android_adb", ENV{adb_user}="yes"
|
||||
# Chuwi Hi 10 Pro (HQ64)
|
||||
ATTR{idVendor}=="8087", ATTR{idProduct}=="2a65", SYMLINK+="android_adb", ENV{adb_user}="yes"
|
||||
ATTR{idVendor}=="8087", ATTR{idProduct}=="07ef", SYMLINK+="android_adb", ENV{adb_user}="yes"
|
||||
# Reference Boards using kernelflinger
|
||||
# See https://github.com/intel/kernelflinger/blob/master/libefiusb/usb.c#L56
|
||||
ATTR{idProduct}=="09ef", ENV{adb_adbfast}="yes"
|
||||
|
||||
# IUNI
|
||||
ATTR{idVendor}!="271d", GOTO="not_IUNI"
|
||||
ENV{adb_user}="yes"
|
||||
# U3
|
||||
ATTR{idProduct}=="bf39", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_IUNI"
|
||||
|
||||
# K-Touch
|
||||
ATTR{idVendor}=="24e3", ENV{adb_user}="yes"
|
||||
|
||||
# KT Tech
|
||||
ATTR{idVendor}=="2116", ENV{adb_user}="yes"
|
||||
|
||||
# Kyocera
|
||||
#ATTR{idVendor}=="0482", ENV{adb_user}="yes"
|
||||
|
||||
# Lenovo
|
||||
ATTR{idVendor}=="17ef", ENV{adb_user}="yes"
|
||||
|
||||
# LeTv
|
||||
ATTR{idVendor}!="2b0e", GOTO="not_letv"
|
||||
ENV{adb_user}="yes"
|
||||
# LEX720 LeEco Pro3 6GB (610c=normal,610d=debug, 610b=camera)
|
||||
ATTR{idProduct}=="610d", ENV{adb_fastboot}="yes"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_letv"
|
||||
|
||||
# LG
|
||||
ATTR{idVendor}!="1004", GOTO="not_LG"
|
||||
ENV{adb_user}="yes"
|
||||
# Ally, Vortex, P500, P500h
|
||||
ATTR{idProduct}=="618f"
|
||||
ATTR{idProduct}=="618e", SYMLINK+="android_adb"
|
||||
# G2 D802
|
||||
ATTR{idProduct}=="61f1", SYMLINK+="android_adb"
|
||||
# G2 D803
|
||||
ATTR{idProduct}=="618c", SYMLINK+="android_adb"
|
||||
# G2 D803 rogers
|
||||
ATTR{idProduct}=="631f", SYMLINK+="android_adb"
|
||||
# G2 mini D620r (PTP)
|
||||
ATTR{idProduct}=="631d", SYMLINK+="android_adb"
|
||||
# G3 D855
|
||||
ATTR{idProduct}=="633e", SYMLINK+="android_adb"
|
||||
# Optimus LTE
|
||||
ATTR{idProduct}=="6315", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="61f9", SYMLINK+="libmtp-%k", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1"
|
||||
# Optimus One
|
||||
ATTR{idProduct}=="61c5", SYMLINK+="android_adb"
|
||||
# Swift GT540
|
||||
ATTR{idProduct}=="61b4", SYMLINK+="android_adb"
|
||||
# P500 CM10
|
||||
ATTR{idProduct}=="61a6", SYMLINK+="android_adb"
|
||||
# 4X HD P880
|
||||
ATTR{idProduct}=="61f9", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_LG"
|
||||
|
||||
# Meizu
|
||||
ATTR{idVendor}!="2a45", GOTO="not_Meizu"
|
||||
ENV{adb_user}="yes"
|
||||
# MX6
|
||||
ATTR{idProduct}=="0c02", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Meizu"
|
||||
|
||||
# Micromax
|
||||
ATTR{idVendor}!="2a96", GOTO="not_Micromax"
|
||||
ENV{adb_user}="yes"
|
||||
# P702
|
||||
ATTR{idProduct}=="201d", SYMLINK+="android_adb", SYMLINK+="android_fastboot"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Micromax"
|
||||
|
||||
# Motorola
|
||||
ATTR{idVendor}!="22b8", GOTO="not_Motorola"
|
||||
ENV{adb_user}="yes"
|
||||
# CLIQ XT/Quench
|
||||
ATTR{idProduct}=="2d66"
|
||||
# Defy/MB525
|
||||
ATTR{idProduct}=="428c"
|
||||
# Droid
|
||||
ATTR{idProduct}=="41db"
|
||||
# Xoom ID 1
|
||||
ATTR{idProduct}=="70a8", ENV{adb_adbfast}="yes"
|
||||
# Xoom ID 2
|
||||
ATTR{idProduct}=="70a9", ENV{adb_adbfast}="yes"
|
||||
# Razr XT912
|
||||
ATTR{idProduct}=="4362", ENV{adb_adbfast}="yes"
|
||||
# Moto XT1052
|
||||
ATTR{idProduct}=="2e83", ENV{adb_adbfast}="yes"
|
||||
# Moto E/G
|
||||
ATTR{idProduct}=="2e76", ENV{adb_adbfast}="yes"
|
||||
# Moto E/G (Dual SIM)
|
||||
ATTR{idProduct}=="2e80", ENV{adb_adbfast}="yes"
|
||||
# Moto E/G (Global GSM)
|
||||
ATTR{idProduct}=="2e82", ENV{adb_adbfast}="yes"
|
||||
# Moto x4
|
||||
ATTR{idProduct}=="2e81", ENV{adb_adbfast}="yes"
|
||||
# Droid Turbo 2
|
||||
ATTR{idProduct}=="2ea4", ENV{adb_adbfast}="yes", SYMLINK+="android%n"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Motorola"
|
||||
|
||||
# MTK
|
||||
ATTR{idVendor}=="0e8d", ENV{adb_user}="yes"
|
||||
|
||||
# NEC
|
||||
ATTR{idVendor}=="0409", ENV{adb_user}="yes"
|
||||
|
||||
# Nextbit
|
||||
ATTR{idVendor}=="2c3f", ENV{adb_user}="yes"
|
||||
|
||||
# Nokia X
|
||||
ATTR{idVendor}=="0421", ENV{adb_user}="yes"
|
||||
|
||||
# Nokia 3
|
||||
ATTR{idVendor}=="2e04", ENV{adb_user}="yes"
|
||||
|
||||
# Nook
|
||||
ATTR{idVendor}=="2080", ENV{adb_user}="yes"
|
||||
|
||||
# Nvidia
|
||||
ATTR{idVendor}=="0955", ENV{adb_user}="yes"
|
||||
# Audi SDIS Rear Seat Entertainment Tablet
|
||||
ATTR{idProduct}=="7000", SYMLINK+="android_fastboot"
|
||||
|
||||
# OnePlus(Oreo)
|
||||
ATTR{idVendor}!="2a70", GOTO="not_OnePlus"
|
||||
ENV{adb_user}="yes"
|
||||
# Charging mode
|
||||
ATTR{idProduct}=="4ee7", SYMLINK+="android_adb"
|
||||
# MTP mode
|
||||
ATTR{idProduct}=="9011", SYMLINK+="android_adb"
|
||||
# PTP mode
|
||||
ATTR{idProduct}=="904e", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_OnePlus"
|
||||
|
||||
# Oppo
|
||||
ATTR{idVendor}=="22d9", ENV{adb_user}="yes"
|
||||
# Find 5
|
||||
ATTR{idProduct}=="2767", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="2764", SYMLINK+="libmtp-%k", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1"
|
||||
|
||||
# OTGV
|
||||
ATTR{idVendor}=="2257", ENV{adb_user}="yes"
|
||||
|
||||
# Pantech
|
||||
ATTR{idVendor}=="10a9", ENV{adb_user}="yes"
|
||||
|
||||
# Pegatron
|
||||
ATTR{idVendor}=="1d4d", ENV{adb_user}="yes"
|
||||
|
||||
# Philips
|
||||
ATTR{idVendor}=="0471", ENV{adb_user}="yes"
|
||||
|
||||
# PMC-Sierra
|
||||
ATTR{idVendor}=="04da", ENV{adb_user}="yes"
|
||||
|
||||
# Qualcomm
|
||||
ATTR{idVendor}!="05c6", GOTO="not_Qualcomm"
|
||||
ENV{adb_user}="yes"
|
||||
# Geeksphone Zero
|
||||
ATTR{idProduct}=="9025", SYMLINK+="android_adb"
|
||||
# OnePlus One
|
||||
ATTR{idProduct}=="676?", SYMLINK+="android_adb"
|
||||
# OnePlus Two
|
||||
ATTR{idProduct}=="9011", SYMLINK+="android_adb"
|
||||
# OnePlus 3
|
||||
ATTR{idProduct}=="900e", SYMLINK+="android_adb"
|
||||
# OnePlus 3T
|
||||
ATTR{idProduct}=="676c", SYMLINK+="android_adb"
|
||||
# OnePlus 3T w/ Oreo MIDI mode
|
||||
ATTR{idProduct}=="90bb", SYMLINK+="android_adb"
|
||||
# OnePlus 5
|
||||
ATTR{idProduct}=="9011", SYMLINK+="android_adb"
|
||||
# Xiaomi A1 (90bb=midi+adb)
|
||||
ATTR{idProduct}=="90bb", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Qualcomm"
|
||||
|
||||
# Research In Motion, Ltd.
|
||||
ATTR{idVendor}!="0fca", GOTO="not_RIM"
|
||||
ENV{adb_user}="yes"
|
||||
# BlackBerry DTEK60
|
||||
ATTR{idProduct}=="8042", ENV{adb_fastboot}="yes"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_RIM"
|
||||
|
||||
# SK Telesys
|
||||
ATTR{idVendor}=="1f53", ENV{adb_user}="yes"
|
||||
|
||||
# Samsung
|
||||
ATTR{idVendor}!="04e8", GOTO="not_Samsung"
|
||||
# False positive printer
|
||||
ATTR{idProduct}=="3???", GOTO="android_usb_rules_end"
|
||||
ENV{adb_user}="yes"
|
||||
# Galaxy i5700
|
||||
ATTR{idProduct}=="681c", ENV{adb_adbfast}="yes"
|
||||
# Galaxy i5800 (681c=debug,6601=fastboot,68a0=mediaplayer)
|
||||
ATTR{idProduct}=="681c", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="6601", SYMLINK+="android_fastboot"
|
||||
ATTR{idProduct}=="68a9", SYMLINK+="libmtp-%k", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1"
|
||||
# Galaxy i7500
|
||||
ATTR{idProduct}=="6640", ENV{adb_adbfast}="yes"
|
||||
# Galaxy i9000 S, i9300 S3
|
||||
ATTR{idProduct}=="6601", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="685d", MODE="0660"
|
||||
ATTR{idProduct}=="68c3", MODE="0660"
|
||||
# Galaxy Ace (S5830) "Cooper"
|
||||
ATTR{idProduct}=="689e", ENV{adb_adbfast}="yes"
|
||||
# Galaxy Tab
|
||||
ATTR{idProduct}=="6877", ENV{adb_adbfast}="yes"
|
||||
# Galaxy Nexus (GSM) (6860=mtp,adb 6864=rndis,adb 6866=ptp,adb)
|
||||
ATTR{idProduct}=="6860", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="6864", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="6866", SYMLINK+="android_adb"
|
||||
# Galaxy Core, Tab 10.1, i9100 S2, i9300 S3, N5100 Note (8.0), Galaxy S3 SHW-M440S 3G (Korea only)
|
||||
ATTR{idProduct}=="6860", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="685e", ENV{adb_adbfast}="yes"
|
||||
# Galaxy i9300 S3
|
||||
ATTR{idProduct}=="6866", SYMLINK+="libmtp-%k", ENV{ID_MTP_DEVICE}="1", ENV{ID_MEDIA_PLAYER}="1"
|
||||
# Galaxy S4 GT-I9500
|
||||
ATTR{idProduct}=="685d", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Samsung"
|
||||
|
||||
# Sharp
|
||||
ATTR{idVendor}=="04dd", ENV{adb_user}="yes"
|
||||
|
||||
# Sony
|
||||
ATTR{idVendor}=="054c", ENV{adb_user}="yes"
|
||||
|
||||
# Sony Ericsson
|
||||
ATTR{idVendor}!="0fce", GOTO="not_Sony_Ericsson"
|
||||
ENV{adb_user}="yes"
|
||||
# Xperia X10 mini
|
||||
ATTR{idProduct}=="3137"
|
||||
ATTR{idProduct}=="2137", SYMLINK+="android_adb"
|
||||
# Xperia X10 mini pro
|
||||
ATTR{idProduct}=="3138"
|
||||
ATTR{idProduct}=="2138", SYMLINK+="android_adb"
|
||||
# Xperia X8
|
||||
ATTR{idProduct}=="3149"
|
||||
ATTR{idProduct}=="2149", SYMLINK+="android_adb"
|
||||
# Xperia X12
|
||||
ATTR{idProduct}=="e14f"
|
||||
ATTR{idProduct}=="614f", SYMLINK+="android_adb"
|
||||
# Xperia Arc S
|
||||
ATTR{idProduct}=="414f", ENV{adb_adbfast}="yes"
|
||||
# Xperia Neo V (6156=debug,0dde=fastboot)
|
||||
ATTR{idProduct}=="6156", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="0dde", SYMLINK+="android_fastboot"
|
||||
# Xperia S
|
||||
ATTR{idProduct}=="5169", ENV{adb_adbfast}="yes"
|
||||
# Xperia SP
|
||||
ATTR{idProduct}=="6195", ENV{adb_adbfast}="yes"
|
||||
# Xperia L
|
||||
ATTR{idProduct}=="5192", ENV{adb_adbfast}="yes"
|
||||
# Xperia Mini Pro
|
||||
ATTR{idProduct}=="0166", ENV{adb_adbfast}="yes"
|
||||
# Xperia V
|
||||
ATTR{idProduct}=="0186", ENV{adb_adbfast}="yes"
|
||||
# Xperia Acro S
|
||||
ATTR{idProduct}=="5176", ENV{adb_adbfast}="yes"
|
||||
# Xperia Z1 Compact
|
||||
ATTR{idProduct}=="51a7", ENV{adb_adbfast}="yes"
|
||||
# Xperia Z2
|
||||
ATTR{idProduct}=="51ba", ENV{adb_adbfast}="yes"
|
||||
# Xperia Z3
|
||||
ATTR{idProduct}=="01af", ENV{adb_adbfast}="yes"
|
||||
# Xperia Z3 Compact
|
||||
ATTR{idProduct}=="01bb", ENV{adb_adbfast}="yes"
|
||||
# Xperia Z3+ Dual
|
||||
ATTR{idProduct}=="51c9", ENV{adb_adbfast}="yes"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Sony_Ericsson"
|
||||
|
||||
# Spreadtrum
|
||||
ATTR{idVendor}=="1782", ENV{adb_user}="yes"
|
||||
|
||||
# T & A Mobile Phones
|
||||
ATTR{idVendor}=="1bbb", ENV{adb_user}="yes"
|
||||
# Alcatel OT991D
|
||||
ATTR{idProduct}=="00f2", SYMLINK+="android_adb"
|
||||
# Alcatel OT6012A
|
||||
ATTR{idProduct}=="0167", SYMLINK+="android_adb"
|
||||
|
||||
# Teleepoch
|
||||
ATTR{idVendor}=="2340", ENV{adb_user}="yes"
|
||||
|
||||
# Texas Instruments UsbBoot
|
||||
ATTR{idVendor}=="0451", ATTR{idProduct}=="d00f", ENV{adb_user}="yes"
|
||||
ATTR{idVendor}=="0451", ATTR{idProduct}=="d010", ENV{adb_user}="yes"
|
||||
|
||||
# Toshiba
|
||||
ATTR{idVendor}=="0930", ENV{adb_user}="yes"
|
||||
|
||||
# WEARNERS
|
||||
ATTR{idVendor}=="05c6", ENV{adb_user}="yes"
|
||||
|
||||
# XiaoMi
|
||||
ATTR{idVendor}!="2717", GOTO="not_XiaoMi"
|
||||
ENV{adb_user}="yes"
|
||||
# Mi2A
|
||||
ATTR{idProduct}=="904e", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="9039", SYMLINK+="android_adb"
|
||||
# Mi3
|
||||
ATTR{idProduct}=="0368", SYMLINK+="android_adb"
|
||||
# RedMi 1S WCDMA (MTP+Debug)
|
||||
ATTR{idProduct}=="1268", SYMLINK+="android_adb"
|
||||
# RedMi / RedMi Note WCDMA (MTP+Debug)
|
||||
ATTR{idProduct}=="1248", SYMLINK+="android_adb"
|
||||
# RedMi 1S / RedMi / RedMi Note WCDMA (PTP+Debug)
|
||||
ATTR{idProduct}=="1218", SYMLINK+="android_adb"
|
||||
# RedMi 1S /RedMi / RedMi Note WCDMA (Usb+Debug)
|
||||
ATTR{idProduct}=="1228", SYMLINK+="android_adb"
|
||||
# RedMi / RedMi Note 4G WCDMA (MTP+Debug)
|
||||
ATTR{idProduct}=="1368", SYMLINK+="android_adb"
|
||||
# RedMi / RedMi Note 4G WCDMA (PTP+Debug)
|
||||
ATTR{idProduct}=="1318", SYMLINK+="android_adb"
|
||||
# RedMi / RedMi Note 4G WCDMA (Usb+Debug)
|
||||
ATTR{idProduct}=="1328", SYMLINK+="android_adb"
|
||||
# Mi Mix / A1 (ff88=rndis+adb, ff18=ptp+adb, ff48=mtp+adb, ff28=storage+adb)
|
||||
ATTR{idProduct}=="ff88", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="ff18", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="ff48", SYMLINK+="android_adb"
|
||||
ATTR{idProduct}=="ff28", SYMLINK+="android_adb"
|
||||
# RedMi / RedMi Note 4G CDMA (Usb+Debug) / Mi4c / Mi5
|
||||
ATTR{idProduct}=="ff68", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_XiaoMi"
|
||||
|
||||
# Yota
|
||||
ATTR{idVendor}!="2916", GOTO="not_Yota"
|
||||
ENV{adb_user}="yes"
|
||||
# YotaPhone2 (f003=normal,9139=debug)
|
||||
ATTR{idProduct}=="9139", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Yota"
|
||||
|
||||
# Wileyfox
|
||||
ATTR{idVendor}=="2970", ENV{adb_user}="yes"
|
||||
|
||||
# YU
|
||||
ATTR{idVendor}=="1ebf", ENV{adb_user}="yes"
|
||||
|
||||
# Zebra
|
||||
ATTR{idVendor}!="05e0", GOTO="not_Zebra"
|
||||
ENV{adb_user}="yes"
|
||||
# TC55
|
||||
ATTR{idProduct}=="2101", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_Zebra"
|
||||
|
||||
# ZTE
|
||||
ATTR{idVendor}!="19d2", GOTO="not_ZTE"
|
||||
ENV{adb_user}="yes"
|
||||
# Blade (1353=normal,1351=debug)
|
||||
ATTR{idProduct}=="1351", SYMLINK+="android_adb"
|
||||
# Blade S (Crescent, Orange San Francisco 2) (1355=normal,1354=debug)
|
||||
ATTR{idProduct}=="1354", SYMLINK+="android_adb"
|
||||
GOTO="android_usb_rule_match"
|
||||
LABEL="not_ZTE"
|
||||
|
||||
# Wileyfox
|
||||
ATTR{idVendor}=="2970", ENV{adb_user}="yes"
|
||||
|
||||
# YU
|
||||
ATTR{idVendor}=="1ebf", ENV{adb_user}="yes"
|
||||
|
||||
# ZUK
|
||||
ATTR{idVendor}=="2b4c", ENV{adb_user}="yes"
|
||||
|
||||
# Skip other vendor tests
|
||||
LABEL="android_usb_rule_match"
|
||||
|
||||
# Symlink shortcuts to reduce code in tests above
|
||||
ENV{adb_adbfast}=="yes", ENV{adb_adb}="yes", ENV{adb_fast}="yes"
|
||||
ENV{adb_adb}=="yes", ENV{adb_user}="yes", SYMLINK+="android_adb"
|
||||
ENV{adb_fast}=="yes", ENV{adb_user}="yes", SYMLINK+="android_fastboot"
|
||||
|
||||
# Enable device as a user device if found (add an "android" SYMLINK)
|
||||
ENV{adb_user}=="yes", MODE="0660", GROUP="adbusers", TAG+="uaccess", SYMLINK+="android"
|
||||
|
||||
# Devices listed here {begin...end} are connected by USB
|
||||
LABEL="android_usb_rules_end"
|
||||
|
||||
Vendored
+10
@@ -0,0 +1,10 @@
|
||||
|
||||
# Qualcomm EDL
|
||||
SUBSYSTEMS=="usb", ATTRS{idVendor}=="05c6", ATTRS{idProduct}=="9008", MODE="0666", GROUP="plugdev"
|
||||
|
||||
# Qualcomm Memory Debug
|
||||
SUBSYSTEMS=="usb", ATTRS{idVendor}=="05c6", ATTRS{idProduct}=="9006", MODE="0666", GROUP="plugdev"
|
||||
|
||||
# LG Memory Debug
|
||||
SUBSYSTEMS=="usb", ATTRS{idVendor}=="1004", ATTRS{idProduct}=="61a1", MODE="0666", GROUP="plugdev"
|
||||
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Bjoern Kerler
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
Whitespace-only changes.
Vendored
+487
@@ -0,0 +1,487 @@
|
||||
import xml.etree.ElementTree as ET
|
||||
import binascii
|
||||
import time
|
||||
import os
|
||||
from Library.utils import *
|
||||
|
||||
class xmlparser():
|
||||
def getresponse(self,input):
|
||||
lines=input.split(b"<?xml")
|
||||
content = {}
|
||||
for line in lines:
|
||||
if line==b'':
|
||||
continue
|
||||
line=b"<?xml"+line
|
||||
parser = ET.XMLParser(encoding="utf-8")
|
||||
tree = ET.fromstring(line, parser=parser)
|
||||
e = ET.ElementTree(tree).getroot()
|
||||
for atype in e.findall('response'):
|
||||
for field in atype.attrib:
|
||||
content[field]=atype.attrib[field]
|
||||
return content
|
||||
|
||||
def getlog(self,input):
|
||||
lines=input.split(b"<?xml")
|
||||
data = ''
|
||||
for line in lines:
|
||||
if line==b'':
|
||||
continue
|
||||
line=b"<?xml"+line
|
||||
parser = ET.XMLParser(encoding="utf-8")
|
||||
tree = ET.fromstring(line, parser=parser)
|
||||
e = ET.ElementTree(tree).getroot()
|
||||
for atype in e.findall('log'):
|
||||
if 'value' in atype.attrib:
|
||||
data+=atype.attrib['value']
|
||||
return data
|
||||
|
||||
class qualcomm_firehose:
|
||||
class cfg:
|
||||
MemoryName = "eMMC"
|
||||
TargetName = ""
|
||||
Version = ""
|
||||
ZLPAwareHost = 1
|
||||
SkipStorageInit = 0
|
||||
SkipWrite = 0
|
||||
MaxPayloadSizeToTargetInBytes = 0x100000
|
||||
SECTOR_SIZE_IN_BYTES=512
|
||||
MaxXMLSizeInBytes=4096
|
||||
bit64=True
|
||||
|
||||
def __init__(self,cdc,xml,cfg):
|
||||
self.cdc=cdc
|
||||
self.xml=xml
|
||||
self.cfg=cfg
|
||||
if self.cfg.MemoryName=="UFS":
|
||||
self.cfg.SECTOR_SIZE_IN_BYTES=4096
|
||||
|
||||
def getstatus(self,resp):
|
||||
if "value" in resp:
|
||||
value = resp["value"]
|
||||
if value == "ACK":
|
||||
return True
|
||||
return False
|
||||
|
||||
def xmlsend(self,data, skipResponse=False):
|
||||
self.cdc.write(data,self.cfg.MaxXMLSizeInBytes)
|
||||
if skipResponse:
|
||||
return True, {}
|
||||
data=bytearray()
|
||||
while b"<response" not in data:
|
||||
try:
|
||||
data+=self.cdc.read(self.cfg.MaxXMLSizeInBytes)
|
||||
except:
|
||||
break
|
||||
resp = self.xml.getresponse(data)
|
||||
return [self.getstatus(resp),resp,data]
|
||||
|
||||
def cmd_reset(self):
|
||||
data = "<?xml version=\"1.0\" ?><data><power value=\"reset\"/></data>"
|
||||
val=self.xmlsend(data)
|
||||
if val[0]==True:
|
||||
print("Reset succeeded.")
|
||||
return True
|
||||
else:
|
||||
print("Reset failed.")
|
||||
return False
|
||||
|
||||
def cmd_xml(self,data):
|
||||
val=self.xmlsend(data)
|
||||
if val[0]==True:
|
||||
print("Command succeeded.")
|
||||
print(val[2])
|
||||
return val[2]
|
||||
else:
|
||||
print("Command failed:")
|
||||
print(val[2])
|
||||
return val[2]
|
||||
|
||||
def cmd_nop(self):
|
||||
data="<?xml version=\"1.0\" ?><data><nop /></data>"
|
||||
val=self.xmlsend(data)
|
||||
if val[0]==True:
|
||||
print("Nop succeeded.")
|
||||
return True
|
||||
else:
|
||||
print("Nop failed.")
|
||||
return False
|
||||
|
||||
def cmd_getsha256digest(self,physical_partition_number,start_sector,num_partition_sectors):
|
||||
data=f"<?xml version=\"1.0\" ?><data><getsha256digest SECTOR_SIZE_IN_BYTES=\"{self.cfg.SECTOR_SIZE_IN_BYTES}\""+\
|
||||
f" num_partition_sectors=\"{num_partition_sectors}\""+\
|
||||
f" physical_partition_number=\"{physical_partition_number}\""+\
|
||||
f" start_sector=\"{start_sector}\"/>\n</data>"
|
||||
val=self.xmlsend(data)
|
||||
if val[0]==True:
|
||||
res = self.xml.getlog(val[2])
|
||||
print(res)
|
||||
if "Digest " in res:
|
||||
return res.split("Digest ")[1]
|
||||
else:
|
||||
return res
|
||||
else:
|
||||
print("GetSha256Digest failed.")
|
||||
return False
|
||||
|
||||
def cmd_setbootablestoragedrive(self,partition_number):
|
||||
data=f"<?xml version=\"1.0\" ?><data>\n<setbootablestoragedrive value=\"{hex(partition_number)}\" /></data>"
|
||||
val=self.xmlsend(data)
|
||||
if val[0]==True:
|
||||
print("Setbootablestoragedrive succeeded.")
|
||||
return True
|
||||
else:
|
||||
print("Setbootablestoragedrive failed.")
|
||||
return False
|
||||
|
||||
|
||||
def wait_response(self):
|
||||
data = bytearray()
|
||||
while b"<response" not in data:
|
||||
try:
|
||||
data += self.cdc.read(self.cfg.MaxXMLSizeInBytes)
|
||||
except:
|
||||
break
|
||||
info = self.xml.getlog(data)
|
||||
rsp = self.xml.getresponse(data)
|
||||
return info, rsp
|
||||
|
||||
def cmd_write(self,physical_partition_number,start_sector,filename,Display=True):
|
||||
size = os.stat(filename).st_size
|
||||
with open(filename,"rb") as rf:
|
||||
#Make sure we fill data up to the sector size
|
||||
num_partition_sectors=size // self.cfg.SECTOR_SIZE_IN_BYTES
|
||||
if (size%self.cfg.SECTOR_SIZE_IN_BYTES)!=0:
|
||||
num_partition_sectors+=1
|
||||
if Display:
|
||||
print(
|
||||
f"\nWriting to physical partition {str(physical_partition_number)}, sector {str(start_sector)}, sectors {str(num_partition_sectors)}")
|
||||
data=f"<?xml version=\"1.0\" ?><data>\n"+\
|
||||
f"<program SECTOR_SIZE_IN_BYTES=\"{self.cfg.SECTOR_SIZE_IN_BYTES}\""+\
|
||||
f" num_partition_sectors=\"{num_partition_sectors}\""+\
|
||||
f" physical_partition_number=\"{physical_partition_number}\""+\
|
||||
f" start_sector=\"{start_sector}\"/>\n</data>"
|
||||
rsp = self.xmlsend(data)
|
||||
pos=0
|
||||
prog=0
|
||||
if Display:
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
if (rsp[0]) == True:
|
||||
bytesToWrite = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors
|
||||
total=self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors
|
||||
old=0
|
||||
while (bytesToWrite>0):
|
||||
wdata=rf.read(self.cfg.MaxPayloadSizeToTargetInBytes)
|
||||
wlen=len(wdata)
|
||||
if (wlen % self.cfg.SECTOR_SIZE_IN_BYTES) != 0:
|
||||
filllen=(wlen//self.cfg.SECTOR_SIZE_IN_BYTES*self.cfg.SECTOR_SIZE_IN_BYTES)+self.cfg.SECTOR_SIZE_IN_BYTES
|
||||
wdata+=b"\x00"*(filllen-wlen)
|
||||
wlen=len(wdata)
|
||||
self.cdc.write(wdata,self.cfg.MaxPayloadSizeToTargetInBytes)
|
||||
prog = int(float(pos) / float(total) * float(100))
|
||||
if (prog > old):
|
||||
if Display:
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
old = prog
|
||||
bytesToWrite -= wlen
|
||||
pos+=wlen
|
||||
#time.sleep(0.05)
|
||||
if Display and prog!=100:
|
||||
print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
self.cdc.write(b'',self.cfg.MaxPayloadSizeToTargetInBytes)
|
||||
time.sleep(0.2)
|
||||
info, rsp = self.wait_response()
|
||||
if rsp.get("value") == "ACK":
|
||||
return True
|
||||
else:
|
||||
print(f"Error:{info}")
|
||||
return False
|
||||
else:
|
||||
print(f"Error:{rsp}")
|
||||
return False
|
||||
return False
|
||||
|
||||
def cmd_erase(self,physical_partition_number,start_sector,num_partition_sectors,Display=True):
|
||||
if Display:
|
||||
print(f"\nErasing from physical partition {str(physical_partition_number)}, sector {str(start_sector)}, sectors {str(num_partition_sectors)}")
|
||||
data=f"<?xml version=\"1.0\" ?><data>\n"+\
|
||||
f"<program SECTOR_SIZE_IN_BYTES=\"{self.cfg.SECTOR_SIZE_IN_BYTES}\""+\
|
||||
f" num_partition_sectors=\"{num_partition_sectors}\""+\
|
||||
f" physical_partition_number=\"{physical_partition_number}\""+\
|
||||
f" start_sector=\"{start_sector}\"/>\n</data>"
|
||||
rsp = self.xmlsend(data)
|
||||
empty = b"\x00" * self.cfg.MaxPayloadSizeToTargetInBytes
|
||||
pos=0
|
||||
prog=0
|
||||
if Display:
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
if (rsp[0]) == True:
|
||||
bytesToWrite = self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors
|
||||
total=self.cfg.SECTOR_SIZE_IN_BYTES * num_partition_sectors
|
||||
old=0
|
||||
while (bytesToWrite>0):
|
||||
wlen=self.cfg.MaxPayloadSizeToTargetInBytes
|
||||
if bytesToWrite<wlen:
|
||||
wlen=bytesToWrite
|
||||
self.cdc.write(empty[0:wlen],self.cfg.MaxPayloadSizeToTargetInBytes)
|
||||
prog = int(float(pos) / float(total) * float(100))
|
||||
if (prog > old):
|
||||
if Display:
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
old = prog
|
||||
bytesToWrite -= wlen
|
||||
pos+=wlen
|
||||
#time.sleep(0.05)
|
||||
if Display and prog!=100:
|
||||
print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
self.cdc.write(b'',self.cfg.MaxPayloadSizeToTargetInBytes)
|
||||
time.sleep(0.2)
|
||||
info, rsp = self.wait_response()
|
||||
if rsp.get("value")=="ACK":
|
||||
return True
|
||||
else:
|
||||
print(f"Error:{info}")
|
||||
else:
|
||||
print(f"Error:{rsp}")
|
||||
return False
|
||||
return False
|
||||
|
||||
def cmd_read_buffer(self,physical_partition_number,start_sector,num_partition_sectors,Display=True):
|
||||
if Display:
|
||||
print(f"\nReading from physical partition {str(physical_partition_number)}, sector {str(start_sector)}, sectors {str(num_partition_sectors)}")
|
||||
data=f"<?xml version=\"1.0\" ?><data><read SECTOR_SIZE_IN_BYTES=\"{self.cfg.SECTOR_SIZE_IN_BYTES}\""+\
|
||||
f" num_partition_sectors=\"{num_partition_sectors}\""+\
|
||||
f" physical_partition_number=\"{physical_partition_number}\""+\
|
||||
f" start_sector=\"{start_sector}\"/>\n</data>"
|
||||
rsp=self.xmlsend(data, True)
|
||||
resData=bytearray()
|
||||
if (rsp[0])==True:
|
||||
bytesToRead=self.cfg.SECTOR_SIZE_IN_BYTES*num_partition_sectors
|
||||
total=bytesToRead
|
||||
dataread=0
|
||||
old=0
|
||||
prog=0
|
||||
if Display:
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
while(bytesToRead>0):
|
||||
tmp=self.cdc.read(self.cfg.MaxPayloadSizeToTargetInBytes)
|
||||
bytesToRead-=len(tmp)
|
||||
dataread+=len(tmp)
|
||||
resData+=tmp
|
||||
prog = int(float(dataread) / float(total) * float(100))
|
||||
if (prog > old):
|
||||
if Display:
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
old = prog
|
||||
if Display and prog!=100:
|
||||
print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
time.sleep(0.2)
|
||||
info, rsp = self.wait_response()
|
||||
if rsp.get("value")=="ACK":
|
||||
return resData
|
||||
else:
|
||||
print(f"Error:{info}")
|
||||
return ""
|
||||
else:
|
||||
print(f"Error:{rsp[2]}")
|
||||
return ""
|
||||
return ""
|
||||
|
||||
def cmd_read(self,physical_partition_number,start_sector,num_partition_sectors,filename,Display=True):
|
||||
if Display:
|
||||
print(f"\nReading from physical partition {str(physical_partition_number)}, sector {str(start_sector)}, sectors {str(num_partition_sectors)}")
|
||||
with open(filename,"wb") as wf:
|
||||
data=f"<?xml version=\"1.0\" ?><data><read SECTOR_SIZE_IN_BYTES=\"{self.cfg.SECTOR_SIZE_IN_BYTES}\""+\
|
||||
f" num_partition_sectors=\"{num_partition_sectors}\""+\
|
||||
f" physical_partition_number=\"{physical_partition_number}\""+\
|
||||
f" start_sector=\"{start_sector}\"/>\n</data>"
|
||||
rsp=self.xmlsend(data, True)
|
||||
if (rsp[0])==True:
|
||||
bytesToRead=self.cfg.SECTOR_SIZE_IN_BYTES*num_partition_sectors
|
||||
total=bytesToRead
|
||||
dataread=0
|
||||
old=0
|
||||
prog=0
|
||||
if Display:
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
while(bytesToRead>0):
|
||||
tmp=self.cdc.read(self.cfg.MaxPayloadSizeToTargetInBytes)
|
||||
bytesToRead-=len(tmp)
|
||||
dataread+=len(tmp)
|
||||
#resData+=tmp
|
||||
wf.write(tmp)
|
||||
prog = int(float(dataread) / float(total) * float(100))
|
||||
if (prog > old):
|
||||
if Display:
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
old = prog
|
||||
#time.sleep(0.05)
|
||||
if Display and prog!=100:
|
||||
print_progress(100, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
time.sleep(0.2)
|
||||
info, rsp = self.wait_response()
|
||||
if rsp.get("value")=="ACK":
|
||||
return tmp
|
||||
else:
|
||||
print(f"Error:{info}")
|
||||
return ""
|
||||
else:
|
||||
print(f"Error:{rsp[1]}")
|
||||
return ""
|
||||
return ""
|
||||
|
||||
def connect(self,lvl):
|
||||
v = b'-1'
|
||||
try:
|
||||
while v != b'':
|
||||
v = self.cdc.read()
|
||||
info=self.xml.getlog(v)
|
||||
print(info)
|
||||
except:
|
||||
lvl=lvl
|
||||
data=f"<?xml version =\"1.0\" ?><data>"+\
|
||||
f"<configure MemoryName=\"{self.cfg.MemoryName}\" ZLPAwareHost=\"{str(self.cfg.ZLPAwareHost)}\" "+\
|
||||
f"SkipStorageInit=\"{str(int(self.cfg.SkipStorageInit))}\" SkipWrite=\"{str(int(self.cfg.SkipWrite))}\" "+\
|
||||
f"MaxPayloadSizeToTargetInBytes=\"{str(self.cfg.MaxPayloadSizeToTargetInBytes)}\"/>"+\
|
||||
"</data>"
|
||||
'''
|
||||
"<?xml version=\"1.0\" encoding=\"UTF-8\" ?><data><response value=\"ACK\" MinVersionSupported=\"1\"" \
|
||||
"MemoryName=\"eMMC\" MaxPayloadSizeFromTargetInBytes=\"4096\" MaxPayloadSizeToTargetInBytes=\"1048576\" " \
|
||||
"MaxPayloadSizeToTargetInBytesSupported=\"1048576\" MaxXMLSizeInBytes=\"4096\" Version=\"1\" TargetName=\"8953\" />" \
|
||||
"</data>"
|
||||
'''
|
||||
rsp=self.xmlsend(data)
|
||||
try:
|
||||
self.cdc.read()
|
||||
except:
|
||||
lvl=lvl
|
||||
|
||||
if rsp[0]==True:
|
||||
self.cfg.MemoryName=rsp[1]["MemoryName"]
|
||||
self.cfg.MaxPayloadSizeToTargetInBytes=int(rsp[1]["MaxPayloadSizeToTargetInBytes"])
|
||||
self.cfg.MaxPayloadSizeToTargetInBytesSupported=int(rsp[1]["MaxPayloadSizeToTargetInBytesSupported"])
|
||||
self.cfg.MaxXMLSizeInBytes=int(rsp[1]["MaxXMLSizeInBytes"])
|
||||
if "MaxPayloadSizeFromTargetInBytes" in rsp[1]:
|
||||
self.cfg.MaxPayloadSizeFromTargetInBytes=int(rsp[1]["MaxPayloadSizeFromTargetInBytes"])
|
||||
else:
|
||||
#print("Unknown cmd structure, please issue this to github: "+str(rsp[1]))
|
||||
self.cfg.MaxPayloadSizeFromTargetInBytes=self.cfg.MaxXMLSizeInBytes
|
||||
if "TargetName" in rsp[1]:
|
||||
self.cfg.TargetName=rsp[1]["TargetName"]
|
||||
if "MSM" not in self.cfg.TargetName:
|
||||
self.cfg.TargetName="MSM"+self.cfg.TargetName
|
||||
else:
|
||||
self.cfg.TargetName="Unknown"
|
||||
if "Version" in rsp[1]:
|
||||
self.cfg.Version=rsp[1]["Version"]
|
||||
else:
|
||||
self.cfg.Version="0"
|
||||
else:
|
||||
if "MaxPayloadSizeToTargetInBytes" in rsp[1]:
|
||||
self.cfg.MemoryName = rsp[1]["MemoryName"]
|
||||
self.cfg.MaxPayloadSizeToTargetInBytes = int(rsp[1]["MaxPayloadSizeToTargetInBytes"])
|
||||
self.cfg.MaxPayloadSizeToTargetInBytesSupported = int(rsp[1]["MaxPayloadSizeToTargetInBytesSupported"])
|
||||
self.cfg.MaxXMLSizeInBytes = int(rsp[1]["MaxXMLSizeInBytes"])
|
||||
self.cfg.MaxPayloadSizeFromTargetInBytes = int(rsp[1]["MaxPayloadSizeFromTargetInBytes"])
|
||||
self.cfg.TargetName = rsp[1]["TargetName"]
|
||||
if "MSM" not in self.cfg.TargetName:
|
||||
self.cfg.TargetName = "MSM" + self.cfg.TargetName
|
||||
self.cfg.Version = rsp[1]["Version"]
|
||||
if lvl==0:
|
||||
return self.connect(lvl+1)
|
||||
else:
|
||||
print(f"Error:{rsp}")
|
||||
exit(0)
|
||||
print(f"TargetName={self.cfg.TargetName}")
|
||||
print(f"MemoryName={self.cfg.MemoryName}")
|
||||
print(f"Version={self.cfg.Version}")
|
||||
if self.cfg.MemoryName.lower()=="emmc":
|
||||
self.cfg.SECTOR_SIZE_IN_BYTES=512
|
||||
elif self.cfg.MemoryName.lower()=="ufs":
|
||||
self.cfg.SECTOR_SIZE_IN_BYTES = 4096
|
||||
return True
|
||||
|
||||
# OEM Stuff here below --------------------------------------------------
|
||||
|
||||
def cmd_writeimei(self,imei):
|
||||
if len(imei)!=16:
|
||||
print("IMEI must be 16 digits")
|
||||
return False
|
||||
data="<?xml version=\"1.0\" ?><data><writeIMEI len=\"16\"/></data>"
|
||||
val=self.xmlsend(data)
|
||||
if val[0]==True:
|
||||
print("writeIMEI succeeded.")
|
||||
return True
|
||||
else:
|
||||
print("writeIMEI failed.")
|
||||
return False
|
||||
|
||||
def cmd_getstorageinfo(self):
|
||||
data="<?xml version=\"1.0\" ?><data><getstorageinfo /></data>"
|
||||
val=self.xmlsend(data)
|
||||
if val[0]==True:
|
||||
print(f"GetStorageInfo:\n--------------------\n")
|
||||
print(val[1])
|
||||
return True
|
||||
else:
|
||||
print("GetStorageInfo command isn't supported.")
|
||||
return False
|
||||
|
||||
def cmd_peek(self,address,SizeInBytes,filename):
|
||||
print(f"Peek: Address({hex(address)}),Size({hex(SizeInBytes)})")
|
||||
with open(filename,"wb") as wf:
|
||||
'''
|
||||
<?xml version="1.0" ?><data><peek address64="1048576" SizeInBytes="90112" /></data>
|
||||
'''
|
||||
data=f"<?xml version=\"1.0\" ?><data><peek address64=\"{address}\" SizeInBytes=\"{SizeInBytes}\" /></data>\n"
|
||||
'''
|
||||
<?xml version="1.0" encoding="UTF-8" ?><data><log value="Using address 00100000" /></data>
|
||||
<?xml version="1.0" encoding="UTF-8" ?><data><log value="0x22 0x00 0x00 0xEA 0x70 0x00 0x00 0xEA 0x74 0x00 0x00 0xEA 0x78 0x00 0
|
||||
x00 0xEA 0x7C 0x00 0x00 0xEA 0x80 0x00 0x00 0xEA 0x84 0x00 0x00 0xEA 0x88 0x00 0x00 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA
|
||||
0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0x
|
||||
FF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF
|
||||
0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF 0xFF 0xEA 0xFE 0xFF " /></data>
|
||||
'''
|
||||
try:
|
||||
self.cdc.write(data, self.cfg.MaxXMLSizeInBytes)
|
||||
except:
|
||||
data=data
|
||||
addrinfo=self.cdc.read(self.cfg.MaxXMLSizeInBytes)
|
||||
if (b"size_in_bytes" in addrinfo):
|
||||
tmp=b""
|
||||
while b"NAK" not in tmp and b"ACK" not in tmp:
|
||||
tmp+=self.cdc.read(self.cfg.MaxXMLSizeInBytes)
|
||||
data = f"<?xml version=\"1.0\" ?><data><peek address64=\"{hex(address)}\" size_in_bytes=\"{hex(SizeInBytes)}\" /></data>"
|
||||
self.cdc.write(data, self.cfg.MaxXMLSizeInBytes)
|
||||
addrinfo = self.cdc.read(self.cfg.MaxXMLSizeInBytes)
|
||||
if b'<response' in addrinfo and 'NAK' in addrinfo:
|
||||
print(f"Error:{addrinfo}")
|
||||
return
|
||||
if (b"address" in addrinfo and b"can\'t" in addrinfo):
|
||||
tmp=b""
|
||||
while b"NAK" not in tmp and b"ACK" not in tmp:
|
||||
tmp+=self.cdc.read(self.cfg.MaxXMLSizeInBytes)
|
||||
print(f"Error:{addrinfo}")
|
||||
return
|
||||
|
||||
data=bytearray()
|
||||
dataread=0
|
||||
old=0
|
||||
print_progress(0, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
while (True):
|
||||
tmp=self.cdc.read(self.cfg.MaxXMLSizeInBytes)
|
||||
if b'<response' in tmp or b"ERROR" in tmp:
|
||||
break
|
||||
tmp2=binascii.unhexlify(self.xml.getlog(tmp).replace("0x","").replace(" ",""))
|
||||
dataread+=len(tmp2)
|
||||
wf.write(tmp2)
|
||||
prog = int(float(dataread) / float(SizeInBytes) * float(100))
|
||||
if (prog > old):
|
||||
print_progress(prog, 100, prefix='Progress:', suffix='Complete', bar_length=50)
|
||||
old=prog
|
||||
|
||||
if b'<response' in tmp and b'ACK' in tmp:
|
||||
print(f"Bytes from {hex(address)}, bytes read {hex(dataread)}, written to {filename}.")
|
||||
return True
|
||||
else:
|
||||
print(f"Error:{addrinfo}")
|
||||
return True
|
||||
Vendored
+187
@@ -0,0 +1,187 @@
|
||||
import binascii
|
||||
from Library.utils import *
|
||||
|
||||
class gpt:
|
||||
from enum import Enum
|
||||
gpt_header = [
|
||||
('signature', '8s'),
|
||||
('revision', '>I'),
|
||||
('header_size', 'I'),
|
||||
('crc32', 'I'),
|
||||
('reserved', 'I'),
|
||||
('current_lba', 'Q'),
|
||||
('backup_lba', 'Q'),
|
||||
('first_usable_lba', 'Q'),
|
||||
('last_usable_lba', 'Q'),
|
||||
('disk_guid', '16s'),
|
||||
('part_entry_start_lba', 'Q')
|
||||
]
|
||||
|
||||
gpt_partition = [
|
||||
('type', '16s'),
|
||||
('unique', '16s'),
|
||||
('first_lba', 'Q'),
|
||||
('last_lba', 'Q'),
|
||||
('flags', '>Q'),
|
||||
('name', '72s')]
|
||||
|
||||
class efi_type(Enum):
|
||||
EFI_UNUSED = 0x00000000
|
||||
EFI_MBR = 0x024DEE41
|
||||
EFI_SYSTEM = 0xC12A7328
|
||||
EFI_BIOS_BOOT = 0x21686148
|
||||
EFI_IFFS = 0xD3BFE2DE
|
||||
EFI_SONY_BOOT = 0xF4019732
|
||||
EFI_LENOVO_BOOT = 0xBFBFAFE7
|
||||
EFI_MSR = 0xE3C9E316
|
||||
EFI_BASIC_DATA = 0xEBD0A0A2
|
||||
EFI_LDM_META = 0x5808C8AA
|
||||
EFI_LDM = 0xAF9B60A0
|
||||
EFI_RECOVERY = 0xDE94BBA4
|
||||
EFI_GPFS = 0x37AFFC90
|
||||
EFI_STORAGE_SPACES = 0xE75CAF8F
|
||||
EFI_HPUX_DATA = 0x75894C1E
|
||||
EFI_HPUX_SERVICE = 0xE2A1E728
|
||||
EFI_LINUX_DAYA = 0x0FC63DAF
|
||||
EFI_LINUX_RAID = 0xA19D880F
|
||||
EFI_LINUX_ROOT32 = 0x44479540
|
||||
EFI_LINUX_ROOT64 = 0x4F68BCE3
|
||||
EFI_LINUX_ROOT_ARM32 = 0x69DAD710
|
||||
EFI_LINUX_ROOT_ARM64 = 0xB921B045
|
||||
EFI_LINUX_SWAP = 0x0657FD6D
|
||||
EFI_LINUX_LVM = 0xE6D6D379
|
||||
EFI_LINUX_HOME = 0x933AC7E1
|
||||
EFI_LINUX_SRV = 0x3B8F8425
|
||||
EFI_LINUX_DM_CRYPT = 0x7FFEC5C9
|
||||
EFI_LINUX_LUKS = 0xCA7D7CCB
|
||||
EFI_LINUX_RESERVED = 0x8DA63339
|
||||
EFI_FREEBSD_BOOT = 0x83BD6B9D
|
||||
EFI_FREEBSD_DATA = 0x516E7CB4
|
||||
EFI_FREEBSD_SWAP = 0x516E7CB5
|
||||
EFI_FREEBSD_UFS = 0x516E7CB6
|
||||
EFI_FREEBSD_VINUM = 0x516E7CB8
|
||||
EFI_FREEBSD_ZFS = 0x516E7CBA
|
||||
EFI_OSX_HFS = 0x48465300
|
||||
EFI_OSX_UFS = 0x55465300
|
||||
EFI_OSX_ZFS = 0x6A898CC3
|
||||
EFI_OSX_RAID = 0x52414944
|
||||
EFI_OSX_RAID_OFFLINE = 0x52414944
|
||||
EFI_OSX_RECOVERY = 0x426F6F74
|
||||
EFI_OSX_LABEL = 0x4C616265
|
||||
EFI_OSX_TV_RECOVERY = 0x5265636F
|
||||
EFI_OSX_CORE_STORAGE = 0x53746F72
|
||||
EFI_SOLARIS_BOOT = 0x6A82CB45
|
||||
EFI_SOLARIS_ROOT = 0x6A85CF4D
|
||||
EFI_SOLARIS_SWAP = 0x6A87C46F
|
||||
EFI_SOLARIS_BACKUP = 0x6A8B642B
|
||||
EFI_SOLARIS_USR = 0x6A898CC3
|
||||
EFI_SOLARIS_VAR = 0x6A8EF2E9
|
||||
EFI_SOLARIS_HOME = 0x6A90BA39
|
||||
EFI_SOLARIS_ALTERNATE = 0x6A9283A5
|
||||
EFI_SOLARIS_RESERVED1 = 0x6A945A3B
|
||||
EFI_SOLARIS_RESERVED2 = 0x6A9630D1
|
||||
EFI_SOLARIS_RESERVED3 = 0x6A980767
|
||||
EFI_SOLARIS_RESERVED4 = 0x6A96237F
|
||||
EFI_SOLARIS_RESERVED5 = 0x6A8D2AC7
|
||||
EFI_NETBSD_SWAP = 0x49F48D32
|
||||
EFI_NETBSD_FFS = 0x49F48D5A
|
||||
EFI_NETBSD_LFS = 0x49F48D82
|
||||
EFI_NETBSD_RAID = 0x49F48DAA
|
||||
EFI_NETBSD_CONCAT = 0x2DB519C4
|
||||
EFI_NETBSD_ENCRYPT = 0x2DB519EC
|
||||
EFI_CHROMEOS_KERNEL = 0xFE3A2A5D
|
||||
EFI_CHROMEOS_ROOTFS = 0x3CB8E202
|
||||
EFI_CHROMEOS_FUTURE = 0x2E0A753D
|
||||
EFI_HAIKU = 0x42465331
|
||||
EFI_MIDNIGHTBSD_BOOT = 0x85D5E45E
|
||||
EFI_MIDNIGHTBSD_DATA = 0x85D5E45A
|
||||
EFI_MIDNIGHTBSD_SWAP = 0x85D5E45B
|
||||
EFI_MIDNIGHTBSD_UFS = 0x0394EF8B
|
||||
EFI_MIDNIGHTBSD_VINUM = 0x85D5E45C
|
||||
EFI_MIDNIGHTBSD_ZFS = 0x85D5E45D
|
||||
EFI_CEPH_JOURNAL = 0x45B0969E
|
||||
EFI_CEPH_ENCRYPT = 0x45B0969E
|
||||
EFI_CEPH_OSD = 0x4FBD7E29
|
||||
EFI_CEPH_ENCRYPT_OSD = 0x4FBD7E29
|
||||
EFI_CEPH_CREATE = 0x89C57F98
|
||||
EFI_CEPH_ENCRYPT_CREATE = 0x89C57F98
|
||||
EFI_OPENBSD = 0x824CC7A0
|
||||
EFI_QNX = 0xCEF5A9AD
|
||||
EFI_PLAN9 = 0xC91818F9
|
||||
EFI_VMWARE_VMKCORE = 0x9D275380
|
||||
EFI_VMWARE_VMFS = 0xAA31E02A
|
||||
EFI_VMWARE_RESERVED = 0x9198EFFC
|
||||
|
||||
def __init__(self, num_part_entries=None, part_entry_size=None, part_entry_start_lba=None, *args, **kwargs):
|
||||
self.num_part_entries = num_part_entries
|
||||
self.part_entry_size = part_entry_size
|
||||
self.part_entry_start_lba = part_entry_start_lba
|
||||
self.gpt_header = list(gpt.gpt_header)
|
||||
if num_part_entries is None:
|
||||
self.gpt_header += [('num_part_entries', 'I'),]
|
||||
if part_entry_size is None:
|
||||
self.gpt_header += [('part_entry_size', 'I'),]
|
||||
|
||||
|
||||
def parse(self, gptdata, sectorsize=512):
|
||||
self.header = read_object(gptdata[sectorsize:sectorsize+0x5C], self.gpt_header)
|
||||
self.sectorsize=sectorsize
|
||||
if self.header["signature"]!=b"EFI PART":
|
||||
print("Invalid or unknown GPT magic.")
|
||||
return False
|
||||
if self.header["revision"]!=0x100:
|
||||
print("Unknown GPT revision.")
|
||||
return False
|
||||
if self.part_entry_start_lba is not None:
|
||||
start = self.part_entry_start_lba
|
||||
else:
|
||||
start=self.header["part_entry_start_lba"]*sectorsize
|
||||
if "part_entry_size" in self.header:
|
||||
entrysize=self.header["part_entry_size"]
|
||||
else:
|
||||
entrysize=self.part_entry_size
|
||||
self.partentries=[]
|
||||
|
||||
class partf:
|
||||
unique=b""
|
||||
first_lba=0
|
||||
last_lba=0
|
||||
flags=0
|
||||
type=b""
|
||||
name=b""
|
||||
|
||||
if "num_part_entries" in self.header:
|
||||
num_part_entries=self.header["num_part_entries"]
|
||||
else:
|
||||
num_part_entries=self.num_part_entries
|
||||
|
||||
for idx in range(0,num_part_entries):
|
||||
data=gptdata[start+(idx*entrysize):start+(idx*entrysize)+entrysize]
|
||||
partentry=read_object(data,self.gpt_partition)
|
||||
pa=partf()
|
||||
guid1=struct.unpack("<I",partentry["unique"][0:0x4])[0]
|
||||
guid2=struct.unpack("<H",partentry["unique"][0x4:0x6])[0]
|
||||
guid3=struct.unpack("<H",partentry["unique"][0x6:0x8])[0]
|
||||
guid4=struct.unpack("<H",partentry["unique"][0x8:0xA])[0]
|
||||
guid5=binascii.hexlify(partentry["unique"][0xA:0x10]).decode('utf-8')
|
||||
pa.unique = "{:08x}-{:04x}-{:04x}-{:04x}-{}".format(guid1,guid2,guid3,guid4,guid5)
|
||||
pa.sector = partentry["first_lba"]
|
||||
pa.sectors = partentry["last_lba"]-partentry["first_lba"]+1
|
||||
pa.flags = partentry["flags"]
|
||||
type=int(struct.unpack("<I",partentry["type"][0:0x4])[0])
|
||||
try:
|
||||
pa.type = self.efi_type(type).name
|
||||
except:
|
||||
pa.type = hex(type)
|
||||
pa.name = partentry["name"].replace(b"\x00\x00",b"").decode('utf-16')
|
||||
if pa.type=="EFI_UNUSED":
|
||||
break
|
||||
self.partentries.append(pa)
|
||||
self.totalsectors=self.header["last_usable_lba"]
|
||||
return True
|
||||
|
||||
def print(self):
|
||||
print("\nGPT Table:\n-------------")
|
||||
for partition in self.partentries:
|
||||
print("{:20} Offset 0x{:016x}, Length 0x{:016x}, Flags 0x{:08x}, UUID {}, Type {}".format(partition.name+":",partition.sector*self.sectorsize,partition.sectors*self.sectorsize,partition.flags,partition.unique,partition.type))
|
||||
print("\nTotal disk size:0x{:016x}, sectors:0x{:016x}".format(self.totalsectors*self.sectorsize,self.totalsectors))
|
||||
Vendored
+71
@@ -0,0 +1,71 @@
|
||||
import os
|
||||
import pt64
|
||||
import pt
|
||||
import argparse
|
||||
|
||||
def pt64_walk(data, ttbr, tnsz, levels=3):
|
||||
print("Dumping page tables (levels=%d)" % levels)
|
||||
print("First level (ptbase = %016x)" % ttbr)
|
||||
print("---------------------------------------------")
|
||||
fl = data[ttbr-ttbr:ttbr-ttbr+0x1000]
|
||||
|
||||
if levels <= 1:
|
||||
return
|
||||
|
||||
for (va, fle) in pt64.parse_pt(fl, 0, tnsz, 1):
|
||||
if "TABLE" in str(fle):
|
||||
print("Second level (ptbase = %016x)" % fle.output)
|
||||
print("---------------------------------------------")
|
||||
|
||||
sl = data[fle.output-ttbr:fle.output-ttbr+0x4000]
|
||||
sl = pt64.parse_pt(sl, va, tnsz, 2)
|
||||
|
||||
if levels <= 2:
|
||||
continue
|
||||
|
||||
for (va, sle) in sl:
|
||||
if "TABLE" in str(sle):
|
||||
print("Third level (ptbase = %016x)" % sle.output)
|
||||
print("---------------------------------------------")
|
||||
tl = data[sle.output-ttbr:sle.output-ttbr+0x1000]
|
||||
pt64.parse_pt(tl, va, tnsz, 3)
|
||||
|
||||
|
||||
def pt32_walk(data, ttbr, skip):
|
||||
print("First level (va = %08x)" % ttbr)
|
||||
print("---------------------------------------------")
|
||||
fl = data[ttbr-ttbr:ttbr-ttbr+0x4000]
|
||||
|
||||
i = 0
|
||||
for (va, fl) in pt.parse_pt(fl):
|
||||
i += 1
|
||||
if i <= skip:
|
||||
continue
|
||||
if type(fl) == pt.pt_desc:
|
||||
print("")
|
||||
print("Second level (va = %08x)" % va)
|
||||
print("---------------------------------------------")
|
||||
sldata = data[fl.coarse_base-ttbr:fl.coarse_base-ttbr+0x400]
|
||||
pt.parse_spt(sldata, va)
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(\
|
||||
prog="memparse",
|
||||
usage="python memparse.py -arch <32,64> -in <filename> -mem <offset>",
|
||||
formatter_class=argparse.RawTextHelpFormatter)
|
||||
parser.add_argument('-in', '--in', dest='infile', help='memory dump', default="")
|
||||
parser.add_argument('-arch', '--arch', dest='arch', help='architecture=32,64', default="32")
|
||||
parser.add_argument('-mem', '--mem', dest='mem', help='memoryoffset', default="0x200000")
|
||||
args = parser.parse_args()
|
||||
if (args.infile==""):
|
||||
print("You need to add an -in [memorydump filename]")
|
||||
return
|
||||
|
||||
with open(args.infile,"rb") as rf:
|
||||
data=rf.read()
|
||||
if args.arch=="32":
|
||||
pt32_walk(data,int(args.mem,16),False)
|
||||
else:
|
||||
pt64_walk(data,int(args.mem,16),0,3)
|
||||
|
||||
main()
|
||||
Vendored
+171
@@ -0,0 +1,171 @@
|
||||
import struct
|
||||
|
||||
|
||||
def get_n(x):
|
||||
return int(x[6:8]+x[4:6]+x[2:4]+x[0:2], 16)
|
||||
|
||||
|
||||
def parse_pt(data):
|
||||
va = 0
|
||||
entries = []
|
||||
while va < len(data):
|
||||
entry = struct.unpack("<L", data[va:va+4])[0]
|
||||
f = get_fld(entry)
|
||||
|
||||
if f is None:
|
||||
va += 4
|
||||
continue
|
||||
|
||||
entries.append((int(va/4) << 20,f))
|
||||
print("%08x %s" % ((int(va/4) << 20), str(f)))
|
||||
va += 4
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def parse_spt(data, base):
|
||||
va = 0
|
||||
while va < 0x400:
|
||||
entry = struct.unpack("<L", data[va:va+4])[0]
|
||||
|
||||
f = get_sld(entry)
|
||||
if (f!='UNSUPPORTED' and f.apx==0 and f.ap==3 and f.nx==0):
|
||||
print("%08x %s - WX !!" % (base + (int(va / 4) << 12), f))
|
||||
else:
|
||||
print("%08x %s" % (base+(int(va/4) << 12), f))
|
||||
va += 4
|
||||
|
||||
|
||||
def get_fld(fld):
|
||||
s = fld & 3
|
||||
if s == 0:
|
||||
return fault_desc(fld)
|
||||
|
||||
if s == 1:
|
||||
return pt_desc(fld)
|
||||
|
||||
if s == 2:
|
||||
return section_desc(fld)
|
||||
|
||||
if s == 3:
|
||||
return reserved_desc(fld)
|
||||
|
||||
|
||||
def get_sld(sld):
|
||||
s = sld & 3
|
||||
if s == 1:
|
||||
return sld_lp(sld)
|
||||
|
||||
if s > 1:
|
||||
return sld_xsp(sld)
|
||||
|
||||
return "UNSUPPORTED"
|
||||
|
||||
|
||||
class descriptor(object):
|
||||
def __init__(self, fld):
|
||||
pass
|
||||
|
||||
def __repr__(self):
|
||||
s = "%8s " % self.get_name()
|
||||
for attr, value in self.__dict__.items():
|
||||
try:
|
||||
s += "%s=%s, " % (attr, hex(value))
|
||||
except:
|
||||
s += "%s=%s, " % (attr, value)
|
||||
|
||||
return s
|
||||
|
||||
|
||||
class fld(descriptor):
|
||||
pass
|
||||
|
||||
|
||||
class fault_desc(fld):
|
||||
|
||||
def get_name(self):
|
||||
return "FAULT"
|
||||
|
||||
|
||||
class reserved_desc(fld):
|
||||
|
||||
def get_name(self):
|
||||
return "RESERVED"
|
||||
|
||||
|
||||
class pt_desc(fld):
|
||||
|
||||
def __init__(self, desc):
|
||||
self.coarse_base = (desc >> 10) << 10
|
||||
self.p = (desc >> 9) & 1
|
||||
self.domain = (desc >> 5) & 15
|
||||
self.sbz1 = (desc >> 4) & 1
|
||||
self.ns = (desc >> 3) & 1
|
||||
self.sbz2 = (desc >> 2) & 1
|
||||
|
||||
|
||||
def get_name(self):
|
||||
return "PT"
|
||||
|
||||
|
||||
class section_desc(fld):
|
||||
def __init__(self, desc):
|
||||
self.section_base = (desc >> 20) << 20
|
||||
self.ns = (desc >> 19) & 1
|
||||
self.zero = ns = (desc >> 18) & 1
|
||||
self.ng = (desc >> 17) & 1
|
||||
self.s = (desc >> 16) & 1
|
||||
self.apx = (desc >> 15) & 1
|
||||
self.tex = (desc >> 12) & 7
|
||||
self.ap = (desc >> 10) & 3
|
||||
self.p = (desc >> 9) & 1
|
||||
self.domain = (desc >> 5) & 15
|
||||
self.nx = (desc >> 4) & 1
|
||||
self.c = (desc >> 3) & 1
|
||||
self.b = (desc >> 2) & 1
|
||||
|
||||
|
||||
def get_name(self):
|
||||
return "SECTION"
|
||||
|
||||
|
||||
class sld(descriptor):
|
||||
pass
|
||||
|
||||
|
||||
class sld_lp(sld):
|
||||
|
||||
def __init__(self, desc):
|
||||
self.page_base = (desc >> 16) << 16
|
||||
self.nx = (desc >> 15) & 1
|
||||
self.tex = (desc >> 12) & 7
|
||||
self.ng = (desc >> 11) & 1
|
||||
self.s = (desc >> 10) & 1
|
||||
self.apx = (desc >> 9) & 1
|
||||
self.sbz = (desc >> 6) & 7
|
||||
self.ap = (desc >> 4) & 3
|
||||
self.c = (desc >> 3) & 1
|
||||
self.b = (desc >> 2) & 1
|
||||
|
||||
|
||||
def get_name(self):
|
||||
return "LARGEPAGE"
|
||||
|
||||
|
||||
class sld_xsp(sld):
|
||||
|
||||
def __init__(self, desc):
|
||||
self.desc = desc
|
||||
self.page_base = (desc >> 12) << 12
|
||||
self.ng = (desc >> 11) & 1
|
||||
self.s = (desc >> 10) & 1
|
||||
self.apx = (desc >> 9) & 1
|
||||
self.tex = (desc >> 6) & 7
|
||||
self.ap = (desc >> 4) & 3
|
||||
self.c = (desc >> 3) & 1
|
||||
self.b = (desc >> 2) & 1
|
||||
self.nx = desc & 1
|
||||
|
||||
|
||||
def get_name(self):
|
||||
return "XSMALLPAGE"
|
||||
Vendored
+149
@@ -0,0 +1,149 @@
|
||||
import struct
|
||||
|
||||
"""
|
||||
only supports 4KB granule w/ 25<=TnSZ<=33
|
||||
https://armv8-ref.codingbelief.com/en/chapter_d4/d42_7_the_algorithm_for_finding_the_translation_table_entries.html
|
||||
|
||||
"""
|
||||
|
||||
def get_level_index(va, level):
|
||||
|
||||
if level == 1:
|
||||
return (va >> 30) & 0x3F
|
||||
|
||||
if level == 2:
|
||||
return (va >> 21) & 0x1FF
|
||||
|
||||
if level == 3:
|
||||
return (va >> 12) & 0x1FF
|
||||
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
def get_level_bits(level, tnsz):
|
||||
if level == 1:
|
||||
return 37-tnsz+26+1-30
|
||||
|
||||
if level == 2:
|
||||
return 9
|
||||
|
||||
if level == 3:
|
||||
return 9
|
||||
|
||||
raise NotImplementedError()
|
||||
|
||||
|
||||
def get_level_size(tnsz, level):
|
||||
return 2**get_level_bits(level, tnsz)*8
|
||||
|
||||
|
||||
def get_va_for_level(va, index, level):
|
||||
if level == 1:
|
||||
return va + (index<<30)
|
||||
|
||||
if level == 2:
|
||||
return va + (index<<21)
|
||||
|
||||
if level == 3:
|
||||
return va + (index<<12)
|
||||
|
||||
|
||||
def parse_pt(data, base, tnsz, level=1):
|
||||
i = 0
|
||||
entries = []
|
||||
while i < min(len(data), get_level_size(tnsz, level)):
|
||||
entry = struct.unpack("<Q", data[i:i+8])[0]
|
||||
|
||||
f = get_fld(entry, level)
|
||||
if f is None:
|
||||
i += 8
|
||||
continue
|
||||
va = get_va_for_level(base, int(i/8), level)
|
||||
if (f!='UNSUPPORTED' and f.apx==0 and f.ap==3 and f.xn==0):
|
||||
print("%016x %s - WX !!" % (va, f))
|
||||
else:
|
||||
print("%016x %s" % (va, f))
|
||||
|
||||
entries.append((va, f))
|
||||
i += 8
|
||||
|
||||
return entries
|
||||
|
||||
|
||||
def get_fld(fld, level):
|
||||
s = fld & 3
|
||||
if s == 0:
|
||||
return None
|
||||
|
||||
if s == 1:
|
||||
return block_entry4k(fld, level)
|
||||
|
||||
if s == 2:
|
||||
return None
|
||||
|
||||
if s == 3:
|
||||
return table_entry4k(fld, level)
|
||||
|
||||
|
||||
class descriptor(object):
|
||||
def __repr__(self):
|
||||
s = "%8s " % self.get_name()
|
||||
for attr, value in self.__dict__.items():
|
||||
try:
|
||||
s += "%s=%s, " % (attr, hex(value))
|
||||
except:
|
||||
s += "%s=%s, " % (attr, value)
|
||||
|
||||
return s
|
||||
|
||||
|
||||
class fld(descriptor):
|
||||
pass
|
||||
|
||||
|
||||
class entry(fld):
|
||||
def __init__(self, desc, level):
|
||||
self.level = level
|
||||
self.nshigh = desc >> 63
|
||||
self.apx = (desc >> 61) & 3
|
||||
self.xn = (desc >> 60) & 1
|
||||
self.pxn = (desc >> 59) & 1
|
||||
self.attrindex = (desc>>2) & 7
|
||||
self.ns = (desc>>5) & 1
|
||||
self.ap = (desc>>6) & 3
|
||||
self.sh = (desc>>8) & 3
|
||||
self.af = (desc>>10) & 1
|
||||
self.nG = (desc>>11) & 1
|
||||
|
||||
|
||||
class entry4k(entry):
|
||||
def __init__(self, desc, level):
|
||||
entry.__init__(self, desc, level)
|
||||
self.output = ((desc & 0xFFFFFFFFFFFF) >> 12) << 12
|
||||
|
||||
|
||||
class fault_entry(fld):
|
||||
|
||||
def get_name(self):
|
||||
return "FAULT"
|
||||
|
||||
|
||||
class block_entry4k(entry4k):
|
||||
|
||||
def __init__(self, desc, level):
|
||||
entry4k.__init__(self, desc, level)
|
||||
# shift = 39-9*level
|
||||
# self.output = ((desc & 0xFFFFFFFFFFFFL) >> shift) << shift
|
||||
|
||||
def get_name(self):
|
||||
return "BLOCK4"
|
||||
|
||||
|
||||
class table_entry4k(entry4k):
|
||||
|
||||
def __init__(self, desc, level):
|
||||
entry4k.__init__(self, desc, level)
|
||||
|
||||
|
||||
def get_name(self):
|
||||
return "TABLE4"
|
||||
Vendored
+487
@@ -0,0 +1,487 @@
|
||||
import binascii
|
||||
import os
|
||||
import time
|
||||
from Library.utils import *
|
||||
from Library.firehose import qualcomm_firehose
|
||||
|
||||
class qualcomm_sahara():
|
||||
SAHARA_VERSION=2
|
||||
SAHARA_MIN_VERSION=1
|
||||
|
||||
class cmd:
|
||||
SAHARA_HELLO_REQ=0x1
|
||||
SAHARA_HELLO_RSP=0x2
|
||||
SAHARA_READ_DATA=0x3
|
||||
SAHARA_END_TRANSFER=0x4
|
||||
SAHARA_DONE_REQ=0x5
|
||||
SAHARA_DONE_RSP=0x6
|
||||
SAHARA_RESET_REQ=0x7
|
||||
SAHARA_RESET_RSP=0x8
|
||||
SAHARA_MEMORY_DEBUG=0x9
|
||||
SAHARA_MEMORY_READ=0xA
|
||||
SAHARA_CMD_READY=0xB
|
||||
SAHARA_SWITCH_MODE=0xC
|
||||
SAHARA_EXECUTE_REQ=0xD
|
||||
SAHARA_EXECUTE_RSP=0xE
|
||||
SAHARA_EXECUTE_DATA=0xF
|
||||
SAHARA_64BIT_MEMORY_DEBUG=0x10
|
||||
SAHARA_64BIT_MEMORY_READ=0x11
|
||||
SAHARA_64BIT_MEMORY_READ_DATA=0x12
|
||||
|
||||
class exec_cmd:
|
||||
SAHARA_EXEC_CMD_NOP=0x00
|
||||
SAHARA_EXEC_CMD_SERIAL_NUM_READ=0x01
|
||||
SAHARA_EXEC_CMD_MSM_HW_ID_READ=0x02
|
||||
SAHARA_EXEC_CMD_OEM_PK_HASH_READ=0x03
|
||||
SAHARA_EXEC_CMD_SWITCH_TO_DMSS_DLOAD=0x04
|
||||
SAHARA_EXEC_CMD_SWITCH_TO_STREAM_DLOAD=0x05
|
||||
SAHARA_EXEC_CMD_READ_DEBUG_DATA=0x06
|
||||
SAHARA_EXEC_CMD_GET_SOFTWARE_VERSION_SBL=0x07
|
||||
|
||||
class mode:
|
||||
SAHARA_MODE_IMAGE_TX_PENDING=0x0
|
||||
SAHARA_MODE_IMAGE_TX_COMPLETE=0x1
|
||||
SAHARA_MODE_MEMORY_DEBUG=0x2
|
||||
SAHARA_MODE_COMMAND=0x3
|
||||
|
||||
class status:
|
||||
SAHARA_STATUS_SUCCESS = 0x00 # Invalid command received in current state
|
||||
SAHARA_NAK_INVALID_CMD = 0x01 # Protocol mismatch between host and target
|
||||
SAHARA_NAK_PROTOCOL_MISMATCH = 0x02 # Invalid target protocol version
|
||||
SAHARA_NAK_INVALID_TARGET_PROTOCOL = 0x03 # Invalid host protocol version
|
||||
SAHARA_NAK_INVALID_HOST_PROTOCOL = 0x04 # Invalid packet size received
|
||||
SAHARA_NAK_INVALID_PACKET_SIZE = 0x05 # Unexpected image ID received
|
||||
SAHARA_NAK_UNEXPECTED_IMAGE_ID = 0x06 # Invalid image header size received
|
||||
SAHARA_NAK_INVALID_HEADER_SIZE = 0x07 # Invalid image data size received
|
||||
SAHARA_NAK_INVALID_DATA_SIZE = 0x08 # Invalid image type received
|
||||
SAHARA_NAK_INVALID_IMAGE_TYPE = 0x09 # Invalid tranmission length
|
||||
SAHARA_NAK_INVALID_TX_LENGTH = 0x0A # Invalid reception length
|
||||
SAHARA_NAK_INVALID_RX_LENGTH = 0x0B # General transmission or reception error
|
||||
SAHARA_NAK_GENERAL_TX_RX_ERROR = 0x0C # Error while transmitting READ_DATA packet
|
||||
SAHARA_NAK_READ_DATA_ERROR = 0x0D # Cannot receive specified number of program headers
|
||||
SAHARA_NAK_UNSUPPORTED_NUM_PHDRS = 0x0E # Invalid data length received for program headers
|
||||
SAHARA_NAK_INVALID_PDHR_SIZE = 0x0F # Multiple shared segments found in ELF image
|
||||
SAHARA_NAK_MULTIPLE_SHARED_SEG = 0x10 # Uninitialized program header location
|
||||
SAHARA_NAK_UNINIT_PHDR_LOC = 0x11 # Invalid destination address
|
||||
SAHARA_NAK_INVALID_DEST_ADDR = 0x12 # Invalid data size received in image header
|
||||
SAHARA_NAK_INVALID_IMG_HDR_DATA_SIZE = 0x13 # Invalid ELF header received
|
||||
SAHARA_NAK_INVALID_ELF_HDR = 0x14 # Unknown host error received in HELLO_RESP
|
||||
SAHARA_NAK_UNKNOWN_HOST_ERROR = 0x15 # Timeout while receiving data
|
||||
SAHARA_NAK_TIMEOUT_RX = 0x16 # Timeout while transmitting data
|
||||
SAHARA_NAK_TIMEOUT_TX = 0x17 # Invalid mode received from host
|
||||
SAHARA_NAK_INVALID_HOST_MODE = 0x18 # Invalid memory read access
|
||||
SAHARA_NAK_INVALID_MEMORY_READ = 0x19 # Host cannot handle read data size requested
|
||||
SAHARA_NAK_INVALID_DATA_SIZE_REQUEST = 0x1A # Memory debug not supported
|
||||
SAHARA_NAK_MEMORY_DEBUG_NOT_SUPPORTED = 0x1B # Invalid mode switch
|
||||
SAHARA_NAK_INVALID_MODE_SWITCH = 0x1C # Failed to execute command
|
||||
SAHARA_NAK_CMD_EXEC_FAILURE = 0x1D # Invalid parameter passed to command execution
|
||||
SAHARA_NAK_EXEC_CMD_INVALID_PARAM = 0x1E # Unsupported client command received
|
||||
SAHARA_NAK_EXEC_CMD_UNSUPPORTED = 0x1F # Invalid client command received for data response
|
||||
SAHARA_NAK_EXEC_DATA_INVALID_CLIENT_CMD = 0x20 # Failed to authenticate hash table
|
||||
SAHARA_NAK_HASH_TABLE_AUTH_FAILURE = 0x21 # Failed to verify hash for a given segment of ELF image
|
||||
SAHARA_NAK_HASH_VERIFICATION_FAILURE = 0x22 # Failed to find hash table in ELF image
|
||||
SAHARA_NAK_HASH_TABLE_NOT_FOUND = 0x23 # Target failed to initialize
|
||||
SAHARA_NAK_TARGET_INIT_FAILURE = 0x24 # Failed to authenticate generic image
|
||||
SAHARA_NAK_IMAGE_AUTH_FAILURE = 0x25 # Invalid ELF hash table size. Too bit or small.
|
||||
SAHARA_NAK_INVALID_IMG_HASH_TABLE_SIZE = 0x26
|
||||
SAHARA_NAK_MAX_CODE = 0x7FFFFFFF # To ensure 32-bits wide */
|
||||
|
||||
ErrorDesc={
|
||||
0x00:"Invalid command received in current state",
|
||||
0x01:"Protocol mismatch between host and target",
|
||||
0x02:"Invalid target protocol version",
|
||||
0x03:"Invalid host protocol version",
|
||||
0x04:"Invalid packet size received",
|
||||
0x05:"Unexpected image ID received",
|
||||
0x06:"Invalid image header size received",
|
||||
0x07:"Invalid image data size received",
|
||||
0x08:"Invalid image type received",
|
||||
0x09:"Invalid tranmission length",
|
||||
0x0A:"Invalid reception length",
|
||||
0x0B:"General transmission or reception error",
|
||||
0x0C:"Error while transmitting READ_DATA packet",
|
||||
0x0D:"Cannot receive specified number of program headers",
|
||||
0x0E:"Invalid data length received for program headers",
|
||||
0x0F:"Multiple shared segments found in ELF image",
|
||||
0x10:"Uninitialized program header location",
|
||||
0x11:"Invalid destination address",
|
||||
0x12:"Invalid data size received in image header",
|
||||
0x13:"Invalid ELF header received",
|
||||
0x14:"Unknown host error received in HELLO_RESP",
|
||||
0x15:"Timeout while receiving data",
|
||||
0x16:"Timeout while transmitting data",
|
||||
0x17:"Invalid mode received from host",
|
||||
0x18:"Invalid memory read access",
|
||||
0x19:"Host cannot handle read data size requested",
|
||||
0x1A:"Memory debug not supported",
|
||||
0x1B:"Invalid mode switch",
|
||||
0x1C:"Failed to execute command",
|
||||
0x1D:"Invalid parameter passed to command execution",
|
||||
0x1E:"Unsupported client command received",
|
||||
0x1F:"Invalid client command received for data response",
|
||||
0x20:"Failed to authenticate hash table",
|
||||
0x21:"Failed to verify hash for a given segment of ELF image",
|
||||
0x22:"Failed to find hash table in ELF image",
|
||||
0x23:"Target failed to initialize",
|
||||
0x24:"Failed to authenticate generic image",
|
||||
0x25:"Invalid ELF hash table size. Too bit or small.",
|
||||
0x26:"Invalid IMG Hash Table Size"
|
||||
}
|
||||
|
||||
def init_loader_db(self):
|
||||
self.loaderdb = {}
|
||||
for (dirpath, dirnames, filenames) in os.walk("Loaders"):
|
||||
for filename in filenames:
|
||||
fn = os.path.join(dirpath, filename)
|
||||
try:
|
||||
hwid = filename.split("_")[0].lower()
|
||||
pkhash = filename.split("_")[1].lower()
|
||||
if hwid not in self.loaderdb:
|
||||
self.loaderdb[hwid] = {}
|
||||
if pkhash not in self.loaderdb[hwid]:
|
||||
self.loaderdb[hwid][pkhash] = fn
|
||||
except:
|
||||
continue
|
||||
return self.loaderdb
|
||||
|
||||
def get_error_desc(self,status):
|
||||
if status in self.ErrorDesc:
|
||||
return "Error: "+self.ErrorDesc[status]
|
||||
else:
|
||||
return "Unknown error"
|
||||
|
||||
pkt_hello_req=[
|
||||
('cmd', 'I'),
|
||||
('len', 'I'),
|
||||
('version', 'I'),
|
||||
('version_min', 'I'),
|
||||
('max_cmd_len', 'I'),
|
||||
('mode', 'I'),
|
||||
('res1', 'I'),
|
||||
('res2', 'I'),
|
||||
('res3', 'I'),
|
||||
('res4', 'I'),
|
||||
('res5', 'I'),
|
||||
('res6', 'I')]
|
||||
|
||||
pkt_cmd_hdr=[
|
||||
('cmd', 'I'),
|
||||
('len', 'I')
|
||||
]
|
||||
|
||||
pkt_read_data=[
|
||||
('id', 'I'),
|
||||
('data_offset', 'I'),
|
||||
('data_len', 'I')
|
||||
]
|
||||
|
||||
pkt_read_data_64=[
|
||||
('id', 'Q'),
|
||||
('data_offset', 'Q'),
|
||||
('data_len', 'Q')
|
||||
]
|
||||
|
||||
'''
|
||||
execute_cmd=[
|
||||
('cmd', 'I'),
|
||||
('len', 'I'),
|
||||
('client_cmd','I')
|
||||
]
|
||||
'''
|
||||
|
||||
pkt_execute_rsp_cmd=[
|
||||
('cmd', 'I'),
|
||||
('len', 'I'),
|
||||
('client_cmd','I'),
|
||||
('data_len','I')
|
||||
]
|
||||
|
||||
pkt_image_end=[
|
||||
('id', 'I'),
|
||||
('status', 'I')
|
||||
]
|
||||
|
||||
pkt_done=[
|
||||
('cmd', 'I'),
|
||||
('len', 'I'),
|
||||
('status','I')
|
||||
]
|
||||
|
||||
pbl_info=[
|
||||
('serial', 'I'),
|
||||
('msm_id', 'I'),
|
||||
('pk_hash','32s'),
|
||||
('pbl_sw','I')
|
||||
]
|
||||
|
||||
def __init__(self,cdc):
|
||||
self.cdc = cdc
|
||||
self.init_loader_db()
|
||||
self.programmer=None
|
||||
|
||||
def get_rsp(self):
|
||||
v = self.cdc.read()
|
||||
if b"<?xml" in v:
|
||||
return [-1,-1]
|
||||
pkt = read_object(v[0:0x2*0x4], self.pkt_cmd_hdr)
|
||||
if pkt['cmd'] == self.cmd.SAHARA_HELLO_REQ:
|
||||
data = read_object(v[0x0:0xC*0x4], self.pkt_hello_req)
|
||||
elif pkt["cmd"] == self.cmd.SAHARA_DONE_RSP:
|
||||
data = read_object(v[0x0:0x3*4], self.pkt_done)
|
||||
elif pkt["cmd"] == self.cmd.SAHARA_END_TRANSFER:
|
||||
data = read_object(v[0x8:0x8+0x2*0x4], self.pkt_image_end)
|
||||
elif pkt["cmd"] == self.cmd.SAHARA_RESET_RSP:
|
||||
data = []
|
||||
elif (pkt["cmd"] == self.cmd.SAHARA_64BIT_MEMORY_READ_DATA):
|
||||
self.bit64 = True
|
||||
data = read_object(v[0x8:0x8 + 0x3 * 0x8], self.pkt_read_data_64)
|
||||
elif (pkt["cmd"] == self.cmd.SAHARA_READ_DATA):
|
||||
self.bit64 = False
|
||||
data = read_object(v[0x8:0x8 + 0x3 * 0x4], self.pkt_read_data)
|
||||
elif (pkt["cmd"] == self.cmd.SAHARA_EXECUTE_RSP):
|
||||
data =read_object(v[0:0x4*0x4], self.pkt_execute_rsp_cmd)
|
||||
elif (pkt["cmd"] == self.cmd.SAHARA_CMD_READY):
|
||||
data=[]
|
||||
else:
|
||||
return None
|
||||
return [pkt,data]
|
||||
|
||||
def cmd_hello(self,mode,version_min=1, max_cmd_len=0): #CMD 0x1, RSP 0x2
|
||||
cmd = self.cmd.SAHARA_HELLO_RSP
|
||||
len = 0x30
|
||||
version = self.SAHARA_VERSION
|
||||
responsedata=struct.pack("<IIIIIIIIIIII",cmd,len,version,version_min,max_cmd_len,mode,0,0,0,0,0,0)
|
||||
try:
|
||||
self.cdc.write(responsedata)
|
||||
return True
|
||||
except:
|
||||
return False
|
||||
return False
|
||||
|
||||
def connect(self):
|
||||
try:
|
||||
v = self.cdc.read()
|
||||
if b"<?xml" in v:
|
||||
return "Firehose"
|
||||
elif v[0]==0x01:
|
||||
cmd = read_object(v[0:0x2 * 0x4], self.pkt_cmd_hdr)
|
||||
if cmd['cmd'] == self.cmd.SAHARA_HELLO_REQ:
|
||||
data = read_object(v[0x0:0xC * 0x4], self.pkt_hello_req)
|
||||
self.pktsize = data['max_cmd_len']
|
||||
self.version_min = data['version_min']
|
||||
return "Sahara"
|
||||
except:
|
||||
try:
|
||||
data = "<?xml version=\"1.0\" ?><data><nop /></data>"
|
||||
val = self.cdc.write(data,4096)
|
||||
res = self.cdc.read()
|
||||
if (b"<?xml" in res):
|
||||
return "Firehose"
|
||||
except:
|
||||
return "Unknown"
|
||||
return "Unknown"
|
||||
|
||||
def enter_command_mode(self):
|
||||
if self.cmd_hello(self.mode.SAHARA_MODE_COMMAND)==False:
|
||||
return False
|
||||
cmd, pkt = self.get_rsp()
|
||||
if (cmd["cmd"] == self.cmd.SAHARA_CMD_READY):
|
||||
return True
|
||||
elif "status" in pkt:
|
||||
print(self.get_error_desc(pkt["status"]))
|
||||
return False
|
||||
return False
|
||||
|
||||
def cmdexec_nop(self):
|
||||
res=self.cmd_exec(self.exec_cmd.SAHARA_EXEC_CMD_NOP)
|
||||
return res
|
||||
|
||||
def cmdexec_get_serial_num(self):
|
||||
res=self.cmd_exec(self.exec_cmd.SAHARA_EXEC_CMD_SERIAL_NUM_READ)
|
||||
return struct.unpack("<I", res)[0]
|
||||
|
||||
def cmdexec_get_msm_hwid(self):
|
||||
res=self.cmd_exec(self.exec_cmd.SAHARA_EXEC_CMD_MSM_HW_ID_READ)
|
||||
return struct.unpack("<Q", res[0:0x8])[0]
|
||||
|
||||
def cmdexec_get_pkhash(self):
|
||||
res=self.cmd_exec(self.exec_cmd.SAHARA_EXEC_CMD_OEM_PK_HASH_READ)[0:0x20]
|
||||
return binascii.hexlify(res).decode('utf-8')
|
||||
|
||||
def cmdexec_get_sbl_version(self):
|
||||
res=self.cmd_exec(self.exec_cmd.SAHARA_EXEC_CMD_GET_SOFTWARE_VERSION_SBL)
|
||||
return struct.unpack("<I", res)[0]
|
||||
|
||||
def cmdexec_switch_to_dmss_dload(self):
|
||||
res=self.cmd_exec(self.exec_cmd.SAHARA_EXEC_CMD_SWITCH_TO_DMSS_DLOAD)
|
||||
return res
|
||||
|
||||
def cmdexec_switch_to_stream_dload(self):
|
||||
res=self.cmd_exec(self.exec_cmd.SAHARA_EXEC_CMD_SWITCH_TO_STREAM_DLOAD)
|
||||
return res
|
||||
|
||||
def cmdexec_read_debug_data(self):
|
||||
res=self.cmd_exec(self.exec_cmd.SAHARA_EXEC_CMD_READ_DEBUG_DATA)
|
||||
return res
|
||||
|
||||
def info(self):
|
||||
if self.enter_command_mode()==True:
|
||||
self.serial = "{:08x}".format(self.cmdexec_get_serial_num())
|
||||
self.sblversion = "{:08x}".format(self.cmdexec_get_sbl_version())
|
||||
self.hwid = self.cmdexec_get_msm_hwid()
|
||||
self.pkhash = self.cmdexec_get_pkhash()
|
||||
self.hwidstr="{:016x}".format(self.hwid)
|
||||
self.msm_id = int(self.hwidstr[0:8],16)
|
||||
self.oem_id = int(self.hwidstr[-8:-4],16)
|
||||
self.model_id = int(self.hwidstr[-4:],16)
|
||||
self.oem_str="{:04x}".format(self.oem_id)
|
||||
self.model_id = "{:04x}".format(self.model_id)
|
||||
self.msm_str="{:08x}".format(self.msm_id)
|
||||
|
||||
print(f"\n------------------------\n" +
|
||||
f"HWID: 0x{self.hwidstr} (MSM_ID:0x{self.msm_str},OEM_ID:0x{self.oem_str},MODEL_ID:0x{self.model_id})\n" +
|
||||
f"PK_HASH: 0x{self.pkhash}\n" +
|
||||
f"Serial: 0x{self.serial}\n" +
|
||||
f"SBL Version: 0x{self.sblversion}\n")
|
||||
if self.programmer==None:
|
||||
if self.hwidstr in self.loaderdb:
|
||||
if self.pkhash[0:16]=="cc3153a80293939b":
|
||||
print("Unfused device detected, so any loader should be fine...")
|
||||
if self.pkhash[0:16] in self.loaderdb[self.hwidstr]:
|
||||
fname=self.loaderdb[self.hwidstr][self.pkhash[0:16]]
|
||||
print(f"Trying loader: {fname}")
|
||||
else:
|
||||
for loader in self.loaderdb[self.hwidstr]:
|
||||
fname = self.loaderdb[self.hwidstr][loader]
|
||||
print(f"Possible loader available: {fname}")
|
||||
for loader in self.loaderdb[self.hwidstr]:
|
||||
fname = self.loaderdb[self.hwidstr][loader]
|
||||
print(f"Trying loader: {fname}")
|
||||
break
|
||||
elif self.pkhash[0:16] in self.loaderdb[self.hwidstr]:
|
||||
fname=self.loaderdb[self.hwidstr][self.pkhash[0:16]]
|
||||
print(f"Detected loader: {fname}")
|
||||
else:
|
||||
for loader in self.loaderdb[self.hwidstr]:
|
||||
fname = self.loaderdb[self.hwidstr][loader]
|
||||
print(f"Trying loader: {fname}")
|
||||
break
|
||||
#print("Couldn't find a loader for given hwid and pkhash :(")
|
||||
#exit(0)
|
||||
else:
|
||||
print("Couldn't find a loader for given hwid and pkhash :(")
|
||||
exit(0)
|
||||
with open(fname,"rb") as rf:
|
||||
self.programmer=rf.read()
|
||||
return True
|
||||
return False
|
||||
|
||||
def cmd_done(self):
|
||||
self.cdc.write(struct.pack("<II", self.cmd.SAHARA_DONE_REQ, 0x8))
|
||||
cmd,pkt=self.get_rsp()
|
||||
time.sleep(0.3)
|
||||
if cmd["cmd"]==self.cmd.SAHARA_DONE_RSP:
|
||||
return True
|
||||
elif cmd["cmd"]==self.cmd.SAHARA_END_TRANSFER:
|
||||
if pkt["status"] == self.status.SAHARA_NAK_INVALID_CMD:
|
||||
print("Invalid Transfer command received.")
|
||||
return False
|
||||
return True
|
||||
|
||||
def cmd_reset(self):
|
||||
self.cdc.write(struct.pack("<II", self.cmd.SAHARA_RESET_REQ, 0x8))
|
||||
cmd, pkt = self.get_rsp()
|
||||
if cmd["cmd"]==self.cmd.SAHARA_RESET_RSP:
|
||||
return True
|
||||
elif "status" in pkt:
|
||||
print(self.get_error_desc(pkt["status"]))
|
||||
return False
|
||||
return False
|
||||
|
||||
def debug_mode(self):
|
||||
self.cmd_modeswitch(self.mode.SAHARA_MODE_COMMAND)
|
||||
if self.connect()==False:
|
||||
return False
|
||||
if self.cmd_hello(self.mode.SAHARA_MODE_MEMORY_DEBUG)==False:
|
||||
return False
|
||||
cmd, pkt = self.get_rsp()
|
||||
if (cmd["cmd"] == self.cmd.SAHARA_END_TRANSFER):
|
||||
if pkt["status"]==self.status.SAHARA_NAK_MEMORY_DEBUG_NOT_SUPPORTED:
|
||||
print("Sorry, Memory Debug is not supported !")
|
||||
return False
|
||||
else:
|
||||
state=str(pkt["status"])
|
||||
print(f"Error occured on memory debug: {state}")
|
||||
return False
|
||||
elif (cmd["cmd"]==self.cmd.SAHARA_MEMORY_DEBUG or cmd["cmd"]==self.cmd.SAHARA_64BIT_MEMORY_DEBUG):
|
||||
return True
|
||||
elif "status" in pkt:
|
||||
print(self.get_error_desc(pkt["status"]))
|
||||
return False
|
||||
return False
|
||||
|
||||
def upload_firehoseloader(self):
|
||||
self.cmd_modeswitch(self.mode.SAHARA_MODE_COMMAND)
|
||||
if self.connect()==False:
|
||||
return False
|
||||
if self.cmd_hello(self.mode.SAHARA_MODE_IMAGE_TX_PENDING)==False:
|
||||
return False
|
||||
|
||||
try:
|
||||
datalen=len(self.programmer)
|
||||
done=False
|
||||
while (datalen>0 or done==True):
|
||||
cmd, pkt = self.get_rsp()
|
||||
if (cmd["cmd"] == self.cmd.SAHARA_64BIT_MEMORY_READ_DATA):
|
||||
self.bit64=True
|
||||
elif (cmd["cmd"] == self.cmd.SAHARA_READ_DATA):
|
||||
self.bit64=False
|
||||
elif (cmd["cmd"] == self.cmd.SAHARA_END_TRANSFER):
|
||||
if pkt["status"] == self.status.SAHARA_STATUS_SUCCESS:
|
||||
self.cmd_done()
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
elif "status" in pkt:
|
||||
print(self.get_error_desc(pkt["status"]))
|
||||
return False
|
||||
else:
|
||||
print("Unexpected error on uploading")
|
||||
return False
|
||||
data_offset=pkt["data_offset"]
|
||||
data_len=pkt["data_len"]
|
||||
data_to_send=self.programmer[data_offset:data_offset+data_len]
|
||||
self.cdc.write(data_to_send,self.pktsize)
|
||||
datalen-=data_len
|
||||
|
||||
cmd, pkt = self.get_rsp()
|
||||
if (cmd["cmd"] == self.cmd.SAHARA_END_TRANSFER):
|
||||
if pkt["status"] == self.status.SAHARA_STATUS_SUCCESS:
|
||||
self.cmd_done()
|
||||
return True
|
||||
return False
|
||||
except:
|
||||
print("Unexpected error on uploading, maybe signature of loader wasn't accepted ?")
|
||||
return False
|
||||
|
||||
|
||||
def cmd_modeswitch(self,mode):
|
||||
data = struct.pack("<III", self.cmd.SAHARA_SWITCH_MODE, 0xC, mode)
|
||||
self.cdc.write(data)
|
||||
|
||||
def cmd_exec(self,mcmd): #CMD 0xD, RSP 0xE, CMD2 0xF
|
||||
#Send request
|
||||
data=struct.pack("<III",self.cmd.SAHARA_EXECUTE_REQ,0xC,mcmd)
|
||||
self.cdc.write(data)
|
||||
#Get info about request
|
||||
cmd, pkt = self.get_rsp()
|
||||
if (cmd["cmd"]==self.cmd.SAHARA_EXECUTE_RSP):
|
||||
#Ack
|
||||
data = struct.pack("<III", self.cmd.SAHARA_EXECUTE_DATA, 0xC, mcmd)
|
||||
self.cdc.write(data)
|
||||
payload=self.cdc.read(pkt["data_len"])
|
||||
return payload
|
||||
elif "status" in pkt:
|
||||
print(self.get_error_desc(pkt["status"]))
|
||||
return None
|
||||
return None
|
||||
Vendored
+75
@@ -0,0 +1,75 @@
|
||||
import usb.core # pyusb
|
||||
import usb.util
|
||||
|
||||
class usb_class():
|
||||
|
||||
def log(self,level,msg):
|
||||
if level>1:
|
||||
if self.debug==True:
|
||||
print(msg)
|
||||
else:
|
||||
print(msg)
|
||||
|
||||
def __init__(self,vid=0x05c6, pid=0x9008, Debug=False):
|
||||
self.vid=vid
|
||||
self.pid=pid
|
||||
self.debug=Debug
|
||||
self.connected=False
|
||||
|
||||
def connect(self):
|
||||
self.device = usb.core.find(idVendor=self.vid, idProduct=self.pid)
|
||||
if self.device is None:
|
||||
self.log(2, "Couldn't detect the device. Is it connected ?")
|
||||
return False
|
||||
|
||||
try:
|
||||
if self.device.is_kernel_driver_active(0):
|
||||
self.device.detach_kernel_driver(0)
|
||||
except:
|
||||
pass
|
||||
|
||||
self.device.set_configuration()
|
||||
self.configuration = self.device.get_active_configuration()
|
||||
self.log(2, self.configuration)
|
||||
for itf_num in [0]:
|
||||
itf = usb.util.find_descriptor(self.configuration,
|
||||
bInterfaceNumber=itf_num)
|
||||
try:
|
||||
if self.device.is_kernel_driver_active(itf_num):
|
||||
self.log(2, "Detaching kernel driver")
|
||||
self.device.detach_kernel_driver(itf_num)
|
||||
except:
|
||||
self.log(2, "No kernel driver supported.")
|
||||
|
||||
usb.util.claim_interface(self.device, itf_num)
|
||||
|
||||
self.EP_OUT = usb.util.find_descriptor(itf,
|
||||
# match the first OUT endpoint
|
||||
custom_match= \
|
||||
lambda e: \
|
||||
usb.util.endpoint_direction(e.bEndpointAddress) == \
|
||||
usb.util.ENDPOINT_OUT)
|
||||
|
||||
self.EP_IN = usb.util.find_descriptor(itf,
|
||||
# match the first OUT endpoint
|
||||
custom_match= \
|
||||
lambda e: \
|
||||
usb.util.endpoint_direction(e.bEndpointAddress) == \
|
||||
usb.util.ENDPOINT_IN)
|
||||
self.connected=True
|
||||
return True
|
||||
|
||||
def write(self,command,pktsize=64):
|
||||
pos=0
|
||||
if command==b'':
|
||||
self.device.write(self.EP_OUT, b'')
|
||||
else:
|
||||
while pos<len(command):
|
||||
self.device.write(self.EP_OUT,command[pos:pos+pktsize])
|
||||
pos+=pktsize
|
||||
|
||||
def read(self,length=0x80000,timeout=None):
|
||||
tmp=b''
|
||||
while (bytearray(tmp) == b''):
|
||||
tmp=self.device.read(self.EP_IN, length,timeout)
|
||||
return bytearray(tmp)
|
||||
Vendored
+274
@@ -0,0 +1,274 @@
|
||||
import sys
|
||||
import struct
|
||||
try:
|
||||
from capstone import *
|
||||
except ImportError:
|
||||
pass
|
||||
try:
|
||||
from keystone import *
|
||||
except ImportError:
|
||||
pass
|
||||
import codecs
|
||||
|
||||
class elf:
|
||||
class memorysegment:
|
||||
phy_addr=0
|
||||
virt_start_addr=0
|
||||
virt_end_addr=0
|
||||
file_start_addr=0
|
||||
file_end_addr=0
|
||||
|
||||
|
||||
def __init__(self,indata):
|
||||
self.data=indata
|
||||
self.header, self.pentry = self.parse()
|
||||
self.memorylayout = []
|
||||
for entry in self.pentry:
|
||||
ms=self.memorysegment()
|
||||
ms.phy_addr=entry.phy_addr
|
||||
ms.virt_start_addr=entry.virt_addr
|
||||
ms.virt_end_addr=entry.virt_addr+entry.seg_mem_len
|
||||
ms.file_start_addr=entry.from_file
|
||||
ms.file_end_addr=entry.from_file+entry.seg_file_len
|
||||
self.memorylayout.append(ms)
|
||||
|
||||
def getfileoffset(self,offset):
|
||||
for memsegment in self.memorylayout:
|
||||
if offset<=memsegment.virt_end_addr and offset>=memsegment.virt_start_addr:
|
||||
return offset-memsegment.virt_start_addr+memsegment.file_start_addr
|
||||
return None
|
||||
|
||||
def getvirtaddr(self,fileoffset):
|
||||
for memsegment in self.memorylayout:
|
||||
if fileoffset<=memsegment.file_end_addr and fileoffset>=memsegment.file_start_addr:
|
||||
return memsegment.virt_start_addr+fileoffset-memsegment.file_start_addr
|
||||
return None
|
||||
|
||||
def getbaseaddr(self,offset):
|
||||
for memsegment in self.memorylayout:
|
||||
if offset<=memsegment.virt_end_addr and offset>=memsegment.virt_start_addr:
|
||||
return memsegment.virt_start_addr
|
||||
return None
|
||||
|
||||
class programentry:
|
||||
p_type = 0
|
||||
from_file = 0
|
||||
virt_addr = 0
|
||||
phy_addr = 0
|
||||
seg_file_len = 0
|
||||
seg_mem_len = 0
|
||||
p_flags = 0
|
||||
p_align = 0
|
||||
|
||||
def parse_programentry(self,dat):
|
||||
pe = self.programentry()
|
||||
if self.elfclass==1:
|
||||
(pe.p_type,pe.from_file,pe.virt_addr,pe.phy_addr,pe.seg_file_len,pe.seg_mem_len,pe.p_flags,pe.p_align) = struct.unpack("<IIIIIIII",dat)
|
||||
elif self.elfclass==2:
|
||||
(pe.p_type, pe.p_flags, pe.from_file, pe.virt_addr, pe.phy_addr, pe.seg_file_len, pe.seg_mem_len,pe.p_align) = struct.unpack("<IIQQQQQQ", dat)
|
||||
return pe
|
||||
|
||||
def parse(self):
|
||||
self.elfclass=self.data[4]
|
||||
if self.elfclass==1: #32Bit
|
||||
start=0x28
|
||||
elif self.elfclass==2: #64Bit
|
||||
start=0x34
|
||||
elfheadersize, programheaderentrysize, programheaderentrycount = struct.unpack("<HHH", self.data[start:start + 3 * 2])
|
||||
programheadersize = programheaderentrysize * programheaderentrycount
|
||||
header = self.data[0:elfheadersize+programheadersize]
|
||||
pentry=[]
|
||||
for i in range(0,programheaderentrycount):
|
||||
start=elfheadersize+(i*programheaderentrysize)
|
||||
end=start+programheaderentrysize
|
||||
pentry.append(self.parse_programentry(self.data[start:end]))
|
||||
|
||||
return [header,pentry]
|
||||
|
||||
|
||||
|
||||
class patchtools:
|
||||
cstyle=False
|
||||
bDebug=False
|
||||
|
||||
def __init__(self, bDebug=False):
|
||||
self.bDebug = bDebug
|
||||
|
||||
def has_bad_uart_chars(self, data):
|
||||
badchars = [b'\x00', b'\n', b'\r', b'\x08', b'\x7f', b'\x20', b'\x09']
|
||||
bad = False
|
||||
for idx, c in enumerate(data):
|
||||
c = bytes([c])
|
||||
if c in badchars:
|
||||
return True
|
||||
return False
|
||||
|
||||
def generate_offset(self, offset):
|
||||
div = 0
|
||||
found = False
|
||||
while (found == False and div < 0x606):
|
||||
data = struct.pack("<I", offset + div)
|
||||
data2 = struct.pack("<H", div)
|
||||
badchars = self.has_bad_uart_chars(data)
|
||||
if not (badchars):
|
||||
badchars = self.has_bad_uart_chars(data2)
|
||||
if not (badchars):
|
||||
return div
|
||||
div += 4
|
||||
|
||||
# if div is not found within positive offset, try negative offset
|
||||
div = 0
|
||||
while (found == False and div < 0x606):
|
||||
data = struct.pack("<I", offset - div)
|
||||
data2 = struct.pack("<H", div)
|
||||
badchars = self.has_bad_uart_chars(data)
|
||||
if not (badchars):
|
||||
badchars = self.has_bad_uart_chars(data2)
|
||||
if not (badchars):
|
||||
return -div
|
||||
break
|
||||
div += 4
|
||||
return 0
|
||||
|
||||
#Usage: offset, "X24"
|
||||
def generate_offset_asm(self, offset, reg):
|
||||
div = self.generate_offset(offset)
|
||||
abase = ((offset + div) & 0xFFFF0000) >> 16
|
||||
a = ((offset + div) & 0xFFFF)
|
||||
str = ""
|
||||
if (div > 0):
|
||||
str += "# " + hex(offset) + "\n"
|
||||
str += "mov " + reg + ", #" + hex(a) + ";\n"
|
||||
str += "movk " + reg + ", #" + hex(abase) + ", LSL#16;\n"
|
||||
str += "sub " + reg + ", " + reg + ", #" + hex(div) + ";\n"
|
||||
else:
|
||||
str += "# " + hex(offset) + "\n"
|
||||
str += "mov " + reg + ", #" + hex(a) + ";\n"
|
||||
str += "movk " + reg + ", #" + hex(abase) + ", LSL#16;\n"
|
||||
str += "add " + reg + ", " + reg + ", #" + hex(-div) + ";\n"
|
||||
return str
|
||||
|
||||
def UART_validSC(self, sc):
|
||||
badchars = [b'\x00', b'\n', b'\r', b'\x08', b'\x7f', b'\x20', b'\x09']
|
||||
for idx, c in enumerate(sc):
|
||||
c = bytes([c])
|
||||
if c in badchars:
|
||||
print("bad char 0x%s in SC at offset %d, opcode # %d!\n" % (codecs.encode(c, 'hex'), idx, idx / 4))
|
||||
print(codecs.encode(sc, 'hex'))
|
||||
return False
|
||||
return True
|
||||
|
||||
def disasm(self, code, size):
|
||||
cs = Cs(CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN)
|
||||
instr = []
|
||||
for i in cs.disasm(code, size):
|
||||
# print("0x%x:\t%s\t%s" % (i.address, i.mnemonic, i.op_str))
|
||||
instr.append("%s\t%s" % (i.mnemonic, i.op_str))
|
||||
return instr
|
||||
|
||||
def assembler(self, code):
|
||||
ks = Ks(KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN)
|
||||
if self.bDebug:
|
||||
try:
|
||||
encoding, count = ks.asm(code)
|
||||
except KsError as e:
|
||||
print(e)
|
||||
print(e.stat_count)
|
||||
print(code[e.stat_count:e.stat_count + 10])
|
||||
exit(0)
|
||||
if self.bDebug:
|
||||
# walk every line to find the (first) error
|
||||
for idx, line in enumerate(code.splitlines()):
|
||||
print("%02d: %s" % (idx, line))
|
||||
if len(line) and line[0] != '.':
|
||||
try:
|
||||
encoding, count = ks.asm(line)
|
||||
except:
|
||||
print("bummer")
|
||||
else:
|
||||
exit(0)
|
||||
else:
|
||||
encoding, count = ks.asm(code)
|
||||
|
||||
sc = ""
|
||||
count = 0
|
||||
out = ""
|
||||
for i in encoding:
|
||||
if self.cstyle:
|
||||
out += ("\\x%02x" % i)
|
||||
else:
|
||||
out += ("%02x" % i)
|
||||
sc += "%02x" % i
|
||||
|
||||
count += 1
|
||||
# if bDebug and count % 4 == 0:
|
||||
# out += ("\n")
|
||||
|
||||
return out
|
||||
|
||||
def find_binary(self,data,strf,pos=0):
|
||||
t=strf.split(b".")
|
||||
pre=0
|
||||
offsets=[]
|
||||
while (pre!=-1):
|
||||
pre = data[pos:].find(t[0],pre)
|
||||
if (pre==-1):
|
||||
if len(offsets)>0:
|
||||
for offset in offsets:
|
||||
error = 0
|
||||
rt = offset + len(t[0])
|
||||
for i in range(1, len(t)):
|
||||
if (t[i] == b''):
|
||||
rt += 1
|
||||
continue
|
||||
rt += 1
|
||||
prep = data[rt:].find(t[i])
|
||||
if (prep != 0):
|
||||
error = 1
|
||||
break
|
||||
rt += len(t[i])
|
||||
if error == 0:
|
||||
return offset
|
||||
else:
|
||||
return None
|
||||
else:
|
||||
offsets.append(pre)
|
||||
pre+=1
|
||||
return None
|
||||
|
||||
def read_object(data, definition):
|
||||
'''
|
||||
Unpacks a structure using the given data and definition.
|
||||
'''
|
||||
obj = {}
|
||||
object_size = 0
|
||||
pos=0
|
||||
for (name, stype) in definition:
|
||||
object_size += struct.calcsize(stype)
|
||||
obj[name] = struct.unpack(stype, data[pos:pos+struct.calcsize(stype)])[0]
|
||||
pos+=struct.calcsize(stype)
|
||||
obj['object_size'] = object_size
|
||||
obj['raw_data'] = data
|
||||
return obj
|
||||
|
||||
def print_progress(iteration, total, prefix='', suffix='', decimals=1, bar_length=100):
|
||||
"""
|
||||
Call in a loop to create terminal progress bar
|
||||
@params:
|
||||
iteration - Required : current iteration (Int)
|
||||
total - Required : total iterations (Int)
|
||||
prefix - Optional : prefix string (Str)
|
||||
suffix - Optional : suffix string (Str)
|
||||
decimals - Optional : positive number of decimals in percent complete (Int)
|
||||
bar_length - Optional : character length of bar (Int)
|
||||
"""
|
||||
str_format = "{0:." + str(decimals) + "f}"
|
||||
percents = str_format.format(100 * (iteration / float(total)))
|
||||
filled_length = int(round(bar_length * iteration / float(total)))
|
||||
bar = '█' * filled_length + '-' * (bar_length - filled_length)
|
||||
|
||||
sys.stdout.write('\r%s |%s| %s%s %s' % (prefix, bar, percents, '%', suffix)),
|
||||
|
||||
if iteration == total:
|
||||
sys.stdout.write('\n')
|
||||
sys.stdout.flush()
|
||||
+424
@@ -0,0 +1,424 @@
|
||||
#!/usr/bin/env python3
|
||||
'''
|
||||
Licensed under MIT License, (c) B. Kerler 2018-2019
|
||||
'''
|
||||
|
||||
import argparse
|
||||
import time
|
||||
import os
|
||||
import sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))
|
||||
from Library.utils import *
|
||||
from Library.usb import usb_class
|
||||
from Library.gpt import gpt
|
||||
from Library.sahara import qualcomm_sahara
|
||||
from Library.firehose import qualcomm_firehose, xmlparser
|
||||
|
||||
msmids={
|
||||
0x006220E1: "MSM7227A",
|
||||
0x008110E1: "MSM8210",
|
||||
0x008140E1: "MSM8212",
|
||||
0x009600E1: "MSM8909",
|
||||
0x007050E1: "MSM8916",
|
||||
0x000560E1: "MSM8917",
|
||||
0x008050E1: "MSM8926",
|
||||
0x009180E1: "MSM8928",
|
||||
0x0091B0E1: "MSM8929",
|
||||
0x0072C0E1: "MSM8930",
|
||||
#0x000000E1: "MSM8936",
|
||||
0x0004F0E1: "MSM8937",
|
||||
0x0090B0E1: "MSM8939",
|
||||
0x0006B0E1: "MSM8940",
|
||||
0x009B00E1: "MSM8952",
|
||||
0x000460E1: "MSM8953",
|
||||
#0x000000E1: "MSM8956",
|
||||
0x007B40E1: "MSM8974",
|
||||
0x007B80E1: "MSM8974AB",
|
||||
0x009900E1: "MSM8976",
|
||||
0x109400E1: "MSM8994",
|
||||
0x009470E1: "MSM8996",
|
||||
0x0005F0E1: "MSM8996Pro",
|
||||
0x0005E0E1: "MSM8998",
|
||||
0x000CC0E1: "SDM636",
|
||||
0x0008C0E1: "SDM660"
|
||||
}
|
||||
|
||||
infotbl={
|
||||
"MSM7227A":[[], [], []],
|
||||
"MSM8210": [[], [], []],
|
||||
"MSM8212": [[], [], []],
|
||||
"MSM8909": [[0x100000, 0x18000], [0x5C000, 0x1000], [0x200000, 0x24000]],
|
||||
"MSM8916": [[0x100000, 0x18000], [0x5C000, 0x1000], [0x200000, 0x24000]],
|
||||
"MSM8917": [[0x100000, 0x18000], [0xA0000, 0x6FFF], [0x200000, 0x24000]],
|
||||
"MSM8926": [[], [], []],
|
||||
"MSM8928": [[], [], []],
|
||||
"MSM8929": [[0x100000, 0x18000], [], []],
|
||||
"MSM8930": [[0x100000, 0x18000], [0x700000, 0x1000], []],
|
||||
"MSM8936": [[0x100000, 0x18000], [0x700000, 0x1000], []],
|
||||
"MSM8937": [[0x100000, 0x18000], [0xA0000, 0x6FFF], [0x200000, 0x24000]],
|
||||
"MSM8939": [[], [], []],
|
||||
"MSM8940": [[], [], []],
|
||||
"MSM8952": [[0x100000, 0x18000], [0xA0000, 0x1000], [0x200000, 0x24000]],
|
||||
"MSM8953": [[0x100000, 0x18000], [0xA0000, 0x1000], [0x200000, 0x24000]],
|
||||
"MSM8956": [[], [], []],
|
||||
"MSM8974": [[0xFC010000, 0x18000], [0xFC4B8000, 0x60F0], [0x200000, 0x24000]],
|
||||
"MSM8974AB": [[0xFC010000, 0x18000], [0xFC4B8000, 0x60F0], [0x200000, 0x24000]],
|
||||
"MSM8976": [[0x100000, 0x18000], [0xA0000, 0x1000], [0x200000, 0x24000]],
|
||||
"MSM8994": [[0xFC010000, 0x18000], [0xFC4B8000, 0x6FFF], [0xFE800000, 0x24000]],
|
||||
"MSM8996": [[],[0x70000, 0x6158], [0x200000, 0x24000]],
|
||||
"MSM8996Pro": [[],[0x70000, 0x6158], [0x200000, 0x24000]],
|
||||
"MSM8998": [[], [0x780000, 0x621c], []],
|
||||
"SDM636": [[], [], []],
|
||||
"SDM660": [[], [0x780000, 0x6220], []]
|
||||
}
|
||||
|
||||
def main():
|
||||
info='Qualcomm Sahara / Firehose Client (c) B.Kerler 2018-2019.'
|
||||
parser = argparse.ArgumentParser(description=info)
|
||||
print("\n"+info+"\n\n")
|
||||
parser.add_argument('-loader',metavar="none,<filename>",help='[Option] Flash programmer to load e.g. prog_emmc_firehose.elf', default='')
|
||||
parser.add_argument('-vid',metavar="<vid>",help='[Option] Specify vid, default=0x05c6)', default="0x05C6")
|
||||
parser.add_argument('-pid',metavar="<pid>", help='[Option] Specify pid, default=0x9008)', default="0x9008")
|
||||
parser.add_argument('-maxpayload',metavar="<bytes>",help='[Option] The max bytes to transfer in firehose mode (default=1048576)', type=int, default=1048576)
|
||||
parser.add_argument('-skipwrite', help='[Option] Do not write actual data to disk (use this for UFS provisioning)', action="store_true")
|
||||
parser.add_argument('-skipstorageinit', help='[Option] Do not initialize storage device (use this for UFS provisioning)',action="store_true")
|
||||
parser.add_argument('-memory', metavar="<UFS/eMMC>",help='[Option] Memory type (default=eMMC)',default='eMMC')
|
||||
parser.add_argument('-sectorsize', metavar="<bytes>",help='[Option] Define Disk Sector Size (default=512)',type=int,default=512)
|
||||
parser.add_argument('-lun', metavar="<num>",help='[Option] Define LUN',type=int,default=0)
|
||||
#parser.add_argument('-debug', help='[Option] Enable debug output', action="store_true")
|
||||
parser.add_argument('-debugmode', help='[CMD:Sahara] Switch to Memory Dump mode (Debug only)',action="store_true")
|
||||
parser.add_argument('-debugread', help='[CMD:Sahara] Read Debug Logs',action="store_true")
|
||||
parser.add_argument('-dmss', help='[CMD:Sahara] Switch to DMSS Download mode',action="store_true")
|
||||
parser.add_argument('-streaming', help='[CMD:Sahara] Switch to Streaming Download mode', action="store_true")
|
||||
parser.add_argument('-r', metavar=("<PartName>","<filename>"), help='[CMD:Firehose] Dump entire partition based on partition name', nargs=2,default=[])
|
||||
parser.add_argument('-rf', metavar=("<filename>"),help='[CMD:Firehose] Dump whole lun', default="")
|
||||
parser.add_argument('-rs', metavar=("<start_sector>","<sectors>","<filename>"), help='[CMD:Firehose] Dump from start sector to end sector to file', nargs=3,default=[])
|
||||
parser.add_argument('-pbl', metavar=("<filename>"),help='[CMD:Firehose] Dump boot rom (pbl)', default="")
|
||||
parser.add_argument('-qfp', metavar=("<filename>"), help='[CMD:Firehose] Dump qfprom', default="")
|
||||
parser.add_argument('-memtbl', metavar=("<filename>"), help='[CMD:Firehose] Dump memory table', default="")
|
||||
parser.add_argument('-footer', metavar=("<filename>"), help='[CMD:Firehose] Dump crypto footer', default="")
|
||||
parser.add_argument('-gpt', metavar="<filename>", help='[CMD:Firehose] Dump gpt to file', default="")
|
||||
parser.add_argument('-printgpt', help='[CMD:Firehose] Print gpt', action="store_true")
|
||||
parser.add_argument('-peek', metavar=("<offset>","<length>","<filename>"),help='[CMD:Firehose] Read memory from offset,length to file', nargs=3, default=[])
|
||||
parser.add_argument('-w', metavar=("<partitionname>","<filename>"), help='[CMD:Firehose] Write filename to GPT partition', nargs=2, default=[])
|
||||
parser.add_argument('-ws', metavar=("<start_sector>","<filename>"), help='[CMD:Firehose] Write filename at sector <start_sector>', nargs=2, default=[])
|
||||
parser.add_argument('-e', metavar="<partitionname>", help='[CMD:Firehose] Erase the entire partition specified',default='')
|
||||
parser.add_argument('-es', metavar=("<start_sector>","<num_sectors>"), help='[CMD:Firehose] Erase disk from start sector for number of sectors',nargs=2,default=[])
|
||||
parser.add_argument('-reset', help='[CMD:Firehose] Reset device', action="store_true")
|
||||
parser.add_argument('-getstorageinfo', help='[CMD:Firehose] Get Storage/Flash Info', action="store_true")
|
||||
parser.add_argument('-setbootablestoragedrive', metavar="<number>",
|
||||
help='[CMD:Firehose] Set the physical partition number active for booting',default='')
|
||||
parser.add_argument('-x', metavar="<xmldata>", help='[CMD:Firehose] XML to run in firehose mode', default='')
|
||||
parser.add_argument('-gpt-num-part-entries', metavar="<number>", type=int, help='[CMD:Firehose] Number of partitions', default=None)
|
||||
parser.add_argument('-gpt-part-entry-size', metavar="<number>", type=int, help='[CMD:Firehose] Size of partition entry', default=None)
|
||||
parser.add_argument('-gpt-part-entry-start-lba', metavar="<number>", type=int, help='[CMD:Firehose] Beginning of partition entries', default=None)
|
||||
|
||||
|
||||
args = parser.parse_args()
|
||||
xml = xmlparser()
|
||||
|
||||
mode=""
|
||||
loop=0
|
||||
if args.vid!="":
|
||||
vid=int(args.vid,16)
|
||||
if args.pid!="":
|
||||
pid=int(args.pid,16)
|
||||
cdc = usb_class(vid=vid, pid=pid)
|
||||
sahara = qualcomm_sahara(cdc)
|
||||
|
||||
if args.loader=='none':
|
||||
print("Trying with no loader given ...")
|
||||
sahara.programmer = None
|
||||
elif (args.loader==""):
|
||||
print("Trying with loaders in Loader directory ...")
|
||||
sahara.programmer = None
|
||||
elif (args.loader!=''):
|
||||
print(f"Using loader {args.loader} ...")
|
||||
with open(args.loader, "rb") as rf:
|
||||
sahara.programmer = rf.read()
|
||||
else:
|
||||
print("Sorry, you need a firehose loader (-loader) or try without loader \"-loader none\" !")
|
||||
print("Use with -h for displaying help.")
|
||||
exit(0)
|
||||
|
||||
print("Waiting for the device")
|
||||
|
||||
while (cdc.connected==False):
|
||||
cdc.connected=cdc.connect()
|
||||
if cdc.connected==False:
|
||||
sys.stdout.write('.')
|
||||
if (loop>=20):
|
||||
sys.stdout.write('\n')
|
||||
loop=0
|
||||
loop+=1
|
||||
time.sleep(1)
|
||||
sys.stdout.flush()
|
||||
else:
|
||||
print("Device detected :)")
|
||||
mode=sahara.connect()
|
||||
print(f"Mode detected: {mode}")
|
||||
break
|
||||
|
||||
if mode=="Sahara":
|
||||
m = sahara.info()
|
||||
if args.debugmode:
|
||||
sahara.debug_mode()
|
||||
exit(0)
|
||||
elif args.debugread:
|
||||
sahara.cmdexec_read_debug_data()
|
||||
elif args.dmss:
|
||||
sahara.cmdexec_switch_to_dmss_dload()
|
||||
exit(0)
|
||||
elif args.streaming:
|
||||
sahara.cmdexec_switch_to_stream_dload()
|
||||
exit(0)
|
||||
else:
|
||||
if sahara.upload_firehoseloader()==True:
|
||||
time.sleep(0.3)
|
||||
mode="Firehose"
|
||||
print("Successfully uploaded programmer :)")
|
||||
else:
|
||||
if sahara.programmer and len(sahara.programmer) > 4 and sahara.programmer[:4] == b"\x7fELF":
|
||||
sahara.bit64 = (sahara.programmer[4] == 2)
|
||||
else:
|
||||
sahara.bit64 = True
|
||||
|
||||
if mode=="Firehose":
|
||||
cfg=qualcomm_firehose.cfg()
|
||||
cfg.MemoryName = args.memory
|
||||
cfg.ZLPAwareHost = 1
|
||||
cfg.SkipStorageInit = args.skipstorageinit
|
||||
cfg.SkipWrite = args.skipwrite
|
||||
cfg.MaxPayloadSizeToTargetInBytes = args.maxpayload
|
||||
cfg.SECTOR_SIZE_IN_BYTES=args.sectorsize
|
||||
cfg.bit64=sahara.bit64
|
||||
fh = qualcomm_firehose(cdc,xml,cfg)
|
||||
info=fh.connect(0)
|
||||
if args.gpt!='':
|
||||
fh.cmd_read(args.lun, 0, 0x4000//cfg.SECTOR_SIZE_IN_BYTES, args.gpt)
|
||||
print(f"Dumped GPT to {args.gpt}")
|
||||
exit(0)
|
||||
elif args.printgpt==True:
|
||||
data = fh.cmd_read_buffer(args.lun, 0, 0x4000 // cfg.SECTOR_SIZE_IN_BYTES)
|
||||
if data!='':
|
||||
guid_gpt = gpt(
|
||||
num_part_entries=args.gpt_num_part_entries,
|
||||
part_entry_size=args.gpt_part_entry_size,
|
||||
part_entry_start_lba=args.gpt_part_entry_start_lba,
|
||||
)
|
||||
guid_gpt.parse(data,cfg.SECTOR_SIZE_IN_BYTES)
|
||||
guid_gpt.print()
|
||||
else:
|
||||
print("Error on reading GPT, maybe wrong memoryname given ?")
|
||||
exit(0)
|
||||
elif len(args.r)!=0:
|
||||
if len(args.r)!=2:
|
||||
print("Usage: -r <partitionname> <filename>")
|
||||
exit(0)
|
||||
partitionname=args.r[0]
|
||||
filename=args.r[1]
|
||||
data = fh.cmd_read_buffer(args.lun, 0, 0x4000 // cfg.SECTOR_SIZE_IN_BYTES,False)
|
||||
guid_gpt = gpt(
|
||||
num_part_entries=args.gpt_num_part_entries,
|
||||
part_entry_size=args.gpt_part_entry_size,
|
||||
part_entry_start_lba=args.gpt_part_entry_start_lba,
|
||||
)
|
||||
guid_gpt.parse(data, cfg.SECTOR_SIZE_IN_BYTES)
|
||||
|
||||
for partition in guid_gpt.partentries:
|
||||
if partition.name==partitionname:
|
||||
data = fh.cmd_read(args.lun, partition.sector, partition.sectors, filename)
|
||||
print(f"Dumped sector {str(partition.sector)} with sector count {str(partition.sectors)} as {filename}.")
|
||||
exit(0)
|
||||
print(f"Error: Couldn't detect partition: {partitionname}")
|
||||
exit(0)
|
||||
elif args.rf!='':
|
||||
filename=args.rf
|
||||
data = fh.cmd_read_buffer(args.lun, 0, 0x4000 // cfg.SECTOR_SIZE_IN_BYTES,False)
|
||||
guid_gpt = gpt(
|
||||
num_part_entries=args.gpt_num_part_entries,
|
||||
part_entry_size=args.gpt_part_entry_size,
|
||||
part_entry_start_lba=args.gpt_part_entry_start_lba,
|
||||
)
|
||||
guid_gpt.parse(data, cfg.SECTOR_SIZE_IN_BYTES)
|
||||
data = fh.cmd_read(args.lun, 0, guid_gpt.totalsectors, filename)
|
||||
print(f"Dumped sector 0 with sector count {str(guid_gpt.totalsectors)} as {filename}.")
|
||||
exit(0)
|
||||
elif args.pbl!='':
|
||||
filename=args.pbl
|
||||
if fh.cfg.TargetName in infotbl:
|
||||
v=infotbl[fh.cfg.TargetName]
|
||||
if len(v[0])>0:
|
||||
if fh.cmd_peek(v[0][0],v[0][1],filename):
|
||||
print(f"Dumped pbl at offset {hex(v[0][0])} as {filename}.")
|
||||
exit(0)
|
||||
else:
|
||||
print("No known pbl offset for this chipset")
|
||||
else:
|
||||
print("Unknown target chipset")
|
||||
print("Error on dumping pbl")
|
||||
exit(0)
|
||||
elif args.qfp!='':
|
||||
filename=args.qfp
|
||||
if fh.cfg.TargetName in infotbl:
|
||||
v=infotbl[fh.cfg.TargetName]
|
||||
if len(v[1])>0:
|
||||
if fh.cmd_peek(v[1][0],v[1][1],filename):
|
||||
print(f"Dumped qfprom at offset {hex(v[1][0])} as {filename}.")
|
||||
exit(0)
|
||||
else:
|
||||
print("No known qfprom offset for this chipset")
|
||||
else:
|
||||
print("Unknown target chipset")
|
||||
print("Error on dumping pbl")
|
||||
exit(0)
|
||||
elif args.memtbl!='':
|
||||
filename=args.memtbl
|
||||
if fh.cfg.TargetName in infotbl:
|
||||
v=infotbl[fh.cfg.TargetName]
|
||||
if len(v[2])>0:
|
||||
if fh.cmd_peek(v[2][0],v[2][1],filename):
|
||||
print(f"Dumped qfprom at offset {hex(v[2][0])} as {filename}.")
|
||||
exit(0)
|
||||
else:
|
||||
print("No known qfprom offset for this chipset")
|
||||
else:
|
||||
print("Unknown target chipset")
|
||||
print("Error on dumping pbl")
|
||||
exit(0)
|
||||
elif args.footer!='':
|
||||
filename=args.footer
|
||||
data = fh.cmd_read_buffer(args.lun, 0, 0x4000 // cfg.SECTOR_SIZE_IN_BYTES,False)
|
||||
guid_gpt = gpt(
|
||||
num_part_entries=args.gpt_num_part_entries,
|
||||
part_entry_size=args.gpt_part_entry_size,
|
||||
part_entry_start_lba=args.gpt_part_entry_start_lba,
|
||||
)
|
||||
guid_gpt.parse(data, cfg.SECTOR_SIZE_IN_BYTES)
|
||||
pnames=["userdata2","metadata","userdata","reserved1","reserved2","reserved3"]
|
||||
for partition in guid_gpt.partentries:
|
||||
if partition.name in pnames:
|
||||
print(f"Detected partition: {partition.name}")
|
||||
data = fh.cmd_read_buffer(args.lun, partition.sector+(partition.sectors-(0x4000 // cfg.SECTOR_SIZE_IN_BYTES)), (0x4000 // cfg.SECTOR_SIZE_IN_BYTES), filename)
|
||||
val=struct.unpack("<I",data[:4])[0]
|
||||
if ((val&0xFFFFFFF0)==0xD0B5B1C0):
|
||||
with open(filename,"wb") as wf:
|
||||
wf.write(data)
|
||||
print(f"Dumped footer from {partition.name} as {filename}.")
|
||||
exit(0)
|
||||
print(f"Error: Couldn't detect partition: {partitionname}")
|
||||
exit(0)
|
||||
elif len(args.rs)!=0:
|
||||
if len(args.rs)!=3:
|
||||
print("Usage: -rs <start_sector> <sectors> <filename>")
|
||||
exit(0)
|
||||
start=int(args.rs[0])
|
||||
sectors=int(args.rs[1])
|
||||
filename=args.rs[2]
|
||||
data = fh.cmd_read(args.lun, start, sectors, filename)
|
||||
print(f"Dumped sector {str(start)} with sector count {str(sectors)} as {filename}.")
|
||||
exit(0)
|
||||
elif len(args.peek)!=0:
|
||||
if len(args.peek)!=3:
|
||||
print("Usage: -peek <offset> <length> <filename>")
|
||||
exit(0)
|
||||
offset=int(args.peek[0],16)
|
||||
length=int(args.peek[1],16)
|
||||
filename=args.peek[2]
|
||||
fh.cmd_peek(offset,length,filename)
|
||||
exit(0)
|
||||
elif args.reset:
|
||||
fh.cmd_reset()
|
||||
exit(0)
|
||||
elif args.setbootablestoragedrive!='':
|
||||
fh.cmd_setbootablestoragedrive(int(args.setbootablestoragedrive))
|
||||
exit(0)
|
||||
elif args.getstorageinfo:
|
||||
fh.cmd_getstorageinfo()
|
||||
exit(0)
|
||||
elif len(args.w) != 0:
|
||||
if len(args.w) != 2:
|
||||
print("Usage: -w <partitionname> <filename>")
|
||||
exit(0)
|
||||
partitionname=args.w[0]
|
||||
filename=args.w[1]
|
||||
if not os.path.exists(filename):
|
||||
print(f"Error: Couldn't find file: {filename}")
|
||||
exit(0)
|
||||
data = fh.cmd_read_buffer(args.lun, 0, 0x4000 // cfg.SECTOR_SIZE_IN_BYTES,False)
|
||||
guid_gpt = gpt(
|
||||
num_part_entries=args.gpt_num_part_entries,
|
||||
part_entry_size=args.gpt_part_entry_size,
|
||||
part_entry_start_lba=args.gpt_part_entry_start_lba,
|
||||
)
|
||||
guid_gpt.parse(data, cfg.SECTOR_SIZE_IN_BYTES)
|
||||
|
||||
for partition in guid_gpt.partentries:
|
||||
if partition.name==partitionname:
|
||||
sectors=os.stat(filename).st_size//fh.cfg.SECTOR_SIZE_IN_BYTES
|
||||
if (os.stat(filename).st_size%fh.cfg.SECTOR_SIZE_IN_BYTES)>0:
|
||||
sectors+=1
|
||||
if sectors>partition.sectors:
|
||||
print(f"Error: {filename} has {sectors} sectors but partition only has {partition.sectors}.")
|
||||
exit(0)
|
||||
data = fh.cmd_write(args.lun, partition.sector, filename)
|
||||
print(f"Wrote {filename} to sector {str(partition.sector)}.")
|
||||
exit(0)
|
||||
print(f"Error: Couldn't detect partition: {partitionname}")
|
||||
exit(0)
|
||||
elif len(args.ws)!=0:
|
||||
if len(args.ws)!=2:
|
||||
print("Usage: -ws <start_sector> <filename>")
|
||||
exit(0)
|
||||
start=int(args.ws[0])
|
||||
filename=args.ws[1]
|
||||
if not os.path.exists(filename):
|
||||
print(f"Error: Couldn't find file: {filename}")
|
||||
exit(0)
|
||||
if fh.cmd_write(args.lun, start, filename)==True:
|
||||
print(f"Wrote {filename} to sector {str(start)}.")
|
||||
else:
|
||||
print(f"Error on writing {filename} to sector {str(start)}")
|
||||
exit(0)
|
||||
elif args.e != '':
|
||||
partitionname=args.e
|
||||
data = fh.cmd_read_buffer(args.lun, 0, 0x4000 // cfg.SECTOR_SIZE_IN_BYTES,False)
|
||||
guid_gpt=gpt(
|
||||
num_part_entries=args.gpt_num_part_entries,
|
||||
part_entry_size=args.gpt_part_entry_size,
|
||||
part_entry_start_lba=args.gpt_part_entry_start_lba,
|
||||
)
|
||||
guid_gpt.parse(data, cfg.SECTOR_SIZE_IN_BYTES)
|
||||
|
||||
for partition in guid_gpt.partentries:
|
||||
if partition.name==partitionname:
|
||||
fh.cmd_erase(args.lun, partition.sector, partition.sectors)
|
||||
print(f"Erased {partitionname} starting at sector {str(partition.sector)} with sector count {str(partition.sectors)}.")
|
||||
exit(0)
|
||||
print(f"Error: Couldn't detect partition: {partitionname}")
|
||||
exit(0)
|
||||
elif len(args.es)!=0:
|
||||
if len(args.es)!=2:
|
||||
print("Usage: -ws <start_sector> <sectors>")
|
||||
exit(0)
|
||||
start=int(args.es[0])
|
||||
sectors=int(args.es[1])
|
||||
data = fh.cmd_erase(args.lun, start, sectors)
|
||||
print(f"Erased sector {str(start)} with sector count {str(sectors)}.")
|
||||
exit(0)
|
||||
elif args.x != '':
|
||||
data=fh.cmd_xml(args.x)
|
||||
exit(0)
|
||||
else:
|
||||
print("Unknown/Missing command, a command is required.")
|
||||
exit(0)
|
||||
else:
|
||||
print("Sorry, couldn't talk to Sahara, please reboot the device !")
|
||||
exit(0)
|
||||
|
||||
|
||||
exit(0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in new issue
Block a user