Compare commits

...
Author SHA1 Message Date
Workbench IA 8037181992 Rétablir le redémarrage à chaud de SpringBoard et de l’affichage 2026-10-01 10:12:48 +00:00
Mahtan 0286ad8380 Merge pull request 'Rétablir PPP après un reset matériel de l’iPod' (#5) from agent/reprise-ppp into ipod_touch_2g 2026-10-01 11:33:12 +02:00
Workbench IA 993cd88488 Rétablir le lien PPP après un reset matériel 2026-10-01 09:31:36 +00:00
Mahtan 6fc3f004cc Merge pull request 'Valider iPhone OS 2.1.1 et rendre les tests Safari reproductibles' (#3) from agent/validation-iphoneos21 into ipod_touch_2g 2026-10-01 09:47:59 +02:00
Workbench IA 53ebaa7e40 Réconcilier la validation 2.1.1 avec le RTC D1759 2026-10-01 07:47:57 +00:00
Mahtan 11a98a7bac Merge pull request 'Émuler le RTC D1759 dès le démarrage' (#4) from agent/rtc-d1759 into ipod_touch_2g 2026-10-01 09:45:44 +02:00
Workbench IA d2c3478fa6 Émuler le RTC D1759 et supprimer le réglage automatique de l'heure 2026-10-01 07:41:33 +00:00
Workbench IA 21a155d35f Valider iPhone OS 2.1.1 et documenter les tests des applications 2026-10-01 07:17:19 +00:00
Mahtan 436bdc536c Valider les boutons, le tactile et les outils du simulateur
Relecture et validations locales terminées : iPhone OS 2.2.1 et 2.1.1, gestes, HTTP, saisie, installation et persistance.
2026-10-01 09:15:58 +02:00
Workbench IA 5f65af21fc Fiabiliser les transferts et automatiser les tests d'applications 2026-09-30 16:27:48 +00:00
Workbench IA 524e9bbb17 Corriger les accès GPIO et fiabiliser le tactile au réveil 2026-09-30 16:25:06 +00:00
Mahtan e0fd5d5eff Fiabiliser le simulateur et déverrouiller SpringBoard après installation
Relecture et validations locales effectuées : démarrage v11, installation persistante et lancement HelloEmu, session déjà lancée, erreurs QEMU et réseau.
2026-09-30 17:13:13 +02:00
Workbench IA 7b6afeb477 Attendre le déverrouillage d’une session déjà lancée 2026-09-30 15:12:13 +00:00
Workbench IA e28583407a Déverrouiller SpringBoard avant le lancement des applications 2026-09-30 15:08:21 +00:00
Workbench IA 72c64688f1 Fiabiliser la reprise du simulateur après déplacement des homes 2026-09-30 14:38:10 +00:00
Codex 163e253af8 Support iPod OS 2.2.1 networking and persistent NAND writes
Implement UART/PPP support, firmware AES/SHA1 compatibility, production VSVFL NAND page programming and block erases, and display clock status.

Preserve the host tools, emuagent v10, firmware generation helpers, dependency patches and handoff in contrib/ipod-emu. NAND data survives restart; application installation can still leave SpringBoard reporting device locked.
2026-09-30 13:15:07 +00:00
Martijn de Vos 328815631b Merge pull request #213 from mrcxlinux/ipod_touch_2g
Include commands for Arch Linux and it's derivatives (RUNNING.MD)
2025-01-02 09:20:51 +01:00
陈华 c5998ab084 Include commands for Arch Linux and it's derivatives 2025-01-01 17:57:06 +02:00
Martijn de Vos 1c586e8a0c Also fixed type of fsize in SPI 2024-12-25 09:46:50 +01:00
Martijn de Vos 7022646c4d Fixed gsize type 2024-12-24 09:06:06 +01:00
Martijn de Vos fa0981b602 Merge pull request #205 from devos50/brightness
Added support for brightness
2024-12-22 11:44:06 +01:00
daniilfigasystems 0cb390e281 Added support for brightness 2024-12-22 11:41:17 +01:00
Martijn de Vos 0d8014f8db Fixed path to configure 2024-12-22 10:39:03 +01:00
Martijn de Vos e241f91a5b Merge pull request #176 from Patrosi73/ipod_touch_2g
fix swapLong argument
2024-08-04 16:44:39 +02:00
PatRyk 4400b861c8 Update ipod_touch_sha1.c
fix swapLong argument
2024-08-04 16:34:49 +02:00
Martijn de Vos cae1b51a78 Merge pull request #172 from daniilfigasystems/ipod_touch_2g
Bugfix
2024-07-31 09:30:34 +02:00
daniilfigasystems a99e51abfa Format code, add more verbosity (for implementing lock screen), fixed warnings 2024-07-31 11:22:16 +09:00
daniilfigasystems ce74809f11 Rename unknown1 to render 2024-07-31 11:00:16 +09:00
daniilfigasystems ceb93afd79 Fix printf newline 2024-07-31 10:58:04 +09:00
Martijn de Vos bad3d0cc90 Merge pull request #170 from daniilfigasystems/ipod_touch_2g
Fixed bugs added new devices
2024-07-30 13:01:57 +02:00
daniilfigasystems 82b95a84a3 Add ctrl reg axis enabled check 2024-07-30 11:35:19 +09:00
daniilfigasystems 28f87fc7d6 Fixed bugs added new devices
Fixed unexpected CLCD interrupt (for now only unexcepted interrupt from mulltitouch), added audio codec skeleton, added light sensor, fixed pressing other buttons lead to crash, added kernel patch check (improves perfomance a little), added more verbosity, planning to add working wifi (need datasheet)
2024-07-30 10:22:49 +09:00
olivia1246 973b5a90ef Build on Linux (Ubuntu) (RUNNING.md) (#143)
* Update RUNNING.md

I think is good now super big thanks to https://github.com/Polytelus on https://github.com/devos50/qemu-ios/issues/92 and ChatGPT lolz

* Update RUNNING.md

thanks for pointing it out https://github.com/MrDiagnose I didnt realise that

* Update RUNNING.md

thank you everyone for the build dir recommendation

* Update RUNNING.md

a little space for easier copying I hope
2024-07-29 20:47:34 +02:00
91 changed files with 7065 additions and 257 deletions

No files matched your search

+19
View File
@@ -2,6 +2,18 @@
This file contains the instructions on how to run the iPod Touch 2G emulator using QEMU.
Note that this is an experimental release and the functionality of the device is still limited.
Linux compatibility is currently unstable. Efforts are underway to improve it.
### Getting the Source Code
Clone the repository using the following commands:
```
git clone https://github.com/devos50/qemu-ios.git
cd qemu-ios
```
Now you can proceed with the rest of the instructions for building and running the emulator.
### Building QEMU
@@ -14,6 +26,9 @@ brew install glib ninja pixman pkg-config sdl2
# On Linux (Ubuntu)
sudo apt install make ninja-build pkg-config libssl-dev libsdl2-dev libpixman-1-dev libpixman-1-0 libglib2.0-dev
# On Linux (Arch)
sudo pacman -S --needed make ninja pkgconf openssl sdl2 pixman glib2
# On Windows (MSYS2/mingw64)
pacman -S base-devel mingw-w64-x86_64-toolchain git python ninja mingw-w64-x86_64-glib2 mingw-w64-x86_64-pixman python-setuptools mingw-w64-x86_64-SDL2
@@ -23,12 +38,16 @@ Compile QEMU by running the following commands from the root directory:
```
mkdir build
cd build
# On Intel Macs
../configure --target-list=arm-softmmu --extra-cflags=-I/usr/local/opt/openssl@3/include --extra-ldflags='-L/usr/local/opt/openssl@3/lib -lcrypto'
# On Apple Silicon Macs
../configure --enable-sdl --target-list=arm-softmmu --disable-capstone --disable-pie --disable-slirp --extra-cflags=-I/opt/homebrew/opt/openssl@3/include --extra-ldflags='-L/opt/homebrew/opt/openssl@3/lib -lcrypto'
# On Linux
../configure --enable-sdl --disable-cocoa --target-list=arm-softmmu --disable-capstone --disable-slirp --extra-cflags=-I/usr/include/openssl --extra-ldflags='-lcrypto' --disable-werror --enable-pie
# On Microsoft Windows (with MINGW64)
../configure --enable-sdl --disable-cocoa --target-list=arm-softmmu --disable-capstone --disable-slirp --disable-pie --extra-cflags=-I/mingw64/include/openssl --extra-ldflags='-L/mingw64/lib -lcrypto' --disable-stack-protector --disable-werror
+24
View File
@@ -0,0 +1,24 @@
__pycache__/
*.pyc
/agent/emuagent
/agent/overlay/
/netd/ipod-netd
/gen-v1/generate_nand_v1
/apps/HelloEmu/HelloEmu.app/HelloEmu
/assets/
/images/
/ipsw/
/run/
/work/
/fs/
/fw-*/
/*.img
/keys-*.txt
/dmg2img/
/xpwn/
/qemu-ios-generate-nand/
/qemu-ios-generate-nor/
!/patches/
!/patches/*.patch
/apps/TouchProbe/TouchProbe.app/
+326
View File
@@ -0,0 +1,326 @@
# Passation — simulateur iPod Touch 2G / iPhone OS 2.2.1
État au 2026-10-01. Environnement : conteneur Arch Linux, utilisateur `dev` avec sudo, sans `CAP_NET_ADMIN`, sans `/dev/ppp` ni TUN.
## Redémarrage à chaud de l'interface
Le blocage de `respring` est reproduit sur 5H11a : le nouveau SpringBoard reste
bloqué dans `IOServiceClose`, après l'ouverture d'AppleM2TVOut. Le modèle de
sortie TV limitait ses interruptions à deux pour toute la vie de QEMU. Il répond
maintenant à chaque soumission, conserve les événements masqués et acquitte les
bits demandés. Le LCD dispose également de registres distincts pour le masque
(0x08) et l'état W1C (0x0c), conformément aux accès du pilote AppleM2CLCD.
Pour le reset matériel, les états LCD, TV et MIPI sont réinitialisés. La machine
réalise désormais le périphérique MIPI : sans cette étape, son callback de reset
n'était jamais appelé, ce qui faisait échouer la lecture de l'identifiant de dalle.
Le tactile libère les transferts/trames en cours, annule ses timers et relâche
son interruption. SPI vide ses FIFO et abaisse aussi sa ligne d'interruption.
`ipod-emu respring -W` et `ipod-emu reset -W` synchronisent la NAND, mémorisent
la position du journal puis attendent uniquement les nouveaux marqueurs. Le
client `unlock` utilise la même position. `ipod-agent respring` et `ipod-qmp reset`
restent des commandes brutes ; utiliser le lanceur pour attendre le nouveau boot.
Régressions : neuf tests tactile/SPI et trois tests d'affichage sous ASan/UBSan,
cinq tests du lanceur et trois resets QMP/QTest des périphériques d'affichage
réels. Le test natif `tests/test-display-session.py` vérifie le déverrouillage,
la calculatrice au premier plan, HTTP local, le fichier témoin en NAND et les PID
QEMU/relais conservés. Diagnostics : `work/interface-20261001/`.
Validation native finale : trois resprings et deux resets complets par firmware
(5H11a et 5F138), avec les mêmes PID QEMU/relais. La calculatrice affiche
`7 × 8 = 56` après les relances sur les deux versions. Les resprings complets
prennent environ 26–28 s, les resets 64–80 s dans cet environnement partagé.
Synthèse : `work/interface-20261001/validation-finale.json`.
La session utilisateur sur VNC 5900 reste sur le binaire précédemment déployé.
## Reprise PPP après reset matériel
L'UART possède maintenant un callback de reset : registres et FIFO remis à
zéro, IRQ baissée, `qemu_chr_fe_disconnect` sur la connexion série. La fermeture
fait repartir la machine LCP/IPCP du relais existant, sans tuer `ipod-netd` ni
QEMU et sans remplacer la NAND. `ipod-qmp reset` expose le reset brut ; faire
`ipod-agent sync` avant son utilisation.
Validation native avec l'agent v12 : deux resets successifs par firmware,
5H11a (48,2 / 51,3 s) et 5F138 (48,4 / 51,6 s), mêmes PID QEMU et relais,
fichier témoin conservé et requête HTTP locale réussie depuis l'iPod.
Le diagnostic attend `ppp0 up` et `configd publié`, puis laisse cinq secondes
au réseau avant les transferts. Des fermetures TCP ponctuelles ont été observées
avec des requêtes immédiatement après les premiers pings ; un ping isolé ne
suffit donc pas à qualifier la stabilité du service.
Les deux régressions UART passent sous ASan/UBSan, dont trois reconnexions avec
émission et réception sur un vrai backend socket QEMU.
Les premiers essais du correctif PPP laissaient encore l'affichage bloqué après
reset. Les causes et les corrections sont décrites dans la section précédente.
Les anciens diagnostics sont conservés dans `work/ppp-20261001` ; ils précèdent
la correction de la sortie TV et ne décrivent plus l'état actuel du code.
## Dernière mise à jour — RTC D1759
Le modèle `d1759` remplace `pcf50633` sur la machine 2G. Il corrige le
pointeur I²C et fournit le compteur LE32 en `0x5c` avec décalage Unix LE32 en
`0x64`. Les notes anciennes attribuant un accès indirect RTC à `0x61/0x62`
étaient incorrectes : ces registres concernent le démarrage.
`start -W` et `wait` ne règlent plus l'heure via l'agent.
Voir [RTC.md](RTC.md) pour le protocole, les preuves et les limites.
Le raccordement GPIO est aussi borné aux cinq IRQ définies, pour éviter
l'accès hors limites révélé à la recompilation.
## Validation du 1er octobre 2026 — iPhone OS 2.1.1
- Image distincte `5F138-validation-20261001`, créée depuis la base 5F138 conservée,
avec agent v12, TouchProbe et HelloEmu. Session : `work/validation-20261001/`.
`system-version.plist` confirme 2.1.1 / 5F138 ; démarrage déverrouillé en 28 s.
- Calibration : sept points exacts de `(20,40)` à `(300,460)` dans
`calibration-complete.log`, après attente du marqueur `TouchProbe ready`.
Les ordonnées du journal sont relatives à la vue, située à y=20.
- Six cycles alternant Power/Home et Power/Power passent, sans perte du tactile.
- Safari : clavier virtuel QWERTY, formulaire envoyé avec `texte=bonjour`,
défilement jusqu'au lien final et requête `/fin` reçue par le serveur HTTP local.
Journal : `http/requests.jsonl`. Une version réutilisable de la page et du serveur
est fournie dans `tests/http-fixture.py` ; aucun site extérieur n'est requis.
- Calculatrice : `7 × 8 = 56`, capture `calculatrice-56.png`.
- Notes : note « Bonjour » créée par le clavier virtuel puis sauvegardée.
Les lignes de `Note` et `note_bodies` sont identiques dans `notes-avant.db` et
`notes-apres.db`, et la note réapparaît dans l'interface après redémarrage.
- Nouvelle app `HelloEmu21.app` (bundle-id `com.ioslegacy.hello21`) installée via
`push-app`, cache reconstruit, redémarrage sans réinitialiser la NAND en 50 s,
lancement au premier plan et journal HelloEmu validés. Captures :
`hello21-apres-push.png` et `note-apres-reboot.png`.
- Synthèse locale : `validation.json`. Session et serveur HTTP de test arrêtés.
Aucun défaut `Killing device`, `Fatal Exception` ou `MACH Reboot` relevé dans
la console finale. Les images et NAND d'origine sont conservées.
- Particularités : l'image 5F138 conserve ses réglages de langue et de fuseau
d'origine ; les captures sont en anglais. Le lancement `--url` d'un Safari
déjà ouvert n'a pas changé la page pendant le test : passer par les liens ou
relancer le navigateur. Le RTC est depuis implémenté (voir ci-dessus) ; la veille profonde reste à faire.
## Historique — fiabilisation GPIO/SPI et agent v12
Les sections de diagnostic plus anciennes ci-dessous décrivent les étapes précédentes.
Le workflow `push-app` puis déverrouillage/lancement a été validé avec l'agent v11.
Cette suite corrige les débordements GPIO/SYSIC, les commandes tactiles invalides,
les trames instables et les transactions SPI abandonnées à la reprise de l'écran.
Huit cycles veille/réveil alternant Home et Power ont passé sur 5H11a sans perte
du tactile. La calibration TouchProbe retrouve les coordonnées écran sur sept
points ; la vitesse verticale et le calcul signé des vitesses sont corrigés.
L'agent v12 conserve le protocole et transfère par blocs de 64 Kio avec fichiers
temporaires distincts. `ipod-test-app` prépare une NAND indépendante, vérifie le
premier plan, récupère journal et capture, puis arrête sa propre session.
Voir le README pour les commandes et les tests reproductibles ASan/UBSan.
Validation finale : huit régressions matérielles avec ASan/UBSan et sept tests
sur les transferts ; HelloEmu réussit le workflow automatique, l'application
absente échoue avec capture et arrêt de la VM. Un fichier de 8 460 608 octets
fait l'aller-retour via l'agent v12 avec SHA-256 identique. Trois cycles de
veille/réveil supplémentaires avec la calibration finale et l'agent v12 passent,
puis HelloEmu se lance au premier plan avec son journal. Diagnostics locaux :
`work/fiabilisation-20260930/` (dont `test-hello`, `test-echec`, `hello-final.png`).
Les sessions de validation sont arrêtées.
Les fichiers générés, images et diagnostics restent hors du dépôt. Les images
5H11a et les NAND d'origine sont conservées ; le RTC, le Wi-Fi matériel, l'audio
et la veille profonde restent à implémenter. Les nouveaux correctifs n’étaient
pas encore validés sur 5F138 à cette étape.
## Objectif
On fournit un simulateur d'**iPod Touch 2G sous iPhone OS 2.2.1** qui sert surtout à un agent IA pour tester les applications iOS 2.x d'AlloVoisins. Les apps sont compilées en armv6 avec `/opt/cctools` et `/opt/theos/sdks/iPhoneOS2.2.1.sdk`. L'agent doit pouvoir faire les choses suivantes, sans intervention humaine :
- installer une app ;
- la lancer ;
- lire ses logs ;
- toucher l'écran et prendre des captures ;
- utiliser le réseau.
On veut le comportement le plus fidèle possible à un vrai appareil. La consigne de l'utilisateur est de travailler en autonomie et de se créer ses propres outils, voire une skill.
## Ce qui marche
- **Boot 2.2.1 (5H11a)**, SpringBoard prêt en environ 25 s.
- **2.1.1 (5F138)** marche aussi, avec l'ancienne image de devos50.
- **Écran** : capture 320×480 par QMP. Touch, boutons et VNC sur `127.0.0.1:5900`.
- **Réseau / Internet** : PPP sur l'UART1 émulée, relié à `ipod-netd` côté hôte (libslirp, en userland).
- iPod en 10.0.2.15, passerelle 10.0.2.2, DNS 10.0.2.3.
- Le DNS et HTTP marchent depuis l'iPod, et Safari affiche example.com.
- **Agent sur l'iPod** (`emuagent`, v10), joignable depuis l'hôte sur `127.0.0.1:7788` via `ipod-agent`. Commandes :
- `launch` (bundle id, avec `--log` pour stdout/stderr et `--url`), `apps`, `front` ;
- `exec`, `ps`, `kill`, `respring` ;
- `put`, `get`, `ls`, `rm`, `mkdir` ;
- `fetch`, `net`, `routes`, `sc` (SCDynamicStore) ;
- `settime`, `sync`.
- **Persistance NAND** : programmation des pages et métadonnées, effacement des blocs de 128 pages et détection des
pages vierges fonctionnent avec le format VSVFL de production. La base 5H11a a été migrée ; `nand-write=on` est
inscrit dans ses options machine. Les nouveaux `ipod-build-fw` / `ipod-mkimage` utilisent `gen-v1/mknand`.
- **Apps** : `ipod-mkimage MonApp.app|.ipa|.deb|dossier/` construit une image dérivée. Les apps signées avec `ldid` passent grâce au boot-arg `amfi_allow_any_signature`.
- **Heure** : `start -W` / `wait` envoie `settime` dès que l'agent répond, avant la fin du démarrage de SpringBoard.
Ce réglage précoce évite d'initialiser les timers de l'interface en 1970 avec des préférences datées dans le futur.
- **Veille** : agent v10, propriété `SleepDisabled=true` sur `IOPMrootDomain` (acceptée). Les assertions publiques
`IOPMAssertionCreateWithName` sont non supportées sur ce firmware. Le SoC ne sait toujours pas reprendre une veille.
- **Réglages de l'image** : langue fr, région fr_FR, fuseau Europe/Paris. Verrouillage auto désactivé, pas d'alerte « Edit Home Screen ».
- **Reconstruction complète** depuis l'IPSW Apple : `ipod-build-fw 5H11a`.
## Limites connues, et suite logique par priorité
1. **Installation / lancement dans une session conservée** : les apps copiées dans `/Applications` sont maintenant
persistées, mais la reconstruction du catalogue lors d'un `respring` reste peu fiable. `push-app` synchronise puis
redémarre l'émulateur **sans `-f` et sans reconstruire l'image**. Le lancement après ce redémarrage répond encore
parfois `device locked` ; un écran de code a été observé dans l'image de test. Ne pas annoncer ce workflow comme
entièrement validé. `ipod-mkimage` reste disponible pour intégrer l'app avant le premier démarrage.
- La persistance elle-même est validée : témoin texte et binaire de 256 Kio identiques après redémarrage ; fichier
aléatoire de 8 Mio conservé, SHA-1 calculé dans l'iPod identique à l'hôte :
`4d322e06f3433b874bc77d8b0298d97346210eb5`.
- Le téléchargement de 8 Mio par `get` a été tronqué. Le client vérifie désormais la longueur reçue et signale
ce cas. Utiliser un calcul d'empreinte dans l'iPod pour distinguer le transport de l'intégrité NAND.
- Ancienne base sauvegardée : `images/5H11a/nand-readonly-backup`, `rootfs-v8-backup.img`,
`machine-opts-readonly-backup`. Session d'origine : `run/nand-before-persistence` et `fw-before-persistence`.
Session de test avec app et fichier de 8 Mio : `run/nand-persistence-verified` (firmware `persistence-test-v10`).
2. **Horloge RTC du PMU** : compteur et décalage D1759 implémentés ; IRQ d'alarme et persistance du décalage entre instances QEMU restent absentes. Voir la dernière mise à jour et `RTC.md`.
3. **Réglages > Wi-Fi** affiche « Pas de Wi-Fi », parce que la puce BCM4325 n'est pas émulée. Le réseau passe par une interface ppp0, que l'app peut voir comme un VPN ou une connexion transitoire. Émuler le WiFi pour de vrai (SDIO + firmware FullMAC) serait un gros chantier ; le pont slirp est réutilisable.
4. **Pas encore écrits** :
- un script `ipod-test-app` (construit l'image, boote, lance l'app avec `--log`, fait une capture, affiche les logs) ;
- une **skill** Claude/Codex qui documente ce workflow ;
- la mise à jour de `~/ipod-emu/README.md` (réseau, agent, heure, français).
5. **Mise à jour de l'agent à chaud** (`put` puis `kill emuagent`) : elle coupe PPP pendant la renégociation. Préférer reconstruire l'image.
## Démarrer
```bash
ipod-emu start -f -W # 2.2.1 (défaut), NAND vierge, attend SpringBoard
ipod-agent ping # l'agent répond quand PPP est monté (quelques secondes)
ipod-agent launch com.apple.mobilesafari --url http://example.com/
ipod-qmp screenshot /tmp/s.png # tap X Y | swipe | home | hmp "info registers"
ipod-emu stop
```
Ne **jamais** toucher l'écran avant la fin de `ipod-emu wait` ou `start -W` : le contrôleur tactile fait planter QEMU s'il est touché pendant son démarrage.
Logs :
- `~/ipod-emu/run/serial.log` : console kernel et syslog, pppd, emuagent ;
- `~/ipod-emu/run/qemu.log` ;
- `~/ipod-emu/run/netd.log` : avec `IPOD_NETD_FWD=-v`, trace de chaque paquet IP.
Debug : `IPOD_QEMU_EXTRA="-d unimp,guest_errors -D ~/ipod-emu/run/int.log"` ; `IPOD_QEMU=~/ipod-emu/bin/qemu-gdb` pour avoir une backtrace en cas de crash.
## Carte des fichiers
| Où | Quoi |
|---|---|
| `~/qemu-ios` | Fork Mahtan/devos50 (branche ipod_touch_2g). Sources et outils sauvegardés dans le dépôt (outils sous `contrib/ipod-emu`). Build : `cd build && make -j4` |
| `/opt/ios-legacy/bin/` | Copies installées des outils (réinstaller avec `sudo install -m 755 ~/ipod-emu/bin/X /opt/ios-legacy/bin/`) |
| `~/ipod-emu/bin/ipod-emu` | Launcher : QEMU (serial0 = fichier, serial1 = `run/uart1.sock`), ipod-netd, wait, settime |
| `~/ipod-emu/bin/ipod-qmp` | Écran, touch, boutons, HMP |
| `~/ipod-emu/bin/ipod-agent` | Client de l'agent (protocole : ligne à champs séparés par TAB, réponse `OK <n> [info]\n` + n octets) |
| `~/ipod-emu/bin/ipod-mkimage` | Image dérivée avec apps / .deb / overlay (re-signe avec `ldid` en **gardant les entitlements**) |
| `~/ipod-emu/bin/ipod-build-fw` | IPSW → NOR + rootfs (`mkbase-rootfs`) + NAND (`gen-v1/mknand`, VSVFL de production, signature 2 et écritures activées) |
| `~/ipod-emu/bin/mkbase-rootfs` | LaunchDaemons réduits, fstab rw, Lockdown (`assets/`), prefs, fr/Paris, **intègre `agent/overlay`** |
| `~/ipod-emu/agent/` | `emuagent.c` + `Makefile` (`make` → `overlay/`), `entitlements.plist` (`com.apple.springboard.launchapplications` etc., **indispensables** pour `SBSLaunchApplication`) |
| `~/ipod-emu/netd/ipod-netd.c` | Serveur PPP (HDLC, LCP, IPCP) ↔ libslirp. `gcc -O2 -o ipod-netd ipod-netd.c $(pkg-config --cflags --libs slirp) -Wno-deprecated-declarations` |
| `~/ipod-emu/bin/armdis.py`, `dtdump.py` | Désassembleur capstone (base, début, fin, `arm`) et dump du DeviceTree. Kexts du kernelcache : base de fichier `0xc0029000` |
| `~/ipod-emu/fw-5H11a/dec/` | kernelcache, iBoot, LLB, DeviceTree déchiffrés (clés via api.ipsw.me) |
| `~/ipod-emu/xpwn/` | Outil `hfsplus` (patché : `grow` alloue ensuite dans l'espace neuf) |
## Découvertes clés (modifs QEMU)
- **AES** (`ipod_touch_aes.c`) :
- clé GID choisie d'après le contenu du KBAG (`ipod_touch_gid_keys.h`) ;
- le dernier bloc incomplet d'une IMG3 est laissé en clair ;
- la vérification de longueur LZSS d'iBoot est patchée, trouvée par signature ;
- dans le DeviceTree déchiffré, les propriétés DMA de `uart1` sont renommées : le pilote reste en PIO.
- **SHA1** (`ipod_touch_sha1.c`) : c'est une fonction de compression brute.
- `CONFIG 0x2` = premier bloc, `0x8` puis `0xa` = suite ;
- état H0–H4 lisible et écrivable, mots byte-swappés ;
- bit `0x4` = mode asynchrone, avec IRQ 40 (activée par `0x0c`, acquittée par `0x08`, levée par un timer de 20 µs).
- **UART** (`ipod_touch_uart.c`, nouveau modèle, remplace l'Exynos) :
- IRQ activées dans UCON (`0x2000` TX, `0x1000`/`0x0880` RX) ;
- flags en attente dans UTRSTAT (`0x08`/`0x10`/`0x20`), effacés en écrivant 1 ;
- `UFSTAT` : un FIFO plein vaut 0 + le bit `0x100` ;
- FIFO limité à 8 octets.
- **NAND / FMSS** (`ipod_touch_fmss.c`) :
- La programmation `CSGENRC=0xa02` utilise une liste de paires en `D10`, terminée par un mot zéro.
`D08=8` est la taille d'une paire, pas le numéro de page ; `D18` est une ancienne valeur de lecture.
- Premier mot : masque CE dans les bits 0–3, commande 80h/81h dans les bits 16–23 et flags dans les autres bits.
Deuxième mot : page physique. `D20` pointe deux adresses de données (2048 octets chacune) par page ; `D1C`
contient les métadonnées de 12 octets. Toutes les paires doivent être enregistrées.
- Effacement reconnu dans la liste du séquenceur `C04` par les écritures immédiates NAND 60h/D0h ; `D0C` pointe
la page de début de bloc, `D10` un **index** CE, `D18=1`. Supprimer les 128 fichiers de pages du bloc.
- Une page sans fichier est vierge (`FF`). `C30=0x20000000` pour une lecture entièrement vierge fait retourner
`0xe00002e5` par le pilote ; sans ce statut, `_FTLRestore` ignore les blocs de logs et perd les écritures.
- Les autres micro-commandes restent émulées par les chemins de haut niveau existants ; pas d'interpréteur complet.
- `.ipod-nand-format=vsvfl-production-v1` dans la NAND : le launcher refuse `nand-write=on` sur une ancienne image.
- **Écran MIPI DSI** : `CLKCTRL[31]` contrôle `STATUS.TxReadyHsClk` ; le bit doit aussi pouvoir retomber à zéro.
Le modèle précédent le renvoyait toujours actif, bloquant le pilote lors de l'arrêt de l'écran.
- **Machine** :
- stubs RAM MPVD (`0x39600000`) et `0x38100000` ;
- la NAND 2.2.1 exige la signature `0x43313132` ;
- options `legacy-nor` et `nand-write`.
- **Réseau iOS** :
- pppd est lancé avec `serviceid emuppp` ;
- l'agent publie `Setup:/Network/Service/emuppp` et `Setup:/Network/Global/IPv4 ServiceOrder`, sans quoi IPMonitor n'installe ni route ni DNS ;
- mDNSResponder est réactivé (nécessaire au DNS) ;
- tous les descripteurs passés à pppd doivent être `FD_CLOEXEC` ;
- SpringBoard refuse `SBSLaunchApplication` sans l'entitlement `launchapplications`.
## Pièges
- `pkill -f 'ipod-netd -s'` tue aussi le shell qui lance la commande : utiliser `pkill -x ipod-netd`.
- `ipod-build-fw` réécrit `images/5H11a/`. Refaire `make` dans `agent/` avant, si l'agent a changé.
- `-f` efface la session persistée. Ne pas l'utiliser pour vérifier la conservation d'un fichier.
- QEMU et netd sont lancés avec `setsid` pour survivre à la fin du terminal appelant. Le launcher suit netd par PID.
- Un `.deb` 2.x qui dépend d'un jailbreak (bash, etc.) ne marchera pas : aucun shell dans l'image.
## Reprise du 30 septembre 2026 — après déplacement des homes
- Projets retrouvés sous `/srv/homes/iphoneos2/{ipod-emu,qemu-ios}`.
- Bibliothèques QEMU/libslirp et ImageMagick réinstallées dans le conteneur courant ;
lien BootROM 5H11a corrigé en relatif ; commandes accessibles par wrappers dans
`/home/dev/.local/bin`. Ces installations locales ne modifient pas l'image Docker.
- Lanceur adapté aux chemins déplacés, sélection automatique des keymaps via `-L`,
contrôle du démarrage QEMU et du relais, nettoyage du relais même après arrêt QEMU.
`ipod-qmp` prend en compte `IPOD_EMU_HOME`.
- Test sur une copie de NAND dans `ipod-emu/work/reprise-20260930` : boot de l'image
de base en 28 s, Safari et HTTP validés. `push-app HelloEmu.app` copie les deux
fichiers, redémarre sans réinitialiser la NAND ; HelloEmu apparaît ensuite dans
le catalogue `apps`. Le lancement répond toujours `device locked`, écran noir.
Le programme de diagnostic `unlock` retourne 0 sans débloquer le lancement.
Ne pas considérer le lancement après installation comme validé.
- La copie de la session initiale est conservée dans
`work/reprise-20260930/run-session-initiale` ; la session d'origine `run/nand`
n'a pas été modifiée. Les captures et préférences de diagnostic sont dans le
dossier de reprise. Les sessions de test ont été arrêtées.
- Un ancien relais survivant à QEMU occupait 7788 : supprimé avant de refaire le
test. L'ancien code continuait malgré l'échec de redirection ; le nouveau échoue.
- Vérifications : syntaxe Bash/Python, compilation du relais avec `-Wall`,
échec QEMU volontaire détecté immédiatement, port 7788 occupé détecté et QEMU
arrêté, `stop` après échec. Aucun changement des modèles matériels dans cette reprise.
## Correction du verrouillage — agent v11
- `SBGetScreenLockStatus` confirme `locked=1 passcode=0` après redémarrage.
`SBApplicationRequestedDeviceUnlock` réveille un clavier de code sans déverrouiller.
- Solution validée : `SBDimScreen(port, false)`, attendre deux secondes, glisser
`(60,450)` → `(319,450)`, attendre deux secondes, vérifier `locked=0`.
Le geste historique `(40,430)` → `(280,430)` n'atteint pas correctement le bord
de la surface tactile émulée. Home/Power et gestes lors de la reprise du pilote
peuvent encore provoquer un arrêt QEMU ; aucun correctif matériel n'est revendiqué.
- Agent v11 : commandes `screen` et `wake`. Client : `unlock`, vérification des
marqueurs de disponibilité, refus si un code est actif, trois essais maximum.
`start -W` / `wait` ne rendent la main avec succès qu'après déverrouillage.
- Validations sans débogueur sur la session copiée : démarrage en 36 s ; nouvelle
installation de HelloEmu avec `push-app`, redémarrage conservant la NAND en 47 s,
`launch` réussi et `front` = `com.allovoisins.helloemu`. Capture :
`work/reprise-20260930/hello-v11-apres-push.png`.
- L'agent v11 a été installé atomiquement dans la session de test puis synchronisé
avant redémarrage ; aucune relance à chaud de l'agent/PPP.
Nouvelle image `images/5H11a-agent-v11` construite avec l'overlay de l'agent,
sans modifier l'image 5H11a ni la NAND d'origine. L'image de base v10 doit être
mise à jour avant d'utiliser le déverrouillage automatique.
- La faute `diff_y` utilisant `x` dans `get_frame` reste à étudier séparément ;
elle n'a pas été modifiée pour cette validation.
## Relecture avant merge
- Corrigé `start -W` sur une session déjà lancée : attendre et vérifier le
déverrouillage avant de rendre la main, au lieu de retourner immédiatement.
- Image distincte 5H11a-agent-v11 démarrée et déverrouillée en 27 s ; agent v11
confirmé. Les deux sessions de test antérieures sont conservées séparément.
+290
View File
@@ -0,0 +1,290 @@
# Simulateur iPod Touch 2G (iPhone OS 2.2.1)
Émulateur [qemu-ios](https://git.mahtan-melwasul.com/Mahtan/qemu-ios) (branche iPod Touch 2G, N72AP), adapté pour
démarrer **iPhone OS 2.2.1 (5H11a)**. iPhone OS 2.1.1 (5F138) reste disponible. Les outils sont dans `ipod-emu/bin` ; dans le workbench actuel, des wrappers les exposent via `/home/dev/.local/bin`.
## Environnement déplacé
Dans le workbench actuel, les projets sont sous `/srv/homes/iphoneos2` :
`ipod-emu` contient les images et les outils, `qemu-ios` contient QEMU.
Les outils utilisés directement depuis `ipod-emu/bin` retrouvent ce dossier ;
le lanceur cherche QEMU dans le dossier voisin et transmet son dossier `pc-bios`
pour retrouver les keymaps VNC après déplacement. `IPOD_EMU_HOME`, `IPOD_QEMU`,
`IPOD_QEMU_DATA` et `IPOD_QMP` permettent de choisir d'autres chemins.
`ipod-qmp` respecte également `IPOD_EMU_HOME` pour le socket de session.
Vérifier les liens symboliques des images après déplacement : le lien de
`images/5H11a/bootrom` doit viser `../5F138/bootrom`, plutôt qu'un ancien home absolu.
Sur Arch, le binaire construit dans cet environnement utilise notamment `pixman`,
`libpng`, `libjpeg-turbo`, `sdl2` et `libslirp` ; les captures PNG utilisent
`imagemagick`. Compiler le relais réseau demande aussi `pkgconf` et `glib2-devel`.
Ces dépendances doivent être présentes dans chaque nouveau conteneur.
Le lanceur échoue explicitement si QEMU ou le relais réseau s'arrête au démarrage.
Un port agent déjà occupé est une erreur : le relais ne poursuit plus sans sa
redirection. `stop` nettoie le relais suivi par PID même si QEMU est déjà arrêté.
## Utilisation
```bash
ipod-emu start -w 5H11a-agent-v12 -W # attend SpringBoard et déverrouille (~25–50 s)
# Ajouter -f uniquement pour remettre la NAND à zéro.
ipod-qmp screenshot ecran.png # capture 320x480
ipod-qmp tap 160 326 # touche (coordonnées écran), ipod-qmp tap X Y 1.5 = appui long
ipod-qmp swipe 300 250 20 250 # glisser (ex. page suivante de SpringBoard)
ipod-qmp home | power # boutons
ipod-emu log # console du kernel + syslog iOS
ipod-emu stop
```
- Attendre `ipod-emu wait` / `start -W` avant les gestes : le pilote tactile invité doit avoir terminé son démarrage.
- VNC sur `127.0.0.1:5900` pour interagir à la main (tunnel SSH : `ssh -L 5900:127.0.0.1:5900 …`).
- Le lancement d'une app prend 10-20 s.
## Déverrouillage après redémarrage
Avec l'agent **v11 ou ultérieur**, `start -W` et `wait` vérifient le verrouillage, réveillent
l'écran et effectuent le glissement normal avant de rendre la main.
`ipod-agent screen` retourne `locked=0 passcode=0` une fois déverrouillé ;
`ipod-agent unlock` permet de refaire ce parcours après démarrage.
Si un code est activé, le client s'arrête et demande un déverrouillage manuel.
Aucun geste n'est envoyé avant les marqueurs de démarrage du pilote tactile.
Le réveil utilise `SBDimScreen(port, false)`, puis un glissement de `(60,450)`
à `(319,450)` adapté à la surface tactile du modèle. Le client laisse deux
secondes au réveil et à la fin du geste, puis vérifie le verrouillage ; trois
essais maximum. `SBApplicationRequestedDeviceUnlock` affiche le clavier de code
sur 2.2.1 même sans code actif : ce n'est pas le parcours utilisé.
Une image contenant l'agent v10 doit être mise à jour avant d'utiliser ce workflow.
Créer une image distincte préserve l'image de base :
```bash
cd /srv/homes/iphoneos2/ipod-emu/agent
PATH=/opt/cctools/bin:$PATH make
ipod-mkimage -o 5H11a-agent-v11 overlay
```
Le firmware se choisit avec `start -w 5H11a-agent-v11 -W`. Attention : comme pour
tout changement de firmware, cette commande remplace la NAND du dossier `run` ;
conserver sa session précédente ou utiliser un environnement de test séparé.
Le dossier de diagnostic `work/reprise-20260930` conserve une session avec l'agent
v11 et HelloEmu, indépendante de la session d'origine.
## Redémarrage à chaud
```bash
ipod-emu respring -W # relance SpringBoard, attend puis déverrouille
ipod-emu reset -W # redémarre iOS dans le même processus QEMU
```
Les deux commandes synchronisent les écritures avant la relance. Elles conservent
la NAND de session et les processus QEMU et `ipod-netd`. Sans `-W`, elles rendent
la main après la demande ; `ipod-emu wait` peut attendre la suite.
L'attente ne lit que les nouveaux marqueurs du journal, puis vérifie le
déverrouillage. Aucun glissement automatique n'est effectué si un code est activé.
La sortie TV émulée répond à chaque soumission, sans l'ancien quota de deux
interruptions qui bloquait SpringBoard dans `IOServiceClose`. Le LCD sépare le
masque d'interruptions de leur acquittement. Un reset réinitialise aussi le
contrôleur MIPI, l'état du tactile et les interruptions SPI.
Le reset de l'UART ferme la connexion série. `ipod-netd` se reconnecte au même
socket et renégocie LCP/IPCP avec le nouveau `pppd`. Pour vérifier le réseau :
```bash
ipod-agent ping
ipod-agent net # ppp0 up et configd publié
```
`ipod-agent respring` et `ipod-qmp reset` restent les accès bruts, sans attente
ni mise à jour du point de départ du journal. Avant un reset brut, exécuter
`ipod-agent sync`. Préférer les commandes `ipod-emu` pour un cycle complet.
## Tester nos apps
```bash
ipod-mkimage -b 5H11a-agent-v11 MonApp.app autre.ipa paquet.deb # -> images/5H11a-agent-v11-apps
ipod-emu start -f -W -w 5H11a-agent-v11-apps
ipod-agent launch com.exemple.monapp --log /private/var/mobile/monapp.log
ipod-agent get /private/var/mobile/monapp.log
# Installation sans reconstruire l'image (synchronise puis redémarre l'iPod) :
ipod-agent push-app MonApp.app
```
Les `.app`/`.ipa` vont dans `/Applications` (re-signés avec `ldid -S` ; le kernel les accepte grâce au boot-arg
`amfi_allow_any_signature` injecté par l'émulateur), les `.deb` sont décompressés à la racine. Compiler en armv6 avec
la toolchain de l'environnement (`arm-apple-darwin9-gcc -isysroot /opt/theos/sdks/iPhoneOS2.2.1.sdk`), voir
`apps/HelloEmu`. Environ 230 Mo libres dans l'image 2.2.1.
## Test automatique et diagnostics
```bash
# Construire d'abord l'agent v12 et une image dédiée depuis la base inchangée :
PATH=/opt/cctools/bin:$PATH make -C agent
ipod-mkimage -b 5H11a -o 5H11a-agent-v12 agent/overlay
# Après avoir arrêté sa session, tester dans une NAND indépendante :
ipod-test-app MonApp.app
ipod-test-app MonApp.ipa --output /chemin/nouveau-dossier
ipod-test-app paquet.deb --bundle-id com.exemple.monapp
```
Les chemins `agent/` ci-dessus sont relatifs au dossier des outils ; dans le dépôt,
utiliser `contrib/ipod-emu/agent`. Choisir un nom d'image absent lors de sa création.
`--base` permet de choisir une autre image contenant l'agent v11 ou ultérieur.
Le bundle-id est lu dans le plist des `.app` et `.ipa` ; il doit être fourni pour
les `.deb` et overlays. Le runner refuse de démarrer si les ports VNC ou agent
sont déjà occupés. Chaque test crée une image et une session dans son propre
répertoire ; la NAND de `run/` et l'image de base restent conservées.
Le code de sortie vaut zéro uniquement si l'app apparaît puis reste au premier
plan pendant `--settle` secondes (3 par défaut), si les diagnostics sont collectés
et si la VM est arrêtée. Ce contrôle ne remplace pas les tests fonctionnels de l'app.
Les résultats vont dans `work/tests/<date>-<identifiant>/`, ou dans un nouveau dossier
`--output` : `result.json`, `workflow.log`, `app.log`, `screen.png` et les logs QEMU,
série et réseau dans `session/run/`. En cas d'échec, les diagnostics disponibles
sont conservés et la session de test est arrêtée.
## Tactile et transferts
Home/Power ne doivent plus écrire hors du tableau GPIO : le port C est inclus.
Les trous des registres SYSIC ne débordent plus dans le groupe voisin.
Le tactile traite séparément les requêtes de longueur et de données, accepte
EA/EB, conserve une trame stable, et abandonne proprement une commande lors de
la réinitialisation SPI. Les commandes et rapports inconnus ne font plus arrêter
QEMU. Le découpage des requêtes est documenté également dans
[OpeniBoot Z2](https://github.com/iDroid-Project/openiBoot/blob/master/plat-s5l8900/multitouch-z2.c).
La vitesse verticale utilise `y`, les vitesses conservent leur signe et sont
bornées à 16 bits. `apps/TouchProbe` permet de mesurer la calibration : compiler
avec son Makefile, lancer avec `--log`, puis comparer les gestes QMP au marqueur
bleu et aux coordonnées du journal (ajouter 20 pixels à l'ordonnée locale de la vue).
La calibration a été vérifiée sur 5H11a et 5F138, sur sept points de `(20,40)` à `(300,460)`.
Agent **v12** : `put` et `get` utilisent des blocs de 64 Kio au lieu d'allouer
le fichier entier dans l'iPod. Un upload incomplet supprime son temporaire et
conserve le fichier précédent ; le client fait de même pour les téléchargements.
Le protocole reste compatible avec l'agent v11. Les téléchargements vers stdout
peuvent naturellement afficher un préfixe avant une erreur de transport.
Depuis le dépôt, les tests sans firmware sont :
```bash
contrib/ipod-emu/tests/run-uart # reset des registres/FIFO/IRQ et trois reconnexions socket, ASan/UBSan
contrib/ipod-emu/tests/run-display # LCD, MIPI, sortie TV et resets, ASan/UBSan
python3 contrib/ipod-emu/tests/test-reset-launcher.py # synchronisation et nouveaux marqueurs
contrib/ipod-emu/tests/run-rtc # protocole I²C et horloge D1759, ASan/UBSan
contrib/ipod-emu/tests/run-multitouch # build QEMU arm existant, Ninja, compilateur avec ASan/UBSan
python3 contrib/ipod-emu/tests/test-transfers.py # Python et compilateur C, sockets locales
```
## Validation sous iPhone OS 2.1.1
Le firmware 5F138 a été vérifié avec l'agent v12 et les mêmes corrections QEMU.
Conserver l'image 5F138 d'origine et produire une image dérivée avec un nom absent :
```bash
ipod-mkimage -b 5F138 -o 5F138-agent-v12 agent/overlay apps/TouchProbe/TouchProbe.app apps/HelloEmu/HelloEmu.app
```
Utiliser ensuite un environnement `IPOD_EMU_HOME` indépendant pour démarrer cette
image ; un changement de firmware remplace la NAND de la session choisie.
`SystemVersion.plist` confirme iPhone OS 2.1.1 / 5F138. Les sept points de
calibration sont exacts et six cycles de veille/réveil alternant Home et Power
passent, sans désactivation du tactile.
Pour tester Safari sans dépendre d'un site extérieur, depuis le dépôt :
```bash
python3 contrib/ipod-emu/tests/http-fixture.py --output /chemin/diagnostic-http
```
Ouvrir l'URL `http://10.0.2.2:<port>/` affichée dans Safari invité. Le serveur
écoute uniquement sur la boucle locale de l'hôte ; il conserve le port et les
requêtes dans le dossier choisi. Saisir `bonjour` avec le clavier virtuel et
soumettre : le journal doit contenir `/submit?texte=bonjour`. Suivre le lien de
défilement, glisser jusqu'au bas, attendre la fin de l'inertie et toucher le lien
final : `/fin` doit apparaître. Arrêter le serveur avec Ctrl-C après le test.
Attendre l'affichage réel d'une application avant d'envoyer des gestes. Pour
TouchProbe, attendre `TouchProbe ready` dans le journal ; une réponse de lancement
ne garantit pas que la vue soit déjà prête. Sous 2.1.1, lancer Safari avec `--url`
alors qu'il est déjà ouvert n'a pas changé la page lors du test ; utiliser les
liens de la page ou relancer Safari pour ouvrir une autre URL.
Notes et la calculatrice complètent ce contrôle : saisir une note, la sauvegarder,
puis comparer son texte dans `Library/Notes/notes.db` avant et après redémarrage ;
vérifier visuellement `7 × 8 = 56` dans la calculatrice. Les diagnostics et le
résultat détaillé de la validation du 1er octobre sont décrits dans `HANDOFF.md`.
## Limites
- **Persistance NAND** : les pages et métadonnées écrites par iOS, ainsi que les effacements de blocs, sont conservés
dans `run/nand`. `ipod-emu start` conserve cet état ; `-f` ou un changement de firmware le remplace par l'image de base.
Les images produites par `gen-v1/mknand` utilisent le format VSVFL de production et `nand-write=on`.
Les anciennes images de `mknand-v1` doivent être reconstruites avant d'activer les écritures.
- **Internet** : PPP sur UART1, pont `ipod-netd` vers libslirp ; DNS et HTTP fonctionnent. `ipod-agent fetch
http://example.com/` teste le réseau depuis l'iPod. L'écran Réglages affiche toujours « Pas de Wi-Fi », car la puce
BCM4325 n'est pas émulée.
- **Heure** : le RTC D1759 fournit l'heure dès le démarrage, avec la configuration QEMU `-rtc`
(UTC et horloge hôte par défaut). `start -W` / `wait` ne modifie plus la date.
`ipod-agent settime SECONDES_UNIX` reste disponible pour les tests explicites.
Le décalage écrit par iOS reste en mémoire pendant la session ; une nouvelle instance QEMU repart
de sa base RTC. Les IRQ d'alarme matérielle ne sont pas émulées. Voir [RTC.md](RTC.md).
L'image de base est en français, région France, fuseau Europe/Paris.
- **Relance de SpringBoard** : `ipod-emu respring -W` attend le retour de l'interface et son déverrouillage.
`push-app` garde son redémarrage de QEMU, sans reconstruire l'image ni réinitialiser la NAND. Avec l'agent v11, le déverrouillage puis
le lancement de HelloEmu au premier plan sont validés après cette installation. Les corrections GPIO/SPI
ont permis huit cycles veille/réveil alternant Home et Power sur 5H11a. Le déverrouillage automatique
continue à vérifier l'état de l'écran.
- **Veille** : l'agent v10 pose `SleepDisabled` sur `IOPMrootDomain`, le SoC ne sachant pas reprendre une veille profonde.
- Pas de son, pas d'accélération graphique (SpringBoard tourne avec `LK_ENABLE_MBX2D=0`).
## Régression native du redémarrage
Avec un firmware local, le test QMP/QTest vérifie trois resets des vrais
périphériques d'affichage (CPU arrêté, NAND en lecture seule) :
```bash
python3 contrib/ipod-emu/tests/test-display-reset.py --firmware /chemin/images/5H11a
```
Pour vérifier iOS, préparer et démarrer une **session de test séparée**, avec un
port d'agent distinct. Le test suivant relance cette session, ouvre la calculatrice
et conserve les captures et résultats JSON. Il vérifie le déverrouillage, les PID,
la persistance d'un fichier témoin et HTTP avec un serveur local temporaire :
```bash
python3 contrib/ipod-emu/tests/test-display-session.py \
--emu-home /chemin/session-test --agent-port 7789 \
--action respring --cycles 3 --output /chemin/resultats-respring
# Même commande avec --action reset pour le redémarrage complet d'iOS.
```
## Reconstruire les images
`ipod-build-fw 5H11a` télécharge l'IPSW iPod2,1 chez Apple et les clés sur api.ipsw.me, génère la NOR, déchiffre et
adapte le rootfs (`bin/mkbase-rootfs` : LaunchDaemons réduits, fstab à une partition, activation Lockdown
d'`assets/Lockdown`, verrouillage auto désactivé) et génère la NAND (`gen-v1/mknand`, format VSVFL de production du générateur
qemu-ios-generate-nand 2ee0d46, signature de format 2 et écritures activées). L'image 5F138 vient de la release `n72ap_v1` de qemu-ios.
## Ce qui a été modifié dans qemu-ios (`~/qemu-ios`)
- `ipod_touch_aes.c` : clés GID choisies d'après le contenu du KBAG (table `ipod_touch_gid_keys.h`, 5F138 + 5H11a)
au lieu de l'ordre des appels ; le dernier bloc incomplet d'une image IMG3 est laissé en clair (supprime les hacks
Adler32 du kernel et de fin de DeviceTree) ; patch de la vérif de longueur LZSS d'iBoot trouvé par signature.
- `ipod_touch_sha1.c` : réécrit comme la fonction de compression SHA1 du matériel (état lisible/écrivable, `0x2` =
premier bloc, `0xa` = suite) + interruption de fin (IRQ 40, registre `0x0c`) — utilisés par le kernel 2.2.1 pour la
signature des pages de code et `IOSHA1Accelerator`.
- `ipod_touch_fmss.c` : chemin Bluetooth dans iBoot trouvé par recherche ; décodage des listes de programmation,
persistance des données et des 12 octets de métadonnées, effacement des blocs de 128 pages ; indicateur de page
vierge dans `0xC30`, nécessaire à la récupération FTL après arrêt de QEMU.
- `ipod_touch_mipi_dsi.c` : le bit d'horloge prête suit `CLKCTRL[31]`, permettant au pilote de terminer l'arrêt
de l'écran. Le SoC ne sait pas encore sortir de veille ; garder le verrouillage automatique désactivé.
- `ipod_touch_uart.c` : UART avec FIFO et interruptions utilisées par PPP.
- `ipod_touch_mbx.c` : patch BCM4325 du kernel limité à 5F138.
- `ipod_touch_2g.c` : stubs mémoire MPVD (`0x39600000`, kernel panic à la mise en veille) et `0x38100000` (écrit
par LLB 2.2.1), option machine `legacy-nor` (NOR à tags SHSH non chiffrés, `off` pour les NOR générées ici).
- xpwn `hfs/hfslib.c` : après `grow`, les nouveaux fichiers sont alloués dans l'espace ajouté (sinon fragmentés).
+82
View File
@@ -0,0 +1,82 @@
# RTC du D1759 — iPod Touch 2G
Le modèle `d1759` fournit l'heure avant le lancement des services iOS. La
machine 2G l'utilise à l'adresse I²C `0x73` ; le modèle historique `pcf50633`
reste disponible séparément. Les images et l'agent v12 existants conviennent.
Il faut reconstruire QEMU et utiliser le lanceur mis à jour.
## Protocole observé
Le désassemblage local du pilote `AppleD1759PMURTC` de 5H11a montre :
| Registres | Comportement |
| --- | --- |
| `0x5c` à `0x5f` | Compteur de secondes sur 32 bits, petit-boutiste |
| `0x64` à `0x67` | Décalage ajouté au compteur pour obtenir les secondes Unix |
| `0x50` à `0x5a` | Réglages d'alarme conservés en mémoire, sans IRQ |
| `0x60` à `0x63` | Suivi du démarrage, indépendant du RTC |
Sur le kernelcache déchiffré, le segment `__PRELINK` a le décalage adresse
virtuelle/fichier `0xc0029000`. La routine à `0xc03c8f08` lit quatre octets en
`0x5c` et ajoute le décalage chargé au démarrage par `0xc03c8c10` depuis `0x64`.
La routine à `0xc03c8f48` règle l'heure en écrivant la différence en `0x64`.
Les routines PMU à `0xc03c11e8` et `0xc03c1228` transmettent directement le
registre au nub I²C. Ce sont des observations du binaire local, pas des
symboles exportés ni une spécification complète du composant.
Le protocole I²C standard, registre puis données, est aussi visible dans
[OpeniBoot pour le S5L8720](https://github.com/iDroid-Project/openiBoot/blob/master/plat-s5l8720/pmu.c).
Sa fonction RTC est laissée à implémenter et ne constitue pas une preuve du
format du compteur. Les anciennes notes décrivant `0x61/0x62` comme un accès
indirect RTC étaient incorrectes.
Une lecture capture le compteur au début de la réception pour éviter de
mélanger deux secondes entre les octets. Les sélections de registre avec STOP
et avec START répété sont acceptées. Le compteur est en lecture seule ; les
écritures de décalage sont conservées pendant la session.
## Configuration et limites
QEMU initialise le compteur via `qemu_get_timedate`, puis le fait avancer avec
`rtc_clock`. Les options habituelles `-rtc base=...,clock=...` sont respectées.
Par défaut, la base est UTC et le temps suit l'horloge de l'hôte. Le fuseau
horaire d'affichage reste un réglage d'iOS. Une base reproductible peut être
passée au lanceur, par exemple :
```bash
IPOD_QEMU_EXTRA='-rtc base=2024-02-29T23:59:59,clock=vm' ipod-emu start -W
```
`start -W` et `wait` ne lancent plus `settime`. La commande
`ipod-agent settime SECONDES_UNIX` reste un réglage volontaire pour les tests.
Le décalage RTC ne persiste pas entre deux processus QEMU ; une nouvelle
instance repart de sa configuration `-rtc`. Les IRQ d'alarme, la veille
profonde et la migration de l'état RTC ne sont pas implémentées.
Un reset QEMU à chaud peut laisser PPP inaccessible. Pour redémarrer une
session conservée, utiliser `ipod-agent sync`, `ipod-emu stop`, puis
`ipod-emu start -W`, qui conserve la NAND.
## Validation
```bash
contrib/ipod-emu/tests/run-rtc
```
Le test compile le modèle réel avec ASan/UBSan et utilise le bus I²C QEMU :
base UTC avec fuseau hôte différent, date fixe bissextile, cohérence des
lectures au changement de seconde, décalages positifs/négatifs et séparation
des registres de démarrage.
Validation du 1er octobre 2026 sur des copies de NAND :
- 5H11a / iPhone OS 2.2.1 et 5F138 / iPhone OS 2.1.1 démarrent sans `settime` ;
`gettimeofday` dans un programme armv6 retrouve l'heure Unix de l'hôte.
- Un changement volontaire de date continue à avancer. Après un reset à
chaud de 5F138, les journaux précoces d'iOS retrouvent le décalage écrit ;
PPP ne reprend pas correctement après ce reset.
- Les démarrages normaux, le déverrouillage et le lancement d'applications
sont vérifiés avec le lanceur sans synchronisation par l'agent.
Les diagnostics restent hors du dépôt dans
`/srv/homes/iphoneos2/ipod-emu/work/rtc-20261001/`.
+32
View File
@@ -0,0 +1,32 @@
# Sources de l'environnement iPod
Ce dossier sauvegarde les sources de `~/ipod-emu` avec les modifications QEMU.
Pour retrouver les chemins utilisés par les outils, copier ce dossier dans `~/ipod-emu`
(ou définir `IPOD_EMU_HOME`). Ne pas remplacer un environnement existant sans conserver
ses images, ses données NAND et ses fichiers d'activation.
Les images Apple, les SDK, les exécutables construits, les sessions NAND et les
certificats/clés privés Lockdown sont exclus de Git. Conserver `assets/Lockdown`
séparément : `mkbase-rootfs` en a besoin pour préparer une image activée. Le dépôt
sauvegarde le code ; il ne constitue pas une sauvegarde des données de l'iPod.
Dépendances Git à cloner sous `~/ipod-emu`, avec les révisions utilisées :
| Dossier | Dépôt | Révision |
| --- | --- | --- |
| xpwn | https://github.com/planetbeing/xpwn | 20c32e5c12d1b22a9d55a59a0ff6267f539b77f4 |
| dmg2img | https://github.com/Lekensteyn/dmg2img | a3e413489ccdd05431401357bf21690536425012 |
| qemu-ios-generate-nand | https://github.com/devos50/qemu-ios-generate-nand | 2ee0d4690612c670dd8d1e9bf3cc7b65aedc4242 |
| qemu-ios-generate-nor | https://github.com/devos50/qemu-ios-generate-nor | 4f822cbe2c74dab3e2e8444c00dfa676ed43dd5e |
Après clonage et checkout, appliquer les adaptations locales avant compilation :
```sh
git -C xpwn apply --unidiff-zero ../patches/xpwn.patch
git -C qemu-ios-generate-nand apply --unidiff-zero ../patches/qemu-ios-generate-nand.patch
```
Les commandes de compilation et démarrage, les validations de persistance et les
limites restantes figurent dans `HANDOFF.md` et `README.md`. L'agent requiert le
compilateur armv6, le SDK iPhone OS 2.2.1 et `ldid` indiqués dans son Makefile.
Le relais réseau `netd/ipod-netd.c` utilise libslirp.
+23
View File
@@ -0,0 +1,23 @@
# Agent iPod émulé (armv6, iPhone OS 2.x)
SDK := /opt/theos/sdks/iPhoneOS2.2.1.sdk
CC := /opt/cctools/bin/arm-apple-darwin9-gcc
CFLAGS := -isysroot $(SDK) -arch armv6 -miphoneos-version-min=2.0 -O2 -Wall -Wno-deprecated-declarations
FRAMEWORKS := -framework CoreFoundation -framework SystemConfiguration
all: overlay
emuagent: emuagent.c entitlements.plist
$(CC) $(CFLAGS) -o $@ $< $(FRAMEWORKS)
ldid -Sentitlements.plist $@ # entitlements vérifiés par SpringBoard pour SBSLaunchApplication
overlay: emuagent com.allovoisins.emuagent.plist
rm -rf overlay && mkdir -p overlay/usr/libexec overlay/System/Library/LaunchDaemons
cp emuagent overlay/usr/libexec/
cp com.allovoisins.emuagent.plist overlay/System/Library/LaunchDaemons/
# résolution DNS (retirée de l'image de base avec les autres démons)
cp apple/com.apple.mDNSResponder.plist apple/com.apple.mDNSResponderHelper.plist overlay/System/Library/LaunchDaemons/
clean:
rm -rf emuagent overlay
.PHONY: all overlay clean
@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.apple.mDNSResponder</string>
<key>OnDemand</key>
<false/>
<key>UserName</key>
<string>_mdnsresponder</string>
<key>GroupName</key>
<string>_mdnsresponder</string>
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/mDNSResponder</string>
<string>-launchd</string>
</array>
<key>MachServices</key>
<dict>
<key>com.apple.mDNSResponder</key>
<true/>
</dict>
<key>Sockets</key>
<dict>
<key>Listeners</key>
<dict>
<key>SockFamily</key>
<string>Unix</string>
<key>SockPathName</key>
<string>/var/run/mDNSResponder</string>
<key>SockPathMode</key>
<integer>438</integer>
</dict>
</dict>
<key>ServiceIPC</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,21 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.apple.mDNSResponderHelper</string>
<key>OnDemand</key>
<true/>
<key>ProgramArguments</key>
<array>
<string>/usr/sbin/mDNSResponderHelper</string>
</array>
<key>MachServices</key>
<dict>
<key>com.apple.mDNSResponderHelper</key>
<true/>
</dict>
<key>ServiceIPC</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>Label</key><string>com.allovoisins.emuagent</string>
<key>ProgramArguments</key><array><string>/usr/libexec/emuagent</string></array>
<key>RunAtLoad</key><true/>
<key>KeepAlive</key><true/>
<key>UserName</key><string>root</string>
</dict></plist>
+913
View File
@@ -0,0 +1,913 @@
/*
* emuagent : agent de pilotage de l'iPod émulé (iPhone OS 2.x), lancé par launchd en root.
*
* 1. Réseau : lance pppd sur l'UART1 (/dev/tty.bluetooth, reliée à ipod-netd côté hôte) et publie le lien dans le
* SCDynamicStore de configd (IPv4, routeur, DNS), pour qu'iOS le considère comme le réseau actif.
* 2. Pilotage : serveur TCP sur le port 7788 (redirigé par ipod-netd vers 127.0.0.1:7788 sur l'hôte).
*
* Protocole : une requête = une ligne, champs séparés par des tabulations. Réponse : "OK <n> [info]\n" ou
* "ERR <n>\n", suivi de n octets. Pour "put", n octets de contenu suivent la ligne de requête.
*/
#include <CoreFoundation/CoreFoundation.h>
/* SCDynamicStore est dans SystemConfiguration.framework mais marqué indisponible dans les en-têtes iPhone */
typedef const struct __SCDynamicStore *SCDynamicStoreRef;
extern SCDynamicStoreRef SCDynamicStoreCreate(CFAllocatorRef, CFStringRef, void *, void *);
extern Boolean SCDynamicStoreSetValue(SCDynamicStoreRef, CFStringRef, CFPropertyListRef);
extern CFPropertyListRef SCDynamicStoreCopyValue(SCDynamicStoreRef, CFStringRef);
extern CFArrayRef SCDynamicStoreCopyKeyList(SCDynamicStoreRef, CFStringRef);
#include <arpa/inet.h>
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <ifaddrs.h>
#include <net/if.h>
/* net/route.h absent du SDK iPhone : structures du socket de routage de XNU 1228 (Darwin 9) */
struct rt_metrics {
u_int32_t rmx_locks, rmx_mtu, rmx_hopcount;
int32_t rmx_expire;
u_int32_t rmx_recvpipe, rmx_sendpipe, rmx_ssthresh, rmx_rtt, rmx_rttvar, rmx_pksent;
u_int32_t rmx_filler[4];
};
struct rt_msghdr {
u_short rtm_msglen;
u_char rtm_version, rtm_type;
u_short rtm_index;
int rtm_flags, rtm_addrs;
pid_t rtm_pid;
int rtm_seq, rtm_errno, rtm_use;
u_int32_t rtm_inits;
struct rt_metrics rtm_rmx;
};
#define RTM_VERSION 5
#define RTM_ADD 0x1
#define RTM_CHANGE 0x3
#define NET_RT_DUMP 1
#define RTF_UP 0x1
#define RTF_GATEWAY 0x2
#define RTF_STATIC 0x800
#define RTA_DST 0x1
#define RTA_GATEWAY 0x2
#define RTA_NETMASK 0x4
#include <netdb.h>
#include <netinet/in.h>
#include <signal.h>
#include <spawn.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <termios.h>
#include <notify.h>
#include <unistd.h>
#define VERSION "12"
#define PORT 7788
#define PPP_TTY "/dev/tty.bluetooth"
#define GUEST_IP "10.0.2.15"
#define GW_IP "10.0.2.2"
#define DNS_IP "10.0.2.3"
#define SERVICE_ID "emuppp" /* pppd publie son état sous State:/Network/Service/<id> */
extern char **environ;
static FILE *con;
static pid_t pppd_pid;
static SCDynamicStoreRef store;
static int net_published;
static void clog_(const char *fmt, ...)
{
va_list ap;
if (!con) return;
fputs("emuagent: ", con);
va_start(ap, fmt);
vfprintf(con, fmt, ap);
va_end(ap);
fputc('\n', con);
}
/* ---------- réseau ---------- */
static void start_pppd(void)
{
char *argv[] = { "/usr/sbin/pppd", PPP_TTY, "115200", "local", "nocrtscts", "noauth", "nodetach",
"persist", "maxfail", "0", "holdoff", "2", "defaultroute", "noipdefault",
"ipcp-accept-local", "ipcp-accept-remote", "usepeerdns", "novj", "noccp",
"lcp-echo-interval", "0", "mtu", "1500", "mru", "1500", "serviceid", SERVICE_ID, NULL };
posix_spawn_file_actions_t fa;
posix_spawn_file_actions_init(&fa);
posix_spawn_file_actions_addopen(&fa, 0, "/dev/null", O_RDONLY, 0);
posix_spawn_file_actions_addopen(&fa, 1, "/dev/console", O_WRONLY, 0);
posix_spawn_file_actions_addopen(&fa, 2, "/dev/console", O_WRONLY, 0);
if (posix_spawn(&pppd_pid, argv[0], &fa, NULL, argv, environ) != 0) {
clog_("pppd : échec du lancement (%s)", strerror(errno));
pppd_pid = 0;
} else {
clog_("pppd lancé (pid %d) sur %s", pppd_pid, PPP_TTY);
}
posix_spawn_file_actions_destroy(&fa);
}
static int ppp_up(char *ifname, size_t len)
{
struct ifaddrs *ifa, *i;
int up = 0;
if (getifaddrs(&ifa)) return 0;
for (i = ifa; i; i = i->ifa_next) {
if (!strncmp(i->ifa_name, "ppp", 3) && i->ifa_addr && i->ifa_addr->sa_family == AF_INET && (i->ifa_flags & IFF_UP)) {
strncpy(ifname, i->ifa_name, len);
up = 1;
}
}
freeifaddrs(ifa);
return up;
}
static CFArrayRef str_array(const char *s)
{
CFStringRef v = CFStringCreateWithCString(NULL, s, kCFStringEncodingUTF8);
CFArrayRef a = CFArrayCreate(NULL, (const void **)&v, 1, &kCFTypeArrayCallBacks);
CFRelease(v);
return a;
}
static void set_key(CFStringRef key, CFDictionaryRef val)
{
if (!SCDynamicStoreSetValue(store, key, val)) clog_("SCDynamicStoreSetValue a échoué");
}
/* Route par défaut via la passerelle PPP (RTM_ADD sur le socket de routage, comme route add default) */
static int route_msg(int type)
{
struct {
struct rt_msghdr h;
struct sockaddr_in dst, gw, mask;
} m;
memset(&m, 0, sizeof m);
m.h.rtm_msglen = sizeof m;
m.h.rtm_version = RTM_VERSION;
m.h.rtm_type = type;
m.h.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
m.h.rtm_addrs = RTA_DST | RTA_GATEWAY | RTA_NETMASK;
m.h.rtm_pid = getpid();
m.h.rtm_seq = 1;
m.dst.sin_len = m.gw.sin_len = m.mask.sin_len = sizeof(struct sockaddr_in);
m.dst.sin_family = m.gw.sin_family = m.mask.sin_family = AF_INET;
inet_aton(GW_IP, &m.gw.sin_addr);
int s = socket(PF_ROUTE, SOCK_RAW, 0);
if (s < 0) return -1;
int r = write(s, &m, sizeof m) == sizeof m ? 0 : -1;
int e = errno;
close(s);
errno = e;
return r;
}
static int add_default_route(void)
{
if (route_msg(RTM_ADD) == 0) return 0;
if (errno == EEXIST && route_msg(RTM_CHANGE) == 0) return 0; /* une route par défaut existait déjà */
clog_("route par défaut : %s", strerror(errno));
return -1;
}
static CFMutableDictionaryRef dict(void)
{
return CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
}
/*
* Déclare le service PPP côté Setup: (ce que contiendrait preferences.plist pour un service configuré) : sans cela,
* IPMonitor ignore l'état publié par pppd et n'installe ni la route par défaut ni le DNS global.
*/
static void publish_setup(void)
{
if (!store) store = SCDynamicStoreCreate(NULL, CFSTR("emuagent"), NULL, NULL);
if (!store) { clog_("SCDynamicStoreCreate a échoué"); return; }
CFMutableDictionaryRef svc = dict(), itf = dict(), ipv4 = dict(), glob = dict();
CFDictionarySetValue(svc, CFSTR("UserDefinedName"), CFSTR("Émulateur (PPP)"));
set_key(CFSTR("Setup:/Network/Service/" SERVICE_ID), svc);
CFDictionarySetValue(itf, CFSTR("Type"), CFSTR("PPP"));
CFDictionarySetValue(itf, CFSTR("SubType"), CFSTR("PPPSerial"));
CFDictionarySetValue(itf, CFSTR("DeviceName"), CFSTR("tty.bluetooth"));
set_key(CFSTR("Setup:/Network/Service/" SERVICE_ID "/Interface"), itf);
CFDictionarySetValue(ipv4, CFSTR("ConfigMethod"), CFSTR("PPP"));
set_key(CFSTR("Setup:/Network/Service/" SERVICE_ID "/IPv4"), ipv4);
CFArrayRef order = str_array(SERVICE_ID);
CFDictionarySetValue(glob, CFSTR("ServiceOrder"), order);
set_key(CFSTR("Setup:/Network/Global/IPv4"), glob);
CFRelease(order); CFRelease(svc); CFRelease(itf); CFRelease(ipv4); CFRelease(glob);
}
/* Lien monté : vérifie qu'IPMonitor a bien installé la route par défaut, sinon la pose nous-mêmes */
static void publish_network(const char *ifname)
{
net_published = 1;
sleep(1);
if (add_default_route() == 0) clog_("lien %s prêt (%s via %s, DNS %s)", ifname, GUEST_IP, GW_IP, DNS_IP);
}
static void net_tick(void)
{
int status;
char ifname[IFNAMSIZ];
if (pppd_pid && waitpid(pppd_pid, &status, WNOHANG) == pppd_pid) {
clog_("pppd terminé (statut %d), relance", status);
pppd_pid = 0;
net_published = 0;
}
if (!pppd_pid) { publish_setup(); start_pppd(); }
int up = ppp_up(ifname, sizeof ifname);
if (up && !net_published) publish_network(ifname);
if (!up) net_published = 0;
}
/* ---------- réponses ---------- */
static int send_all(int fd, const void *b, size_t n)
{
const char *p = b;
while (n) {
ssize_t w = write(fd, p, n);
if (w <= 0) { if (w < 0 && errno == EINTR) continue; if (!w) errno = EIO; return -1; }
p += w; n -= w;
}
return 0;
}
static void reply(int fd, int ok, const char *info, const void *data, size_t len)
{
char hdr[128];
snprintf(hdr, sizeof hdr, "%s %zu%s%s\n", ok ? "OK" : "ERR", len, info ? " " : "", info ? info : "");
send_all(fd, hdr, strlen(hdr));
if (len) send_all(fd, data, len);
}
static void reply_str(int fd, int ok, const char *fmt, ...)
{
char buf[4096];
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof buf, fmt, ap);
va_end(ap);
reply(fd, ok, NULL, buf, strlen(buf));
}
/* tampon dynamique */
struct buf { char *p; size_t n, cap; };
static void bput(struct buf *b, const void *d, size_t n)
{
if (b->n + n + 1 > b->cap) {
b->cap = (b->n + n + 1) * 2;
b->p = realloc(b->p, b->cap);
}
memcpy(b->p + b->n, d, n);
b->n += n;
b->p[b->n] = 0;
}
static void bprintf(struct buf *b, const char *fmt, ...)
{
char tmp[2048];
va_list ap;
va_start(ap, fmt);
int n = vsnprintf(tmp, sizeof tmp, fmt, ap);
va_end(ap);
bput(b, tmp, n < (int)sizeof tmp ? n : (int)sizeof tmp - 1);
}
/* ---------- commandes ---------- */
static void cmd_exec(int fd, char **args, int nargs)
{
int pfd[2];
pid_t pid;
if (nargs < 1) { reply_str(fd, 0, "usage: exec<TAB>programme<TAB>args..."); return; }
pipe(pfd);
posix_spawn_file_actions_t fa;
posix_spawn_file_actions_init(&fa);
posix_spawn_file_actions_addopen(&fa, 0, "/dev/null", O_RDONLY, 0);
posix_spawn_file_actions_adddup2(&fa, pfd[1], 1);
posix_spawn_file_actions_adddup2(&fa, pfd[1], 2);
posix_spawn_file_actions_addclose(&fa, pfd[0]);
char *argv[64];
int i;
for (i = 0; i < nargs && i < 63; i++) argv[i] = args[i];
argv[i] = NULL;
int err = posix_spawn(&pid, argv[0], &fa, NULL, argv, environ);
posix_spawn_file_actions_destroy(&fa);
close(pfd[1]);
if (err) { close(pfd[0]); reply_str(fd, 0, "posix_spawn %s : %s", argv[0], strerror(err)); return; }
struct buf out = { 0 };
char tmp[4096];
time_t start = time(NULL);
fcntl(pfd[0], F_SETFL, O_NONBLOCK);
for (;;) {
fd_set rs;
struct timeval tv = { 1, 0 };
FD_ZERO(&rs); FD_SET(pfd[0], &rs);
if (select(pfd[0] + 1, &rs, NULL, NULL, &tv) > 0) {
ssize_t n = read(pfd[0], tmp, sizeof tmp);
if (n > 0) { bput(&out, tmp, n); continue; }
if (n == 0) break;
}
if (time(NULL) - start > 120) { kill(pid, SIGKILL); bprintf(&out, "\n[emuagent: délai dépassé, processus tué]\n"); break; }
}
close(pfd[0]);
int status = 0;
waitpid(pid, &status, 0);
char info[32];
snprintf(info, sizeof info, "%d", WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status));
reply(fd, 1, info, out.p, out.n);
free(out.p);
}
static int (*p_SBSLaunchApplication)(CFStringRef, CFURLRef, CFArrayRef, CFDictionaryRef, CFStringRef, CFStringRef, unsigned);
static CFStringRef (*p_SBSApplicationLaunchingErrorString)(int);
static CFStringRef (*p_SBSCopyFrontmostApplicationDisplayIdentifier)(void);
static unsigned (*p_SBSSpringBoardServerPort)(void);
static int (*p_SBGetScreenLockStatus)(unsigned, unsigned char *, unsigned char *);
static int (*p_SBDimScreen)(unsigned, unsigned char);
static void load_sbs(void)
{
static void *h;
if (h) return;
h = dlopen("/System/Library/PrivateFrameworks/SpringBoardServices.framework/SpringBoardServices", RTLD_NOW);
if (!h) return;
p_SBSSpringBoardServerPort = dlsym(h, "SBSSpringBoardServerPort");
p_SBGetScreenLockStatus = dlsym(h, "SBGetScreenLockStatus");
p_SBDimScreen = dlsym(h, "SBDimScreen");
p_SBSLaunchApplication = dlsym(h, "SBSLaunchApplication");
p_SBSApplicationLaunchingErrorString = dlsym(h, "SBSApplicationLaunchingErrorString");
p_SBSCopyFrontmostApplicationDisplayIdentifier = dlsym(h, "SBSCopyFrontmostApplicationDisplayIdentifier");
}
static void cfstr(CFStringRef s, char *out, size_t len)
{
out[0] = 0;
if (s) CFStringGetCString(s, out, len, kCFStringEncodingUTF8);
}
/* API MIG du firmware 2.2.1 : les deux états sont des octets, retour kern_return_t. */
static void cmd_screen(int fd, int wake)
{
load_sbs();
if (!p_SBSSpringBoardServerPort || !p_SBGetScreenLockStatus || !p_SBDimScreen) {
reply_str(fd, 0, "API d'écran indisponible"); return;
}
unsigned port = p_SBSSpringBoardServerPort();
unsigned char locked = 0, passcode = 0;
int rc = p_SBGetScreenLockStatus(port, &locked, &passcode);
if (rc) { reply_str(fd, 0, "SBGetScreenLockStatus : %d", rc); return; }
if (wake) {
/* SBApplicationRequestedDeviceUnlock affiche le clavier de code même
sans code activé. Réveiller seulement l'écran, puis glisser côté hôte. */
rc = p_SBDimScreen(port, 0);
if (rc) { reply_str(fd, 0, "SBDimScreen : %d", rc); return; }
}
reply_str(fd, 1, "locked=%u passcode=%u", locked, passcode);
}
static void cmd_launch(int fd, char **args, int nargs)
{
load_sbs();
if (!p_SBSLaunchApplication) { reply_str(fd, 0, "SpringBoardServices indisponible"); return; }
if (nargs < 1) { reply_str(fd, 0, "usage: launch<TAB>bundle-id[<TAB>fichier stdout/stderr ou -[<TAB>url]]"); return; }
CFStringRef id = CFStringCreateWithCString(NULL, args[0], kCFStringEncodingUTF8);
CFStringRef out = nargs > 1 && args[1][0] != '-' ? CFStringCreateWithCString(NULL, args[1], kCFStringEncodingUTF8) : NULL;
CFURLRef url = NULL;
if (nargs > 2) {
CFStringRef us = CFStringCreateWithCString(NULL, args[2], kCFStringEncodingUTF8);
url = CFURLCreateWithString(NULL, us, NULL);
CFRelease(us);
}
/* SpringBoard refuse les demandes de lancement venant de root (« security policy error ») : l'appel est fait
par un fils qui passe en mobile (501) */
int r = -1;
pid_t child = fork();
if (child == 0) {
setgid(501);
setuid(501);
_exit(p_SBSLaunchApplication(id, url, NULL, NULL, out, out, 0) & 0xff);
}
int status = 0;
for (int i = 0; child > 0 && i < 300; i++) { /* 30 s max : SpringBoard peut être occupé (relance, cache des apps) */
if (waitpid(child, &status, WNOHANG) == child) { if (WIFEXITED(status)) r = WEXITSTATUS(status); child = 0; break; }
usleep(100000);
}
if (child > 0) {
kill(child, SIGKILL);
waitpid(child, NULL, 0);
if (url) CFRelease(url);
CFRelease(id);
if (out) CFRelease(out);
reply_str(fd, 0, "SpringBoard ne répond pas (relance ou reconstruction du cache des apps en cours ?)");
return;
}
if (url) CFRelease(url);
CFRelease(id);
if (out) CFRelease(out);
if (r == 0) { reply_str(fd, 1, "lancé"); return; }
char err[256] = "?";
if (p_SBSApplicationLaunchingErrorString) cfstr(p_SBSApplicationLaunchingErrorString(r), err, sizeof err);
reply_str(fd, 0, "SBSLaunchApplication : %d (%s)", r, err);
}
/* fetch<TAB>http://hôte[:port]/chemin : résolution DNS + GET HTTP depuis l'iPod (diagnostic réseau) */
static void cmd_fetch(int fd, char **args, int nargs)
{
char host[256], path[1024] = "/", port[8] = "80";
if (nargs < 1 || strncmp(args[0], "http://", 7)) { reply_str(fd, 0, "usage: fetch<TAB>http://hôte[:port]/chemin"); return; }
const char *h = args[0] + 7, *slash = strchr(h, '/');
size_t hl = slash ? (size_t)(slash - h) : strlen(h);
if (hl >= sizeof host) hl = sizeof host - 1;
memcpy(host, h, hl); host[hl] = 0;
if (slash) strncpy(path, slash, sizeof path - 1);
char *colon = strchr(host, ':');
if (colon) { *colon = 0; strncpy(port, colon + 1, sizeof port - 1); }
struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_STREAM }, *res;
int e = getaddrinfo(host, port, &hints, &res);
if (e) { reply_str(fd, 0, "getaddrinfo %s : %s", host, gai_strerror(e)); return; }
char ip[32];
inet_ntop(AF_INET, &((struct sockaddr_in *)res->ai_addr)->sin_addr, ip, sizeof ip);
int s = socket(AF_INET, SOCK_STREAM, 0);
struct timeval to = { 15, 0 };
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &to, sizeof to);
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &to, sizeof to);
if (connect(s, res->ai_addr, res->ai_addrlen)) { reply_str(fd, 0, "connect %s (%s) : %s", host, ip, strerror(errno)); close(s); freeaddrinfo(res); return; }
freeaddrinfo(res);
char req[1400];
snprintf(req, sizeof req, "GET %s HTTP/1.0\r\nHost: %s\r\nUser-Agent: emuagent\r\nConnection: close\r\n\r\n", path, host);
send_all(s, req, strlen(req));
struct buf b = { 0 };
bprintf(&b, "[%s -> %s]\n", host, ip);
char tmp[4096];
ssize_t n;
while (b.n < 256 * 1024 && (n = read(s, tmp, sizeof tmp)) > 0) bput(&b, tmp, n);
close(s);
reply(fd, 1, NULL, b.p, b.n);
free(b.p);
}
/* sc[<TAB>clé] : liste des clés du SCDynamicStore, ou valeur d'une clé (plist XML) */
static void cmd_sc(int fd, char **args, int nargs)
{
if (!store) store = SCDynamicStoreCreate(NULL, CFSTR("emuagent"), NULL, NULL);
CFStringRef k = CFStringCreateWithCString(NULL, nargs ? args[0] : ".*", kCFStringEncodingUTF8);
CFPropertyListRef v = nargs && !strchr(args[0], '*') ? SCDynamicStoreCopyValue(store, k) : SCDynamicStoreCopyKeyList(store, k);
CFRelease(k);
if (!v) { reply_str(fd, 0, "clé absente"); return; }
CFDataRef x = CFPropertyListCreateXMLData(NULL, v);
reply(fd, 1, NULL, CFDataGetBytePtr(x), CFDataGetLength(x));
CFRelease(x);
CFRelease(v);
}
/* routes : table de routage IPv4 (sysctl NET_RT_DUMP) */
static void cmd_routes(int fd)
{
int mib[6] = { CTL_NET, PF_ROUTE, 0, AF_INET, NET_RT_DUMP, 0 };
size_t len = 0;
if (sysctl(mib, 6, NULL, &len, NULL, 0)) { reply_str(fd, 0, "sysctl : %s", strerror(errno)); return; }
char *b = malloc(len), *p;
sysctl(mib, 6, b, &len, NULL, 0);
struct buf out = { 0 };
for (p = b; p < b + len;) {
struct rt_msghdr *h = (struct rt_msghdr *)p;
struct sockaddr *sa = (struct sockaddr *)(h + 1);
char txt[3][32] = { "-", "-", "-" };
for (int i = 0; i < 3; i++) {
if (!(h->rtm_addrs & (1 << i))) continue;
if (sa->sa_family == AF_INET) inet_ntop(AF_INET, &((struct sockaddr_in *)sa)->sin_addr, txt[i], 32);
else if (sa->sa_family == AF_LINK) strcpy(txt[i], "link");
else if (sa->sa_len == 0) strcpy(txt[i], "0");
sa = (struct sockaddr *)((char *)sa + (sa->sa_len ? ((sa->sa_len + 3) & ~3) : 4));
}
char ifn[IFNAMSIZ] = "?";
if_indextoname(h->rtm_index, ifn);
bprintf(&out, "%-16s gw %-16s mask %-16s %s flags 0x%x\n", txt[0], txt[1], txt[2], ifn, h->rtm_flags);
p += h->rtm_msglen;
}
free(b);
reply(fd, 1, NULL, out.p ? out.p : "", out.n);
free(out.p);
}
static void cmd_front(int fd)
{
load_sbs();
char s[256] = "";
if (p_SBSCopyFrontmostApplicationDisplayIdentifier) {
CFStringRef f = p_SBSCopyFrontmostApplicationDisplayIdentifier();
cfstr(f, s, sizeof s);
if (f) CFRelease(f);
}
reply_str(fd, 1, "%s", s[0] ? s : "com.apple.springboard");
}
static void list_apps_in(struct buf *b, const char *dir, int depth)
{
DIR *d = opendir(dir);
struct dirent *e;
if (!d) return;
while ((e = readdir(d))) {
char path[1024];
if (e->d_name[0] == '.') continue;
snprintf(path, sizeof path, "%s/%s", dir, e->d_name);
size_t l = strlen(e->d_name);
if (l > 4 && !strcmp(e->d_name + l - 4, ".app")) {
CFURLRef u = CFURLCreateFromFileSystemRepresentation(NULL, (UInt8 *)path, strlen(path), true);
CFBundleRef bundle = CFBundleCreate(NULL, u);
char id[256] = "", name[256] = "";
if (bundle) {
cfstr(CFBundleGetIdentifier(bundle), id, sizeof id);
CFTypeRef n = CFBundleGetValueForInfoDictionaryKey(bundle, CFSTR("CFBundleDisplayName"));
if (!n) n = CFBundleGetValueForInfoDictionaryKey(bundle, kCFBundleNameKey);
if (n && CFGetTypeID(n) == CFStringGetTypeID()) cfstr(n, name, sizeof name);
CFRelease(bundle);
}
CFRelease(u);
bprintf(b, "%s\t%s\t%s\n", id, name, path);
} else if (depth > 0) {
list_apps_in(b, path, depth - 1);
}
}
closedir(d);
}
static void cmd_apps(int fd)
{
struct buf b = { 0 };
list_apps_in(&b, "/Applications", 0);
list_apps_in(&b, "/private/var/mobile/Applications", 1);
reply(fd, 1, NULL, b.p, b.n);
free(b.p);
}
static int mkdirs(const char *path)
{
char tmp[1024];
strncpy(tmp, path, sizeof tmp - 1);
tmp[sizeof tmp - 1] = 0;
for (char *p = tmp + 1; *p; p++) {
if (*p == '/') { *p = 0; mkdir(tmp, 0755); *p = '/'; }
}
return mkdir(tmp, 0755) == 0 || errno == EEXIST ? 0 : -1;
}
static int read_full(int fd, void *b, size_t n)
{
char *p = b;
while (n) {
ssize_t r = read(fd, p, n);
if (r <= 0) { if (r < 0 && errno == EINTR) continue; if (!r) errno = EIO; return -1; }
p += r; n -= r;
}
return 0;
}
/* Transferts par blocs : ne pas allouer la taille du fichier sur l'iPod. */
static void cmd_put(int fd, char **args, int nargs)
{
if (nargs < 3) { reply_str(fd, 0, "usage: put<TAB>chemin<TAB>mode octal<TAB>taille + données"); return; }
char *end;
errno = 0;
unsigned long size = strtoul(args[2], &end, 10);
if (errno || !args[2][0] || args[2][0] == '-' || *end) {
reply_str(fd, 0, "taille invalide"); return;
}
char dir[1024];
if (strlen(args[0]) >= sizeof dir) { reply_str(fd, 0, "chemin trop long"); return; }
strcpy(dir, args[0]);
char *slash = strrchr(dir, '/');
if (slash && slash != dir) { *slash = 0; mkdirs(dir); }
char tmp[1100];
snprintf(tmp, sizeof tmp, "%s.emuagent-XXXXXX", args[0]);
int f = mkstemp(tmp);
if (f < 0) { reply_str(fd, 0, "création : %s", strerror(errno)); return; }
char data[65536];
size_t remaining = size;
int failed = 0;
while (remaining) {
size_t chunk = remaining < sizeof data ? remaining : sizeof data;
if (read_full(fd, data, chunk) || send_all(f, data, chunk)) { failed = 1; break; }
remaining -= chunk;
}
if (!failed && (fchmod(f, strtoul(args[1], NULL, 8)) || fsync(f))) failed = 1;
int saved = errno;
if (close(f) && !failed) { failed = 1; saved = errno; }
if (!failed && rename(tmp, args[0])) { failed = 1; saved = errno; }
if (failed) {
unlink(tmp);
reply_str(fd, 0, "écriture de %s : %s", args[0], strerror(saved));
return;
}
reply_str(fd, 1, "%lu octets écrits", size);
}
static void cmd_get(int fd, char **args, int nargs)
{
if (nargs < 1) { reply_str(fd, 0, "usage: get<TAB>chemin"); return; }
int f = open(args[0], O_RDONLY | O_NONBLOCK);
struct stat st;
if (f < 0 || fstat(f, &st) || !S_ISREG(st.st_mode)) {
reply_str(fd, 0, "lecture de %s impossible", args[0]);
if (f >= 0) close(f);
return;
}
char hdr[128], data[65536];
snprintf(hdr, sizeof hdr, "OK %llu\n", (unsigned long long)st.st_size);
if (send_all(fd, hdr, strlen(hdr))) { close(f); return; }
off_t remaining = st.st_size;
while (remaining) {
size_t chunk = remaining < (off_t)sizeof data ? (size_t)remaining : sizeof data;
/* Après l'en-tête, une erreur impose de fermer la connexion :
le client détecte la réponse incomplète et conserve son ancien fichier. */
if (read_full(f, data, chunk) || send_all(fd, data, chunk)) {
close(f); shutdown(fd, SHUT_RDWR); return;
}
remaining -= chunk;
}
close(f);
}
static void cmd_ls(int fd, char **args, int nargs)
{
const char *path = nargs ? args[0] : "/";
DIR *d = opendir(path);
if (!d) { reply_str(fd, 0, "%s : %s", path, strerror(errno)); return; }
struct buf b = { 0 };
struct dirent *e;
while ((e = readdir(d))) {
char p[1024];
struct stat st;
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
snprintf(p, sizeof p, "%s/%s", path, e->d_name);
if (lstat(p, &st)) continue;
bprintf(&b, "%c%04o %5d %5d %10lld %s\n", S_ISDIR(st.st_mode) ? 'd' : S_ISLNK(st.st_mode) ? 'l' : '-',
st.st_mode & 07777, st.st_uid, st.st_gid, (long long)st.st_size, e->d_name);
}
closedir(d);
reply(fd, 1, NULL, b.p ? b.p : "", b.n);
free(b.p);
}
static int rm_rf(const char *path)
{
struct stat st;
if (lstat(path, &st)) return -1;
if (S_ISDIR(st.st_mode)) {
DIR *d = opendir(path);
struct dirent *e;
while (d && (e = readdir(d))) {
char p[1024];
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
snprintf(p, sizeof p, "%s/%s", path, e->d_name);
rm_rf(p);
}
if (d) closedir(d);
return rmdir(path);
}
return unlink(path);
}
static void cmd_ps(int fd)
{
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
size_t len = 0;
sysctl(mib, 3, NULL, &len, NULL, 0);
struct kinfo_proc *procs = malloc(len);
if (sysctl(mib, 3, procs, &len, NULL, 0)) { reply_str(fd, 0, "sysctl : %s", strerror(errno)); free(procs); return; }
struct buf b = { 0 };
bprintf(&b, " PID PPID UID COMMAND\n");
for (size_t i = 0; i < len / sizeof *procs; i++) {
struct kinfo_proc *p = &procs[i];
bprintf(&b, "%5d %5d %5d %s\n", p->kp_proc.p_pid, p->kp_eproc.e_ppid, p->kp_eproc.e_ucred.cr_uid, p->kp_proc.p_comm);
}
reply(fd, 1, NULL, b.p, b.n);
free(b.p);
free(procs);
}
static int kill_by_name(const char *name, int sig)
{
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 }, n = 0;
size_t len = 0;
sysctl(mib, 3, NULL, &len, NULL, 0);
struct kinfo_proc *procs = malloc(len);
if (!sysctl(mib, 3, procs, &len, NULL, 0)) {
for (size_t i = 0; i < len / sizeof *procs; i++) {
if (!strcmp(procs[i].kp_proc.p_comm, name) && !kill(procs[i].kp_proc.p_pid, sig)) n++;
}
}
free(procs);
return n;
}
static void cmd_kill(int fd, char **args, int nargs)
{
if (nargs < 1) { reply_str(fd, 0, "usage: kill<TAB>pid|nom[<TAB>signal]"); return; }
int sig = nargs > 1 ? atoi(args[1]) : SIGTERM;
char *end;
long pid = strtol(args[0], &end, 10);
if (!*end) {
if (kill(pid, sig)) reply_str(fd, 0, "kill %ld : %s", pid, strerror(errno));
else reply_str(fd, 1, "1");
} else {
int n = kill_by_name(args[0], sig);
reply_str(fd, n > 0, "%d", n);
}
}
static void cmd_net(int fd)
{
struct ifaddrs *ifa, *i;
struct buf b = { 0 };
if (!getifaddrs(&ifa)) {
for (i = ifa; i; i = i->ifa_next) {
if (i->ifa_addr && i->ifa_addr->sa_family == AF_INET) {
char a[32], dst[32] = "";
inet_ntop(AF_INET, &((struct sockaddr_in *)i->ifa_addr)->sin_addr, a, sizeof a);
if (i->ifa_dstaddr && (i->ifa_flags & IFF_POINTOPOINT))
inet_ntop(AF_INET, &((struct sockaddr_in *)i->ifa_dstaddr)->sin_addr, dst, sizeof dst);
bprintf(&b, "%s %s%s%s %s\n", i->ifa_name, a, dst[0] ? " -> " : "", dst, (i->ifa_flags & IFF_UP) ? "up" : "down");
}
}
freeifaddrs(ifa);
}
bprintf(&b, "pppd: %s, configd: %s\n", pppd_pid ? "actif" : "arrêté", net_published ? "publié" : "non publié");
reply(fd, 1, NULL, b.p, b.n);
free(b.p);
}
static void handle(int fd, char *line)
{
char *args[64];
int n = 0;
for (char *t = strtok(line, "\t"); t && n < 64; t = strtok(NULL, "\t")) args[n++] = t;
if (!n) return;
char *cmd = args[0];
char **a = args + 1;
int na = n - 1;
if (!strcmp(cmd, "ping")) reply_str(fd, 1, "emuagent %s", VERSION);
else if (!strcmp(cmd, "exec")) cmd_exec(fd, a, na);
else if (!strcmp(cmd, "launch")) cmd_launch(fd, a, na);
else if (!strcmp(cmd, "front")) cmd_front(fd);
else if (!strcmp(cmd, "screen")) cmd_screen(fd, 0);
else if (!strcmp(cmd, "wake")) cmd_screen(fd, 1);
else if (!strcmp(cmd, "fetch")) cmd_fetch(fd, a, na);
else if (!strcmp(cmd, "sc")) cmd_sc(fd, a, na);
else if (!strcmp(cmd, "routes")) cmd_routes(fd);
else if (!strcmp(cmd, "settime")) {
/* Réglage explicite de l'heure pour les tests (secondes Unix). */
struct timeval tv = { na ? strtol(a[0], NULL, 10) : 0, 0 };
if (na && !settimeofday(&tv, NULL)) {
notify_post("com.apple.system.clock_set"); /* SpringBoard et les apps mettent leur horloge à jour */
reply_str(fd, 1, "%ld", (long)tv.tv_sec);
}
else reply_str(fd, 0, "settimeofday : %s", strerror(errno));
}
else if (!strcmp(cmd, "apps")) cmd_apps(fd);
else if (!strcmp(cmd, "put")) cmd_put(fd, a, na);
else if (!strcmp(cmd, "get")) cmd_get(fd, a, na);
else if (!strcmp(cmd, "ls")) cmd_ls(fd, a, na);
else if (!strcmp(cmd, "rm")) { if (na && !rm_rf(a[0])) reply_str(fd, 1, "supprimé"); else reply_str(fd, 0, "rm : %s", strerror(errno)); }
else if (!strcmp(cmd, "mkdir")) { if (na && !mkdirs(a[0])) reply_str(fd, 1, "ok"); else reply_str(fd, 0, "mkdir : %s", strerror(errno)); }
else if (!strcmp(cmd, "ps")) cmd_ps(fd);
else if (!strcmp(cmd, "kill")) cmd_kill(fd, a, na);
else if (!strcmp(cmd, "net")) cmd_net(fd);
else if (!strcmp(cmd, "respring")) reply_str(fd, kill_by_name("SpringBoard", SIGTERM) > 0, "SpringBoard relancé");
else if (!strcmp(cmd, "sync")) { sync(); reply_str(fd, 1, "ok"); }
else reply_str(fd, 0, "commande inconnue : %s (ping exec launch fetch sc routes settime screen wake front apps put get ls rm mkdir ps kill net respring sync)", cmd);
}
static void serve_client(int fd)
{
char line[8192];
size_t len = 0;
for (;;) {
char c;
ssize_t r = read(fd, &c, 1);
if (r <= 0) break;
if (c == '\n') {
line[len] = 0;
handle(fd, line);
len = 0;
} else if (len < sizeof line - 1) {
line[len++] = c;
}
}
close(fd);
}
/* diagnostic : si /private/var/root/emuagent-ttytest existe, lit la ligne série brute pendant 20 s avant pppd */
static void tty_selftest(void)
{
struct stat st;
if (stat("/private/var/root/emuagent-ttytest", &st)) return;
int fd = open(PPP_TTY, O_RDWR | O_NOCTTY | O_NONBLOCK);
clog_("ttytest : open %s -> %d (%s)", PPP_TTY, fd, fd < 0 ? strerror(errno) : "ok");
if (fd < 0) return;
struct termios t;
tcgetattr(fd, &t); cfmakeraw(&t); cfsetspeed(&t, B115200); t.c_cflag |= CLOCAL | CREAD; t.c_cflag &= ~CRTSCTS;
tcsetattr(fd, TCSANOW, &t);
write(fd, "EMUAGENT-TTYTEST\n", 17);
time_t start = time(NULL);
size_t total = 0;
while (time(NULL) - start < 20) {
char b[256];
ssize_t n = read(fd, b, sizeof b);
if (n > 0) {
total += n;
char hex[64] = "";
for (int i = 0; i < n && i < 16; i++) sprintf(hex + 3 * i, "%02x ", (unsigned char)b[i]);
clog_("ttytest : %zd octets : %s", n, hex);
} else {
usleep(100000);
}
}
clog_("ttytest : %zu octets reçus au total", total);
close(fd);
}
/* iPhone OS 2.x does not implement the public idle-sleep assertions.
* Its root power domain does support SleepDisabled, which is required
* because this emulated SoC cannot resume from deep sleep. */
static void prevent_idle_sleep(void)
{
void *h = dlopen("/System/Library/Frameworks/IOKit.framework/IOKit", RTLD_NOW);
CFMutableDictionaryRef (*matching)(const char *) = h ? dlsym(h, "IOServiceMatching") : NULL;
unsigned (*get_service)(unsigned, CFDictionaryRef) = h ? dlsym(h, "IOServiceGetMatchingService") : NULL;
int (*set_property)(unsigned, CFStringRef, CFTypeRef) = h ? dlsym(h, "IORegistryEntrySetCFProperty") : NULL;
int (*release)(unsigned) = h ? dlsym(h, "IOObjectRelease") : NULL;
if (!matching || !get_service || !set_property || !release) {
clog_("controle de veille IOKit indisponible");
return;
}
unsigned root = get_service(0, matching("IOPMrootDomain"));
if (!root) {
clog_("IOPMrootDomain indisponible");
return;
}
int rc = set_property(root, CFSTR("SleepDisabled"), kCFBooleanTrue);
release(root);
clog_("SleepDisabled: 0x%x", rc);
}
int main(void)
{
con = fopen("/dev/console", "w");
if (con) setvbuf(con, NULL, _IONBF, 0);
signal(SIGPIPE, SIG_IGN);
clog_("version %s, port %d", VERSION, PORT);
prevent_idle_sleep();
tty_selftest();
/* agent relancé (mise à jour, crash) : le pppd de l'instance précédente tient encore la ligne série */
if (kill_by_name("pppd", SIGTERM) > 0) { clog_("ancien pppd arrêté"); sleep(2); }
int s = socket(AF_INET, SOCK_STREAM, 0), one = 1;
fcntl(s, F_SETFD, FD_CLOEXEC); /* sinon pppd hérite du port d'écoute */
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one);
struct sockaddr_in a = { .sin_family = AF_INET, .sin_port = htons(PORT), .sin_addr.s_addr = htonl(INADDR_ANY) };
while (bind(s, (struct sockaddr *)&a, sizeof a)) { clog_("bind : %s, nouvel essai", strerror(errno)); sleep(2); }
listen(s, 4);
for (;;) {
pid_t z;
int zs;
while ((z = waitpid(-1, &zs, WNOHANG)) > 0) {
if (z == pppd_pid) { clog_("pppd terminé (statut %d), relance", zs); pppd_pid = 0; net_published = 0; }
}
net_tick();
fd_set rs;
struct timeval tv = { 2, 0 };
FD_ZERO(&rs);
FD_SET(s, &rs);
if (select(s + 1, &rs, NULL, NULL, &tv) > 0) {
int c = accept(s, NULL, NULL);
if (c >= 0) {
fcntl(c, F_SETFD, FD_CLOEXEC);
/* un processus par client : une commande longue ou bloquée ne gêne ni les autres ni le suivi réseau */
pid_t p = fork();
if (p == 0) {
close(s);
struct timeval to = { 300, 0 };
setsockopt(c, SOL_SOCKET, SO_RCVTIMEO, &to, sizeof to);
serve_client(c);
_exit(0);
}
close(c);
}
}
}
}
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>com.apple.springboard.launchapplications</key><true/>
<key>com.apple.springboard.debugapplications</key><true/>
<key>com.apple.springboard.opensensitiveurl</key><true/>
</dict></plist>
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"><dict>
<key>CFBundleExecutable</key><string>HelloEmu</string>
<key>CFBundleIdentifier</key><string>com.allovoisins.helloemu</string>
<key>CFBundleName</key><string>HelloEmu</string>
<key>CFBundleDisplayName</key><string>HelloEmu</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleVersion</key><string>1.0</string>
<key>MinimumOSVersion</key><string>2.0</string>
</dict></plist>
+27
View File
@@ -0,0 +1,27 @@
#import <UIKit/UIKit.h>
@interface HelloApp : NSObject <UIApplicationDelegate> { UIWindow *window; }
@end
@implementation HelloApp
- (void)applicationDidFinishLaunching:(UIApplication *)app {
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
window.backgroundColor = [UIColor colorWithRed:0.1 green:0.4 blue:0.8 alpha:1];
UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 320, 60)];
l.text = @"HelloEmu OK";
l.textAlignment = UITextAlignmentCenter;
l.font = [UIFont boldSystemFontOfSize:32];
l.textColor = [UIColor whiteColor];
l.backgroundColor = [UIColor clearColor];
[window addSubview:l];
[window makeKeyAndVisible];
NSLog(@"HelloEmu: launched");
}
@end
int main(int argc, char *argv[]) {
NSAutoreleasePool *p = [[NSAutoreleasePool alloc] init];
int r = UIApplicationMain(argc, argv, nil, @"HelloApp");
[p release];
return r;
}
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key>
<string>TouchProbe</string>
<key>CFBundleIdentifier</key>
<string>com.ioslegacy.touchprobe</string>
<key>CFBundleName</key>
<string>TouchProbe</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleVersion</key>
<string>1.0</string>
<key>MinimumOSVersion</key>
<string>2.0</string>
</dict>
</plist>
+10
View File
@@ -0,0 +1,10 @@
# Sonde de calibration tactile pour iPhone OS 2.
SDK := /opt/theos/sdks/iPhoneOS2.2.1.sdk
CC := /opt/cctools/bin/arm-apple-darwin9-gcc
all: TouchProbe.app/TouchProbe
TouchProbe.app/TouchProbe: main.m Info.plist
mkdir -p TouchProbe.app
$(CC) -isysroot $(SDK) -arch armv6 -miphoneos-version-min=2.0 -O2 -o $@ main.m -framework UIKit -framework Foundation
cp Info.plist TouchProbe.app/
ldid -S $@
.PHONY: all
+30
View File
@@ -0,0 +1,30 @@
#import <UIKit/UIKit.h>
@interface ProbeView : UIView
@end
@implementation ProbeView
- (void)record:(NSSet *)touches phase:(NSString *)phase {
CGPoint p=[[touches anyObject] locationInView:self];
UIView *marker=[self viewWithTag:99];
if (!marker) {
marker=[[[UIView alloc] initWithFrame:CGRectMake(0,0,0,0)] autorelease];
marker.tag=99; marker.backgroundColor=[UIColor blueColor]; marker.userInteractionEnabled=NO;
[self addSubview:marker];
}
marker.frame=CGRectMake(p.x-2,p.y-2,5,5);
NSLog(@"TOUCH %@ %.1f %.1f",phase,p.x,p.y);
}
- (void)touchesBegan:(NSSet *)t withEvent:(UIEvent *)e { [self record:t phase:@"begin"]; }
- (void)touchesMoved:(NSSet *)t withEvent:(UIEvent *)e { [self record:t phase:@"move"]; }
- (void)touchesEnded:(NSSet *)t withEvent:(UIEvent *)e { [self record:t phase:@"end"]; }
@end
@interface ProbeApp : NSObject <UIApplicationDelegate> { UIWindow *window; }
@end
@implementation ProbeApp
- (void)applicationDidFinishLaunching:(UIApplication *)app {
window=[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
ProbeView *v=[[ProbeView alloc] initWithFrame:CGRectMake(0,20,320,460)];
v.backgroundColor=[UIColor whiteColor];[window addSubview:v];[v release];[window makeKeyAndVisible];
NSLog(@"TouchProbe ready window=%@ view=%@",NSStringFromCGRect(window.frame),NSStringFromCGRect(v.frame));
}
@end
int main(int argc,char **argv) { NSAutoreleasePool *p=[[NSAutoreleasePool alloc] init];int rc=UIApplicationMain(argc,argv,nil,@"ProbeApp");[p release];return rc; }
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env python3
# armdis.py FICHIER BASE DEBUT FIN [arm] — désassemble (Thumb par défaut) avec résolution des ldr pc-relatifs
import sys, struct, capstone
f, base, start, end = sys.argv[1], int(sys.argv[2], 16), int(sys.argv[3], 16), int(sys.argv[4], 16)
mode = capstone.CS_MODE_ARM if len(sys.argv) > 5 else capstone.CS_MODE_THUMB
d = open(f, 'rb').read()
md = capstone.Cs(capstone.CS_ARCH_ARM, mode); md.detail = True; md.skipdata = True
def s(a):
o = a - base
if 0 <= o < len(d):
e = d.find(b'\0', o, o + 80)
t = d[o:e]
if len(t) >= 4 and all(32 <= c < 127 for c in t): return ' "%s"' % t.decode()
return ''
for i in md.disasm(d[start - base:end - base], start):
x = ''
if i.mnemonic.startswith('ldr') and '[pc' in i.op_str:
disp = i.operands[1].mem.disp
la = ((i.address + (4 if mode == capstone.CS_MODE_THUMB else 8)) & ~3) + disp
v = struct.unpack('<I', d[la - base:la - base + 4])[0]
x = ' ; =%#x%s' % (v, s(v))
elif i.mnemonic in ('bl', 'blx', 'b', 'b.w'):
pass
print('%08x: %-8s %s%s' % (i.address, i.mnemonic, i.op_str, x))
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
# Dump d'un DeviceTree Apple (format img3 déchiffré, "flat" iBoot)
import struct, sys
d = open(sys.argv[1], 'rb').read()
if d[:4] == b'3gmI': # img3 -> DATA tag
o = 20
while o < len(d):
magic, total, dlen = struct.unpack('<4sII', d[o:o+12])
if magic == b'ATAD': d = d[o+12:o+12+dlen]; break
o += total
def node(o, depth, path):
np, nc = struct.unpack('<II', d[o:o+8]); o += 8
props = {}
for _ in range(np):
name = d[o:o+32].split(b'\0')[0].decode(); ln = struct.unpack('<I', d[o+32:o+36])[0] & 0x7fffffff
props[name] = d[o+36:o+36+ln]; o += 36 + ((ln + 3) & ~3)
nm = props.get('name', b'?').split(b'\0')[0].decode()
p = path + '/' + nm
reg = props.get('reg')
comp = props.get('compatible', b'').split(b'\0')[0].decode()
regs = ' '.join('%08x+%x' % struct.unpack('<II', reg[i:i+8]) for i in range(0, len(reg) - 7, 8)) if reg else ''
print('%s%s [%s] reg=%s' % (' ' * depth, p, comp, regs))
for _ in range(nc): o = node(o, depth + 1, p)
return o
node(0, 0, '')
+250
View File
@@ -0,0 +1,250 @@
#!/usr/bin/env python3
"""Client de l'agent de l'iPod émulé (emuagent, via ipod-netd sur 127.0.0.1:7788).
ipod-agent ping
ipod-agent apps bundle-id, nom et chemin des apps installées
ipod-agent launch BUNDLE_ID [--log F] [--url URL]
lance une app (stdout/stderr, donc NSLog, dans F sur l'iPod ; URL à ouvrir)
ipod-agent fetch http://hôte/chemin requête HTTP depuis l'iPod (test réseau : DNS + TCP)
ipod-agent front app au premier plan
ipod-agent screen | wake état du verrouillage / réveil sans clavier de code (agent v11)
ipod-agent unlock réveille puis glisse et vérifie le déverrouillage (sans code)
ipod-agent exec PROG [ARGS...] exécute un programme (pas de shell : chemin absolu)
ipod-agent ps | net | respring | sync
ipod-agent kill PID|NOM [SIGNAL]
ipod-agent ls CHEMIN | rm CHEMIN | mkdir CHEMIN
ipod-agent get CHEMIN_IPOD [FICHIER_LOCAL]
ipod-agent put FICHIER_LOCAL CHEMIN_IPOD [MODE]
ipod-agent push-app MonApp.app copie l'app, synchronise et redémarre l'iPod (NAND conservée)
ipod-agent wait [SECONDES] attend que l'agent réponde (réseau PPP monté)
Code de sortie : 0 si OK, 1 si erreur, code de sortie du programme pour exec.
"""
import os, socket, subprocess, sys, tempfile, time
HOST = os.environ.get("IPOD_AGENT_HOST", "127.0.0.1")
PORT = int(os.environ.get("IPOD_AGENT_PORT", "7788"))
class Agent:
def __init__(self, timeout=330):
self.s = socket.create_connection((HOST, PORT), timeout=timeout)
self.f = self.s.makefile("rb")
def call(self, *fields, data=None, sink=None):
line = "\t".join(str(x) for x in fields) + "\n"
self.s.sendall(line.encode())
if data is not None:
if hasattr(data, "read"):
remaining = int(fields[-1])
while remaining:
chunk = data.read(min(65536, remaining))
if not chunk:
raise ConnectionError("fichier local tronqué pendant l'upload")
self.s.sendall(chunk)
remaining -= len(chunk)
else:
self.s.sendall(data)
hdr = self.f.readline(4096).decode().rstrip("\n")
if not hdr:
raise ConnectionError("connexion fermée par l'agent")
parts = hdr.split(" ", 2)
if len(parts) < 2:
raise ConnectionError("en-tête invalide")
n = int(parts[1])
if n < 0 or parts[0] not in ("OK", "ERR"):
raise ConnectionError("en-tête invalide")
body = bytearray()
received = 0
while received < n:
chunk = self.f.read(min(65536, n - received))
if not chunk:
raise ConnectionError(f"réponse tronquée : {received} octets reçus sur {n}")
received += len(chunk)
if sink is not None and parts[0] == "OK":
sink.write(chunk)
else:
body.extend(chunk)
body = bytes(body)
return parts[0] == "OK", body, parts[2] if len(parts) > 2 else None
def out(body):
sys.stdout.buffer.write(body)
if body and not body.endswith(b"\n"):
sys.stdout.buffer.write(b"\n")
def emu_home():
tools_home = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
default_home = tools_home if os.path.isdir(os.path.join(tools_home, "images")) else os.path.expanduser("~/ipod-emu")
return os.environ.get("IPOD_EMU_HOME", default_home)
def unlock(a):
def screen():
ok, body, _ = a.call("screen")
if not ok:
sys.exit("État d'écran indisponible (agent v11 requis) : " + body.decode())
return dict(field.split("=", 1) for field in body.decode().split())
state = screen()
if state.get("locked") == "0":
print("Écran déverrouillé")
return
if state.get("passcode") != "0":
sys.exit("Un code de verrouillage est activé : déverrouiller manuellement.")
# Le pilote tactile doit avoir terminé son démarrage avant tout glissement.
try:
offset_path = os.path.join(emu_home(), "run", "boot-log-offset")
offset = 0
if os.path.exists(offset_path):
with open(offset_path) as f:
offset = int(f.read())
with open(os.path.join(emu_home(), "run", "serial.log"), "rb") as f:
f.seek(offset)
serial = f.read()
except OSError as e:
sys.exit(f"Console de session inaccessible : {e}")
helper_ready = any(b"SCHelper" in line and b'"EXIT"' in line for line in serial.splitlines())
if serial.count(b"AppleMultitouchSPIUserClient::attach") < 2 or not helper_ready:
sys.exit("Contrôleur tactile pas encore prêt : attendre ipod-emu wait.")
qmp = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ipod-qmp")
sock = os.environ.get("IPOD_QMP", os.path.join(emu_home(), "run", "qmp.sock"))
for attempt in range(3):
ok, body, _ = a.call("wake")
if not ok:
sys.exit(body.decode())
time.sleep(2) # laisser le pilote réactiver l'écran et le tactile
# Terminer le geste au bord droit du curseur de déverrouillage.
subprocess.run([qmp, "-s", sock, "swipe", "60", "450", "319", "450"], check=True)
time.sleep(2)
state = screen()
if state.get("locked") == "0":
print("Écran déverrouillé")
return
if state.get("passcode") != "0":
sys.exit("Un code de verrouillage est activé : déverrouiller manuellement.")
sys.exit("Écran toujours verrouillé après trois glissements.")
def push_app(a, app):
home = emu_home()
run = os.path.join(home, "run")
try:
with open(os.path.join(run, "nand", ".ipod-nand-format")) as f:
layout = f.read().strip()
with open(os.path.join(run, "fw")) as f:
firmware = f.read().strip()
with open(os.path.join(home, "images", firmware, "machine-opts")) as f:
machine_opts = f.read()
except OSError:
sys.exit("push-app nécessite une image locale avec persistance NAND (ipod-mkimage / ipod-build-fw).")
if layout != "vsvfl-production-v1" or ",nand-write=on" not in machine_opts:
sys.exit("Écritures NAND désactivées : reconstruire l'image avant push-app.")
app = app.rstrip("/")
dest = "/Applications/" + os.path.basename(app)
a.call("rm", dest)
n = 0
for root, dirs, files in os.walk(app):
for f in files:
p = os.path.join(root, f)
rel = os.path.relpath(p, app)
st = os.stat(p)
with open(p, "rb") as fh:
data = fh.read()
mode = "755" if (st.st_mode & 0o111 or data[:4] in (b"\xce\xfa\xed\xfe", b"\xca\xfe\xba\xbe")) else "644"
ok, body, _ = a.call("put", f"{dest}/{rel}", mode, len(data), data=data)
if not ok:
sys.exit(body.decode())
n += 1
# SpringBoard ne relit la liste des apps qu'à son démarrage
a.call("rm", "/private/var/mobile/Library/Caches/com.apple.mobile.installation.plist")
ok, body, _ = a.call("sync")
if not ok:
sys.exit(body.decode())
# Le cache d'installation iOS 2.x peut bloquer SpringBoard lors d'une
# relance seule. Un démarrage complet le reconstruit, sans refaire l'image.
a.f.close()
a.s.close()
launcher = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ipod-emu")
print(f"{n} fichiers copiés dans {dest}, redémarrage de l'iPod", flush=True)
subprocess.run([launcher, "stop"], check=True)
subprocess.run([launcher, "start", "-w", firmware, "-W"], check=True)
def main():
args = sys.argv[1:]
if not args or args[0] in ("-h", "--help"):
sys.exit(__doc__)
cmd, rest = args[0], args[1:]
if cmd == "wait":
limit = float(rest[0]) if rest else 300
t0 = time.time()
while True:
try:
ok, body, _ = Agent(timeout=5).call("ping")
print(body.decode(), f"({time.time() - t0:.0f} s)")
return
except OSError:
if time.time() - t0 > limit:
sys.exit("agent injoignable (ipod-netd lancé ? réseau PPP monté ?)")
time.sleep(2)
try:
a = Agent()
except OSError as e:
sys.exit(f"agent injoignable sur {HOST}:{PORT} ({e}) — ipod-netd lancé ?")
if cmd == "unlock":
a.s.settimeout(15)
unlock(a)
return
if cmd == "get":
tmp = None
try:
if len(rest) > 1:
destination = os.path.abspath(rest[1])
fd, tmp = tempfile.mkstemp(prefix=".ipod-get-", dir=os.path.dirname(destination))
with os.fdopen(fd, "wb") as fh:
ok, body, _ = a.call("get", rest[0], sink=fh)
fh.flush()
os.fsync(fh.fileno())
if ok:
os.replace(tmp, destination)
tmp = None
else:
ok, body, _ = a.call("get", rest[0], sink=sys.stdout.buffer)
if not ok:
sys.exit(body.decode())
finally:
if tmp is not None:
os.unlink(tmp)
return
if cmd == "put":
mode = rest[2] if len(rest) > 2 else ("755" if os.access(rest[0], os.X_OK) else "644")
with open(rest[0], "rb") as fh:
ok, body, _ = a.call("put", rest[1], mode, os.fstat(fh.fileno()).st_size, data=fh)
elif cmd == "push-app":
push_app(a, rest[0])
return
elif cmd == "launch":
fields = ["launch", rest[0], rest[rest.index("--log") + 1] if "--log" in rest else "-"]
if "--url" in rest:
fields.append(rest[rest.index("--url") + 1])
ok, body, _ = a.call(*fields)
else:
ok, body, info = a.call(cmd, *rest)
if cmd == "exec":
out(body)
sys.exit(int(info) if ok and info else (0 if ok else 1))
out(body)
sys.exit(0 if ok else 1)
if __name__ == "__main__":
try:
main()
except (OSError, ValueError, ConnectionError) as e:
sys.exit(f"Erreur de transfert ou de protocole : {e}")
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
# Reconstruit une image firmware de l'émulateur à partir de l'IPSW officiel iPod2,1.
#
# ipod-build-fw [BUILD] (défaut : 5H11a = iPhone OS 2.2.1)
#
# Étapes : téléchargement de l'IPSW (serveurs Apple) et des clés (api.ipsw.me), NOR (LLB, iBoot, DeviceTree, logos),
# déchiffrement du rootfs, adaptations pour l'émulateur (mkbase-rootfs), NAND. Résultat : ~/ipod-emu/images/BUILD/
set -euo pipefail
BUILD=${1:-5H11a}
E="${IPOD_EMU_HOME:-$HOME/ipod-emu}"
W="$E/fw-$BUILD"
OUT="$E/images/$BUILD"
BOOTROM="$E/images/5F138/bootrom" # bootrom S5L8720 (release n72ap_v1 de qemu-ios)
case $BUILD in
5F138) NAND_VERSION=1 ;; # 2.1.1 : driver NAND au format 1
*) NAND_VERSION=2 ;; # 2.2.x : iBoot 385.49 exige le format 2
esac
mkdir -p "$W/enc" "$W/dec" "$OUT" "$E/ipsw"
info=$(curl -fsS "https://api.ipsw.me/v4/ipsw/iPod2,1/$BUILD")
url=$(python3 -c 'import json,sys; print(json.load(sys.stdin)["url"])' <<<"$info")
ipsw="$E/ipsw/$(basename "$url")"
[ -f "$ipsw" ] || { echo "Téléchargement de $url"; curl -fL -o "$ipsw" "$url"; }
curl -fsS "https://api.ipsw.me/v4/keys/ipsw/iPod2,1/$BUILD" > "$W/keys.json"
key() { python3 -c 'import json,sys; k=[k for k in json.load(open(sys.argv[1]))["keys"] if k["image"]==sys.argv[2]][0]; print(k["filename"], k["key"])' "$W/keys.json" "$1"; }
echo "== NOR"
unzip -qo "$ipsw" 'Firmware/all_flash/*' -d "$W/enc"
F=$(echo "$W"/enc/Firmware/all_flash/all_flash.n72ap.production)
nor="$E/qemu-ios-generate-nor"
rm -rf "$nor/data" && mkdir "$nor/data"
for pair in applelogo:applelogo batterylow0:batterylow0 batterylow1:batterylow1 dtree:DeviceTree \
glyphcharging:glyphcharging glyphplugin:glyphplugin iboot:iBoot llb:LLB \
needservice:needservice recoverymode:recoverymode; do
cp "$F/${pair#*:}"*.img3 "$nor/data/${pair%%:*}.img3"
done
(cd "$nor" && ./generate_nor >/dev/null && mv nor.bin "$OUT/nor.bin")
echo "== rootfs"
read -r rootfs_dmg rootfs_key < <(key RootFS)
unzip -qo "$ipsw" "$rootfs_dmg" -d "$W/enc"
"$E/dmg2img/vfdecrypt" -i "$W/enc/$rootfs_dmg" -k "$rootfs_key" -o "$W/dec/rootfs.dmg" >/dev/null
part=$("$E/dmg2img/dmg2img" -l "$W/dec/rootfs.dmg" 2>&1 | sed -n 's/^partition \([0-9]*\): .*Apple_HFS.*/\1/p' | head -1)
"$E/dmg2img/dmg2img" -p "$part" "$W/dec/rootfs.dmg" -o "$W/dec/rootfs-$BUILD.img" >/dev/null 2>&1
"$E/bin/mkbase-rootfs" "$W/dec/rootfs-$BUILD.img" "$OUT/rootfs.img"
echo "== NAND"
"$E/gen-v1/mknand" "$OUT/rootfs.img" "$OUT/nand" "$NAND_VERSION"
echo "$NAND_VERSION" > "$OUT/nand-version"
echo ",legacy-nor=off,nand-write=on" > "$OUT/machine-opts"
ln -sf "$BOOTROM" "$OUT/bootrom"
echo "Image prête : $OUT → ipod-emu start -f -W -w $BUILD"
+172
View File
@@ -0,0 +1,172 @@
#!/usr/bin/env bash
# Lance / arrête l'émulateur iPod Touch 2G (qemu-ios, N72AP).
set -euo pipefail
TOOLS_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
DEFAULT_EMU_HOME="$HOME/ipod-emu"
# Les outils peuvent être utilisés directement depuis un home de toolchain déplacé.
[ ! -d "$TOOLS_DIR/../images" ] || DEFAULT_EMU_HOME=$(cd "$TOOLS_DIR/.." && pwd)
EMU_HOME="${IPOD_EMU_HOME:-$DEFAULT_EMU_HOME}"
QEMU="${IPOD_QEMU:-$(dirname "$EMU_HOME")/qemu-ios/build/qemu-system-arm}"
QEMU_DATA="${IPOD_QEMU_DATA:-$(dirname "$(dirname "$QEMU")")/pc-bios}"
FW="${IPOD_FW:-5H11a}" # dossier $EMU_HOME/images/<FW>/ : bootrom, nor.bin, nand/ (5H11a = 2.2.1, 5F138 = 2.1.1)
RUN="$EMU_HOME/run"
VNC="${IPOD_VNC:-127.0.0.1:0}" # :0 => port 5900
usage() {
cat <<USAGE
Usage : ipod-emu start [-f] [-W] [-w FW] démarre (headless, VNC $VNC, QMP $RUN/qmp.sock)
-f repart d'une NAND vierge (sinon garde l'état de la session précédente)
-W attend que SpringBoard soit prêt à recevoir des touches
-w FW firmware à utiliser (défaut : $FW ; dispo : $(ls "$EMU_HOME/images" 2>/dev/null | tr '\n' ' '))
ipod-emu respring [-W] relance SpringBoard dans la session courante
ipod-emu reset [-W] synchronise la NAND et redémarre iOS dans le même QEMU
ipod-emu wait [SECONDES] attend SpringBoard (défaut 300 s) — n'envoyez PAS de touch avant :
le pilote tactile doit avoir terminé son démarrage
ipod-emu stop | status | log | console
Pilotage (écran, touch, boutons) : ipod-qmp --help
USAGE
exit "${1:-0}"
}
boot_log() {
local offset
offset=$(cat "$RUN/boot-log-offset" 2>/dev/null || echo 0)
[[ "$offset" =~ ^[0-9]+$ ]] || return 1
tail -c "+$((offset + 1))" "$RUN/serial.log"
}
ready() {
local n; n=$(boot_log | grep -ac "AppleMultitouchSPIUserClient::attach"); [ "${n:-0}" -ge 2 ] &&
grep -a 'SCHelper.*"EXIT"' <(boot_log) >/dev/null
}
wait_ready() {
local t=${1:-300} s=$SECONDS
# Le RTC D1759 fournit l'heure avant le démarrage des services iOS.
until ready; do
[ -n "$(pid)" ] || { echo "L'émulateur s'est arrêté (voir $RUN/qemu.log)" >&2; return 1; }
grep -a 'Fatal Exception\|MACH Reboot' <(boot_log) >/dev/null && { echo "Kernel panic / reboot (voir $RUN/serial.log)" >&2; return 1; }
[ $((SECONDS - s)) -lt "$t" ] || { echo "Timeout : SpringBoard pas prêt après ${t}s" >&2; return 1; }
sleep 2
done
sleep 3
"$(dirname "$0")/ipod-agent" unlock
echo "SpringBoard prêt et déverrouillé ($((SECONDS - s)) s)"
}
pid() { [ -f "$RUN/qemu.pid" ] && kill -0 "$(cat "$RUN/qemu.pid")" 2>/dev/null && cat "$RUN/qemu.pid"; }
stop_netd() {
local netd_pid
netd_pid=$(cat "$RUN/netd.pid" 2>/dev/null || true)
if [ -n "$netd_pid" ] && [ -r "/proc/$netd_pid/comm" ] &&
[ "$(cat "/proc/$netd_pid/comm")" = "ipod-netd" ]; then
kill "$netd_pid" 2>/dev/null || true
fi
rm -f "$RUN/netd.pid"
}
cmd=${1:-}; shift || true
case $cmd in
start)
fresh=0 waitr=0
while getopts "fWw:" o; do case $o in f) fresh=1 ;; W) waitr=1 ;; w) FW=$OPTARG ;; *) usage 1 ;; esac; done
img="$EMU_HOME/images/$FW"
[ -d "$img" ] || { echo "Firmware inconnu : $img" >&2; exit 1; }
if [ -n "$(pid)" ]; then
echo "Déjà lancé (pid $(pid))"
[ $waitr = 0 ] || wait_ready
exit 0
fi
[ -x "$QEMU" ] || { echo "QEMU introuvable : $QEMU (définir IPOD_QEMU)" >&2; exit 1; }
[ -r "$img/bootrom" ] || { echo "BootROM introuvable : $img/bootrom (vérifier les liens après déplacement du home)" >&2; exit 1; }
[ -x "$EMU_HOME/netd/ipod-netd" ] || { echo "Relais réseau introuvable : $EMU_HOME/netd/ipod-netd" >&2; exit 1; }
"$QEMU" --version >/dev/null
qemu_data_args=()
[ ! -d "$QEMU_DATA/keymaps" ] || qemu_data_args=(-L "$QEMU_DATA")
mkdir -p "$RUN"
if [ $fresh = 1 ] || [ ! -d "$RUN/nand" ] || [ "$(cat "$RUN/fw" 2>/dev/null)" != "$FW" ]; then
rm -rf "$RUN/nand"; cp -rL "$img/nand" "$RUN/nand"; echo "$FW" > "$RUN/fw"
fi
stop_netd
rm -f "$RUN/qmp.sock" "$RUN/serial.log"
printf '0\n' > "$RUN/boot-log-offset.tmp"
mv "$RUN/boot-log-offset.tmp" "$RUN/boot-log-offset"
mopts=$(cat "$img/machine-opts" 2>/dev/null || true) # ex. ",legacy-nor=off"
if [[ "$mopts" == *",nand-write=on"* ]] &&
[ "$(cat "$RUN/nand/.ipod-nand-format" 2>/dev/null || true)" != "vsvfl-production-v1" ]; then
echo "NAND incompatible avec les écritures : reconstruire l'image avec ipod-mkimage / ipod-build-fw, puis démarrer avec -f." >&2
exit 1
fi
nohup setsid "$QEMU" -M "iPod-Touch,bootrom=$img/bootrom,nand=$RUN/nand,nor=$img/nor.bin$mopts" \
"${qemu_data_args[@]}" -cpu max -m 2G -serial "file:$RUN/serial.log" -serial "unix:$RUN/uart1.sock,server=on,wait=off" \
-display none -vnc "$VNC" -qmp "unix:$RUN/qmp.sock,server,nowait" \
-pidfile "$RUN/qemu.pid" ${IPOD_QEMU_EXTRA:-} > "$RUN/qemu.log" 2>&1 &
qemu_pid=$!
for _ in $(seq 50); do
if ! kill -0 "$qemu_pid" 2>/dev/null; then
echo "Échec du démarrage de QEMU :" >&2
cat "$RUN/qemu.log" >&2
exit 1
fi
[ ! -S "$RUN/qmp.sock" ] || [ -z "$(pid)" ] || break
sleep 0.2
done
if [ ! -S "$RUN/qmp.sock" ] || [ -z "$(pid)" ]; then
kill "$qemu_pid" 2>/dev/null || true
echo "QEMU n'a pas ouvert son socket QMP (voir $RUN/qemu.log)" >&2
exit 1
fi
# réseau : PPP sur l'UART1 -> slirp (NAT, DNS, 127.0.0.1:7788 -> agent de l'iPod)
stop_netd
nohup setsid "$EMU_HOME/netd/ipod-netd" -s "$RUN/uart1.sock" ${IPOD_NETD_FWD:-} > "$RUN/netd.log" 2>&1 &
netd_pid=$!
echo "$netd_pid" > "$RUN/netd.pid"
sleep 0.3
if ! kill -0 "$netd_pid" 2>/dev/null; then
echo "Échec du relais réseau :" >&2
cat "$RUN/netd.log" >&2
"$(dirname "$0")/ipod-qmp" -s "$RUN/qmp.sock" quit 2>/dev/null || kill "$qemu_pid"
stop_netd
exit 1
fi
echo "Démarré ($FW) — pid $(pid), VNC $VNC. SpringBoard apparaît en ~1 min."
echo "Logs iOS : $RUN/serial.log"
[ $waitr = 0 ] || wait_ready
;;
respring|reset)
waitr=0
while getopts "W" o; do case $o in W) waitr=1 ;; *) usage 1 ;; esac; done
shift $((OPTIND - 1))
[ "$#" = 0 ] || usage 1
pid >/dev/null || { echo "L'émulateur n'est pas lancé" >&2; exit 1; }
timeout 15 "$TOOLS_DIR/ipod-agent" sync
offset=$(stat -c %s "$RUN/serial.log")
printf '%s\n' "$offset" > "$RUN/boot-log-offset.tmp"
mv "$RUN/boot-log-offset.tmp" "$RUN/boot-log-offset"
if [ "$cmd" = reset ]; then
"$TOOLS_DIR/ipod-qmp" -s "$RUN/qmp.sock" reset
echo "Reset demandé ; QEMU et NAND conservés"
else
timeout 15 "$TOOLS_DIR/ipod-agent" respring
fi
[ "$waitr" = 0 ] || wait_ready
;;
wait) wait_ready "${1:-300}" ;;
stop)
p=$(pid) || { stop_netd; echo "Pas lancé"; exit 0; }
"$(dirname "$0")/ipod-qmp" -s "$RUN/qmp.sock" quit 2>/dev/null || kill "$p"
for _ in $(seq 50); do kill -0 "$p" 2>/dev/null || break; sleep 0.2; done
kill -0 "$p" 2>/dev/null && kill -9 "$p"
stop_netd
echo "Arrêté"
;;
status)
if p=$(pid); then echo "En marche (pid $p, firmware $(cat "$RUN/fw"), VNC $VNC)"; else echo "Arrêté"; exit 1; fi
;;
log) tail -f "$RUN/serial.log" ;;
console) tail -f "$RUN/qemu.log" ;;
-h|--help|help) usage ;;
*) usage 1 ;;
esac
+162
View File
@@ -0,0 +1,162 @@
#!/usr/bin/env python3
"""Construit une image NAND pour l'émulateur iPod Touch 2G avec nos apps / paquets dedans.
ipod-mkimage [-b BASE] [-o NOM] fichier.app|fichier.ipa|fichier.deb|dossier/ [...]
-b BASE firmware de base (défaut : 5H11a = iPhone OS 2.2.1 ; 5F138 = 2.1.1) — utilise ~/ipod-emu/images/BASE/rootfs.img
-o NOM nom de l'image produite (défaut : BASE-apps) — ensuite : ipod-emu start -f -w NOM
Les .app et .ipa sont installés dans /Applications (apps système : pas besoin d'installd,
la signature ldid suffit), les .deb sont décompressés à la racine comme dpkg le ferait, un dossier est copié tel quel
à la racine (arborescence « overlay » : ses binaires Mach-O sont signés avec ldid).
"""
import argparse, io, lzma, gzip, bz2, os, re, shutil, subprocess, sys, tarfile, tempfile, zipfile
EMU = os.environ.get("IPOD_EMU_HOME", os.path.expanduser("~/ipod-emu"))
HFSPLUS = os.path.join(EMU, "xpwn/b/hfs/hfsplus")
MKNAND = os.path.join(EMU, "gen-v1/mknand")
MACHO = (b"\xce\xfa\xed\xfe", b"\xca\xfe\xba\xbe")
def hfs(img, *args, check=True):
r = subprocess.run([HFSPLUS, img, *args], capture_output=True, text=True)
if check and r.returncode:
sys.exit(f"hfsplus {' '.join(args)} : {r.stderr or r.stdout}")
return r.stdout
def exists(img, path):
return "No such file" not in hfs(img, "ls", path, check=False) and hfs(img, "ls", path, check=False).strip() != ""
def mkdirs(img, path):
cur = ""
for part in path.strip("/").split("/"):
cur += "/" + part
if not exists(img, cur):
hfs(img, "mkdir", cur)
def add_tree(img, src, dest):
"""Copie récursive src -> dest dans l'image, en gardant les bits d'exécution."""
mkdirs(img, dest)
for root, dirs, files in os.walk(src):
rel = os.path.relpath(root, src)
tgt = dest if rel == "." else f"{dest}/{rel}"
for d in dirs:
p = os.path.join(root, d)
if os.path.islink(p):
continue
hfs(img, "mkdir", f"{tgt}/{d}", check=False)
for f in files:
p = os.path.join(root, f)
if os.path.islink(p):
print(f" (lien symbolique ignoré : {p})")
continue
hfs(img, "add", p, f"{tgt}/{f}")
with open(p, "rb") as fh:
macho = fh.read(4) in MACHO
if macho or os.stat(p).st_mode & 0o111:
hfs(img, "chmod", "755", f"{tgt}/{f}")
def sign(tree):
for root, _, files in os.walk(tree):
for f in files:
p = os.path.join(root, f)
if os.path.islink(p):
continue
with open(p, "rb") as fh:
if fh.read(4) not in MACHO:
continue
# re-signe en gardant les entitlements déjà présents (ldid -S seul les efface)
ents = subprocess.run(["ldid", "-e", p], capture_output=True).stdout
if ents.strip():
with tempfile.NamedTemporaryFile(suffix=".plist", delete=False) as t:
t.write(ents)
subprocess.run(["ldid", "-S" + t.name, p], check=True)
os.unlink(t.name)
else:
subprocess.run(["ldid", "-S", p], check=True)
def deb_data(path, out):
with open(path, "rb") as f:
assert f.read(8) == b"!<arch>\n", f"{path} : pas un .deb"
while hdr := f.read(60):
name, size = hdr[:16].decode().strip().rstrip("/"), int(hdr[48:58])
data = f.read(size)
f.read(size % 2)
if name.startswith("data.tar"):
opener = {".gz": gzip.decompress, ".bz2": bz2.decompress, ".xz": lzma.decompress, ".lzma": lzma.decompress}
ext = os.path.splitext(name)[1]
raw = opener.get(ext, lambda x: x)(data)
tarfile.open(fileobj=io.BytesIO(raw)).extractall(out, filter="fully_trusted")
return
sys.exit(f"{path} : pas de data.tar")
def main():
p = argparse.ArgumentParser(usage=__doc__)
p.add_argument("-b", "--base", default="5H11a")
p.add_argument("-o", "--out")
p.add_argument("items", nargs="+")
a = p.parse_args()
out = a.out or f"{a.base}-apps"
base_dir = os.path.join(EMU, "images", a.base)
base_img = os.path.join(base_dir, "rootfs.img")
if not os.path.exists(base_img):
sys.exit(f"Pas de {base_img}")
out_dir = os.path.join(EMU, "images", out)
os.makedirs(out_dir, exist_ok=True)
for f in ("bootrom", "nor.bin", "nand-version"):
src, dst = os.path.join(base_dir, f), os.path.join(out_dir, f)
if os.path.exists(src) and not os.path.lexists(dst):
os.symlink(os.path.realpath(src), dst)
with tempfile.TemporaryDirectory() as tmp:
img = os.path.join(out_dir, "rootfs.img")
shutil.copyfile(base_img, img)
for item in a.items:
item = os.path.abspath(item.rstrip("/"))
print(f"+ {os.path.basename(item)}")
stage = tempfile.mkdtemp(dir=tmp)
if item.endswith(".app") and os.path.isdir(item):
shutil.copytree(item, os.path.join(stage, os.path.basename(item)), symlinks=True)
sign(stage)
add_tree(img, os.path.join(stage, os.path.basename(item)), f"/Applications/{os.path.basename(item)}")
elif item.endswith(".ipa"):
zipfile.ZipFile(item).extractall(stage)
apps = [d for d in os.listdir(os.path.join(stage, "Payload")) if d.endswith(".app")]
for app in apps:
src = os.path.join(stage, "Payload", app)
sign(src)
add_tree(img, src, f"/Applications/{app}")
elif os.path.isdir(item):
shutil.copytree(item, os.path.join(stage, "root"), symlinks=True)
sign(os.path.join(stage, "root"))
add_tree(img, os.path.join(stage, "root"), "/")
elif item.endswith(".deb"):
deb_data(item, stage)
add_tree(img, stage, "/")
else:
sys.exit(f"Type non géré : {item}")
print(hfs(img, "ls", "/Applications").splitlines()[-1])
try:
version = open(os.path.join(base_dir, "nand-version")).read().strip()
except FileNotFoundError:
version = "1"
subprocess.run([MKNAND, img, os.path.join(out_dir, "nand"), version], check=True)
opts_path = os.path.join(base_dir, "machine-opts")
opts = open(opts_path).read().strip() if os.path.exists(opts_path) else ""
opts = re.sub(r",nand-write=(?:on|off)", "", opts) + ",nand-write=on"
out_opts = os.path.join(out_dir, "machine-opts")
if os.path.islink(out_opts):
os.unlink(out_opts)
with open(out_opts, "w") as f:
f.write(opts + "\n")
print(f"Image prête : {out_dir}\n ipod-emu start -f -w {out}")
if __name__ == "__main__":
main()
+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""Pilote l'émulateur iPod Touch 2G (qemu-ios) via son socket QMP.
ipod-qmp screenshot [sortie.png] capture l'écran (320x480, PNG ou PPM)
ipod-qmp tap X Y [DURÉE] touche l'écran (coordonnées 320x480, appui 0.3 s par défaut)
ipod-qmp swipe X1 Y1 X2 Y2 glisse (ex. déverrouiller : swipe 40 430 280 430)
ipod-qmp home | power appuie sur Home / Power
ipod-qmp status état de la VM
ipod-qmp hmp COMMANDE commande du moniteur QEMU (ex. "info registers", "x/8i $pc")
ipod-qmp quit arrête l'émulateur
ipod-qmp reset reset matériel brut (synchroniser la NAND avec ipod-agent sync avant)
Socket : -s SOCK, sinon $IPOD_QMP, sinon ~/ipod-emu/run/qmp.sock
"""
import argparse, json, os, socket, subprocess, sys, tempfile, time
W, H = 320, 480
class QMP:
def __init__(self, path):
self.s = socket.socket(socket.AF_UNIX)
self.s.connect(path)
self.f = self.s.makefile("rw")
json.loads(self.f.readline()) # greeting
self.cmd("qmp_capabilities")
def cmd(self, name, **args):
msg = {"execute": name}
if args:
msg["arguments"] = args
self.f.write(json.dumps(msg) + "\n")
self.f.flush()
while True:
line = self.f.readline()
if not line:
return None
r = json.loads(line)
if "event" in r:
continue
if "error" in r:
sys.exit(f"QMP {name}: {r['error']['desc']}")
return r.get("return")
def pos(x, y):
return [{"type": "abs", "data": {"axis": "x", "value": int(x * 0x7fff / (W - 1))}},
{"type": "abs", "data": {"axis": "y", "value": int(y * 0x7fff / (H - 1))}}]
def btn(down):
return [{"type": "btn", "data": {"button": "left", "down": down}}]
def key(q, qcode):
for down in (True, False):
q.cmd("input-send-event", events=[{"type": "key", "data": {"down": down, "key": {"type": "qcode", "data": qcode}}}])
time.sleep(0.2)
def main():
p = argparse.ArgumentParser(usage=__doc__)
tools_home = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
default_home = tools_home if os.path.isdir(os.path.join(tools_home, "images")) else os.path.expanduser("~/ipod-emu")
emu_home = os.environ.get("IPOD_EMU_HOME", default_home)
p.add_argument("-s", "--sock", default=os.environ.get("IPOD_QMP", os.path.join(emu_home, "run", "qmp.sock")))
p.add_argument("action")
p.add_argument("args", nargs="*")
a = p.parse_args()
q = QMP(a.sock)
if a.action == "screenshot":
out = os.path.abspath(a.args[0] if a.args else time.strftime("ipod-%Y%m%d-%H%M%S.png"))
if out.endswith(".ppm"):
q.cmd("screendump", filename=out)
else:
fd, tmp = tempfile.mkstemp(suffix=".ppm")
os.close(fd)
q.cmd("screendump", filename=tmp)
subprocess.run(["magick", tmp, out], check=True)
os.unlink(tmp)
print(out)
elif a.action == "tap":
x, y = map(float, a.args[:2])
hold = float(a.args[2]) if len(a.args) > 2 else 0.3
q.cmd("input-send-event", events=pos(x, y))
time.sleep(0.1)
q.cmd("input-send-event", events=btn(True))
time.sleep(hold)
q.cmd("input-send-event", events=btn(False))
elif a.action == "swipe":
x1, y1, x2, y2 = map(float, a.args)
q.cmd("input-send-event", events=pos(x1, y1))
q.cmd("input-send-event", events=btn(True))
for i in range(1, 16):
t = i / 15
q.cmd("input-send-event", events=pos(x1 + (x2 - x1) * t, y1 + (y2 - y1) * t))
time.sleep(0.03)
q.cmd("input-send-event", events=btn(False))
elif a.action == "home":
key(q, "h")
elif a.action == "power":
key(q, "p")
elif a.action == "status":
print(q.cmd("query-status"))
elif a.action == "hmp":
print(q.cmd("human-monitor-command", **{"command-line": " ".join(a.args)}))
elif a.action == "quit":
q.cmd("quit")
elif a.action == "reset":
q.cmd("system_reset")
else:
sys.exit(__doc__)
if __name__ == "__main__":
main()
+147
View File
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
"""Teste une application dans une NAND indépendante et conserve les diagnostics."""
import argparse
import json
import os
from pathlib import Path
import plistlib
import shutil
import socket
import subprocess
import tempfile
import time
import zipfile
def bundle_id(package):
if package.is_dir() and package.suffix == '.app':
with (package / 'Info.plist').open('rb') as f:
return plistlib.load(f)['CFBundleIdentifier']
if package.suffix == '.ipa':
with zipfile.ZipFile(package) as z:
plists = [n for n in z.namelist() if n.startswith('Payload/') and
n.endswith('.app/Info.plist') and n.count('/') == 2]
if len(plists) != 1:
raise ValueError('IPA ambiguë : préciser --bundle-id')
return plistlib.loads(z.read(plists[0]))['CFBundleIdentifier']
raise ValueError('Préciser --bundle-id pour un paquet .deb ou un overlay')
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('package', type=Path, help='.app, .ipa, .deb ou overlay')
p.add_argument('--bundle-id')
p.add_argument('--base', default=os.environ.get('IPOD_TEST_BASE', '5H11a-agent-v12'))
p.add_argument('--output', type=Path, help='nouveau dossier de résultats (doit être absent)')
p.add_argument('--settle', type=float, default=3, help='attente après apparition au premier plan')
args = p.parse_args()
package = args.package.resolve()
tools = Path(__file__).resolve().parent
default_home = tools.parent if (tools.parent / 'images').is_dir() else Path.home() / 'ipod-emu'
home = Path(os.environ.get('IPOD_EMU_HOME', default_home)).resolve()
try:
if not package.exists():
raise ValueError('Application introuvable')
identifier = args.bundle_id or bundle_id(package)
if not isinstance(identifier, str) or not identifier or any(c in identifier for c in '\t\r\n'):
raise ValueError('Bundle-id invalide')
if Path(args.base).name != args.base or args.base in ('.', '..'):
raise ValueError('Nom de firmware invalide')
if args.settle < 0:
raise ValueError('--settle doit être positif')
base = home / 'images' / args.base
if not (base / 'rootfs.img').is_file():
raise ValueError(f'Image de base introuvable : {base}')
# Les ports sont partagés par les sessions : ne jamais arrêter une VM tierce.
vnc = os.environ.get('IPOD_VNC', '127.0.0.1:0')
host, display = vnc.rsplit(':', 1)
for address, port in [(os.environ.get('IPOD_AGENT_HOST', '127.0.0.1'),
int(os.environ.get('IPOD_AGENT_PORT', '7788'))),
(host or '127.0.0.1', 5900 + int(display))]:
try:
connection = socket.create_connection((address, port), timeout=1)
except ConnectionRefusedError:
continue
else:
connection.close()
raise ValueError(f'Port {port} occupé : arrêter votre session avant ce test')
if args.output:
result = args.output.resolve()
result.mkdir(parents=True, exist_ok=False)
else:
parent = home / 'work' / 'tests'
parent.mkdir(parents=True, exist_ok=True)
result = Path(tempfile.mkdtemp(prefix=time.strftime('%Y%m%d-%H%M%S-'), dir=parent))
except (OSError, ValueError, KeyError, plistlib.InvalidFileException, zipfile.BadZipFile) as e:
p.exit(1, f'{e}\n')
print(f'Diagnostics : {result}', flush=True)
session = result / 'session'
(session / 'images').mkdir(parents=True)
(session / 'images' / args.base).symlink_to(base, target_is_directory=True)
for dependency in ('xpwn', 'gen-v1', 'netd'):
(session / dependency).symlink_to(home / dependency, target_is_directory=True)
env = dict(os.environ, IPOD_EMU_HOME=str(session),
IPOD_QEMU=os.environ.get('IPOD_QEMU', str(home.parent / 'qemu-ios/build/qemu-system-arm')))
# Un socket de session explicite ne doit pas viser la VM de l'utilisateur.
env.pop('IPOD_QMP', None)
image_name = 'test-app' if args.base != 'test-app' else 'test-app-result'
started = False
report = {'package': str(package), 'bundle_id': identifier, 'base': args.base, 'ok': False}
with (result / 'workflow.log').open('w') as workflow:
def run(tool, *argv, capture=False, timeout=360):
r = subprocess.run([str(tools / tool), *map(str, argv)], env=env,
stdout=subprocess.PIPE if capture else workflow,
stderr=workflow, text=True, timeout=timeout)
if capture:
workflow.write(r.stdout)
workflow.flush()
if r.returncode:
raise RuntimeError(f'{tool} {argv[0] if argv else ""} : code {r.returncode}')
return r.stdout if capture else None
try:
run('ipod-mkimage', '-b', args.base, '-o', image_name, package, timeout=900)
started = True # nettoie également un démarrage partiel
run('ipod-emu', 'start', '-w', image_name, '-W')
run('ipod-agent', 'launch', identifier, '--log', '/private/var/mobile/ipod-test-app.log')
deadline = time.monotonic() + 30
while run('ipod-agent', 'front', capture=True, timeout=20).strip() != identifier:
if time.monotonic() >= deadline:
raise RuntimeError('Application absente du premier plan après 30 s')
time.sleep(1)
time.sleep(args.settle)
front = run('ipod-agent', 'front', capture=True, timeout=20).strip()
report['front'] = front
if front != identifier:
raise RuntimeError('Application quittée pendant la période de stabilisation')
report['ok'] = True
except (OSError, RuntimeError, subprocess.TimeoutExpired) as e:
report['error'] = str(e)
finally:
if started:
for tool, argv in [('ipod-agent', ['get', '/private/var/mobile/ipod-test-app.log', result / 'app.log']),
('ipod-qmp', ['screenshot', result / 'screen.png'])]:
try:
run(tool, *argv, timeout=30)
except (OSError, RuntimeError, subprocess.TimeoutExpired) as e:
report.setdefault('diagnostic_errors', []).append(str(e))
try:
run('ipod-agent', 'sync', timeout=15)
except (OSError, RuntimeError, subprocess.TimeoutExpired):
pass
try:
run('ipod-emu', 'stop', timeout=30)
except (OSError, RuntimeError, subprocess.TimeoutExpired) as e:
report['ok'] = False
report['stop_error'] = str(e)
if report.get('diagnostic_errors'):
report['ok'] = False
(result / 'result.json').write_text(json.dumps(report, indent=2, ensure_ascii=False) + '\n')
print('Test réussi' if report['ok'] else 'Test échoué : consulter workflow.log et result.json')
return 0 if report['ok'] else 1
if __name__ == '__main__':
raise SystemExit(main())
+102
View File
@@ -0,0 +1,102 @@
#!/usr/bin/env python3
"""Prépare le rootfs d'un firmware stock pour l'émulateur (mêmes modifs que l'image 5F138 de devos50).
mkbase-rootfs ROOTFS_STOCK.img SORTIE.img [--size-mb 700]
- ne garde que les LaunchDaemons nécessaires à SpringBoard (les autres attendent du matériel absent)
- SpringBoard sans accélération MBX 2D (LK_ENABLE_MBX2D=0), lockbot sans redirection vers /dev/null
- une seule partition, montée en écriture (pas de /private/var séparé)
- enregistrements d'activation Lockdown (sinon écran « Connectez à iTunes »)
- verrouillage automatique désactivé (le SoC émulé ne sait pas sortir de veille)
- emuagent (réseau PPP + pilotage, ~/ipod-emu/agent/overlay, à construire avec make) et mDNSResponder (DNS)
"""
import argparse, os, plistlib, shutil, subprocess, sys, tempfile
from importlib.machinery import SourceFileLoader
EMU = os.environ.get("IPOD_EMU_HOME", os.path.expanduser("~/ipod-emu"))
mk = SourceFileLoader("mk", os.path.join(os.path.dirname(os.path.realpath(__file__)), "ipod-mkimage")).load_module()
hfs = mk.hfs
KEEP = {
"com.apple.ReportCrash.DirectoryService.plist", "com.apple.ReportCrash.Jetsam.plist",
"com.apple.ReportCrash.SafetyNet.plist", "com.apple.ReportCrash.SimulateCrash.plist",
"com.apple.ReportCrash.plist", "com.apple.SCHelper-embedded.plist", "com.apple.SpringBoard.plist",
"com.apple.configd.plist", "com.apple.mobile.lockbot.plist", "com.apple.mobile.lockdown.plist",
"com.apple.notifyd.plist",
}
LD = "/System/Library/LaunchDaemons"
AGENT = os.path.join(EMU, "agent/overlay")
LOCKDOWN = os.path.join(EMU, "assets/Lockdown") # enregistrements d'activation (extraits de la NAND 5F138 de devos50)
def edit_plist(img, path, fn, tmp):
data = subprocess.run([mk.HFSPLUS, img, "cat", path], capture_output=True, check=True).stdout
p = plistlib.loads(data)
fn(p)
out = os.path.join(tmp, os.path.basename(path))
with open(out, "wb") as f:
plistlib.dump(p, f, fmt=plistlib.FMT_BINARY)
hfs(img, "rm", path)
hfs(img, "add", out, path)
def main():
a = argparse.ArgumentParser(usage=__doc__)
a.add_argument("src"); a.add_argument("dst"); a.add_argument("--size-mb", type=int, default=700)
a = a.parse_args()
shutil.copyfile(a.src, a.dst)
img = a.dst
with tempfile.TemporaryDirectory() as tmp:
for line in hfs(img, "ls", LD).splitlines():
name = line.split()[-1] if line.startswith("1") else None
if name and name.endswith(".plist") and name not in KEEP:
hfs(img, "rm", f"{LD}/{name}")
# grow juste après les suppressions : il lui faut un peu de place pour agrandir le bitmap d'allocation (le
# rootfs stock est plein), et les fichiers ajoutés ensuite sont alloués d'un bloc dans l'espace neuf
out = hfs(img, "grow", str(a.size_mb * 1024 * 1024))
if "grew volume" not in out:
sys.exit(f"grow : {out}")
edit_plist(img, f"{LD}/com.apple.SpringBoard.plist",
lambda p: p.setdefault("EnvironmentVariables", {}).update({"LK_ENABLE_MBX2D": "0"}), tmp)
edit_plist(img, f"{LD}/com.apple.mobile.lockbot.plist",
lambda p: [p.pop(k, None) for k in ("StandardErrorPath", "StandardOutPath")], tmp)
fstab = os.path.join(tmp, "fstab")
open(fstab, "w").write("/dev/disk0s1 / hfs rw 0 1\n")
hfs(img, "rm", "/private/etc/fstab")
hfs(img, "add", fstab, "/private/etc/fstab")
mk.add_tree(img, LOCKDOWN, "/private/var/root/Library/Lockdown")
sb = os.path.join(tmp, "com.apple.springboard.plist")
with open(sb, "wb") as f:
# pas de verrouillage auto, pas d'alerte « Edit Home Screen » au premier démarrage
plistlib.dump({"SBAutoLockTime": -1, "SBAutoDimTime": -1, "SBDidShowReorderText": True}, f, fmt=plistlib.FMT_BINARY)
prefs = "/private/var/mobile/Library/Preferences"
mk.mkdirs(img, prefs)
hfs(img, "add", sb, f"{prefs}/com.apple.springboard.plist")
# iPod d'un utilisateur français : langue, région, fuseau (localtime est un lien symbolique, que xpwn ne sait
# pas créer : on y copie le fichier de zone)
gp = os.path.join(tmp, ".GlobalPreferences.plist")
g = plistlib.loads(subprocess.run([mk.HFSPLUS, img, "cat", f"{prefs}/.GlobalPreferences.plist"], capture_output=True).stdout)
langs = [l for l in g.get("AppleLanguages", []) if l != "fr"]
g["AppleLanguages"] = ["fr"] + langs
g["AppleLocale"] = "fr_FR"
with open(gp, "wb") as f:
plistlib.dump(g, f, fmt=plistlib.FMT_BINARY)
hfs(img, "rm", f"{prefs}/.GlobalPreferences.plist")
hfs(img, "add", gp, f"{prefs}/.GlobalPreferences.plist")
tz = os.path.join(tmp, "localtime")
with open(tz, "wb") as f:
f.write(subprocess.run([mk.HFSPLUS, img, "cat", "/usr/share/zoneinfo/Europe/Paris"], capture_output=True, check=True).stdout)
hfs(img, "rm", "/private/var/db/timezone/localtime")
hfs(img, "add", tz, "/private/var/db/timezone/localtime")
if not os.path.isdir(AGENT):
sys.exit(f"{AGENT} absent : lancer make dans {os.path.dirname(AGENT)}")
mk.add_tree(img, AGENT, "/")
print(hfs(img, "ls", LD).splitlines()[-1])
if __name__ == "__main__":
main()
+25
View File
@@ -0,0 +1,25 @@
#!/usr/bin/env python3
"""Extrait l'image HFS+ d'une NAND produite par l'ancien qemu-ios-generate-nand (<= 10f542f, 2023)."""
import struct, sys
nand, out = sys.argv[1], sys.argv[2]
PPB, PPSB, CS, BANKS, PAGE = 128, 1024, 4, 8, 4096
def lpn2ppn(lpn):
vpn = (lpn // PPSB + 1) * PPSB + lpn % PPSB
bank, vbn = vpn % BANKS, vpn // PPSB
tpn = vbn * PPB
cpn = (tpn & (PPB - 1)) | (PPB if (bank // CS) & 1 else 0) | ((tpn & ~(PPB - 1)) << 1)
return bank % CS, (cpn // PPB) * PPB + (vpn % PPSB) // BANKS
def page(lpn):
cs, ppn = lpn2ppn(lpn)
try:
return open(f'{nand}/cs{cs}/{ppn}.page', 'rb').read()[:PAGE]
except FileNotFoundError:
return bytes(PAGE)
first = page(3)
sig, ver, attr, lmv, jib, cdate, mdate, bdate, chk, files, folders, bsize, total = struct.unpack('>2sHI4sIIIIIIIII', first[1024:1024+48])
assert sig in (b'H+', b'HX'), sig
n = bsize * total // PAGE
print(f'{sig.decode()} blocksize={bsize} blocks={total} -> {n} pages', file=sys.stderr)
with open(out, 'wb') as f:
for i in range(n):
f.write(page(3 + i))
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
# lance qemu-system-arm sous gdb et affiche la backtrace en cas de crash (IPOD_QEMU=.../qemu-gdb ipod-emu start)
exec gdb -q -batch -ex 'handle SIGUSR1 SIGUSR2 SIGPIPE nostop noprint' -ex run -ex 'bt 15' -ex 'info registers pc' --args "$HOME/qemu-ios/build/qemu-system-arm" "$@"
+85
View File
@@ -0,0 +1,85 @@
#ifndef FTL_H
#define FTL_H
#include "wmr.h"
#include <stdint.h>
#define FTL_CXT_SECTION_SIZE 3
#define FTL_SPARE_TYPE_CXT_INDEX 0x43
#define FREE_SECTION_SIZE 20
#define FREE_SECTION_START FTL_CXT_SECTION_SIZE
#define FREE_LIST_SIZE 3
#define FTL_READ_REFRESH_LIST_SIZE 5
#define BYTES_PER_SECTOR 512
#define LOG_SECTION_SIZE (FREE_SECTION_SIZE - FREE_LIST_SIZE)
#define MAX_NUM_OF_MAP_TABLES (WMR_MAX_VB / (WMR_SECTORS_PER_PAGE_MIN * WMR_SECTOR_SIZE) + (WMR_MAX_VB % (WMR_SECTORS_PER_PAGE_MIN * WMR_SECTOR_SIZE) ? 1 : 0)) * (sizeof(uint16_t))
#define MAX_NUM_OF_EC_TABLES (WMR_MAX_VB / (WMR_SECTORS_PER_PAGE_MIN * WMR_SECTOR_SIZE) + (WMR_MAX_VB % (WMR_SECTORS_PER_PAGE_MIN * WMR_SECTOR_SIZE) ? 1 : 0)) * (sizeof(uint32_t))
#define MAX_NUM_OF_LOGCXT_MAPS (((LOG_SECTION_SIZE * WMR_MAX_PAGES_PER_BLOCK * WMR_NUM_OF_BANKS * sizeof(uint16_t)) / (WMR_SECTOR_SIZE * WMR_SECTORS_PER_PAGE_MIN)) + (((LOG_SECTION_SIZE * WMR_MAX_PAGES_PER_BLOCK * WMR_NUM_OF_BANKS * sizeof(uint16_t)) % (WMR_SECTOR_SIZE * WMR_SECTORS_PER_PAGE_MIN)) ? 1 : 0))
#define FTL_CXT_SECTION_START 201
typedef struct __attribute__((__packed__))
{
uint32_t dwLogAge; /* log age - uses a global counter starting from 0 */
uint16_t wVbn; /* the virtual block number of log block */
uint16_t wLbn; /* the logical block number of log block */
uint32_t paPOffsetL2P; /* L2P page offset mapping table *//* size - PAGES_PER_SUBLK * sizeof(UInt16) functionality - maps pages of a logical block inside the block */
uint16_t wFreePOffset; /* free page offset in log block *//* the next physical page to write to */
uint16_t wNumOfValidLP; /* the number of valid page *//* the number of valid pages in the log - stay the same when rewriting a page */
uint32_t boolCopyMerge; /* can be copymerged or not *//* ??? */
/* name sure this structure is aligned 16-bit */
} LOGCxt;
typedef struct
{
uint16_t wLbn;
uint16_t wVbn;
} FTLReadRefreshStruct;
typedef struct
{
uint32_t dwAge; /* Cxt Write Age - Counter starting From 0xFFFFFFFF going down */
uint32_t dwWriteAge; /* counter starting from 0 - unique age of the first ftl write operation to the block */
uint16_t wNumOfFreeVb; /* number of free VB */
uint16_t wFreeVbListTail; /* marks the first available VB in a cyclic list */
uint16_t wWearLevelCounter; /* this counter is by the FTL to decide whether an Autowearlevel operation is needed after FTL_Write is done */
uint16_t awFreeVbList[FREE_SECTION_SIZE]; /* cyclic list of the free VBs */
uint32_t adwMapTablePtrs[MAX_NUM_OF_MAP_TABLES]; /* page address (Vpn) of the Map table pages in the Cxt block - only valid when boolFlashCxtIsValid is TRUE32 */
uint32_t adwECTablePtrs[MAX_NUM_OF_EC_TABLES]; /* page address of the Erase Counter table */
uint32_t adwLOGCxtMapPtrs[MAX_NUM_OF_LOGCXT_MAPS]; /* page address of the LOGCxt map table */
uint32_t pawMapTable; /* cached map table logical blocks to virtual blocks - value will be recalculated in FTL_Init */
uint32_t pawECCacheTable; /* cached Erase counter table - value will be recalculated in FTL_Init - data is recovered from the last valid Erase Map in case of power failure */
uint32_t pawLOGCxtMapTable; /* pointer to the map of the logs - this is a pointer and will be calculated in the Init - data can be restored if the info is flushed */
LOGCxt aLOGCxtTable[LOG_SECTION_SIZE + 1]; /* LOGCxt array */
uint32_t dwMetaWearLevelCounter; /* used to decide whether the index info super blocks need to be replaced or not (slows down VFL Cxt blocks wear) */
uint16_t wOverErasedBlock; /* should not be used - mark the last erased vb before setting boolFlushECTable */
uint16_t awMapCxtVbn[FTL_CXT_SECTION_SIZE]; /* vb address of the FTL Cxt information */
uint32_t dwCurrMapCxtPage; /* pointer to the last written Cxt info page */
uint32_t boolFlashCxtIsValid; /* mark whether the FTLCxt on the flash is up to date or not */
// this code was added Apr 4th 2007
uint32_t adwRCTablePtrs[MAX_NUM_OF_EC_TABLES]; /* page address of the Read Counter table */
uint32_t pawRCCacheTable; /* cached Erase counter table - value will be recalculated in FTL_Init - data is recovered from the last valid Erase Map in case of power failure */
FTLReadRefreshStruct aFTLReadRefreshList[FTL_READ_REFRESH_LIST_SIZE];
uint32_t dwRefreshListIdx;
uint32_t dwReadsSinceLastRefreshMark;
// this code was added Apr 20th 2007
uint32_t adwStatPtrs[2]; // allocate 2 pages for stats
} FTLCxt2;
typedef struct
{
FTLCxt2 stFTLCxt;
uint8_t abReserved[((BYTES_PER_SECTOR - 2) * sizeof(uint32_t)) - sizeof(FTLCxt2)];
uint32_t dwVersion;
uint32_t dwVersionNot;
} FTLMeta;
#endif
+377
View File
@@ -0,0 +1,377 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stddef.h>
#include "vfl.h"
#include "mbr.h"
#include "gpt.h"
#define BYTES_PER_PAGE 4096
#define BYTES_PER_SPARE 64
#define PAGES_PER_BLOCK 128
#define VFL_CTX_PHYSICAL_PAGE PAGES_PER_BLOCK * 1
#define PAGES_PER_SUBLOCK 1024
#define CS_TOTAL 4
#define NAND_SIG_PAGE 524160
#define BBT_PAGE 524161
#define FTL_CTX_VBLK_IND 0 // virtual block index of the FTL Context
#define NUM_PARTITIONS 1
#define BOOT_PARTITION_FIRST_PAGE (NUM_PARTITIONS + 2) // first two LBAs are for MBR and GUID header
static uint32_t crc32_table[256];
static int crc32_table_computed = 0;
/*
CRC32 logic
*/
static void make_crc32_table(void)
{
uint32_t c;
int n, k;
for (n = 0; n < 256; n++) {
c = (uint32_t) n;
for (k = 0; k < 8; k++) {
if (c & 1)
c = 0xedb88320L ^ (c >> 1);
else
c = c >> 1;
}
crc32_table[n] = c;
}
crc32_table_computed = 1;
}
uint32_t update_crc32(uint32_t crc, const uint8_t *buf,
int len)
{
uint32_t c = crc;
int n;
if (!crc32_table_computed)
make_crc32_table();
for (n = 0; n < len; n++) {
c = crc32_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
}
return c;
}
uint32_t crc32(const uint8_t *buf, int len)
{
return update_crc32(0xffffffffL, buf, len) ^ 0xffffffffL;
}
uint8_t *get_valid_ftl_spare() {
uint32_t *spare = (uint32_t *)calloc(BYTES_PER_SPARE, sizeof(char));
spare[2] = 0x00FF00FF;
return (uint8_t *)spare;
}
void _Helper_ConvertP2C_OneBitReorder(uint32_t dwBank, uint32_t dwPpn, uint32_t* pdwCE, uint32_t* pdwCpn, uint32_t dwReorderMask)
{
const uint32_t dwBelowReorderMask = dwReorderMask - 1; // Assumption: dwReorderMask is a power of 2!
const uint32_t dwAboveReorderMask = ~dwBelowReorderMask;
// insert reorder bit back in correct position of "chip" page number by extracting from MSB of "physical" bank number
*pdwCpn = ((dwPpn & dwBelowReorderMask) |
(((dwBank / CS_TOTAL) & 0x1) ? dwReorderMask : 0) |
((dwPpn & dwAboveReorderMask) << 1));
// strip reorder bit from MSB of "physical" bank number to produce "chip" CE
*pdwCE = dwBank % CS_TOTAL;
}
void _pfnConvertP2C_TwoPlaneLSB(uint32_t dwBank, uint32_t dwPpn, uint32_t* pdwCE, uint32_t* pdwCpn)
{
_Helper_ConvertP2C_OneBitReorder(dwBank, dwPpn, pdwCE, pdwCpn, PAGES_PER_BLOCK);
}
void _ConvertT2P_Default(uint16_t wBank, uint16_t wTbn, uint16_t *pwPbn)
{
uint32_t dwCpn, dwCS;
_pfnConvertP2C_TwoPlaneLSB((uint32_t)wBank, (uint32_t)(wTbn * PAGES_PER_BLOCK), &dwCS, &dwCpn);
*pwPbn = (uint16_t)(dwCpn / PAGES_PER_BLOCK);
}
void _Vpn2Ppn(uint32_t dwVpn, uint16_t *pwCS, uint32_t *pdwPpn) {
uint16_t wPbn, wPOffset;
uint16_t wBank = dwVpn % WMR_NUM_OF_BANKS;
uint16_t wVbn = dwVpn / PAGES_PER_SUBLOCK;
_ConvertT2P_Default((wBank & 0xffff), wVbn, &wPbn);
*pwCS = wBank % CS_TOTAL;
wPOffset = (uint16_t)((dwVpn % PAGES_PER_SUBLOCK) / WMR_NUM_OF_BANKS);
*pdwPpn = wPbn * PAGES_PER_BLOCK + wPOffset;
}
void _Lpn2Ppn(uint32_t dwLpn, uint16_t *pwCS, uint32_t *pdwPpn) {
uint32_t dwLbn = dwLpn / PAGES_PER_SUBLOCK;
uint16_t wLPOffset = (uint16_t)(dwLpn - dwLbn * PAGES_PER_SUBLOCK);
uint32_t dwVbn = dwLbn + 1;
uint32_t dwVpn = dwVbn * PAGES_PER_SUBLOCK + wLPOffset;
_Vpn2Ppn(dwVpn, pwCS, pdwPpn);
}
void write_page(uint8_t *page, uint8_t *spare, int cs, int page_index) {
char filename[100];
sprintf(filename, "nand/cs%d", cs);
struct stat st = {0};
if (stat(filename, &st) == -1) {
mkdir(filename, 0700);
}
sprintf(filename, "nand/cs%d/%d.page", cs, page_index);
FILE *f = fopen(filename, "wb");
if(!page) {
page = (uint8_t *)calloc(BYTES_PER_PAGE, sizeof(char));
}
fwrite(page, sizeof(char), BYTES_PER_PAGE, f);
if(!spare) {
spare = (uint8_t *)calloc(BYTES_PER_SPARE, sizeof(char));
}
fwrite(spare, sizeof(char), BYTES_PER_SPARE, f);
fclose(f);
}
void write_bbts() {
// create the bad block table on each CS
for(int cs = 0; cs < CS_TOTAL; cs++) {
uint8_t *page = calloc(BYTES_PER_PAGE, sizeof(char));
memcpy(page, "DEVICEINFOBBT\0\0\0", 16);
// set all bits in this page to 1, to indicate that all blocks are of good health.
for(int i = 16; i < BYTES_PER_PAGE; i++) {
page[i] = 0xFF;
}
write_page(page, NULL, cs, BBT_PAGE);
}
}
void write_nand_sig_page() {
// write the NAND signature page
uint8_t *page = calloc(0x100, sizeof(uint8_t));
char *magic = "NANDDRIVERSIGN";
memcpy(page, magic, strlen(magic));
page[0x34] = 0x4; // length of the info
// signature (0x4331313X): the last digit is the NAND driver format version, 1 for iPhone OS 2.1.1, 2 for 2.2.x
const char *ver = getenv("NAND_SIG_VERSION");
page[0x38] = (ver && *ver) ? ver[0] : 0x31;
page[0x39] = 0x31;
page[0x3A] = 0x31;
page[0x3B] = 0x43;
write_page(page, NULL, 0, NAND_SIG_PAGE);
}
void write_vfl_context() {
for (int wCSIdx = 0; wCSIdx < CS_TOTAL; wCSIdx++) {
// initialize VFL context block on physical block 35, page 0
VFLMeta *vfl_meta = (VFLMeta *)calloc(sizeof(VFLMeta), sizeof(char));
vfl_meta->dwVersion = VFL_META_VERSION;
VFLCxt *pVFLCxt = &vfl_meta->stVFLCxt;
// we set the number of VFL/FTL user blocks to 2048 which doesn't give any room for the BBT table. This is fine as we do not have bad blocks.
pVFLCxt->wNumOfVFLSuBlk = 2048;
pVFLCxt->wNumOfFTLSuBlk = 2048;
pVFLCxt->abVSFormtType = VFL_VENDOR_SPECIFIC_TYPE;
pVFLCxt->dwGlobalCxtAge = wCSIdx;
pVFLCxt->wCxtLocation = 1; // the VFL context is located in the first physical block
for (int wIdx = 0; wIdx < FTL_CXT_SECTION_SIZE; wIdx++)
{
pVFLCxt->awFTLCxtVbn[wIdx] = (uint16_t)(wIdx);
}
pVFLCxt->wNumOfInitBadBlk = 0;
for (int wIdx = 0, wPbn = VFL_FIRST_BLK_TO_SEARCH_CXT; wIdx < VFL_INFO_SECTION_SIZE && wPbn < VFL_LAST_BLK_TO_SEARCH_CXT; wPbn++)
{
pVFLCxt->awInfoBlk[wIdx++] = wPbn;
}
// update the bad block map
for(int i = 0; i < WMR_MAX_RESERVED_SIZE; i++) {
pVFLCxt->awBadMapTable[i] = VFL_BAD_MAP_TABLE_AVAILABLE_MARK;
}
VFLSpare *vfl_ctx_spare = (VFLSpare *)calloc(BYTES_PER_SPARE, sizeof(char));
vfl_ctx_spare->dwCxtAge = 1;
vfl_ctx_spare->bSpareType = VFL_CTX_SPARE_TYPE;
// store some copies of the VFL
for (uint8_t wPageIdx = 0; wPageIdx < VFL_NUM_OF_VFL_CXT_COPIES; wPageIdx++) {
write_page((uint8_t *)vfl_meta, (uint8_t *)vfl_ctx_spare, wCSIdx, VFL_CTX_PHYSICAL_PAGE + wPageIdx);
}
}
}
void write_ftl_context() {
uint16_t cs;
uint32_t ppn;
// set the FTL spare type of the first page of the FTL CXT block to indicate that there is a CTX index
VFLSpare *vfl_ctx_spare = (VFLSpare *)calloc(BYTES_PER_SPARE, sizeof(char));
vfl_ctx_spare->bSpareType = FTL_SPARE_TYPE_CXT_INDEX;
write_page(NULL, (uint8_t *)vfl_ctx_spare, 0, 0);
// create the FTL Meta page on the last page of the FTL Cxt block and embed the right versions
FTLMeta *ftl_meta = (FTLMeta *)calloc(sizeof(FTLMeta), sizeof(char));
ftl_meta->dwVersion = 0x46560000;
ftl_meta->dwVersionNot = -0x46560001;
// initialize the number of empty VBs for logs and the free areas
ftl_meta->stFTLCxt.wNumOfFreeVb = FREE_SECTION_SIZE;
for(int i = 0; i < FREE_SECTION_SIZE; i++) {
ftl_meta->stFTLCxt.awFreeVbList[i] = FREE_SECTION_START + i;
}
// create empty logs
for(int i = 0; i < LOG_SECTION_SIZE + 1; i++) {
ftl_meta->stFTLCxt.aLOGCxtTable[i].wVbn = 0xFFFF;
}
// prepare the logical block -> virtual block mapping tables
for(int i = 0; i < MAX_NUM_OF_MAP_TABLES; i++) {
ftl_meta->stFTLCxt.adwMapTablePtrs[i] = i + 5; // the mapping will start from the 2nd page in the FTL context block
uint16_t *mapping_page = calloc(BYTES_PER_PAGE / sizeof(uint16_t), sizeof(uint16_t));
uint32_t items_per_map = BYTES_PER_PAGE / sizeof(uint16_t);
for(int ind_in_map = 0; ind_in_map < items_per_map; ind_in_map++) {
mapping_page[ind_in_map] = (i * items_per_map) + ind_in_map + 1;
}
_Vpn2Ppn(i + 5, &cs, &ppn);
printf("Writing logical -> virtual block map page %d to physical page %d @ cs %d\n", i, ppn, cs);
write_page((uint8_t *)mapping_page, NULL, cs, ppn);
}
vfl_ctx_spare = (VFLSpare *)calloc(BYTES_PER_SPARE, sizeof(char));
vfl_ctx_spare->bSpareType = FTL_SPARE_TYPE_CXT_INDEX;
// we place the FTL Meta on the last page of the first virtual block.
_Vpn2Ppn(PAGES_PER_SUBLOCK - 1, &cs, &ppn);
printf("Writing FTL Meta to physical page %d @ cs %d\n", ppn, cs);
write_page((uint8_t *)ftl_meta, (uint8_t *)vfl_ctx_spare, cs, ppn);
}
uint32_t write_hfs_partition(char *filename, uint32_t page_offset) {
// write the HFS+ partition to the first page and update the associated spare
uint16_t cs; uint32_t ppn;
FILE *hfs_file = fopen(filename, "rb");
fseek(hfs_file, 0L, SEEK_END);
int partition_size = ftell(hfs_file);
fclose(hfs_file);
hfs_file = fopen(filename, "rb");
int lpn = page_offset;
uint8_t *spare = get_valid_ftl_spare();
uint32_t required_pages_for_partition = partition_size / BYTES_PER_PAGE;
printf("Writing HFS partition using %d pages...\n", required_pages_for_partition);
for(int i = 0; i < required_pages_for_partition; i++) {
uint8_t *page = malloc(BYTES_PER_PAGE);
fread(page, BYTES_PER_PAGE, sizeof(uint8_t), hfs_file);
_Lpn2Ppn(lpn, &cs, &ppn);
printf("Writing HFS partition to physical page %d @ cs %d\n", ppn, cs);
write_page(page, spare, cs, ppn);
lpn++;
//if(i == 2000) break;
}
fclose(hfs_file);
return required_pages_for_partition;
}
void write_mbr(int boot_partition_size) {
uint16_t cs; uint32_t ppn;
// write the MBR bytes (LBA 0)
uint8_t *mbr_page = malloc(BYTES_PER_PAGE);
struct mbr_partition *boot_partition = (struct mbr_partition *)(mbr_page + MBR_ADDRESS);
boot_partition->sysid = 0xEE;
boot_partition->startlba = BOOT_PARTITION_FIRST_PAGE;
boot_partition->size = boot_partition_size;
mbr_page[510] = 0x55;
mbr_page[511] = 0xAA;
_Lpn2Ppn(0, &cs, &ppn);
printf("Writing MBR to physical page %d @ cs %d\n", ppn, cs);
uint8_t *spare = get_valid_ftl_spare();
write_page(mbr_page, spare, cs, ppn);
}
void write_filesystem() {
uint16_t cs; uint32_t ppn;
int pages_for_boot_partition = write_hfs_partition("filesystem-it2g-readonly.img", BOOT_PARTITION_FIRST_PAGE);
printf("Required pages for boot partition: %d\n", pages_for_boot_partition);
// initialize the EFI header (LBA 1)
uint8_t *gpt_header_page = malloc(BYTES_PER_PAGE);
gpt_hdr *gpt_header = (gpt_hdr *)gpt_header_page;
// create the boot partition entry (LBA 2)
uint8_t *gpt_entry_boot_partition_page = malloc(BYTES_PER_PAGE);
gpt_ent *gpt_entry_boot_partition = (gpt_ent *)gpt_entry_boot_partition_page;
gpt_entry_boot_partition->ent_type[0] = 0x48465300;
gpt_entry_boot_partition->ent_type[1] = 0x11AA0000;
gpt_entry_boot_partition->ent_type[2] = 0x300011AA;
gpt_entry_boot_partition->ent_type[3] = 0xACEC4365;
gpt_entry_boot_partition->ent_lba_start = BOOT_PARTITION_FIRST_PAGE;
gpt_entry_boot_partition->ent_lba_end = BOOT_PARTITION_FIRST_PAGE + pages_for_boot_partition;
printf("Boot system partition located on page %lld - %lld\n", gpt_entry_boot_partition->ent_lba_start, gpt_entry_boot_partition->ent_lba_end);
_Lpn2Ppn(2, &cs, &ppn);
printf("Writing GUID boot partition entry to page %d @ cs %d\n", ppn, cs);
uint8_t *spare = get_valid_ftl_spare();
write_page(gpt_entry_boot_partition_page, spare, cs, ppn);
// finalize the GPT header
// TODO add the secondary GPT entry!
memcpy(gpt_header, GPT_HDR_SIG, 8);
gpt_header->hdr_revision = GPT_HDR_REVISION;
gpt_header->hdr_size = 0x5C; // 92 bytes
gpt_header->hdr_lba_table = 2;
gpt_header->hdr_entries = NUM_PARTITIONS;
gpt_header->hdr_entsz = 0x80;
gpt_header->hdr_crc_table = crc32(gpt_entry_boot_partition_page, sizeof(gpt_ent));
gpt_header->hdr_crc_self = crc32((uint8_t *)gpt_header, 0x5C);
_Lpn2Ppn(1, &cs, &ppn);
printf("Writing GUID header to page %d @ cs %d\n", ppn, cs);
write_page(gpt_header_page, spare, cs, ppn);
// finally, write the MBR
write_mbr(pages_for_boot_partition);
}
int main(int argc, char *argv[]) {
// create the output dir if it does not exist
struct stat st = {0};
if (stat("nand", &st) == -1) {
mkdir("nand", 0700);
}
write_vfl_context();
write_ftl_context();
write_nand_sig_page();
write_bbts();
write_filesystem();
// testing
uint32_t num = 49188;
uint16_t cs; uint32_t ppn;
_Lpn2Ppn(num, &cs, &ppn);
printf("LPN %d => %d, cs %d\n", num, ppn, cs);
}
+36
View File
@@ -0,0 +1,36 @@
#ifndef GPT_H
#define GPT_H
typedef struct gpt_hdr
{
uint8_t hdr_sig[8];
uint32_t hdr_revision;
uint32_t hdr_size;
uint32_t hdr_crc_self;
uint32_t __reserved;
uint64_t hdr_lba_self;
uint64_t hdr_lba_alt;
uint64_t hdr_lba_start;
uint64_t hdr_lba_end;
uint8_t hdr_uuid[16];
uint64_t hdr_lba_table;
uint32_t hdr_entries; // the number of partition entries
uint32_t hdr_entsz; // size of each partition entry
uint32_t hdr_crc_table;
uint32_t padding;
} gpt_hdr;
typedef struct gpt_ent
{
uint32_t ent_type[4];
uint8_t ent_uuid[16];
uint64_t ent_lba_start;
uint64_t ent_lba_end;
uint64_t ent_attr;
uint16_t ent_name[36];
} gpt_ent;
#define GPT_HDR_SIG "EFI PART"
#define GPT_HDR_REVISION 0x00010000
#endif
+19
View File
@@ -0,0 +1,19 @@
#ifndef MBR_H
#define MBR_H
#define MBR_ADDRESS 0x1be
struct mbr_partition {
uint8_t bootid;
uint8_t starthead;
uint8_t startsect;
uint8_t startcyl;
uint8_t sysid;
uint8_t endhead;
uint8_t endsect;
uint8_t endcyl;
uint32_t startlba;
uint32_t size;
} __packed;
#endif
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
# mknand <image HFS+> <dossier nand de sortie> [version] — NAND au format VSVFL/FTL de production
# (qemu-ios-generate-nand 2ee0d46, supporte les écritures). version : 1 = iPhone OS 2.1.1, 2 = 2.2.x (défaut 1)
set -euo pipefail
here=$(dirname "$(readlink -f "$0")")
rm -rf "$2"
NAND_SIG_VERSION="${3:-1}" "$here/../qemu-ios-generate-nand/generate_nand" "$(readlink -f "$1")" "$(readlink -m "$2")" >/dev/null
printf 'vsvfl-production-v1\n' > "$2/.ipod-nand-format"
+7
View File
@@ -0,0 +1,7 @@
#!/usr/bin/env bash
# mknand-v1 <image HFS+> <dossier nand de sortie> [version] — NAND au format compatible avec le FMSS actuel (lecture seule)
# version : version du format du driver NAND dans la signature (1 = iPhone OS 2.1.1, 2 = 2.2.x ; défaut 1)
set -euo pipefail
here=$(dirname "$(readlink -f "$0")"); img=$(readlink -f "$1"); out=$(readlink -m "$2"); tmp=$(mktemp -d)
cd "$tmp" && ln -s "$img" filesystem-it2g-readonly.img && NAND_SIG_VERSION="${3:-1}" "$here/generate_nand_v1" >/dev/null
rm -rf "$out" && mv nand "$out" && cd / && rm -rf "$tmp"
+74
View File
@@ -0,0 +1,74 @@
#ifndef VFL_H
#define VFL_H
#include "ftl.h"
#define VFL_CTX_SPARE_TYPE 0x80
#define VFL_INFO_SECTION_SIZE 4
#define VFL_BAD_MARK_INFO_TABLE_SIZE (WMR_MAX_VB / 8 / BAD_MARK_COMPRESS_SIZE)
#define VFL_NUM_OF_VFL_CXT_COPIES 8
#define VFL_AREA_START 0x0
#define VFL_FIRST_BLK_TO_SEARCH_CXT VFL_AREA_START
#define VFL_LAST_BLK_TO_SEARCH_CXT (VFL_AREA_START + 199)
#define AND_MAX_BANKS_PER_CS (8)
#define VFL_SCRUB_LIST_SIZE (20)
#define FTL_FORMAT_STRUCT_SIZE (16) // packed
#define BAD_MARK_COMPRESS_SIZE 8
#define VFL_BAD_MAP_TABLE_AVAILABLE_MARK 0xFFF0;
#define VFL_META_VERSION 0x00000002
#define VFL_VENDOR_SPECIFIC_TYPE 0x100014
typedef struct
{
uint32_t dwGlobalCxtAge; /* age for FTL meta information search */
uint32_t dwCxtAge; /* context age 0xFFFFFFFF --> 0x0 */
uint32_t dwFTLType; /* FTL identifier */
uint16_t wCxtLocation; /* current context block location (Physical) */
uint16_t wNextCxtPOffset; /* current context page offset information */
/* this data is used for summary */
uint16_t wNumOfInitBadBlk; /* the number of initial bad blocks - used for VFL format */
uint16_t wNumOfWriteFail; /* the number of failed write operations*/
uint16_t wNumOfEraseFail; /* the number of failed erase operations */
/* bad blocks management table & good block pointer */
uint16_t awReplacementIdx[AND_MAX_BANKS_PER_CS]; /* index to the last bad block updated in the awBadMapTable per bank
(some might be bad blocks) the array is divided to banks */
uint16_t awBadMapTable[WMR_MAX_RESERVED_SIZE]; /* remapping table of bad blocks - the UInt 16 value set here is the virtual block (vfl address space) that is being replaced */
/* bad blocks management table within VFL info area */
uint16_t awInfoBlk[VFL_INFO_SECTION_SIZE]; /* physical block addresses where FTL Cxt information is stored */
uint16_t wNumOfFTLSuBlk; /* the number of super blocks allocated for the FTL - default id to give all to FTL */
uint16_t wNumOfVFLSuBlk; /* the total number of available super blocks */
uint16_t awFTLCxtVbn[FTL_CXT_SECTION_SIZE]; /* page address (FTL virtual addressing space) of FTL Cxt */
uint16_t wScrubIdx; /* Index for the scrub list */
uint16_t awScrubList[VFL_SCRUB_LIST_SIZE]; /* scrub list */
uint8_t abFTLFormat[FTL_FORMAT_STRUCT_SIZE];
uint32_t abVSFormtType;
} __attribute__((packed)) VFLCxt;
typedef struct
{
VFLCxt stVFLCxt;
uint8_t abReserved[2048 - ((3 * sizeof(uint32_t)) + sizeof(VFLCxt))];
uint32_t dwVersion;
uint32_t dwCheckSum;
uint32_t dwXorSum;
} VFLMeta;
typedef struct
{
uint32_t dwCxtAge; /* context age 0xFFFFFFFF --> 0x0 */
uint32_t dwReserved; /* reserved */
uint8_t cStatusMark; /* status (confirm) mark - currently not used for anything */
uint8_t bSpareType; /* spare type */
/* reserved for main ECC */
} VFLSpare;
#endif
+11
View File
@@ -0,0 +1,11 @@
#ifndef WMR_H
#define WMR_H
#define WMR_MAX_RESERVED_SIZE 820
#define WMR_MAX_VB 18000
#define WMR_SECTORS_PER_PAGE_MIN 4
#define WMR_SECTOR_SIZE 512
#define WMR_MAX_PAGES_PER_BLOCK 0x100
#define WMR_NUM_OF_BANKS 8
#endif
+657
View File
@@ -0,0 +1,657 @@
#define SLIRP_DEPRECATED_OK 1
/*
* ipod-netd : réseau pour l'émulateur iPod Touch 2G, sans privilèges.
*
* Termine le lien PPP que pppd (côté iPhone OS) ouvre sur l'UART1 émulée, et passe les paquets IP à libslirp :
* NAT vers Internet, DNS (10.0.2.3), redirections de ports hôte -> iPod.
*
* ipod-netd [-s uart1.sock] [-L [addr:]hostport:guestport]... [-v]
*
* Adresses : iPod 10.0.2.15, passerelle 10.0.2.2, DNS 10.0.2.3. Défaut : -L 127.0.0.1:7788:7788 (emuagent).
*/
#include <arpa/inet.h>
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
#include <slirp/libslirp.h>
#define GUEST_IP "10.0.2.15"
#define GW_IP "10.0.2.2"
#define DNS_IP "10.0.2.3"
static const uint8_t guest_mac[6] = { 0x52, 0x54, 0x00, 0x12, 0x34, 0x56 };
static const uint8_t slirp_mac[6] = { 0x52, 0x55, 0x0a, 0x00, 0x02, 0x02 };
static int verbose;
static int uart = -1;
static const char *sock_path;
static Slirp *slirp;
static void logm(const char *fmt, ...)
{
va_list ap;
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
fprintf(stderr, "[%ld.%03ld] ", (long)ts.tv_sec % 100000, ts.tv_nsec / 1000000);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
}
/* ---------- PPP : trames HDLC (RFC 1662) ---------- */
static uint16_t fcstab[256];
static void fcs_init(void)
{
for (int b = 0; b < 256; b++) {
uint16_t v = b;
for (int i = 0; i < 8; i++) {
v = (v & 1) ? (v >> 1) ^ 0x8408 : v >> 1;
}
fcstab[b] = v;
}
}
static uint16_t fcs16(uint16_t fcs, const uint8_t *p, size_t len)
{
while (len--) {
fcs = (fcs >> 8) ^ fcstab[(fcs ^ *p++) & 0xff];
}
return fcs;
}
static void ppp_send(uint16_t proto, const uint8_t *data, size_t len)
{
static uint8_t raw[4 + 2048], out[2 * (sizeof(raw) + 2) + 2];
if (uart < 0 || len > 2048) {
return;
}
raw[0] = 0xff; raw[1] = 0x03; raw[2] = proto >> 8; raw[3] = proto & 0xff;
memcpy(raw + 4, data, len);
size_t n = 4 + len;
uint16_t fcs = fcs16(0xffff, raw, n) ^ 0xffff;
raw[n++] = fcs & 0xff;
raw[n++] = fcs >> 8;
size_t o = 0;
out[o++] = 0x7e;
for (size_t i = 0; i < n; i++) {
uint8_t c = raw[i];
if (c < 0x20 || c == 0x7e || c == 0x7d) {
out[o++] = 0x7d;
c ^= 0x20;
}
out[o++] = c;
}
out[o++] = 0x7e;
for (size_t w = 0; w < o;) {
ssize_t r = write(uart, out + w, o - w);
if (r < 0) {
if (errno == EINTR || errno == EAGAIN) {
continue;
}
return;
}
w += r;
}
}
/* ---------- LCP / IPCP ---------- */
enum { CONF_REQ = 1, CONF_ACK, CONF_NAK, CONF_REJ, TERM_REQ, TERM_ACK, CODE_REJ, PROTO_REJ, ECHO_REQ, ECHO_REP, DISC_REQ };
#define PROTO_IP 0x0021
#define PROTO_LCP 0xc021
#define PROTO_IPCP 0x8021
struct ncp {
const char *name;
uint16_t proto;
int acked_peer; /* on a acquitté la requête du pair */
int acked_ours; /* le pair a acquitté la nôtre */
uint8_t id;
time_t last_req;
};
static struct ncp lcp = { "LCP", PROTO_LCP }, ipcp = { "IPCP", PROTO_IPCP };
static uint32_t lcp_magic = 0x49504f44; /* "IPOD" */
static int is_open(struct ncp *n)
{
return n->acked_peer && n->acked_ours;
}
static void send_ctl(uint16_t proto, uint8_t code, uint8_t id, const uint8_t *opts, size_t len)
{
uint8_t pkt[1500];
pkt[0] = code; pkt[1] = id; pkt[2] = (len + 4) >> 8; pkt[3] = (len + 4) & 0xff;
memcpy(pkt + 4, opts, len);
ppp_send(proto, pkt, len + 4);
}
static void send_conf_req(struct ncp *n)
{
uint8_t opts[16];
size_t len = 0;
if (n == &ipcp) {
struct in_addr a;
inet_aton(GW_IP, &a);
opts[len++] = 3; opts[len++] = 6;
memcpy(opts + len, &a, 4); len += 4;
} else {
opts[len++] = 5; opts[len++] = 6;
uint32_t m = htonl(lcp_magic);
memcpy(opts + len, &m, 4); len += 4;
}
send_ctl(n->proto, CONF_REQ, ++n->id, opts, len);
n->last_req = time(NULL);
}
static void guest_announce(void);
static void ncp_opened(struct ncp *n)
{
logm("%s ouvert", n->name);
if (n == &lcp) {
send_conf_req(&ipcp);
} else {
logm("lien IP prêt : iPod %s, passerelle %s, DNS %s", GUEST_IP, GW_IP, DNS_IP);
guest_announce();
}
}
/* Traite une Configure-Request du pair : Ack / Nak / Rej, option par option (RFC 1661 §5.1) */
static void handle_conf_req(struct ncp *n, uint8_t id, const uint8_t *opts, size_t len)
{
uint8_t ack[1500], nak[1500], rej[1500];
size_t na = 0, nn = 0, nr = 0;
struct in_addr want_ip, want_dns;
inet_aton(GUEST_IP, &want_ip);
inet_aton(DNS_IP, &want_dns);
for (size_t i = 0; i + 2 <= len;) {
uint8_t type = opts[i], olen = opts[i + 1];
if (olen < 2 || i + olen > len) {
break;
}
const uint8_t *o = opts + i;
int reject = 0, naked = 0;
if (n == &lcp) {
switch (type) {
case 1: /* MRU */
case 2: /* ACCM : on échappe de toute façon tous les caractères de contrôle */
case 5: /* magic */
case 7: /* PFC */
case 8: /* ACFC */
break;
default: /* authentification, callback... */
reject = 1;
}
} else {
if ((type == 3 || type == 129 || type == 131) && olen == 6) {
const struct in_addr *want = type == 3 ? &want_ip : &want_dns;
if (memcmp(o + 2, want, 4)) {
memcpy(nak + nn, o, 2);
memcpy(nak + nn + 2, want, 4);
nn += 6;
naked = 1;
}
} else {
reject = 1; /* compression VJ, NBNS... */
}
}
if (reject) {
memcpy(rej + nr, o, olen); nr += olen;
} else if (!naked) {
memcpy(ack + na, o, olen); na += olen;
}
i += olen;
}
if (nr) {
send_ctl(n->proto, CONF_REJ, id, rej, nr);
} else if (nn) {
send_ctl(n->proto, CONF_NAK, id, nak, nn);
} else {
int was_open = is_open(n);
send_ctl(n->proto, CONF_ACK, id, ack, na);
n->acked_peer = 1;
if (!n->acked_ours) {
send_conf_req(n);
}
if (!was_open && is_open(n)) {
ncp_opened(n);
}
}
}
static void handle_ctl(struct ncp *n, const uint8_t *p, size_t len)
{
if (len < 4) {
return;
}
uint8_t code = p[0], id = p[1];
size_t plen = (p[2] << 8) | p[3];
if (plen < 4 || plen > len) {
return;
}
const uint8_t *data = p + 4;
size_t dlen = plen - 4;
if (verbose) {
logm("%s <- code %d id %d len %zu", n->name, code, id, dlen);
}
switch (code) {
case CONF_REQ:
if (n == &lcp && is_open(&lcp)) { /* renégociation : tout repart de zéro */
lcp.acked_ours = 0;
ipcp.acked_peer = ipcp.acked_ours = 0;
}
if (n == &ipcp && !is_open(&lcp)) {
return;
}
handle_conf_req(n, id, data, dlen);
break;
case CONF_ACK:
if (id == n->id && !n->acked_ours) {
n->acked_ours = 1;
if (is_open(n)) {
ncp_opened(n);
}
}
break;
case CONF_NAK:
case CONF_REJ:
/* nos options sont minimales : on les renvoie sans l'option refusée */
send_ctl(n->proto, CONF_REQ, ++n->id, NULL, 0);
break;
case TERM_REQ:
send_ctl(n->proto, TERM_ACK, id, NULL, 0);
logm("%s fermé par l'iPod", n->name);
n->acked_peer = n->acked_ours = 0;
if (n == &lcp) {
ipcp.acked_peer = ipcp.acked_ours = 0;
}
break;
case ECHO_REQ:
if (n == &lcp && dlen >= 4) {
uint8_t rep[1500];
uint32_t m = htonl(lcp_magic);
memcpy(rep, &m, 4);
memcpy(rep + 4, data + 4, dlen - 4);
send_ctl(PROTO_LCP, ECHO_REP, id, rep, dlen);
}
break;
default:
break;
}
}
/* ---------- IP <-> slirp (trames Ethernet fictives) ---------- */
static void log_ip(const char *dir, const uint8_t *ip, size_t len)
{
if (!verbose || len < 20) return;
char a[16], b[16];
snprintf(a, sizeof a, "%d.%d.%d.%d", ip[12], ip[13], ip[14], ip[15]);
snprintf(b, sizeof b, "%d.%d.%d.%d", ip[16], ip[17], ip[18], ip[19]);
int ihl = (ip[0] & 0xf) * 4, proto = ip[9];
if (proto == 1 && len > (size_t)ihl + 1) logm("%s ICMP %s -> %s type %d code %d", dir, a, b, ip[ihl], ip[ihl + 1]);
else if ((proto == 6 || proto == 17) && len >= (size_t)ihl + 4)
logm("%s %s %s:%d -> %s:%d len %zu", dir, proto == 6 ? "TCP" : "UDP", a, (ip[ihl] << 8) | ip[ihl + 1], b, (ip[ihl + 2] << 8) | ip[ihl + 3], len);
else logm("%s proto %d %s -> %s", dir, proto, a, b);
}
static void slirp_ip_input(const uint8_t *ip, size_t len)
{
log_ip("iPod ->", ip, len);
uint8_t frame[14 + 2048];
if (len > 2048) {
return;
}
memcpy(frame, slirp_mac, 6);
memcpy(frame + 6, guest_mac, 6);
frame[12] = 0x08; frame[13] = 0x00;
memcpy(frame + 14, ip, len);
slirp_input(slirp, frame, len + 14);
}
static void arp_packet(uint16_t op, const uint8_t *dst_mac, const uint8_t *target_ip)
{
uint8_t f[42];
struct in_addr gip;
inet_aton(GUEST_IP, &gip);
memcpy(f, dst_mac, 6);
memcpy(f + 6, guest_mac, 6);
f[12] = 0x08; f[13] = 0x06;
f[14] = 0; f[15] = 1; f[16] = 8; f[17] = 0; f[18] = 6; f[19] = 4;
f[20] = 0; f[21] = op;
memcpy(f + 22, guest_mac, 6);
memcpy(f + 28, &gip, 4);
memcpy(f + 32, op == 2 ? dst_mac : (const uint8_t *)"\0\0\0\0\0\0", 6);
memcpy(f + 38, target_ip, 4);
slirp_input(slirp, f, sizeof f);
}
/* ARP gratuit : slirp apprend l'adresse MAC de l'iPod */
static void guest_announce(void)
{
static const uint8_t bcast[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
struct in_addr gw;
inet_aton(GW_IP, &gw);
arp_packet(1, bcast, (const uint8_t *)&gw);
}
static slirp_ssize_t slirp_send(const void *buf, size_t len, void *opaque)
{
const uint8_t *f = buf;
if (len < 14) {
return len;
}
uint16_t type = (f[12] << 8) | f[13];
if (type == 0x0806 && len >= 42 && f[21] == 1) {
struct in_addr gip;
inet_aton(GUEST_IP, &gip);
if (!memcmp(f + 38, &gip, 4)) {
arp_packet(2, f + 22, f + 28);
}
} else if (type == 0x0800 && is_open(&ipcp)) {
log_ip("-> iPod", f + 14, len - 14);
ppp_send(PROTO_IP, f + 14, len - 14);
}
return len;
}
/* ---------- réception PPP ---------- */
static void ppp_frame(uint8_t *p, size_t len)
{
if (len < 4 || fcs16(0xffff, p, len) != 0xf0b8) {
if (verbose && len) {
logm("trame invalide (%zu octets)", len);
}
return;
}
len -= 2;
if (len >= 2 && p[0] == 0xff && p[1] == 0x03) {
p += 2; len -= 2;
}
if (!len) {
return;
}
uint16_t proto;
if (p[0] & 1) {
proto = p[0]; p += 1; len -= 1;
} else {
if (len < 2) {
return;
}
proto = (p[0] << 8) | p[1]; p += 2; len -= 2;
}
switch (proto) {
case PROTO_LCP:
handle_ctl(&lcp, p, len);
break;
case PROTO_IPCP:
if (is_open(&lcp)) {
handle_ctl(&ipcp, p, len);
}
break;
case PROTO_IP:
if (is_open(&ipcp)) {
slirp_ip_input(p, len);
}
break;
default:
if (is_open(&lcp)) { /* IPV6CP, CCP... : Protocol-Reject */
uint8_t rej[1500];
size_t n = len > 1400 ? 1400 : len;
rej[0] = proto >> 8; rej[1] = proto & 0xff;
memcpy(rej + 2, p, n);
send_ctl(PROTO_LCP, PROTO_REJ, ++lcp.id, rej, n + 2);
}
}
}
static void uart_input(const uint8_t *buf, size_t n)
{
static uint8_t frame[4096];
static size_t flen;
static int esc;
for (size_t i = 0; i < n; i++) {
uint8_t c = buf[i];
if (c == 0x7e) {
ppp_frame(frame, flen);
flen = 0; esc = 0;
} else if (c == 0x7d) {
esc = 1;
} else {
if (esc) {
c ^= 0x20; esc = 0;
}
if (flen < sizeof frame) {
frame[flen++] = c;
}
}
}
}
/* ---------- boucle principale, timers slirp ---------- */
struct timer { SlirpTimerCb cb; void *cb_opaque; SlirpTimerId id; int by_id; int64_t expire; int used; };
static struct timer timers[16];
static int64_t now_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1000000000LL + ts.tv_nsec;
}
static int64_t cb_clock(void *o) { return now_ns(); }
static void cb_guest_error(const char *msg, void *o) { logm("slirp : %s", msg); }
static void cb_notify(void *o) {}
static void cb_register_poll_fd(int fd, void *o) {} /* on repasse tous les sockets à poll() à chaque tour */
static void cb_unregister_poll_fd(int fd, void *o) {}
static struct timer *timer_alloc(void)
{
for (int i = 0; i < 16; i++) {
if (!timers[i].used) {
memset(&timers[i], 0, sizeof timers[i]);
timers[i].used = 1;
timers[i].expire = -1;
return &timers[i];
}
}
abort();
}
static void *cb_timer_new(SlirpTimerCb cb, void *cb_opaque, void *o)
{
struct timer *t = timer_alloc();
t->cb = cb; t->cb_opaque = cb_opaque;
return t;
}
static void *cb_timer_new_opaque(SlirpTimerId id, void *cb_opaque, void *o)
{
struct timer *t = timer_alloc();
t->id = id; t->by_id = 1; t->cb_opaque = cb_opaque;
return t;
}
static void cb_timer_free(void *t, void *o) { ((struct timer *)t)->used = 0; }
static void cb_timer_mod(void *t, int64_t expire_ms, void *o) { ((struct timer *)t)->expire = expire_ms; }
static struct pollfd pfds[1024];
static int npfds;
static int add_poll(slirp_os_socket fd, int events, void *o)
{
short ev = 0;
if (events & SLIRP_POLL_IN) ev |= POLLIN;
if (events & SLIRP_POLL_OUT) ev |= POLLOUT;
if (events & SLIRP_POLL_PRI) ev |= POLLPRI;
pfds[npfds].fd = fd;
pfds[npfds].events = ev;
pfds[npfds].revents = 0;
return npfds++;
}
static int get_revents(int idx, void *o)
{
short r = pfds[idx].revents;
int ev = 0;
if (r & POLLIN) ev |= SLIRP_POLL_IN;
if (r & POLLOUT) ev |= SLIRP_POLL_OUT;
if (r & POLLPRI) ev |= SLIRP_POLL_PRI;
if (r & POLLERR) ev |= SLIRP_POLL_ERR;
if (r & POLLHUP) ev |= SLIRP_POLL_HUP;
return ev;
}
static int uart_connect(void)
{
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un a = { .sun_family = AF_UNIX };
strncpy(a.sun_path, sock_path, sizeof a.sun_path - 1);
if (connect(fd, (struct sockaddr *)&a, sizeof a) < 0) {
close(fd);
return -1;
}
return fd;
}
static void add_fwd(const char *spec)
{
char buf[128], *parts[3];
int n = 0;
strncpy(buf, spec, sizeof buf - 1);
buf[sizeof buf - 1] = 0;
for (char *t = strtok(buf, ":"); t && n < 3; t = strtok(NULL, ":")) {
parts[n++] = t;
}
struct in_addr host, guest;
inet_aton("127.0.0.1", &host);
inet_aton(GUEST_IP, &guest);
int hp, gp;
if (n == 3) {
inet_aton(parts[0], &host);
hp = atoi(parts[1]); gp = atoi(parts[2]);
} else if (n == 2) {
hp = atoi(parts[0]); gp = atoi(parts[1]);
} else {
fprintf(stderr, "redirection invalide : %s\n", spec);
exit(1);
}
if (slirp_add_hostfwd(slirp, 0, host, hp, guest, gp) < 0) {
logm("redirection %s impossible (port occupé ?)", spec);
/* Ne pas laisser le client contacter le relais d'une autre session. */
exit(1);
} else {
logm("redirection tcp %s:%d -> iPod:%d", inet_ntoa(host), hp, gp);
}
}
int main(int argc, char **argv)
{
const char *fwds[32];
int nfwd = 0;
static char default_sock[512];
snprintf(default_sock, sizeof default_sock, "%s/ipod-emu/run/uart1.sock", getenv("HOME"));
sock_path = default_sock;
for (int i = 1; i < argc; i++) {
if (!strcmp(argv[i], "-s") && i + 1 < argc) sock_path = argv[++i];
else if (!strcmp(argv[i], "-L") && i + 1 < argc && nfwd < 32) fwds[nfwd++] = argv[++i];
else if (!strcmp(argv[i], "-v")) verbose = 1;
else { fprintf(stderr, "usage: %s [-s uart1.sock] [-L [addr:]hostport:guestport]... [-v]\n", argv[0]); return 1; }
}
if (!nfwd) fwds[nfwd++] = "127.0.0.1:7788:7788";
signal(SIGPIPE, SIG_IGN);
fcs_init();
SlirpConfig cfg = { 0 };
cfg.version = 4;
cfg.in_enabled = true;
inet_aton("10.0.2.0", &cfg.vnetwork);
inet_aton("255.255.255.0", &cfg.vnetmask);
inet_aton(GW_IP, &cfg.vhost);
inet_aton(DNS_IP, &cfg.vnameserver);
inet_aton(GUEST_IP, &cfg.vdhcp_start);
cfg.vhostname = "ipod-emu-host";
cfg.if_mtu = 1500;
cfg.if_mru = 1500;
static const SlirpCb cb = {
.send_packet = slirp_send, .guest_error = cb_guest_error, .clock_get_ns = cb_clock,
.timer_new = cb_timer_new, .timer_free = cb_timer_free, .timer_mod = cb_timer_mod,
.notify = cb_notify, .timer_new_opaque = cb_timer_new_opaque,
.register_poll_fd = cb_register_poll_fd, .unregister_poll_fd = cb_unregister_poll_fd,
};
slirp = slirp_new(&cfg, &cb, NULL);
for (int i = 0; i < nfwd; i++) add_fwd(fwds[i]);
for (;;) {
if (uart < 0) {
uart = uart_connect();
if (uart < 0) {
sleep(1);
continue;
}
logm("connecté à %s, en attente de pppd", sock_path);
lcp.acked_peer = lcp.acked_ours = ipcp.acked_peer = ipcp.acked_ours = 0;
}
uint32_t timeout = 1000;
npfds = 0;
int uidx = add_poll(uart, SLIRP_POLL_IN, NULL);
slirp_pollfds_fill_socket(slirp, &timeout, add_poll, NULL);
int64_t now_ms = now_ns() / 1000000;
for (int i = 0; i < 16; i++) {
if (timers[i].used && timers[i].expire >= 0) {
int64_t d = timers[i].expire - now_ms;
if (d < 0) d = 0;
if (d < timeout) timeout = d;
}
}
int r = poll(pfds, npfds, timeout);
slirp_pollfds_poll(slirp, r < 0, get_revents, NULL);
now_ms = now_ns() / 1000000;
for (int i = 0; i < 16; i++) {
struct timer *t = &timers[i];
if (t->used && t->expire >= 0 && t->expire <= now_ms) {
t->expire = -1;
if (t->by_id) slirp_handle_timer(slirp, t->id, t->cb_opaque);
else t->cb(t->cb_opaque);
}
}
if (r > 0 && (pfds[uidx].revents & (POLLIN | POLLHUP | POLLERR))) {
uint8_t buf[4096];
ssize_t n = read(uart, buf, sizeof buf);
if (n <= 0) {
logm("UART déconnectée (émulateur arrêté ?)");
close(uart);
uart = -1;
continue;
}
uart_input(buf, n);
}
/* relance des Configure-Request non acquittées */
time_t t = time(NULL);
if (is_open(&lcp) && !ipcp.acked_ours && t - ipcp.last_req >= 2) send_conf_req(&ipcp);
if (lcp.acked_peer && !lcp.acked_ours && t - lcp.last_req >= 2) send_conf_req(&lcp);
}
}
@@ -0,0 +1,9 @@
diff --git a/generate_nand.c b/generate_nand.c
index 8fd3837..4ba5c12 100644
--- a/generate_nand.c
+++ b/generate_nand.c
@@ -212 +212,3 @@ static void write_nand_sig_page(void) {
- uint32_t signature = 0x43313131;
+ // the low byte is the NAND driver format version: '1' for iPhone OS 2.1.1, '2' for 2.2.x (NAND_SIG_VERSION)
+ const char *ver = getenv("NAND_SIG_VERSION");
+ uint32_t signature = 0x43313100 | (uint8_t)((ver && *ver) ? ver[0] : '1');
+8
View File
@@ -0,0 +1,8 @@
diff --git a/hfs/hfslib.c b/hfs/hfslib.c
index 2b0274b..78aa3bc 100644
--- a/hfs/hfslib.c
+++ b/hfs/hfslib.c
@@ -225,0 +226,3 @@ void grow_hfs(Volume* volume, uint64_t newSize) {
+ /* allocate new files in the new, contiguous free space: the free blocks left in a full image are scattered and
+ files spread over them need extents overflow records */
+ volume->volumeHeader->nextAllocation = volume->volumeHeader->totalBlocks;
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""Page HTTP compatible Safari mobile 3 pour valider saisie et défilement.
Lancer sur l'hôte avec --output DOSSIER ; ouvrir l'URL 10.0.2.2 affichée dans
Safari invité. Le port et les requêtes reçues sont enregistrés dans ce dossier.
Arrêter avec Ctrl-C après le test. Aucun accès Internet n'est nécessaire.
"""
import argparse
from datetime import datetime, timezone
from html import escape
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from pathlib import Path
from urllib.parse import parse_qs, urlparse
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
args.output.mkdir(parents=True, exist_ok=True)
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
with (args.output / 'requests.jsonl').open('a', encoding='utf-8') as log:
log.write(json.dumps({'utc': datetime.now(timezone.utc).isoformat(),
'path': self.path}, ensure_ascii=False) + '\n')
url = urlparse(self.path)
if url.path == '/submit':
content = 'Recu : ' + escape(parse_qs(url.query).get('texte', [''])[0])
elif url.path == '/scroll':
content = '<h1>Debut</h1>' + ''.join(
'<p style="height:60px">Ligne %02d</p>' % i for i in range(24))
content += '<a href="/fin">Fin du defilement</a>'
elif url.path == '/fin':
content = '<h1>Defilement OK</h1>'
else:
content = ('<h1>Validation HTTP</h1><form action="/submit" method="get">'
'<input type="text" name="texte"><input type="submit" value="Envoyer">'
'</form><p><a href="/scroll">Test de defilement</a></p>')
body = ('<html><head><meta name="viewport" content="width=device-width">'
'<title>Test iPhone OS</title></head><body>' + content + '</body></html>').encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(body)))
self.end_headers()
self.wfile.write(body)
with HTTPServer(('127.0.0.1', 0), Handler) as server:
(args.output / 'port').write_text(str(server.server_port) + '\n', encoding='utf-8')
print(f'URL depuis l’iPod : http://10.0.2.2:{server.server_port}/', flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
main()
+41
View File
@@ -0,0 +1,41 @@
#!/usr/bin/env python3
"""Compile et exécute les régressions LCD, MIPI et sortie TV avec ASan/UBSan sur un build QEMU existant."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--build', type=Path)
a = p.parse_args()
root = Path(__file__).resolve().parents[3]
build = (a.build or root / 'build').resolve()
source = Path(__file__).with_name('test-display.c')
commands = json.loads((build / 'compile_commands.json').read_text())
c = next(c for c in commands if c['file'].endswith('ipod_touch_lcd.c'))
old_root = str(Path(c['directory']).parent)
args = shlex.split(c['command'].replace(old_root, str(root)))
obj = str(build / 'test-ipod-display.o')
args[args.index('-c') + 1] = str(source)
args[args.index('-o') + 1] = obj
args[args.index('-MF') + 1] = obj + '.d'
args += ['-fsanitize=address,undefined', '-fno-omit-frame-pointer']
subprocess.run(args, cwd=build, check=True)
links = json.loads(subprocess.check_output(
['ninja', '-C', str(build), '-t', 'compdb', '-x', 'c_LINKER_RSP', 'c_LINKER'], text=True))
link = next(c for c in links if c.get('output') == 'qemu-system-arm')
args = shlex.split(link['command'].replace(old_root, str(root)))
args = [x for x in args if x not in (
'qemu-system-arm.p/system_main.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_lcd.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_mipi_dsi.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_tvout.c.o')]
out = str(build / 'test-ipod-display')
args[args.index('-o') + 1] = out
args += [obj, '-fsanitize=address,undefined']
subprocess.run(args, cwd=build, check=True)
# QEMU conserve volontairement ses registres de types et sa boucle globale à la sortie.
env = dict(os.environ, ASAN_OPTIONS='detect_leaks=0', UBSAN_OPTIONS='halt_on_error=1')
subprocess.run([out], env=env, check=True)
+42
View File
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""Compile et exécute les régressions tactiles avec ASan/UBSan sur un build QEMU existant."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--build', type=Path)
a = p.parse_args()
root = Path(__file__).resolve().parents[3]
build = (a.build or root / 'build').resolve()
source = Path(__file__).with_name('test-multitouch.c')
commands = json.loads((build / 'compile_commands.json').read_text())
c = next(c for c in commands if c['file'].endswith('ipod_touch_multitouch.c'))
old_root = str(Path(c['directory']).parent)
args = shlex.split(c['command'].replace(old_root, str(root)))
obj = str(build / 'test-ipod-multitouch.o')
args[args.index('-c') + 1] = str(source)
args[args.index('-o') + 1] = obj
args[args.index('-MF') + 1] = obj + '.d'
args += ['-fsanitize=address,undefined', '-fno-omit-frame-pointer']
subprocess.run(args, cwd=build, check=True)
links = json.loads(subprocess.check_output(
['ninja', '-C', str(build), '-t', 'compdb', '-x', 'c_LINKER_RSP', 'c_LINKER'], text=True))
link = next(c for c in links if c.get('output') == 'qemu-system-arm')
args = shlex.split(link['command'].replace(old_root, str(root)))
args = [x for x in args if x not in (
'qemu-system-arm.p/system_main.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_multitouch.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_gpio.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_sysic.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_spi.c.o')]
out = str(build / 'test-ipod-multitouch')
args[args.index('-o') + 1] = out
args += [obj, '-fsanitize=address,undefined']
subprocess.run(args, cwd=build, check=True)
# QEMU conserve volontairement ses registres de types et sa boucle globale à la sortie.
env = dict(os.environ, ASAN_OPTIONS='detect_leaks=0', UBSAN_OPTIONS='halt_on_error=1')
subprocess.run([out], env=env, check=True)
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Compile et exécute les régressions RTC avec ASan/UBSan sur un build QEMU existant."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--build', type=Path)
a = p.parse_args()
root = Path(__file__).resolve().parents[3]
build = (a.build or root / 'build').resolve()
source = Path(__file__).with_name('test-rtc.c')
commands = json.loads((build / 'compile_commands.json').read_text())
c = next(c for c in commands if c['file'].endswith('ipod_touch_pcf50633_pmu.c'))
old_root = str(Path(c['directory']).parent)
args = shlex.split(c['command'].replace(old_root, str(root)))
obj = str(build / 'test-ipod-rtc.o')
args[args.index('-c') + 1] = str(source)
args[args.index('-o') + 1] = obj
args[args.index('-MF') + 1] = obj + '.d'
args += ['-fsanitize=address,undefined', '-fno-omit-frame-pointer']
subprocess.run(args, cwd=build, check=True)
links = json.loads(subprocess.check_output(
['ninja', '-C', str(build), '-t', 'compdb', '-x', 'c_LINKER_RSP', 'c_LINKER'], text=True))
link = next(c for c in links if c.get('output') == 'qemu-system-arm')
args = shlex.split(link['command'].replace(old_root, str(root)))
args = [x for x in args if x not in (
'qemu-system-arm.p/system_main.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_pcf50633_pmu.c.o')]
out = str(build / 'test-ipod-rtc')
args[args.index('-o') + 1] = out
args += [obj, '-fsanitize=address,undefined']
subprocess.run(args, cwd=build, check=True)
# QEMU conserve volontairement ses registres de types et sa boucle globale à la sortie.
env = dict(os.environ, ASAN_OPTIONS='detect_leaks=0', UBSAN_OPTIONS='halt_on_error=1')
subprocess.run([out], env=env, check=True)
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Compile et exécute les régressions UART avec ASan/UBSan sur un build QEMU existant."""
import argparse
import json
import os
from pathlib import Path
import shlex
import subprocess
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--build', type=Path)
a = p.parse_args()
root = Path(__file__).resolve().parents[3]
build = (a.build or root / 'build').resolve()
source = Path(__file__).with_name('test-uart.c')
commands = json.loads((build / 'compile_commands.json').read_text())
c = next(c for c in commands if c['file'].endswith('ipod_touch_uart.c'))
old_root = str(Path(c['directory']).parent)
args = shlex.split(c['command'].replace(old_root, str(root)))
obj = str(build / 'test-ipod-uart.o')
args[args.index('-c') + 1] = str(source)
args[args.index('-o') + 1] = obj
args[args.index('-MF') + 1] = obj + '.d'
args += ['-fsanitize=address,undefined', '-fno-omit-frame-pointer']
subprocess.run(args, cwd=build, check=True)
links = json.loads(subprocess.check_output(
['ninja', '-C', str(build), '-t', 'compdb', '-x', 'c_LINKER_RSP', 'c_LINKER'], text=True))
link = next(c for c in links if c.get('output') == 'qemu-system-arm')
args = shlex.split(link['command'].replace(old_root, str(root)))
args = [x for x in args if x not in (
'qemu-system-arm.p/system_main.c.o',
'libqemu-arm-softmmu.fa.p/hw_arm_ipod_touch_uart.c.o')]
out = str(build / 'test-ipod-uart')
args[args.index('-o') + 1] = out
args += [obj, '-fsanitize=address,undefined']
subprocess.run(args, cwd=build, check=True)
# QEMU conserve volontairement ses registres de types et sa boucle globale à la sortie.
env = dict(os.environ, ASAN_OPTIONS='detect_leaks=0', UBSAN_OPTIONS='halt_on_error=1')
subprocess.run([out], env=env, check=True)
@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""Vérifie le reset des périphériques d’affichage de la machine, CPU arrêté et NAND en lecture seule."""
import argparse
import json
from pathlib import Path
import socket
import subprocess
import tempfile
import time
def main():
parser = argparse.ArgumentParser(description=__doc__)
root = Path(__file__).resolve().parents[3]
parser.add_argument('--qemu', type=Path, default=root / 'build/qemu-system-arm')
parser.add_argument('--firmware', type=Path, required=True, help='dossier avec bootrom, nor.bin et nand/')
args = parser.parse_args()
fw = args.firmware.resolve()
with tempfile.TemporaryDirectory(prefix='ipod-reset-') as directory:
directory = Path(directory)
paths = [directory / name for name in ['qmp.sock', 'qtest.sock']]
with (directory / 'qemu.log').open('w+') as log:
proc = subprocess.Popen([
str(args.qemu.resolve()), '-M',
f'iPod-Touch,bootrom={fw}/bootrom,nor={fw}/nor.bin,nand={fw}/nand,legacy-nor=off,nand-write=off',
'-cpu', 'max', '-m', '2G', '-S', '-display', 'none', '-serial', 'null', '-serial', 'null',
'-qmp', f'unix:{paths[0]},server=on,wait=off',
'-qtest', f'unix:{paths[1]},server=on,wait=off'], stdout=log, stderr=log)
connections = []
try:
deadline = time.monotonic() + 10
while not all(p.exists() for p in paths):
if proc.poll() is not None or time.monotonic() >= deadline:
log.seek(0)
raise RuntimeError(log.read())
time.sleep(.02)
for path in paths:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.settimeout(5)
sock.connect(str(path))
connections.append((sock, sock.makefile('rwb')))
qmp, test = [f for _, f in connections]
json.loads(qmp.readline())
def command(name):
qmp.write((json.dumps({'execute': name}) + '\n').encode())
qmp.flush()
while True:
r = json.loads(qmp.readline())
if 'error' in r:
raise RuntimeError(r['error'])
if 'return' in r:
return r['return']
def access(line):
test.write((line + '\n').encode())
test.flush()
r = test.readline().decode().strip()
assert r.startswith('OK'), r
return int(r.split()[1], 0) if len(r.split()) > 1 else None
command('qmp_capabilities')
# Registres d'affichage de la machine réelle : le reset doit atteindre MIPI.
regs = [0x38900004, 0x38900008, 0x38900024, 0x3d800008,
0x39100004, 0x39200004, 0x39300000, 0x39300284]
rom = access('readl 0')
for cycle in range(3):
for address in regs:
access(f'writel {address:#x} 0x1234')
assert access(f'readl {address:#x}') == 0x1234, hex(address)
# Abandonner une lecture au milieu de la réponse d'identification de la dalle.
assert access('readl 0x3d80003c') == 0x31a
command('system_reset')
for address in regs:
assert access(f'readl {address:#x}') == 0, hex(address)
assert access('readl 0x3d80003c') == 0x31a
assert access('readl 0x3d80003c') == 0x00a1d13c
assert access('readl 0') == rom
print('Trois resets d’affichage : registres effacés, réponse MIPI réinitialisée, BootROM conservée.')
command('quit')
proc.wait(timeout=5)
finally:
for sock, stream in connections:
stream.close()
sock.close()
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=5)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
if __name__ == '__main__':
main()
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
"""Relances natives dans une session de test déjà démarrée (firmware non distribué)."""
import argparse
import http.server
import json
import os
from pathlib import Path
import runpy
import subprocess
import threading
import time
import uuid
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--emu-home', type=Path, required=True)
p.add_argument('--agent-port', type=int, required=True)
p.add_argument('--action', choices=('respring', 'reset'), required=True)
p.add_argument('--cycles', type=int, default=3)
p.add_argument('--output', type=Path, required=True)
args = p.parse_args()
if args.cycles < 1:
p.error('--cycles doit être positif')
home = args.emu_home.resolve()
run = home / 'run'
bindir = Path(__file__).resolve().parents[1] / 'bin'
os.environ.update(IPOD_EMU_HOME=str(home), IPOD_AGENT_PORT=str(args.agent_port))
Agent = runpy.run_path(str(bindir / 'ipod-agent'))['Agent']
def call(*fields, data=None):
a = Agent(timeout=10)
try:
ok, body, detail = a.call(*fields, data=data)
if not ok:
raise RuntimeError(body.decode(errors='replace'))
return body
finally:
a.f.close()
a.s.close()
def springboard():
return next(line.split()[0] for line in call('ps').decode().splitlines()
if line.endswith(' SpringBoard'))
nonce = uuid.uuid4().hex.encode()
marker = '/private/var/mobile/Library/test-display-' + nonce.decode()
class Fixture(http.server.BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-Length', str(len(nonce)))
self.end_headers()
self.wfile.write(nonce)
def log_message(self, *unused):
pass
server = http.server.ThreadingHTTPServer(('127.0.0.1', 0), Fixture)
threading.Thread(target=server.serve_forever, daemon=True).start()
url = f'http://10.0.2.2:{server.server_port}/preuve'
args.output.mkdir(parents=True, exist_ok=True)
qpid = (run / 'qemu.pid').read_text()
npid = (run / 'netd.pid').read_text()
inode = (run / 'nand').stat().st_ino
results = []
try:
call('put', marker, '600', len(nonce), data=nonce)
for cycle in range(args.cycles):
oldpid = springboard()
offset = (run / 'serial.log').stat().st_size
started = time.monotonic()
subprocess.run([str(bindir / 'ipod-emu'), args.action, '-W'],
check=True, timeout=340)
newpid = springboard()
fresh = (run / 'serial.log').read_bytes()[offset:]
if args.action == 'reset':
assert b'Darwin Kernel Version' in fresh
else:
assert oldpid != newpid
assert b'Darwin Kernel Version' not in fresh
assert b'locked=0 passcode=0' in call('screen')
assert (run / 'qemu.pid').read_text() == qpid
assert (run / 'netd.pid').read_text() == npid
assert (run / 'nand').stat().st_ino == inode
assert call('get', marker) == nonce
assert nonce in call('fetch', url)
call('launch', 'com.apple.calculator', '-')
time.sleep(3)
assert call('front').strip() == b'com.apple.calculator'
capture = args.output.resolve() / f'{args.action}-{cycle + 1}.png'
subprocess.run([str(bindir / 'ipod-qmp'), 'screenshot', str(capture)],
check=True, timeout=15)
result = dict(cycle=cycle + 1, seconds=round(time.monotonic() - started, 1),
qemu_pid=int(qpid), netd_pid=int(npid), springboard_pid=newpid,
unlocked=True, nand_preserved=True, http=True,
net=call('net').decode(), front='com.apple.calculator')
results.append(result)
print(json.dumps(result, ensure_ascii=False), flush=True)
(args.output / 'validation.json').write_text(
json.dumps(results, ensure_ascii=False, indent=2) + '\n')
call('rm', marker)
call('sync')
finally:
server.shutdown()
server.server_close()
if __name__ == '__main__':
main()
+119
View File
@@ -0,0 +1,119 @@
/* Le masque LCD et l'acquittement doivent survivre à plusieurs resprings. */
#include "qemu/osdep.h"
#include "qemu/main-loop.h"
#include "sysemu/cpus.h"
#include "hw/arm/ipod_touch_lcd.c"
#define ipod_touch_machine_types test_mipi_register_types
#include "hw/arm/ipod_touch_mipi_dsi.c"
#undef ipod_touch_machine_types
#include "hw/arm/ipod_touch_tvout.c"
static void irq_changed(void *opaque, int n, int level)
{
*(int *)opaque = level;
}
static void test_interrupt_reenable(void)
{
IPodTouchLCDState *s = IPOD_TOUCH_LCD(object_new(TYPE_IPOD_TOUCH_LCD));
int level = 0;
qemu_irq irq = qemu_allocate_irq(irq_changed, &level, 0);
sysbus_connect_irq(SYS_BUS_DEVICE(s), 0, irq);
s->refresh_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, refresh_timer_tick, s);
for (int cycle = 0; cycle < 3; cycle++) {
/* Vblank masqué : état en attente, aucune interruption CPU. */
ipod_touch_lcd_write(s, 0x8, 0, 4);
refresh_timer_tick(s);
g_assert_cmpint(level, ==, 0);
g_assert_cmpuint(ipod_touch_lcd_read(s, 0xc, 4), ==, 1);
ipod_touch_lcd_write(s, 0xc, 0xff, 4);
g_assert_cmpuint(ipod_touch_lcd_read(s, 0xc, 4), ==, 0);
/* Nouveau client : le masque réactive les vblanks après cet ACK. */
ipod_touch_lcd_write(s, 0x8, 1, 4);
g_assert_cmpint(level, ==, 0);
refresh_timer_tick(s);
g_assert_cmpint(level, ==, 1);
ipod_touch_lcd_write(s, 0xc, 2, 4);
g_assert_cmpint(level, ==, 1);
ipod_touch_lcd_write(s, 0xc, 1, 4);
g_assert_cmpint(level, ==, 0);
g_assert_cmpuint(ipod_touch_lcd_read(s, 0x8, 4), ==, 1);
refresh_timer_tick(s);
g_assert_cmpint(level, ==, 1);
ipod_touch_lcd_write(s, 0x8, 0, 4);
g_assert_cmpint(level, ==, 0);
ipod_touch_lcd_write(s, 0x8, 1, 4);
g_assert_cmpint(level, ==, 1);
}
ipod_touch_lcd_write(s, 0x24, 0x12340000, 4);
device_cold_reset(DEVICE(s));
g_assert_cmpint(level, ==, 0);
g_assert_cmpuint(ipod_touch_lcd_read(s, 0x8, 4), ==, 0);
g_assert_cmpuint(ipod_touch_lcd_read(s, 0xc, 4), ==, 0);
g_assert_cmpuint(ipod_touch_lcd_read(s, 0x24, 4), ==, 0);
timer_del(s->refresh_timer);
timer_free(s->refresh_timer);
object_unref(OBJECT(s));
qemu_free_irq(irq);
}
static void test_tvout_submissions(void)
{
IPodTouchTVOutState *s = IPOD_TOUCH_TVOUT(object_new(TYPE_IPOD_TOUCH_TVOUT));
int level = 0;
qemu_irq irq = qemu_allocate_irq(irq_changed, &level, 0);
sysbus_connect_irq(SYS_BUS_DEVICE(s), 0, irq);
/* L'ancien quota global cessait de répondre dès la troisième soumission. */
for (int cycle = 0; cycle < 20; cycle++) {
ipod_touch_tvout_mixer1_write(s, MXR_STATUS, 0x85, 4);
g_assert_cmpint(level, ==, 1);
ipod_touch_tvout_sdo_write(s, SDO_IRQ, 2, 4);
g_assert_cmpint(level, ==, 1);
ipod_touch_tvout_sdo_write(s, SDO_IRQ, 1, 4);
g_assert_cmpint(level, ==, 0);
}
ipod_touch_tvout_sdo_write(s, SDO_IRQMASK, 1, 4);
ipod_touch_tvout_mixer1_write(s, MXR_STATUS, 0x85, 4);
g_assert_cmpint(level, ==, 0);
g_assert_cmpuint(ipod_touch_tvout_sdo_read(s, SDO_IRQ, 4), ==, 1);
ipod_touch_tvout_sdo_write(s, SDO_IRQMASK, 0, 4);
g_assert_cmpint(level, ==, 1);
device_cold_reset(DEVICE(s));
g_assert_cmpint(level, ==, 0);
g_assert_cmpuint(ipod_touch_tvout_sdo_read(s, SDO_IRQ, 4), ==, 0);
ipod_touch_tvout_mixer1_write(s, MXR_STATUS, 0x85, 4);
g_assert_cmpint(level, ==, 1);
object_unref(OBJECT(s));
qemu_free_irq(irq);
}
static void test_panel_reset(void)
{
IPodTouchMIPIDSIState *s = IPOD_TOUCH_MIPI_DSI(object_new(TYPE_IPOD_TOUCH_MIPI_DSI));
for (int cycle = 0; cycle < 3; cycle++) {
ipod_touch_mipi_dsi_write(s, REG_CLKCTRL, DSIM_CLKCTRL_TX_REQUEST_HSCLK, 4);
g_assert_cmpuint(ipod_touch_mipi_dsi_read(s, 0, 4) & rDSIM_STATUS_TxReadyHsClk, !=, 0);
g_assert_cmpuint(ipod_touch_mipi_dsi_read(s, REG_RXFIFO, 4), ==, 0x31a);
/* Un reset pendant une réponse doit recommencer par son en-tête. */
device_cold_reset(DEVICE(s));
g_assert_cmpuint(ipod_touch_mipi_dsi_read(s, 0, 4) & rDSIM_STATUS_TxReadyHsClk, ==, 0);
g_assert_cmpuint(ipod_touch_mipi_dsi_read(s, REG_RXFIFO, 4), ==, 0x31a);
g_assert_cmpuint(ipod_touch_mipi_dsi_read(s, REG_RXFIFO, 4), ==, 0x00a1d13c);
}
object_unref(OBJECT(s));
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
module_call_init(MODULE_INIT_QOM);
qemu_init_main_loop(&error_abort);
qemu_init_cpu_loop();
qemu_mutex_lock_iothread();
g_test_add_func("/ipod-lcd/interrupt-reenable", test_interrupt_reenable);
g_test_add_func("/ipod-tvout/repeated-submissions", test_tvout_submissions);
g_test_add_func("/ipod-mipi/panel-reset", test_panel_reset);
return g_test_run();
}
+242
View File
@@ -0,0 +1,242 @@
/* Régressions du protocole tactile : commandes invalides et trames concurrentes. */
#include "qemu/osdep.h"
#include "qemu/main-loop.h"
#include "sysemu/cpus.h"
#include "hw/arm/ipod_touch_multitouch.c"
#include "hw/arm/ipod_touch_gpio.c"
#include "hw/arm/ipod_touch_sysic.c"
#include "hw/arm/ipod_touch_spi.c"
static IPodTouchMultitouchState *new_sensor(void)
{
IPodTouchMultitouchState *s = IPOD_TOUCH_MULTITOUCH(
object_new(TYPE_IPOD_TOUCH_MULTITOUCH));
ipod_touch_multitouch_realize(SSI_PERIPHERAL(s), &error_abort);
return s;
}
static void destroy_sensor(IPodTouchMultitouchState *s)
{
finish_transfer(s);
timer_free(s->touch_timer);
timer_free(s->touch_end_timer);
g_free(s->next_frame);
g_free(s->read_frame);
object_unref(OBJECT(s));
}
static uint8_t transfer(IPodTouchMultitouchState *s, uint8_t byte)
{
return ipod_touch_multitouch_transfer(SSI_PERIPHERAL(s), byte);
}
static void test_unknown(void)
{
IPodTouchMultitouchState *s = new_sensor();
for (int i = 0; i < 10000; i++) {
g_assert_cmpuint(transfer(s, 0xab), ==, 0xff);
g_assert_cmpuint(s->cur_cmd, ==, 0);
g_assert_null(s->in_buffer);
}
uint8_t out[16];
out[0] = transfer(s, MT_CMD_GET_INTERFACE_VERSION);
for (int i = 1; i < 16; i++) out[i] = transfer(s, 0);
g_assert_cmpuint(out[2], ==, MT_INTERFACE_VERSION);
destroy_sensor(s);
}
static void test_snapshot(void)
{
IPodTouchMultitouchState *s = new_sensor();
MTFrame expected = *s->next_frame;
uint8_t out[sizeof(MTFrame)];
out[0] = transfer(s, MT_CMD_FRAME_READ);
for (int i = 1; i < 16; i++) out[i] = transfer(s, 0);
g_free(s->next_frame);
s->next_frame = get_frame(s, MT_EVENT_TOUCH_START, .4, .6,
100, 660, 580, 150);
g_assert_cmpuint(s->cur_cmd, ==, 0);
out[16] = transfer(s, 0xeb);
out[17] = transfer(s, 0);
out[18] = transfer(s, 1);
for (size_t i = 19; i < sizeof out; i++) out[i] = transfer(s, 0);
expected.frame_packet.unused1 = expected.frame_length.length1;
expected.frame_packet.checksum_pad = -(expected.frame_packet.cmd +
expected.frame_packet.unused1 + expected.frame_packet.length1 +
expected.frame_packet.length2);
g_assert_cmpmem(out, sizeof out, &expected, sizeof expected);
g_assert_cmpuint(s->next_frame->finger_data.event, ==, MT_EVENT_TOUCH_START);
destroy_sensor(s);
}
static void test_reports(void)
{
IPodTouchMultitouchState *s = new_sensor();
uint8_t out[16];
for (int cmd = MT_CMD_GET_REPORT_INFO; cmd <= MT_CMD_SHORT_CONTROL_READ; cmd += 3) {
out[0] = transfer(s, cmd);
out[1] = transfer(s, 0xff);
for (int i = 2; i < 16; i++) out[i] = transfer(s, 0);
g_assert_cmpuint(out[2], ==, 1);
unsigned sum = 0;
for (int i = 0; i < 14; i++) sum += out[i];
g_assert_cmpuint(lduw_le_p(out + 14), ==, sum);
}
transfer(s, MT_CMD_SHORT_CONTROL_READ);
transfer(s, MT_REPORT_SENSOR_DIMENSIONS);
for (int i = 2; i < 16; i++) out[i] = transfer(s, 0);
g_assert_cmpuint(ldl_le_p(out + 3), ==, 5000);
g_assert_cmpuint(ldl_le_p(out + 7), ==, 7500);
destroy_sensor(s);
}
static void test_spi_abort(void)
{
IPodTouchSPIState *spi = IPOD_TOUCH_SPI(object_new(TYPE_IPOD_TOUCH_SPI));
DEVICE(spi)->id = g_strdup("spi-test");
set_spi_base(4);
ipod_touch_spi_realize(DEVICE(spi), &error_abort);
ipod_touch_spi_write(spi, R_TXCNT, 2, 4);
ipod_touch_spi_write(spi, R_RXCNT, 2, 4);
ipod_touch_spi_write(spi, R_TXDATA, MT_CMD_FRAME_READ, 4);
ipod_touch_spi_write(spi, R_TXDATA, 2, 4);
ipod_touch_spi_write(spi, R_CTRL, R_CTRL_RUN, 4);
g_assert_cmpuint(spi->mt->in_buffer_ind, ==, 2);
ipod_touch_spi_write(spi, R_CTRL, R_CTRL_TX_RESET | R_CTRL_RX_RESET, 4);
g_assert_cmpuint(spi->mt->cur_cmd, ==, 0);
g_assert_null(spi->mt->in_buffer);
uint8_t response[16];
response[0] = transfer(spi->mt, MT_CMD_GET_INTERFACE_VERSION);
for (int i = 1; i < 16; i++) response[i] = transfer(spi->mt, 0);
g_assert_cmpuint(response[2], ==, MT_INTERFACE_VERSION);
spi->last_irq = 1;
fifo8_push(&spi->tx_fifo, 0x12);
fifo8_push(&spi->rx_fifo, 0x34);
device_cold_reset(DEVICE(spi));
g_assert_cmpuint(spi->last_irq, ==, 0);
g_assert_true(fifo8_is_empty(&spi->tx_fifo));
g_assert_true(fifo8_is_empty(&spi->rx_fifo));
g_assert_cmpuint(ipod_touch_spi_read(spi, R_TXCNT, 4), ==, 0);
timer_free(spi->mt->touch_timer);
timer_free(spi->mt->touch_end_timer);
g_free(spi->mt->next_frame);
fifo8_destroy(&spi->tx_fifo);
fifo8_destroy(&spi->rx_fifo);
object_unref(OBJECT(spi));
}
static void test_hbpp(void)
{
IPodTouchMultitouchState *s = new_sensor();
uint8_t bad[10] = {MT_CMD_HBPP_DATA_PACKET, 0, 0, 4};
for (int i = 0; i < 10; i++) transfer(s, bad[i]);
g_assert_cmpuint(s->cur_cmd, ==, 0);
uint8_t good[10] = {MT_CMD_HBPP_DATA_PACKET, 0, 0, 4, 0, 0, 0, 0, 0, 4};
for (int i = 0; i < 10; i++) transfer(s, good[i]);
for (int i = 1; i < 21; i++) transfer(s, 0);
g_assert_cmpuint(s->cur_cmd, ==, 0);
destroy_sensor(s);
}
static void test_velocity(void)
{
IPodTouchMultitouchState *s = new_sensor();
MTFrame *f = get_frame(s, MT_EVENT_TOUCH_MOVED, .4, .6, 1, 1, 1, 1);
g_free(f);
f = get_frame(s, MT_EVENT_TOUCH_MOVED, .4, .7, 1, 1, 1, 1);
g_assert_cmpint(f->finger_data.velX, ==, 0);
g_assert_cmpint(f->finger_data.velY, >, 0);
g_free(f);
f = get_frame(s, MT_EVENT_TOUCH_MOVED, .4, .7, 1, 1, 1, 1);
g_assert_cmpint(f->finger_data.velX, ==, 0);
g_assert_cmpint(f->finger_data.velY, ==, 0);
g_free(f);
destroy_sensor(s);
}
static void test_buttons(void)
{
IPodTouchGPIOState *s = IPOD_TOUCH_GPIO(object_new(TYPE_IPOD_TOUCH_GPIO));
g_assert_cmpuint(GPIO2PAD(GPIO_BUTTON_HOME), <, NUM_GPIO_PADS);
gpio_set_on(s->gpio_state, GPIO_BUTTON_HOME);
gpio_set_on(s->gpio_state, GPIO_BUTTON_POWER);
g_assert_true(gpio_is_on(s->gpio_state, GPIO_BUTTON_HOME));
g_assert_true(gpio_is_on(s->gpio_state, GPIO_BUTTON_POWER));
gpio_set_off(s->gpio_state, GPIO_BUTTON_HOME);
g_assert_true(gpio_is_off(s->gpio_state, GPIO_BUTTON_HOME));
g_assert_true(gpio_is_on(s->gpio_state, GPIO_BUTTON_POWER));
object_unref(OBJECT(s));
}
static void test_gpio_ranges(void)
{
IPodTouchSYSICState *s = IPOD_TOUCH_SYSIC(object_new(TYPE_IPOD_TOUCH_SYSIC));
uint32_t arrays[4][GPIO_NUMINTGROUPS];
s->gpio_int_level[0] = 0x1234;
memcpy(arrays[0], s->gpio_int_level, sizeof arrays[0]);
memcpy(arrays[1], s->gpio_int_status, sizeof arrays[1]);
memcpy(arrays[2], s->gpio_int_enabled, sizeof arrays[2]);
memcpy(arrays[3], s->gpio_int_type, sizeof arrays[3]);
/* Les quatre trous entre groupes ne doivent pas accéder au tableau suivant. */
for (int addr = GPIO_INTLEVEL; addr <= GPIO_INTTYPE; addr += 0x20) {
ipod_touch_sysic_write(s, addr + GPIO_NUMINTGROUPS * 4, 0xffffffff, 4);
g_assert_cmpuint(ipod_touch_sysic_read(s, addr + GPIO_NUMINTGROUPS * 4, 4), ==, 0);
}
g_assert_cmpmem(arrays[0], sizeof arrays[0], s->gpio_int_level, sizeof arrays[0]);
g_assert_cmpmem(arrays[1], sizeof arrays[1], s->gpio_int_status, sizeof arrays[1]);
g_assert_cmpmem(arrays[2], sizeof arrays[2], s->gpio_int_enabled, sizeof arrays[2]);
g_assert_cmpmem(arrays[3], sizeof arrays[3], s->gpio_int_type, sizeof arrays[3]);
object_unref(OBJECT(s));
}
static void test_reset(void)
{
IPodTouchMultitouchState *s = new_sensor();
IPodTouchSYSICState *sysic = IPOD_TOUCH_SYSIC(object_new(TYPE_IPOD_TOUCH_SYSIC));
s->sysic = sysic;
ipod_touch_multitouch_on_touch(s);
/* Capture d'une trame, puis interruption au milieu d'une autre commande. */
transfer(s, MT_CMD_FRAME_READ);
for (int i = 1; i < 16; i++) transfer(s, 0);
transfer(s, MT_CMD_GET_INTERFACE_VERSION);
s->hbpp_atn_ack_response[0] = 0xaa;
g_assert_true(timer_pending(s->touch_timer));
g_assert_nonnull(s->read_frame);
g_assert_nonnull(s->out_buffer);
device_cold_reset(DEVICE(s));
g_assert_false(timer_pending(s->touch_timer));
g_assert_false(timer_pending(s->touch_end_timer));
g_assert_false(s->touch_down);
g_assert_null(s->read_frame);
g_assert_null(s->in_buffer);
g_assert_null(s->out_buffer);
g_assert_cmpuint(s->cur_cmd, ==, 0);
g_assert_cmpuint(s->hbpp_atn_ack_response[0], ==, 0);
g_assert_cmpuint(sysic->gpio_int_status[3], ==, 0);
g_assert_cmpuint(s->next_frame->finger_data.event, ==, MT_EVENT_TOUCH_FULL_END);
transfer(s, MT_CMD_GET_INTERFACE_VERSION);
transfer(s, 0);
g_assert_cmpuint(transfer(s, 0), ==, MT_INTERFACE_VERSION);
destroy_sensor(s);
object_unref(OBJECT(sysic));
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
module_call_init(MODULE_INIT_QOM);
qemu_init_main_loop(&error_abort);
qemu_init_cpu_loop();
qemu_mutex_lock_iothread();
g_test_add_func("/ipod-multitouch/unknown", test_unknown);
g_test_add_func("/ipod-multitouch/snapshot", test_snapshot);
g_test_add_func("/ipod-multitouch/hbpp", test_hbpp);
g_test_add_func("/ipod-multitouch/spi-abort", test_spi_abort);
g_test_add_func("/ipod-multitouch/reports", test_reports);
g_test_add_func("/ipod-multitouch/velocity", test_velocity);
g_test_add_func("/ipod-multitouch/reset", test_reset);
g_test_add_func("/ipod-input/buttons", test_buttons);
g_test_add_func("/ipod-input/gpio-ranges", test_gpio_ranges);
return g_test_run();
}
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Vérifie le reset du lanceur sans QEMU : synchronisation et nouveau journal de boot."""
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
import time
import unittest
ROOT = Path(__file__).resolve().parents[3]
BOOT = b'AppleMultitouchSPIUserClient::attach\n' * 2 + b'SCHelper "EXIT"\n'
class ResetLauncher(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.home = Path(self.tmp.name)
self.run = self.home / 'run'
self.run.mkdir()
(self.run / 'nand').mkdir()
(self.run / 'nand/temoin').write_bytes(b'NAND conservee')
(self.run / 'qemu.pid').write_text(str(os.getpid()))
# Une ancienne erreur et beaucoup de données ne doivent pas contaminer le nouveau boot.
self.old = b'Fatal Exception\x00\n' + b'x' * 100000 + b'\n' + BOOT
(self.run / 'serial.log').write_bytes(self.old)
tools = self.home / 'bin'
tools.mkdir()
self.launcher = tools / 'ipod-emu'
shutil.copy2(ROOT / 'contrib/ipod-emu/bin/ipod-emu', self.launcher)
scripts = {
'ipod-agent': '''#!/usr/bin/env bash
set -euo pipefail
printf '%s\n' "$1" >> "$IPOD_EMU_HOME/actions"
if [ "$1" = sync ] && [ "${IPOD_TEST_SYNC_FAIL:-0}" = 1 ]; then exit 1; fi
''',
'ipod-qmp': '''#!/usr/bin/env bash
set -euo pipefail
printf 'reset\n' >> "$IPOD_EMU_HOME/actions"
'''
}
for name, content in scripts.items():
path = tools / name
path.write_text(content)
path.chmod(0o755)
self.env = dict(os.environ, IPOD_EMU_HOME=str(self.home))
def tearDown(self):
self.tmp.cleanup()
def test_reset_preserves_nand(self):
subprocess.run([str(self.launcher), 'reset'], env=self.env,
capture_output=True, check=True, timeout=5)
self.assertEqual((self.home / 'actions').read_text().splitlines(), ['sync', 'reset'])
self.assertEqual(int((self.run / 'boot-log-offset').read_text()), len(self.old))
self.assertEqual((self.run / 'nand/temoin').read_bytes(), b'NAND conservee')
self.assertEqual((self.run / 'qemu.pid').read_text(), str(os.getpid()))
def test_wait_ignores_previous_boot(self):
proc = subprocess.Popen([str(self.launcher), 'reset', '-W'], env=self.env,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
deadline = time.monotonic() + 5
while not (self.run / 'boot-log-offset').exists():
self.assertLess(time.monotonic(), deadline)
self.assertIsNone(proc.poll())
time.sleep(.02)
# L'ancien journal contient déjà tous les marqueurs, mais l'attente doit continuer.
time.sleep(3.5)
self.assertIsNone(proc.poll())
self.assertNotIn('unlock', (self.home / 'actions').read_text())
with (self.run / 'serial.log').open('ab') as log:
log.write(BOOT)
out, err = proc.communicate(timeout=15)
self.assertEqual(proc.returncode, 0, err.decode())
self.assertIn('SpringBoard prêt', out.decode())
self.assertEqual((self.home / 'actions').read_text().splitlines(), ['sync', 'reset', 'unlock'])
finally:
if proc.poll() is None:
proc.kill()
proc.communicate()
def test_sync_failure_prevents_reset(self):
env = dict(self.env, IPOD_TEST_SYNC_FAIL='1')
r = subprocess.run([str(self.launcher), 'reset'], env=env,
capture_output=True, timeout=5)
self.assertNotEqual(r.returncode, 0)
self.assertEqual((self.home / 'actions').read_text().splitlines(), ['sync'])
self.assertFalse((self.run / 'boot-log-offset').exists())
def test_respring_preserves_session(self):
subprocess.run([str(self.launcher), 'respring'], env=self.env,
capture_output=True, check=True, timeout=5)
self.assertEqual((self.home / 'actions').read_text().splitlines(), ['sync', 'respring'])
self.assertEqual(int((self.run / 'boot-log-offset').read_text()), len(self.old))
self.assertEqual((self.run / 'nand/temoin').read_bytes(), b'NAND conservee')
self.assertEqual((self.run / 'qemu.pid').read_text(), str(os.getpid()))
def test_invalid_option_does_not_restart(self):
r = subprocess.run([str(self.launcher), 'reset', '-f'], env=self.env,
capture_output=True, timeout=5)
self.assertNotEqual(r.returncode, 0)
self.assertFalse((self.home / 'actions').exists())
if __name__ == '__main__':
unittest.main()
+155
View File
@@ -0,0 +1,155 @@
/* Régressions du D1759 sur le bus I²C réel de QEMU. */
#include "qemu/osdep.h"
#include "qemu/main-loop.h"
#include "qemu/option.h"
#include "sysemu/cpus.h"
#include "hw/arm/ipod_touch_pcf50633_pmu.c"
static QemuOptsList rtc_test_opts = {
.name = "rtc-test",
.head = QTAILQ_HEAD_INITIALIZER(rtc_test_opts.head),
.desc = {
{ .name = "base", .type = QEMU_OPT_STRING },
{ .name = "clock", .type = QEMU_OPT_STRING },
{ }
}
};
static I2CBus *bus;
static Pcf50633State *pmu;
static DeviceState *parent;
static void setup(const char *base, const char *clock)
{
QemuOpts *opts = qemu_opts_create(&rtc_test_opts, NULL, 0, &error_abort);
qemu_opt_set(opts, "base", base, &error_abort);
qemu_opt_set(opts, "clock", clock, &error_abort);
configure_rtc(opts);
qemu_opts_del(opts);
parent = qdev_new(TYPE_PCF50633);
bus = i2c_init_bus(parent, "rtc-test");
pmu = PCF50633(i2c_slave_create_simple(bus, TYPE_D1759, 0x73));
}
static void teardown(void)
{
qdev_unrealize(DEVICE(pmu));
object_unref(OBJECT(parent));
}
static void select_register(uint8_t reg, bool stop)
{
g_assert_cmpint(i2c_start_transfer(bus, 0x73, false), ==, 0);
g_assert_cmpint(i2c_send(bus, reg), ==, 0);
if (stop) {
i2c_end_transfer(bus);
}
g_assert_cmpint(i2c_start_transfer(bus, 0x73, true), ==, 0);
}
static uint32_t read_word(uint8_t reg, bool stop)
{
uint32_t value = 0;
select_register(reg, stop);
for (int i = 0; i < 4; i++) {
value |= (uint32_t)i2c_recv(bus) << (i * 8);
}
i2c_end_transfer(bus);
return value;
}
static void write_word(uint8_t reg, uint32_t value)
{
g_assert_cmpint(i2c_start_transfer(bus, 0x73, false), ==, 0);
g_assert_cmpint(i2c_send(bus, reg), ==, 0);
for (int i = 0; i < 4; i++) {
g_assert_cmpint(i2c_send(bus, value >> (i * 8)), ==, 0);
}
i2c_end_transfer(bus);
}
static void test_host_utc(void)
{
time_t before = time(NULL);
/* Le fuseau de l'hôte ne doit pas décaler le compteur Unix. */
setenv("TZ", "Pacific/Honolulu", 1);
tzset();
setup("utc", "host");
uint32_t value = read_word(0x5c, false);
g_assert_cmpuint(value, >=, before);
g_assert_cmpuint(value, <=, time(NULL));
g_assert_cmpuint(read_word(0x64, true), ==, 0);
teardown();
unsetenv("TZ");
tzset();
}
static void test_fixed_base(void)
{
setup("2024-02-29T23:59:59", "vm");
g_assert_cmpint(rtc_clock, ==, QEMU_CLOCK_VIRTUAL);
g_assert_cmpuint(read_word(0x5c, true), ==, 1709251199);
g_assert_cmpuint(read_word(0x5c, false), ==, 1709251199);
teardown();
}
static void test_snapshot_rollover(void)
{
setup("2024-02-29T23:59:59", "vm");
uint32_t boundaries[] = { 1709251199, 0x00ffffff, 0xffffffff };
for (size_t n = 0; n < G_N_ELEMENTS(boundaries); n++) {
pmu->rtc_tick_offset = boundaries[n];
select_register(0x5c, false);
uint32_t value = i2c_recv(bus);
/* Le temps change entre deux octets, après capture du premier. */
pmu->rtc_tick_offset++;
for (int i = 1; i < 4; i++) {
value |= (uint32_t)i2c_recv(bus) << (8 * i);
}
i2c_end_transfer(bus);
g_assert_cmpuint(value, ==, boundaries[n]);
g_assert_cmpuint(read_word(0x5c, true), ==, boundaries[n] + 1);
}
teardown();
}
static void test_offsets(void)
{
setup("2024-02-29T23:59:59", "vm");
uint32_t counter = read_word(0x5c, true);
uint32_t offsets[] = { 3600, (uint32_t)-86400, 0x12345678, 0 };
for (size_t i = 0; i < G_N_ELEMENTS(offsets); i++) {
write_word(0x64, offsets[i]);
g_assert_cmpuint(read_word(0x64, false), ==, offsets[i]);
g_assert_cmpuint(read_word(0x5c, true), ==, counter);
}
/* Un changement de date ne doit pas réécrire le compteur matériel. */
write_word(0x5c, 1234);
g_assert_cmpuint(read_word(0x5c, false), ==, counter);
teardown();
}
static void test_boot_registers(void)
{
setup("2024-02-29T23:59:59", "vm");
write_word(0x60, 0xffffffff);
g_assert_cmpuint(read_word(0x60, true), ==, 0);
g_assert_cmpuint(read_word(0x5c, false), ==, 1709251199);
g_assert_cmpuint(read_word(0x64, true), ==, 0);
teardown();
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
module_call_init(MODULE_INIT_QOM);
qemu_init_main_loop(&error_abort);
qemu_init_cpu_loop();
qemu_mutex_lock_iothread();
g_test_add_func("/ipod-rtc/host-utc", test_host_utc);
g_test_add_func("/ipod-rtc/fixed-base", test_fixed_base);
g_test_add_func("/ipod-rtc/snapshot-rollover", test_snapshot_rollover);
g_test_add_func("/ipod-rtc/offsets", test_offsets);
g_test_add_func("/ipod-rtc/boot-registers", test_boot_registers);
return g_test_run();
}
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
"""Teste les transferts réels de l'agent sur socket local, sans firmware Apple."""
import importlib.util
from importlib.machinery import SourceFileLoader
import io
import os
from pathlib import Path
import socket
import subprocess
import tempfile
import threading
import unittest
ROOT = Path(__file__).resolve().parents[1]
loader = SourceFileLoader('ipod_agent', str(ROOT / 'bin/ipod-agent'))
spec = importlib.util.spec_from_loader(loader.name, loader)
client = importlib.util.module_from_spec(spec)
loader.exec_module(client)
class Transfers(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.work = tempfile.TemporaryDirectory()
cls.binary = Path(cls.work.name) / 'transfer-agent'
source = (ROOT / 'agent/emuagent.c').read_text()
# Compile les fonctions de production, sans dépendances privées d'iOS.
functions = source[source.index('static int send_all('):source.index('/* tampon dynamique */')]
functions += source[source.index('static int read_full('):source.index('static void cmd_ls(')]
harness = '''#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
static void mkdirs(const char *path) { (void)path; }
''' + functions + '''
int main(int argc, char **argv) {
if (argc < 4) return 2;
int fd = atoi(argv[1]);
if (!strcmp(argv[2], "get")) cmd_get(fd, argv+3, argc-3);
else cmd_put(fd, argv+3, argc-3);
char ignored[256]; read(fd, ignored, sizeof ignored);
close(fd); return 0;
}
'''
c = Path(cls.work.name) / 'transfer-agent.c'
c.write_text(harness)
subprocess.run(['cc', '-Wall', '-Wextra', '-Werror', '-fsanitize=undefined',
'-o', str(cls.binary), str(c)], check=True)
@classmethod
def tearDownClass(cls):
cls.work.cleanup()
def agent(self, command, *args):
a, b = socket.socketpair()
process = subprocess.Popen([str(self.binary), str(b.fileno()), command, *map(str, args)],
pass_fds=(b.fileno(),), env=dict(os.environ, UBSAN_OPTIONS='halt_on_error=1'))
b.close()
agent = client.Agent.__new__(client.Agent)
agent.s, agent.f = a, a.makefile('rb')
self.addCleanup(agent.f.close)
self.addCleanup(a.close)
self.addCleanup(lambda: self.assertEqual(process.wait(timeout=5), 0))
return agent
def test_large_round_trip(self):
data = os.urandom(8 * 1024 * 1024 + 37)
with tempfile.TemporaryDirectory() as d:
path = Path(d) / 'file'
a = self.agent('put', path, '640', len(data))
# Le harness reçoit les arguments hors bande, puis le contenu du protocole.
a.s.sendall(data)
ok, _, _ = a.call() # ligne vide ignorée par ce harness
self.assertTrue(ok)
self.assertEqual(path.read_bytes(), data)
self.assertEqual(path.stat().st_mode & 0o777, 0o640)
a = self.agent('get', path)
with (Path(d) / 'download').open('wb') as out:
ok, _, _ = a.call(sink=out)
self.assertTrue(ok)
self.assertEqual((Path(d) / 'download').read_bytes(), data)
def test_interrupted_put_preserves_existing_file(self):
with tempfile.TemporaryDirectory() as d:
path = Path(d) / 'file'
path.write_bytes(b'ancienne version')
a = self.agent('put', path, '644', 100000)
a.s.sendall(b'court')
a.s.shutdown(socket.SHUT_WR)
response = a.f.read()
self.assertTrue(response.startswith(b'ERR '))
self.assertEqual(path.read_bytes(), b'ancienne version')
self.assertEqual(list(Path(d).iterdir()), [path])
def test_empty_file(self):
with tempfile.TemporaryDirectory() as d:
path = Path(d) / 'empty'
a = self.agent('put', path, '644', 0)
self.assertTrue(a.call()[0])
self.assertEqual(path.read_bytes(), b'')
self.assertEqual(self.agent('get', path).call()[1], b'')
def test_download_failure_preserves_destination(self):
listener = socket.socket()
listener.bind(('127.0.0.1', 0)); listener.listen()
def server():
connection, _ = listener.accept()
connection.recv(1024)
connection.sendall(b'OK 100\npartiel')
connection.close()
thread = threading.Thread(target=server); thread.start()
try:
with tempfile.TemporaryDirectory() as d:
destination = Path(d) / 'download'
destination.write_bytes(b'original')
r = subprocess.run([str(ROOT / 'bin/ipod-agent'), 'get', '/file', str(destination)],
env=dict(os.environ, IPOD_AGENT_PORT=str(listener.getsockname()[1]),
IPOD_AGENT_HOST='127.0.0.1'), capture_output=True)
self.assertEqual(r.returncode, 1)
self.assertIn('tronquée', r.stderr.decode())
self.assertEqual(destination.read_bytes(), b'original')
self.assertEqual(list(Path(d).iterdir()), [destination])
finally:
thread.join(); listener.close()
def test_upload_respects_announced_size(self):
a, b = socket.socketpair()
agent = client.Agent.__new__(client.Agent)
agent.s, agent.f = a, a.makefile('rb')
received = []
def server():
f = b.makefile('rb')
received.append(f.readline())
received.append(f.read(3))
b.sendall(b'OK 0\n')
f.close(); b.close()
thread = threading.Thread(target=server); thread.start()
try:
data = io.BytesIO(b'abcEXTRA')
self.assertTrue(agent.call('put', '/file', '644', 3, data=data)[0])
self.assertEqual(data.tell(), 3)
self.assertEqual(received, [b'put\t/file\t644\t3\n', b'abc'])
finally:
agent.f.close(); a.close(); thread.join()
def test_get_rejects_fifo_without_blocking(self):
with tempfile.TemporaryDirectory() as d:
path = Path(d) / 'fifo'
os.mkfifo(path)
self.assertFalse(self.agent('get', path).call()[0])
def test_fragmented_and_truncated_reply(self):
for truncated in (False, True):
a, b = socket.socketpair()
agent = client.Agent.__new__(client.Agent)
agent.s, agent.f = a, a.makefile('rb')
def server():
b.recv(100)
for part in (b'OK ', b'10\n', b'123', b'4567', b'890' if not truncated else b''):
b.sendall(part)
b.close()
thread = threading.Thread(target=server)
thread.start()
try:
if truncated:
with self.assertRaisesRegex(ConnectionError, 'tronquée'):
agent.call('get', '/test')
else:
self.assertEqual(agent.call('get', '/test')[1], b'1234567890')
finally:
agent.f.close(); a.close(); thread.join()
if __name__ == '__main__':
unittest.main()
+122
View File
@@ -0,0 +1,122 @@
/* Reset UART : registres, FIFO, IRQ et reconnexion du relais série. */
#include "qemu/osdep.h"
#include "qemu/main-loop.h"
#include "qemu/config-file.h"
#include "qemu/option.h"
#include "sysemu/cpus.h"
#include "sysemu/sysemu.h"
#include <sys/socket.h>
#include <sys/un.h>
#include "hw/arm/ipod_touch_uart.c"
static void irq_changed(void *opaque, int n, int level)
{
*(int *)opaque = level;
}
static void test_register_reset(void)
{
IPodTouchUARTState *s = IPOD_TOUCH_UART(object_new(TYPE_IPOD_TOUCH_UART));
int level = 0;
qemu_irq irq = qemu_allocate_irq(irq_changed, &level, 0);
sysbus_connect_irq(SYS_BUS_DEVICE(s), 0, irq);
uint8_t bytes[] = { 0x7e, 0xff, 0x03, 0x7d };
uart_write(s, ULCON, 3, 4);
uart_write(s, UCON, UCON_RX_INT | UCON_RXTO_INT | UCON_TX_INT, 4);
uart_write(s, UMCON, 1, 4);
uart_write(s, UBRDIV, 100, 4);
uart_receive(s, bytes, sizeof bytes);
g_assert_cmpint(level, ==, 1);
g_assert_cmpuint(uart_read(s, UFSTAT, 4), ==, sizeof bytes);
device_cold_reset(DEVICE(s));
g_assert_cmpint(level, ==, 0);
g_assert_cmpuint(uart_read(s, UTRSTAT, 4), ==,
UTRSTAT_TXBUF_EMPTY | UTRSTAT_TX_EMPTY);
g_assert_cmpuint(uart_read(s, UFSTAT, 4), ==, 0);
g_assert_cmpuint(uart_read(s, ULCON, 4), ==, 0);
g_assert_cmpuint(uart_read(s, UCON, 4), ==, 0);
g_assert_cmpuint(uart_read(s, UMCON, 4), ==, 0);
g_assert_cmpuint(uart_read(s, UBRDIV, 4), ==, 0);
object_unref(OBJECT(s));
qemu_free_irq(irq);
}
static void wait_open(IPodTouchUARTState *s)
{
int64_t deadline = g_get_monotonic_time() + 5 * G_USEC_PER_SEC;
while (!qemu_chr_fe_backend_open(&s->chr)) {
g_assert_cmpint(g_get_monotonic_time(), <, deadline);
main_loop_wait(true);
g_usleep(1000);
}
}
static int connect_client(const char *path)
{
int fd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un addr = { .sun_family = AF_UNIX };
g_strlcpy(addr.sun_path, path, sizeof addr.sun_path);
g_assert_cmpint(fd, >=, 0);
struct timeval limit = { .tv_sec = 5 };
g_assert_cmpint(setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &limit, sizeof limit), ==, 0);
g_assert_cmpint(connect(fd, (struct sockaddr *)&addr, sizeof addr), ==, 0);
return fd;
}
static void test_socket_reconnect(void)
{
char *dir = g_dir_make_tmp("ipod-uart-XXXXXX", NULL);
g_assert_nonnull(dir);
char *path = g_build_filename(dir, "uart.sock", NULL);
char *spec = g_strdup_printf("unix:%s,server=on,wait=off", path);
Chardev *chr = qemu_chr_new("uart-test", spec, NULL);
g_assert_nonnull(chr);
IPodTouchUARTState *s = IPOD_TOUCH_UART(object_new(TYPE_IPOD_TOUCH_UART));
qemu_chr_fe_init(&s->chr, chr, &error_abort);
uart_realize(DEVICE(s), &error_abort);
for (int cycle = 0; cycle < 3; cycle++) {
int fd = connect_client(path);
wait_open(s);
uint8_t incoming = 0x41 + cycle;
g_assert_cmpint(write(fd, &incoming, 1), ==, 1);
int64_t deadline = g_get_monotonic_time() + 5 * G_USEC_PER_SEC;
while (!s->rx_count) {
g_assert_cmpint(g_get_monotonic_time(), <, deadline);
main_loop_wait(true);
g_usleep(1000);
}
g_assert_cmpuint(uart_read(s, URXH, 1), ==, incoming);
uart_write(s, UTXH, 0x7e, 1);
uint8_t b = 0;
g_assert_cmpint(read(fd, &b, 1), ==, 1);
g_assert_cmpuint(b, ==, 0x7e);
device_cold_reset(DEVICE(s));
/* Le relais voit la fin du lien et peut renégocier avec le nouvel iOS. */
g_assert_false(qemu_chr_fe_backend_open(&s->chr));
g_assert_cmpint(read(fd, &b, 1), ==, 0);
close(fd);
}
qemu_chr_fe_deinit(&s->chr, false);
object_unref(OBJECT(s));
object_unparent(OBJECT(chr));
unlink(path);
rmdir(dir);
g_free(spec);
g_free(path);
g_free(dir);
}
int main(int argc, char **argv)
{
g_test_init(&argc, &argv, NULL);
module_call_init(MODULE_INIT_QOM);
qemu_add_opts(&qemu_chardev_opts);
qemu_init_main_loop(&error_abort);
qemu_init_cpu_loop();
qemu_mutex_lock_iothread();
g_test_add_func("/ipod-uart/register-reset", test_register_reset);
g_test_add_func("/ipod-uart/socket-reconnect", test_socket_reconnect);
return g_test_run();
}
+42 -9
View File
@@ -3,6 +3,8 @@
#include "hw/arm/boot.h"
#include "exec/address-spaces.h"
#include "hw/misc/unimp.h"
#include "hw/arm/ipod_touch_aes.h"
#include "hw/arm/ipod_touch_uart.h"
#include "hw/irq.h"
#include "sysemu/sysemu.h"
#include "sysemu/reset.h"
@@ -93,10 +95,12 @@ static void ipod_touch_memory_setup(MachineState *machine, MemoryRegion *sysmem,
allocate_ram(sysmem, "edgeic", EDGEIC_MEM_BASE, 0x1000);
allocate_ram(sysmem, "swi", SWI_MEM_BASE, 0x1000);
allocate_ram(sysmem, "h264", H264_MEM_BASE, 0x4000);
allocate_ram(sysmem, "mpvd", MPVD_MEM_BASE, 0x70000); // évite un kernel panic dans AppleMPVDDriver::setPowerStateGated
allocate_ram(sysmem, "unknown2", UNKNOWN2_MEM_BASE, 0x1000);
// load the bootrom (vrom)
uint8_t *file_data = NULL;
unsigned long fsize;
gsize fsize;
if (g_file_get_contents(nms->bootrom_path, (char **)&file_data, &fsize, NULL)) {
allocate_ram(sysmem, "vrom", 0x0, 0x20000);
address_space_rw(nsas, VROM_MEM_BASE, MEMTXATTRS_UNSPECIFIED, (uint8_t *)file_data, fsize, 1);
@@ -157,6 +161,19 @@ static void ipod_touch_set_nand_path(Object *obj, const char *value, Error **err
g_strlcpy(nms->nand_path, value, sizeof(nms->nand_path));
}
static bool ipod_touch_get_legacy_nor(Object *obj, Error **errp)
{
return ipod_touch_legacy_nor;
}
static void ipod_touch_set_legacy_nor(Object *obj, bool value, Error **errp)
{
ipod_touch_legacy_nor = value;
}
static bool ipod_touch_get_nand_write(Object *obj, Error **errp) { return ipod_touch_nand_write; }
static void ipod_touch_set_nand_write(Object *obj, bool value, Error **errp) { ipod_touch_nand_write = value; }
static void ipod_touch_instance_init(Object *obj)
{
object_property_add_str(obj, "bootrom", ipod_touch_get_bootrom_path, ipod_touch_set_bootrom_path);
@@ -167,6 +184,12 @@ static void ipod_touch_instance_init(Object *obj)
object_property_add_str(obj, "nand", ipod_touch_get_nand_path, ipod_touch_set_nand_path);
object_property_set_description(obj, "nand", "Path to the NAND files");
object_property_add_bool(obj, "legacy-nor", ipod_touch_get_legacy_nor, ipod_touch_set_legacy_nor);
object_property_add_bool(obj, "nand-write", ipod_touch_get_nand_write, ipod_touch_set_nand_write);
object_property_set_description(obj, "nand-write", "Persist NAND page programs and block erases (requires production VSVFL image; default off)");
object_property_set_description(obj, "legacy-nor", "The NOR image has unencrypted SHSH tags (old qemu-ios-generate-nor, default on)");
}
static inline qemu_irq s5l8900_get_irq(IPodTouchMachineState *s, int n)
@@ -236,6 +259,7 @@ static void ipod_touch_key_event(void *opaque, int keycode)
gpio_set_off(s->gpio_state->gpio_state, GPIO_BUTTON_VOLUP);
}
}
else return;
s->sysic->gpio_int_status[gpio_group] |= (1 << gpio_selector);
qemu_irq_raise(s->sysic->gpio_irqs[gpio_group]);
@@ -304,7 +328,7 @@ static void ipod_touch_machine_init(MachineState *machine)
nms->sysic = (IPodTouchSYSICState *) g_malloc0(sizeof(struct IPodTouchSYSICState));
memory_region_add_subregion(sysmem, SYSIC_MEM_BASE, &sysic_state->iomem);
busdev = SYS_BUS_DEVICE(dev);
for(int grp = 0; grp < GPIO_NUMINTGROUPS; grp++) {
for (int grp = 0; grp < G_N_ELEMENTS(S5L8900_GPIO_IRQS); grp++) {
sysbus_connect_irq(busdev, grp, s5l8900_get_irq(nms, S5L8900_GPIO_IRQS[grp]));
}
@@ -329,27 +353,27 @@ static void ipod_touch_machine_init(MachineState *machine)
sysbus_realize(busdev, &error_fatal);
sysbus_connect_irq(busdev, 0, s5l8900_get_irq(nms, S5L8720_SDIO_IRQ));
dev = exynos4210_uart_create(UART0_MEM_BASE, 256, 0, serial_hd(0), nms->irq[0][24]);
dev = ipod_touch_uart_create(UART0_MEM_BASE, serial_hd(0), nms->irq[0][24]);
if (!dev) {
hw_error("Failed to create UART0 device!");
}
dev = exynos4210_uart_create(UART1_MEM_BASE, 256, 1, serial_hd(1), nms->irq[0][25]);
dev = ipod_touch_uart_create(UART1_MEM_BASE, serial_hd(1), nms->irq[0][25]);
if (!dev) {
hw_error("Failed to create UART0 device!");
}
dev = exynos4210_uart_create(UART2_MEM_BASE, 256, 2, serial_hd(2), nms->irq[0][26]);
dev = ipod_touch_uart_create(UART2_MEM_BASE, serial_hd(2), nms->irq[0][26]);
if (!dev) {
hw_error("Failed to create UART0 device!");
}
dev = exynos4210_uart_create(UART3_MEM_BASE, 256, 3, serial_hd(3), nms->irq[0][27]);
dev = ipod_touch_uart_create(UART3_MEM_BASE, serial_hd(3), nms->irq[0][27]);
if (!dev) {
hw_error("Failed to create UART0 device!");
}
// dev = exynos4210_uart_create(UART4_MEM_BASE, 256, 4, serial_hd(4), nms->irq[0][28]);
// dev = ipod_touch_uart_create(UART4_MEM_BASE, serial_hd(4), nms->irq[0][28]);
// if (!dev) {
// printf("Failed to create uart4 device!\n");
// abort();
@@ -437,11 +461,14 @@ static void ipod_touch_machine_init(MachineState *machine)
sysbus_connect_irq(busdev, 0, s5l8900_get_irq(nms, S5L8720_I2C0_IRQ));
// init the PMU
I2CSlave * pmu = i2c_slave_create_simple(i2c_state->bus, "pcf50633", 0x73);
I2CSlave * pmu = i2c_slave_create_simple(i2c_state->bus, "d1759", 0x73);
// init the accelerometer
I2CSlave *accelerometer = i2c_slave_create_simple(i2c_state->bus, "lis302dl", 0x1D);
// init the audio codec (disabled because unused)
// I2CSlave *audio_codec = i2c_slave_create_simple(i2c_state->bus, "cs42l58", 0x4A);
// Init I2C1
dev = qdev_new("ipodtouch.i2c");
i2c_state = IPOD_TOUCH_I2C(dev);
@@ -451,6 +478,9 @@ static void ipod_touch_machine_init(MachineState *machine)
memory_region_add_subregion(sysmem, I2C1_MEM_BASE, &i2c_state->iomem);
sysbus_realize(busdev, &error_fatal);
sysbus_connect_irq(busdev, 0, s5l8900_get_irq(nms, S5L8720_I2C1_IRQ));
// Init the light sensor
I2CSlave *isl29003dl = i2c_slave_create_simple(i2c_state->bus, "isl29003dl", 0x44);
// init the Mikey
I2CSlave *cd327mikey = i2c_slave_create_simple(i2c_state->bus, "cd3272mikey", 0x39);
@@ -478,6 +508,7 @@ static void ipod_touch_machine_init(MachineState *machine)
IPodTouchMIPIDSIState *mipi_dsi_state = IPOD_TOUCH_MIPI_DSI(dev);
nms->mipi_dsi_state = mipi_dsi_state;
memory_region_add_subregion(sysmem, MIPI_DSI_MEM_BASE, &mipi_dsi_state->iomem);
sysbus_realize(SYS_BUS_DEVICE(dev), &error_fatal);
// init LCD
dev = qdev_new("ipodtouch.lcd");
@@ -503,6 +534,8 @@ static void ipod_touch_machine_init(MachineState *machine)
IPodTouchSHA1State *sha1_state = IPOD_TOUCH_SHA1(dev);
nms->sha1_state = sha1_state;
memory_region_add_subregion(sysmem, SHA1_MEM_BASE, &sha1_state->iomem);
sysbus_realize(SYS_BUS_DEVICE(dev), &error_fatal);
sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, s5l8900_get_irq(nms, S5L8720_SHA1_IRQ));
// init AES engine
dev = qdev_new("ipodtouch.aes");
@@ -551,4 +584,4 @@ static void ipod_touch_machine_types(void)
type_register_static(&ipod_touch_machine_info);
}
type_init(ipod_touch_machine_types)
type_init(ipod_touch_machine_types)
+91 -58
View File
@@ -1,4 +1,67 @@
#include "hw/arm/ipod_touch_aes.h"
#include "hw/arm/ipod_touch_gid_keys.h"
const char *ipod_touch_fw_build = NULL;
bool ipod_touch_legacy_nor = true;
/*
* Device tree patches, applied once iBoot has decrypted it (its signature has been checked by then).
* uart1 (/dev/tty.bluetooth, the PPP line to the host) loses its DMA channels: the serial driver then receives in PIO
* mode, which the emulated UART supports (the emulated DMA controller does not serve the UART).
*/
static uint32_t dt_node(uint8_t *d, uint32_t len, uint32_t o, int in_uart1)
{
if(o + 8 > len) return len;
uint32_t nprops = ldl_le_p(d + o), nchildren = ldl_le_p(d + o + 4);
o += 8;
uint32_t props = o;
int is_uart1 = 0;
for(uint32_t i = 0; i < nprops && o + 36 <= len; i++) {
uint32_t plen = ldl_le_p(d + o + 32) & 0x7fffffff;
if(!strcmp((char *)d + o, "name") && plen >= 6 && !memcmp(d + o + 36, "uart1", 6)) is_uart1 = 1;
o += 36 + ((plen + 3) & ~3);
}
if(is_uart1) {
for(uint32_t p = props, i = 0; i < nprops && p + 36 <= len; i++) {
uint32_t plen = ldl_le_p(d + p + 32) & 0x7fffffff;
if(!strcmp((char *)d + p, "dma-channels") || !strcmp((char *)d + p, "dma-types") || !strcmp((char *)d + p, "dma-parent")) {
d[p] = 'x';
printf("AES: device tree: uart1 %s disabled (PIO serial)\n", (char *)d + p);
}
p += 36 + ((plen + 3) & ~3);
}
}
for(uint32_t i = 0; i < nchildren && o < len; i++) o = dt_node(d, len, o, is_uart1);
return o;
}
static const IPodTouchGIDKey *ipod_touch_find_gid_key(const uint8_t *kbag, uint32_t len)
{
if(len < 32) return NULL;
for(size_t i = 0; i < ARRAY_SIZE(ipod_touch_gid_keys); i++) {
if(memcmp(ipod_touch_gid_keys[i].kbag, kbag, 32) == 0) return &ipod_touch_gid_keys[i];
}
return NULL;
}
// iBoot checks that the LZSS decompression produced exactly the expected number of bytes. NOP out the
// "cmp r5, r3; bne" (same code in iBoot-385.22 and iBoot-385.49, at a different address).
static void ipod_touch_patch_iboot_lzss_check(void)
{
static const uint8_t sig[] = { 0x04, 0x23, 0x00, 0xe0, 0x02, 0x23, 0x53, 0x43, 0x9d, 0x42, 0x20, 0xd1 };
const uint32_t iboot_base = 0x0ff00000, iboot_size = 0x29000;
uint8_t *iboot = g_malloc(iboot_size);
cpu_physical_memory_read(iboot_base, iboot, iboot_size);
for(uint32_t off = 0; off + sizeof(sig) <= iboot_size; off += 2) {
if(memcmp(iboot + off, sig, sizeof(sig)) == 0) {
uint32_t nop = 0;
cpu_physical_memory_write(iboot_base + off + 8, &nop, 4);
printf("AES: patched iBoot LZSS length check at 0x%08x\n", iboot_base + off + 8);
break;
}
}
g_free(iboot);
}
static uint64_t ipod_touch_aes_read(void *opaque, hwaddr offset, unsigned size)
{
@@ -23,7 +86,6 @@ static void ipod_touch_aes_write(void *opaque, hwaddr offset, uint64_t value, un
uint8_t *buf;
// fprintf(stderr, "%s: offset 0x%08x value 0x%08x\n", __FUNCTION__, offset, value);
uint32_t *data = malloc(sizeof(uint16_t) * 9);
switch(offset) {
case AES_GO:
@@ -48,72 +110,43 @@ static void ipod_touch_aes_write(void *opaque, hwaddr offset, uint64_t value, un
printf("In size: %d, out size: %d, in addr: 0x%08x, in buf: 0x%08x, out addr: 0x%08x, %d\n", aesop->insize, aesop->outsize, aesop->inaddr, ((uint32_t *)inbuf)[0], aesop->outaddr, aesop->gid_encryption_count);
if(aesop->keytype == AESGID) {
// Unfortunately, we don't have access to the GID key.
// However, we know that when the AES engine is invoked with the GID key type, it's for the decryption of the IMG file.
// Instead, we provide an hard-coded key as result and copy it to the output buffer.
// source: https://www.theiphonewiki.com/wiki/Sugar_Bowl_5F138_(iPod2,1)
if(aesop->gid_encryption_count == 0) { // LLB
char key[] = {
0xce, 0x97, 0xa7, 0xc8, 0x2e, 0xf8, 0x64, 0x67, 0x5e, 0xd3, 0x68, 0x05, 0x97, 0xec, 0x2a, 0xef, // IV
0x27, 0x73, 0x2a, 0x6b, 0xbf, 0xb1, 0x4a, 0x07, 0x25, 0x0a, 0x2e, 0x46, 0x82, 0xbf, 0x3c, 0xba, // key
};
for(int i = 0; i < aesop->insize; i++) { buf[i] = key[i]; }
// We don't have the GID key. The GID key is only used to decrypt the KBAG of an IMG3 image, so we
// look the KBAG up in the table of published keys and return its IV + key.
const IPodTouchGIDKey *gk = ipod_touch_find_gid_key(inbuf, aesop->insize);
if(gk) {
printf("AES: GID key for %s %s\n", gk->build, gk->image);
ipod_touch_fw_build = gk->build;
aesop->next_is_devicetree = strncmp(gk->image, "DeviceTree", 10) == 0;
memcpy(buf, gk->iv_key, MIN(aesop->insize, sizeof(gk->iv_key)));
} else {
printf("AES: unknown KBAG %08x (GID decryption #%d), output left zeroed\n", ((uint32_t *)inbuf)[0], aesop->gid_encryption_count);
memset(buf, 0, aesop->insize);
}
else if(aesop->gid_encryption_count == 1) { // iBoot
char key[] = {
0xb3, 0x63, 0x3a, 0xfb, 0xe0, 0x2e, 0x0e, 0x9b, 0xa4, 0xd7, 0x36, 0x6c, 0x47, 0xab, 0xe5, 0xa8, // IV
0x2d, 0x91, 0x6d, 0xab, 0xb6, 0xdf, 0xd4, 0x59, 0x4d, 0xbe, 0x36, 0x35, 0xb4, 0xc7, 0x16, 0x62, // key
};
for(int i = 0; i < aesop->insize; i++) { buf[i] = key[i]; }
}
else if(aesop->gid_encryption_count == 2) { // apple logo
// very ugly - we patch out here the LZSS check
data[0] = 0x0; // NOP
cpu_physical_memory_write(0x0ff119f0, (uint8_t *)data, 4);
char key[] = {
0x64, 0x23, 0x8f, 0xb0, 0x32, 0x91, 0x42, 0x25, 0x22, 0xb5, 0xdd, 0x28, 0x3f, 0xc3, 0x89, 0x5c, // IV
0x85, 0x9f, 0xd4, 0xd3, 0x82, 0xb8, 0x38, 0x51, 0x56, 0xfc, 0x58, 0x1a, 0x7f, 0x1d, 0x97, 0x22, // key
};
for(int i = 0; i < aesop->insize; i++) { buf[i] = key[i]; }
}
else if(aesop->gid_encryption_count == 3) { // kernelcache
char key[] = {
0xa1, 0x91, 0x29, 0x12, 0x90, 0xd4, 0x87, 0xff, 0x07, 0x31, 0x96, 0x9c, 0x5f, 0xc8, 0xd9, 0x18, // IV
0x0e, 0x4d, 0x23, 0xfa, 0x67, 0x59, 0x99, 0xd5, 0x95, 0x9d, 0xd1, 0x0c, 0x8d, 0xd7, 0x3d, 0x20, // key
};
for(int i = 0; i < aesop->insize; i++) { buf[i] = key[i]; }
}
else if(aesop->gid_encryption_count == 4) { // device tree
char key[] = {
0xcc, 0xff, 0x63, 0x4e, 0xe1, 0x27, 0x35, 0xf0, 0x19, 0x16, 0xc4, 0xa6, 0xb2, 0x0f, 0xf1, 0x45, // IV
0xe1, 0x7b, 0xcd, 0x56, 0x8d, 0xf1, 0xcd, 0xdc, 0x8f, 0xec, 0xbf, 0x54, 0x87, 0xd5, 0xc3, 0xce, // key
};
for(int i = 0; i < aesop->insize; i++) { buf[i] = key[i]; }
// the image after iBoot is decompressed by iBoot: skip its length check after the LZSS decompression
if(aesop->gid_encryption_count == 2) {
ipod_touch_patch_iboot_lzss_check();
}
aesop->gid_encryption_count++;
}
else {
AES_cbc_encrypt(inbuf, buf, aesop->insize, &aesop->decryptKey, (uint8_t *)aesop->ivec, AES_DECRYPT);
// IMG3 payloads are encrypted in whole AES blocks only: a trailing partial block is stored in clear
// (e.g. the kernelcache and the device tree). Decrypt the whole blocks and copy the rest unchanged.
uint32_t full = aesop->insize & ~(AES_BLOCK_SIZE - 1);
AES_cbc_encrypt(inbuf, buf, full, &aesop->decryptKey, (uint8_t *)aesop->ivec, AES_DECRYPT);
memcpy(buf + full, inbuf + full, aesop->insize - full);
// the payload following the device tree KBAG is the device tree itself
if(aesop->next_is_devicetree && aesop->insize > 0x1000) {
dt_node(buf, aesop->insize, 0, 0);
aesop->next_is_devicetree = false;
}
}
if(aesop->outaddr != 0x220100ac && aesop->outaddr != 0x0bf08468 && aesop->outaddr != 0x0fb9bcdc) { // TODO very ugly hack - for the RSA key decryption, it seems that doing nothing results in the correct decryption key??
// BUG: after decrypting the kernel, we update the Adler CRC code and number of expected bytes.
if(aesop->outaddr == 0x0b000020) {
uint32_t *cast_buf = (uint32_t *)buf;
cast_buf[2] = 0xA7886041; // adler
cast_buf[3] = 0xF5D37E00; // 8311797 in big endian
}
// BUG: after decrypting the device tree, the last few bytes are incorrect
if(aesop->outaddr == 0x0bf00020) {
uint32_t *cast_buf = (uint32_t *)buf;
cast_buf[8429] = 0x4; // setting the size of the AAPL,phandle property to 4
cast_buf[8430] = 0x0011C4F0; // set the right handle
}
// the NOR images generated by older versions of qemu-ios-generate-nor have an unencrypted SHSH tag: leave it
// as is (only the 5F138 NOR image published with qemu-ios is concerned)
bool legacy_shsh = aesop->outaddr == 0x220100ac || aesop->outaddr == 0x0bf08468 || aesop->outaddr == 0x0fb9bcdc;
if(!(legacy_shsh && ipod_touch_legacy_nor)) {
cpu_physical_memory_write((aesop->outaddr), buf, aesop->insize);
}
+54
View File
@@ -0,0 +1,54 @@
#include "hw/arm/ipod_touch_cs42l58.h"
static int cs42l58_event(I2CSlave *i2c, enum i2c_event event)
{
return 0;
}
static uint8_t cs42l58_recv(I2CSlave *i2c)
{
CS42L58State *s = CS42L58(i2c);
printf("Reading stereo codec register %d\n", s->cmd);
switch(s->cmd) {
default:
return 0;
}
}
static int cs42l58_send(I2CSlave *i2c, uint8_t data)
{
CS42L58State *s = CS42L58(i2c);
s->cmd = data;
printf("Writing stereo codec register %d\n", s->cmd);
return 0;
}
static void cs42l58_init(Object *obj)
{
}
static void cs42l58_class_init(ObjectClass *klass, void *data)
{
I2CSlaveClass *k = I2C_SLAVE_CLASS(klass);
k->event = cs42l58_event;
k->recv = cs42l58_recv;
k->send = cs42l58_send;
}
static const TypeInfo cs42l58_info = {
.name = TYPE_CS42L58,
.parent = TYPE_I2C_SLAVE,
.instance_init = cs42l58_init,
.instance_size = sizeof(CS42L58State),
.class_init = cs42l58_class_init,
};
static void cs42l58_register_types(void)
{
type_register_static(&cs42l58_info);
}
type_init(cs42l58_register_types)
+156 -24
View File
@@ -1,4 +1,8 @@
#include "hw/arm/ipod_touch_fmss.h"
#include "qemu/log.h"
uint64_t temp_storage[512];
bool ipod_touch_nand_write = false;
static uint8_t find_bit_index(uint8_t num) {
int index = 0;
@@ -15,24 +19,33 @@ static void write_chip_info(IPodTouchFMSSState *s)
cpu_physical_memory_write(s->reg_cinfo_target_addr, &chipid, 0x10);
}
static void dump_registers(IPodTouchFMSSState *s) {
printf("FMSS_PAGES_IN_ADDR: 0x%08x\n", s->reg_pages_in_addr);
printf("FMSS_CS_BUF_ADDR: 0x%08x\n", s->reg_cs_buf_addr);
printf("FMSS_NUM_PAGES: 0x%08x\n", s->reg_num_pages);
}
static void read_nand_pages(IPodTouchFMSSState *s)
{
// boot args
const char *boot_args = "kextlog=0xfff debug=0x8 cpus=1 rd=disk0s1 serial=1 pmu-debug=0x1 io=0xffff8fff debug-usb=0xffffffff amfi_allow_any_signature=1"; // if not const then overwritten
const char *boot_args = "kextlog=0xfff debug=0x8 cpus=1 rd=disk0s1 serial=1 pmu-debug=0x1 io=0xffff8fff debug-usb=0xffffffff amfi_allow_any_signature=1 -v zalloc_debug"; // if not const then overwritten
cpu_physical_memory_write(0x0ff2a584, boot_args, strlen(boot_args));
// patch iBoot - we want to inject the bluetooth MAC address which is located as sub-node of uart1 and not uart3 in the device tree...
const char *chr = "arm-io/uart1/bluetooth";
cpu_physical_memory_write(0x0ff2206c, chr, strlen(chr));
// (0x0ff2206c in iBoot-385.22, 0x0ff22084 in iBoot-385.49: look the string up once)
static bool bt_path_patched = false;
if(!bt_path_patched) {
const uint32_t iboot_base = 0x0ff00000, iboot_size = 0x29000;
const char *orig = "arm-io/uart3/bluetooth";
char *iboot = g_malloc(iboot_size);
cpu_physical_memory_read(iboot_base, iboot, iboot_size);
char *hit = memmem(iboot, iboot_size, orig, strlen(orig) + 1);
if(hit) {
const char *chr = "arm-io/uart1/bluetooth";
cpu_physical_memory_write(iboot_base + (hit - iboot), chr, strlen(chr));
printf("FMSS: patched iBoot bluetooth node path at 0x%08lx\n", iboot_base + (hit - iboot));
}
bt_path_patched = true;
g_free(iboot);
}
int page_out_buf_ind = 0;
//dump_registers(s);
bool all_erased = s->reg_num_pages != 0;
s->read_pending = true;
//printf("Start CMD...\n");
for(int page_ind = 0; page_ind < s->reg_num_pages; page_ind++) {
uint32_t page_nr = 0;
@@ -45,8 +58,7 @@ static void read_nand_pages(IPodTouchFMSSState *s)
if(cs > 3) {
printf("CS %d invalid! (original CS: %d, reading page %d)\n", cs, og_cs, page_nr);
dump_registers(s);
hw_error("CS %d invalid!", cs);
hw_error("CS %d invalid!", cs);
}
// prepare the page
@@ -55,13 +67,12 @@ static void read_nand_pages(IPodTouchFMSSState *s)
struct stat st = {0};
if (stat(filename, &st) == -1) {
// page storage does not exist - initialize an empty buffer
memset(s->page_buffer, 0, NAND_BYTES_PER_PAGE);
memset(s->page_spare_buffer, 0, NAND_BYTES_PER_SPARE);
memset(s->page_buffer, 0xff, NAND_BYTES_PER_PAGE);
memset(s->page_spare_buffer, 0xff, NAND_BYTES_PER_SPARE);
uint32_t *buf_cst = (uint32_t *) s->page_spare_buffer;
buf_cst[2] = 0x00FF00FF;
}
else {
all_erased = false;
FILE *f = fopen(filename, "rb");
if (f == NULL) { hw_error("Unable to read file!"); }
fread(s->page_buffer, sizeof(char), NAND_BYTES_PER_PAGE, f);
@@ -80,13 +91,112 @@ static void read_nand_pages(IPodTouchFMSSState *s)
}
// finally, write the spare
cpu_physical_memory_write(s->reg_page_spare_out_addr + page_ind * 0xc, s->page_spare_buffer, NAND_BYTES_PER_SPARE);
cpu_physical_memory_write(s->reg_page_spare_out_addr + page_ind * 0xc, s->page_spare_buffer, 12);
}
/* C30 bit 29 with no ECC correction bits makes the driver return
* kIOReturnNotFound (blank NAND), which FTL recovery relies on. */
s->reg_result = all_erased ? 0x20000000 : 0;
}
/* The program script consumes a NAND command/address pair from D10.
* D08 is its byte length; D18 is left over from the last read request.
* The low nibble selects a CE, bits 16..23 contain the NAND command.
*/
static void write_nand_pages(IPodTouchFMSSState *s)
{
if (s->shadow[0xd08 / 4] != 8) {
hw_error("FMSS: unsupported program command length");
}
/* A zero command terminates the list. D18 is not a program count. */
for (unsigned page = 0; page <= NAND_MAX_TRANSFER_PAGES; page++) {
uint32_t cmd[2], data_addr[2];
cpu_physical_memory_read(s->reg_cs_buf_addr + page * 8, cmd, sizeof(cmd[0]));
if (!cmd[0]) {
return;
}
if (page == NAND_MAX_TRANSFER_PAGES) {
hw_error("FMSS: unterminated program list");
}
cpu_physical_memory_read(s->reg_cs_buf_addr + page * 8 + 4,
&cmd[1], sizeof(cmd[1]));
uint32_t cs_mask = cmd[0] & 0xf;
if (!cs_mask || (cs_mask & (cs_mask - 1)) ||
((cmd[0] >> 16) & 0xfe) != 0x80 || cmd[1] >= NAND_PAGES_PER_CHIP) {
hw_error("FMSS: unsupported program %08x %08x", cmd[0], cmd[1]);
}
unsigned cs = find_bit_index(cs_mask);
cpu_physical_memory_read(s->reg_pages_out_addr + page * 8, data_addr, sizeof(data_addr));
for (int i = 0; i < 2; i++) {
cpu_physical_memory_read(data_addr[i],
s->page_buffer + i * NAND_BYTES_PER_PAGE / 2,
NAND_BYTES_PER_PAGE / 2);
}
memset(s->page_spare_buffer, 0xff, NAND_BYTES_PER_SPARE);
cpu_physical_memory_read(s->reg_page_spare_out_addr + page * 12, s->page_spare_buffer, 12);
g_autofree char *filename = g_strdup_printf("%s/cs%u/%u.page",
s->nand_path, cs, cmd[1]);
FILE *f = fopen(filename, "wb");
if (!f) {
hw_error("FMSS: cannot write %s", filename);
}
bool ok = fwrite(s->page_buffer, 1, NAND_BYTES_PER_PAGE, f) == NAND_BYTES_PER_PAGE;
ok &= fwrite(s->page_spare_buffer, 1, NAND_BYTES_PER_SPARE, f) == NAND_BYTES_PER_SPARE;
int close_result = fclose(f);
if (!ok || close_result) {
hw_error("FMSS: failed writing %s", filename);
}
qemu_log_mask(LOG_UNIMP, "fmss: PROGRAM cs%u page %u\n", cs, cmd[1]);
}
hw_error("FMSS: unterminated program list");
}
/* Identify the sequencer's erase operation by its NAND 60h/D0h pair,
* independently of where iBoot or the kernel allocated the script.
* The other sequencer operations retain the existing high-level emulation.
*/
static bool erase_nand_blocks(IPodTouchFMSSState *s)
{
uint32_t header[8];
cpu_physical_memory_read(s->shadow[0xc04 / 4], header, sizeof(header));
if (header[6] != 0x01000c4c || header[7] > 8192 || (header[7] & 7)) {
return false;
}
bool setup = false, confirm = false;
for (unsigned offset = 0; offset < header[7]; offset += 8) {
uint32_t op[2];
cpu_physical_memory_read(s->shadow[0xc04 / 4] + offset, op, sizeof(op));
if (op[0] == 0x01000008) {
setup |= op[1] == 0x60;
confirm |= op[1] == 0xd0;
}
}
if (!setup || !confirm) {
return false;
}
if (s->reg_num_pages != 1) {
hw_error("FMSS: unsupported erase count %u", s->reg_num_pages);
}
uint32_t cs, page;
cpu_physical_memory_read(s->reg_cs_buf_addr, &cs, sizeof(cs));
cpu_physical_memory_read(s->reg_pages_in_addr, &page, sizeof(page));
/* Erase uses a CE index, unlike read's mask and program's packed command. */
if (cs >= 4 || page >= NAND_PAGES_PER_CHIP || (page & (NAND_PAGES_PER_BLOCK - 1))) {
hw_error("FMSS: invalid erase cs%u page %u", cs, page);
}
for (unsigned i = 0; i < NAND_PAGES_PER_BLOCK; i++) {
g_autofree char *filename = g_strdup_printf("%s/cs%u/%u.page",
s->nand_path, cs, page + i);
if (unlink(filename) && errno != ENOENT) {
hw_error("FMSS: cannot erase %s", filename);
}
}
qemu_log_mask(LOG_UNIMP, "fmss: ERASE cs%u block %u\n", cs, page / NAND_PAGES_PER_BLOCK);
return true;
}
static uint64_t ipod_touch_fmss_read(void *opaque, hwaddr addr, unsigned size)
{
//fprintf(stderr, "%s: read from location 0x%08x\n", __func__, addr);
//fprintf(stderr, "%s: read from location 0x%08lx\n", __func__, addr);
IPodTouchFMSSState *s = (IPodTouchFMSSState *)opaque;
switch(addr)
@@ -101,8 +211,10 @@ static uint64_t ipod_touch_fmss_read(void *opaque, hwaddr addr, unsigned size)
return (0x1 << 30);
case 0xD00:
return 42;
case 0x00000C30:
return s->reg_result;
default:
// hw_error("%s: read invalid location 0x%08x.\n", __func__, addr);
qemu_log_mask(LOG_UNIMP, "%s: read invalid location 0x%08" HWADDR_PRIx "\n", __func__, addr);
break;
}
return 0;
@@ -111,20 +223,32 @@ static uint64_t ipod_touch_fmss_read(void *opaque, hwaddr addr, unsigned size)
static void ipod_touch_fmss_write(void *opaque, hwaddr addr, uint64_t val, unsigned size)
{
IPodTouchFMSSState *s = (IPodTouchFMSSState *)opaque;
//printf("%s: writing 0x%08x to 0x%08x\n", __func__, val, addr);
if(addr < 0x1000) s->shadow[addr / 4] = val;
if(qemu_loglevel_mask(LOG_UNIMP))
qemu_log("fmss: write 0x%03x = 0x%08x\n", (unsigned)addr, (unsigned)val);
switch(addr) {
case 0xC00:
if(val == 0x0000ffb5) { s->reg_cs_irq_bit = 1; } // TODO ugly and hard-coded
if(val == 0xfff5) { s->reg_cs_irq_bit = 1; qemu_set_irq(s->irq, 1); }
if(val == 0xfff5) {
if (!s->read_pending) {
s->reg_result = 0;
}
s->read_pending = false;
if (ipod_touch_nand_write) {
erase_nand_blocks(s);
}
s->reg_cs_irq_bit = 1; qemu_set_irq(s->irq, 1);
}
break;
case FMSS__CS_IRQ:
s->reg_cs_irq_bit = 0;
qemu_set_irq(s->irq, 0);
break;
case FMSS_CINFO_TARGET_ADDR:
// le même registre sert aussi au numéro de page dans les séquences d'écriture : pas une adresse RAM
s->reg_cinfo_target_addr = val;
write_chip_info(s);
if(val >= 0x08000000) write_chip_info(s);
break;
case FMSS_PAGES_IN_ADDR:
s->reg_pages_in_addr = val;
@@ -146,8 +270,16 @@ static void ipod_touch_fmss_write(void *opaque, hwaddr addr, uint64_t val, unsig
break;
case 0xD38:
if(s->reg_csgenrc == 0xa01) { read_nand_pages(s); }
else { printf("NAND write not suported yet!\n"); }
/* Programs use a packed command list, not the read page/CE arrays. */
else if(s->reg_csgenrc == 0xa02 && ipod_touch_nand_write) { write_nand_pages(s); }
else {
qemu_log_mask(LOG_UNIMP, "fmss: unhandled command csgenrc 0x%x go 0x%x pages %u in 0x%x cs 0x%x out 0x%x spare 0x%x\n",
s->reg_csgenrc, (unsigned)val, s->reg_num_pages, s->reg_pages_in_addr, s->reg_cs_buf_addr, s->reg_pages_out_addr, s->reg_page_spare_out_addr);
}
break;
default:
//printf("%s unknown write %lx to %lx\n", __func__, val, addr);
break;
}
}
+101
View File
@@ -0,0 +1,101 @@
#include "hw/arm/ipod_touch_isl29003dl.h"
static int isl29003dl_event(I2CSlave *i2c, enum i2c_event event)
{
ISL29003DLState *s = ISL29003DL(i2c);
printf("%s Got event %d\n", __func__, event);
if (event == I2C_START_SEND)
s->ready = 1;
return 0;
}
static uint8_t isl29003dl_recv(I2CSlave *i2c)
{
ISL29003DLState *s = ISL29003DL(i2c);
printf("Reading lightsensor register %d\n", s->cmd);
int res = 0;
switch(s->cmd) {
case LIGHTSENSOR_COMMAND:
res = s->command;
break;
case LIGHTSENSOR_CONTROL:
res = s->ctrl;
break;
case LIGHTSENSOR_LSB_SENSOR:
res = s->lsb_sensor;
break;
case LIGHTSENSOR_MSB_SENSOR:
res = s->msb_sensor;
break;
default:
res = 0;
printf("%s unknown register %d\n", __func__, s->cmd);
}
s->cmd += 1;
return res;
}
static int isl29003dl_send(I2CSlave *i2c, uint8_t data)
{
ISL29003DLState *s = ISL29003DL(i2c);
if (s->ready)
{
s->curreg = data;
s->ready = 0;
printf("%s Lightsensor ready\n", __func__);
}
else
{
switch(s->curreg++)
{
case LIGHTSENSOR_COMMAND:
s->command = data;
if ((s->command >> 7) == 1)
{
s->lsb_sensor = 0xE;
s->msb_sensor = 0xE << 4;
s->it_hi = 0xF;
s->it_lo = 0x0;
}
break;
default:
printf("%s unknown register %d\n", __func__, s->curreg-1);
}
}
printf("Writing lightsensor data %d\n", s->cmd);
return 0;
}
static void isl29003dl_init(Object *obj)
{
}
static void isl29003dl_class_init(ObjectClass *klass, void *data)
{
I2CSlaveClass *k = I2C_SLAVE_CLASS(klass);
k->event = isl29003dl_event;
k->recv = isl29003dl_recv;
k->send = isl29003dl_send;
}
static const TypeInfo isl29003dl_info = {
.name = TYPE_ISL29003DL,
.parent = TYPE_I2C_SLAVE,
.instance_init = isl29003dl_init,
.instance_size = sizeof(ISL29003DLState),
.class_init = isl29003dl_class_init,
};
static void isl29003dl_register_types(void)
{
type_register_static(&isl29003dl_info);
}
type_init(isl29003dl_register_types)
+44 -15
View File
@@ -3,9 +3,11 @@
#include "ui/console.h"
#include "hw/display/framebuffer.h"
int lcd_brightness = 255;
static uint64_t ipod_touch_lcd_read(void *opaque, hwaddr addr, unsigned size)
{
//printf("%s: read from location 0x%08x\n", __func__, addr);
// printf("%s: read from location 0x%08x\n", __func__, addr);
IPodTouchLCDState *s = (IPodTouchLCDState *)opaque;
switch(addr)
@@ -14,8 +16,10 @@ static uint64_t ipod_touch_lcd_read(void *opaque, hwaddr addr, unsigned size)
return 2;
case 0x4:
return s->lcd_con;
case 0x8:
return s->int_enable;
case 0xC:
return 0x1; //s->unknown1;
return s->int_status;
case 0x20:
return s->w1_display_depth_info;
case 0x24:
@@ -26,8 +30,10 @@ static uint64_t ipod_touch_lcd_read(void *opaque, hwaddr addr, unsigned size)
return s->w1_display_resolution_info;
case 0x1b10:
return 2;
case 0x1b14:
return 0x3;
default:
// hw_error("%s: read invalid location 0x%08x.\n", __func__, addr);
printf("%s: read invalid location 0x%08x.\n", __func__, addr);
break;
}
return 0;
@@ -36,15 +42,20 @@ static uint64_t ipod_touch_lcd_read(void *opaque, hwaddr addr, unsigned size)
static void ipod_touch_lcd_write(void *opaque, hwaddr addr, uint64_t val, unsigned size)
{
IPodTouchLCDState *s = (IPodTouchLCDState *)opaque;
//printf("%s: writing 0x%08x to 0x%08x\n", __func__, val, addr);
// printf("%s: writing 0x%08x to 0x%08x\n", __func__, val, addr);
switch(addr) {
case 0x4:
s->lcd_con = val;
break;
case 0x8:
s->int_enable = val;
qemu_set_irq(s->irq, !!(s->int_status & s->int_enable));
break;
case 0xC:
s->unknown1 = val;
qemu_irq_lower(s->irq);
/* Acquittement W1C, indépendant du masque d'interruptions. */
s->int_status &= ~val;
qemu_set_irq(s->irq, !!(s->int_status & s->int_enable));
break;
case 0x20:
s->w1_display_depth_info = val;
@@ -61,6 +72,11 @@ static void ipod_touch_lcd_write(void *opaque, hwaddr addr, uint64_t val, unsign
}
}
void lcd_changebrightness(int brightness)
{
lcd_brightness = brightness & 0xFF;
}
static void lcd_invalidate(void *opaque)
{
IPodTouchLCDState *s = opaque;
@@ -69,6 +85,7 @@ static void lcd_invalidate(void *opaque)
static void draw_line32_32(void *opaque, uint8_t *d, const uint8_t *s, int width, int deststep)
{
// IPodTouchLCDState *lcd = (IPodTouchLCDState *) opaque;
uint8_t r, g, b;
do {
@@ -77,8 +94,8 @@ static void draw_line32_32(void *opaque, uint8_t *d, const uint8_t *s, int width
b = s[0];
g = s[1];
r = s[2];
//printf("R: %d, G: %d, B: %d\n", r, g, b);
((uint32_t *) d)[0] = rgb_to_pixel32(r, g, b);
// printf("R: %d, G: %d, B: %d, A: %d\n", r, g, b, lcd_brightness);
((uint32_t *) d)[0] = rgb_to_pixel32(round((float)r * ((float)lcd_brightness / 255.0f)), round((float)g * ((float)lcd_brightness / 255.0f)), round((float)b * ((float)lcd_brightness / 255.0f)));
s += 4;
d += 4;
} while (-- width != 0);
@@ -86,7 +103,7 @@ static void draw_line32_32(void *opaque, uint8_t *d, const uint8_t *s, int width
static void lcd_refresh(void *opaque)
{
//fprintf(stderr, "%s: refreshing LCD screen\n", __func__);
// printf("%s: refreshing LCD screen\n", __func__);
IPodTouchLCDState *lcd = (IPodTouchLCDState *) opaque;
DisplaySurface *surface = qemu_console_surface(lcd->con);
@@ -141,15 +158,13 @@ static const GraphicHwOps gfx_ops = {
static void ipod_touch_lcd_mouse_event(void *opaque, int x, int y, int z, int buttons_state)
{
//printf("CLICKY %d %d %d %d\n", x, y, z, buttons_state);
// printf("x %d y %d z %d state %d\n", x, y, z, buttons_state);
// convert x and y to fractional numbers
float fx = x / pow(2, 15);
float fy = 1 - y / pow(2, 15);
IPodTouchLCDState *lcd = (IPodTouchLCDState *) opaque;
lcd->mt->prev_touch_x = lcd->mt->touch_x;
lcd->mt->prev_touch_y = lcd->mt->touch_y;
lcd->mt->touch_x = fx;
lcd->mt->touch_y = fy;
@@ -165,9 +180,10 @@ static void refresh_timer_tick(void *opaque)
{
IPodTouchLCDState *s = (IPodTouchLCDState *)opaque;
qemu_irq_raise(s->irq);
s->int_status |= 1;
qemu_set_irq(s->irq, !!(s->int_status & s->int_enable));
timer_mod(s->refresh_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + NANOSECONDS_PER_SECOND / LCD_REFRESH_RATE_FREQUENCY);
timer_mod(s->refresh_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + NANOSECONDS_PER_SECOND / 60);//LCD_REFRESH_RATE_FREQUENCY);
}
static void ipod_touch_lcd_realize(DeviceState *dev, Error **errp)
@@ -195,11 +211,24 @@ static void ipod_touch_lcd_init(Object *obj)
sysbus_init_irq(sbd, &s->irq);
}
static void ipod_touch_lcd_reset(DeviceState *dev)
{
IPodTouchLCDState *s = IPOD_TOUCH_LCD(dev);
s->lcd_con = s->int_enable = s->int_status = 0;
s->w1_display_resolution_info = s->w1_framebuffer_base = 0;
s->w1_hspan = s->w1_display_depth_info = 0;
s->invalidate = 1;
lcd_brightness = 255;
qemu_irq_lower(s->irq);
}
static void ipod_touch_lcd_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
dc->realize = ipod_touch_lcd_realize;
dc->reset = ipod_touch_lcd_reset;
}
static const TypeInfo ipod_touch_lcd_info = {
@@ -215,4 +244,4 @@ static void ipod_touch_machine_types(void)
type_register_static(&ipod_touch_lcd_info);
}
type_init(ipod_touch_machine_types)
type_init(ipod_touch_machine_types)
+15 -2
View File
@@ -12,8 +12,21 @@ static uint8_t lis302dl_recv(I2CSlave *i2c)
switch(s->cmd) {
case ACCEL_WHOAMI:
return ACCEL_WHOAMI_VALUE; // whoami value
return ACCEL_WHOAMI_VALUE;
case ACCEL_OUT_X:
return s->ctrl_reg1 == 1 ? s->out_x : 0;
case ACCEL_OUT_Y:
return s->ctrl_reg1 << 1 == 1 ? s->out_y : 0;
case ACCEL_OUT_Z:
return s->ctrl_reg1 << 2 == 1 ? s->out_z : 0;
case ACCEL_CTRL_REG1:
return s->ctrl_reg1;
case ACCEL_CTRL_REG2:
return s->ctrl_reg2;
case ACCEL_CTRL_REG3:
return s->ctrl_reg3;
default:
printf("%s Unknown register %d\n", __func__, s->cmd);
return 0;
}
}
@@ -52,4 +65,4 @@ static void lis302dl_register_types(void)
type_register_static(&lis302dl_info);
}
type_init(lis302dl_register_types)
type_init(lis302dl_register_types)
+24 -5
View File
@@ -1,3 +1,4 @@
#include "hw/arm/ipod_touch_aes.h"
#include "hw/arm/ipod_touch_mbx.h"
static uint32_t reverse_byte_order(uint32_t value) {
@@ -9,7 +10,9 @@ static uint32_t reverse_byte_order(uint32_t value) {
static uint64_t ipod_touch_mbx1_read(void *opaque, hwaddr addr, unsigned size)
{
printf("%s: read from location 0x%08x\n", __func__, addr);
IPodTouchMBXState *s = (IPodTouchMBXState *)opaque;
if (addr != 0x1020)
printf("%s: read from location 0x%08x\n", __func__, addr);
switch(addr)
{
case 0x12c:
@@ -17,7 +20,7 @@ static uint64_t ipod_touch_mbx1_read(void *opaque, hwaddr addr, unsigned size)
case 0xf00:
return (2 << 0x10) | (1 << 0x18); // seems to be some kind of identifier
case 0x1020:
return 0x10000;
return s->addr != 0x0 ? s->addr : 0x10000;
default:
break;
}
@@ -28,10 +31,21 @@ static void ipod_touch_mbx1_write(void *opaque, hwaddr addr, uint64_t val, unsig
{
IPodTouchMBXState *s = (IPodTouchMBXState *)opaque;
fprintf(stderr, "%s: writing 0x%08x to 0x%08x\n", __func__, val, addr);
switch(addr)
{
case 0x1020:
s->addr = val;
break;
}
}
static void patch_kernel()
static void patch_kernel(bool alreadypatched)
{
if (alreadypatched) return;
// the addresses below are those of the 5F138 (iPhone OS 2.1.1) kernel
if (!ipod_touch_fw_build || strcmp(ipod_touch_fw_build, "5F138") != 0) return;
alreadypatched = 1;
// patch the loading of the AppleBCM4325 driver
char *bcm4325_vars = "test";
@@ -91,11 +105,16 @@ static void patch_kernel()
static uint64_t ipod_touch_mbx2_read(void *opaque, hwaddr addr, unsigned size)
{
IPodTouchMBXState *s = (IPodTouchMBXState *)opaque;
printf("%s: read from location 0x%08x\n", __func__, addr);
switch(addr)
{
case 0xC:
patch_kernel();
patch_kernel(s->alreadypatched);
break;
case 0x4:
return 0xFF;
break;
default:
break;
}
@@ -149,4 +168,4 @@ static void ipod_touch_mbx_register_types(void)
type_register_static(&ipod_touch_mbx_type_info);
}
type_init(ipod_touch_mbx_register_types)
type_init(ipod_touch_mbx_register_types)
+23 -5
View File
@@ -2,13 +2,18 @@
static uint64_t ipod_touch_mipi_dsi_read(void *opaque, hwaddr addr, unsigned size)
{
fprintf(stderr, "%s: read from location 0x%08x\n", __func__, addr);
if (addr != 0x00000)
fprintf(stderr, "%s: read from location 0x%08lx\n", __func__, addr);
IPodTouchMIPIDSIState *s = (IPodTouchMIPIDSIState *)opaque;
switch(addr)
{
case 0x0:
return 0x103 | rDSIM_STATUS_TxReadyHsClk;
/* The panel driver waits for this bit to clear when powering down. */
return 0x103 | ((s->clkctrl_reg & DSIM_CLKCTRL_TX_REQUEST_HSCLK) ?
rDSIM_STATUS_TxReadyHsClk : 0);
case REG_CLKCTRL:
return s->clkctrl_reg;
case REG_INTSRC:
return rDSIM_INTSRC_RxDatDone;
case REG_RXFIFO:
@@ -24,7 +29,7 @@ static uint64_t ipod_touch_mipi_dsi_read(void *opaque, hwaddr addr, unsigned siz
case REG_FIFOCTRL:
return rDSIM_FIFOCTRL_EmptyHSfr;
default:
// hw_error("%s: read invalid location 0x%08x.\n", __func__, addr);
printf("%s: read invalid location 0x%08lx.\n", __func__, addr);
break;
}
return 0;
@@ -33,13 +38,16 @@ static uint64_t ipod_touch_mipi_dsi_read(void *opaque, hwaddr addr, unsigned siz
static void ipod_touch_mipi_dsi_write(void *opaque, hwaddr addr, uint64_t val, unsigned size)
{
IPodTouchMIPIDSIState *s = (IPodTouchMIPIDSIState *)opaque;
fprintf(stderr, "%s: writing 0x%08x to 0x%08x\n", __func__, val, addr);
fprintf(stderr, "%s: writing 0x%08lx to 0x%08lx\n", __func__, val, addr);
switch(addr)
{
case REG_PKTHDR:
s->pkthdr_reg = val;
break;
case REG_CLKCTRL:
s->clkctrl_reg = val;
break;
default:
break;
}
@@ -69,11 +77,21 @@ static void ipod_touch_mipi_dsi_init(Object *obj)
s->return_panel_id = 0;
}
static void ipod_touch_mipi_dsi_reset(DeviceState *dev)
{
IPodTouchMIPIDSIState *s = IPOD_TOUCH_MIPI_DSI(dev);
s->pkthdr_reg = s->clkctrl_reg = 0;
s->return_panel_id = false;
qemu_irq_lower(s->irq);
}
static void ipod_touch_mipi_dsi_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
dc->realize = ipod_touch_mipi_dsi_realize;
dc->reset = ipod_touch_mipi_dsi_reset;
}
static const TypeInfo ipod_touch_mipi_dsi_info = {
@@ -89,4 +107,4 @@ static void ipod_touch_machine_types(void)
type_register_static(&ipod_touch_mipi_dsi_info);
}
type_init(ipod_touch_machine_types)
type_init(ipod_touch_machine_types)
+132 -32
View File
@@ -1,4 +1,6 @@
#include "hw/arm/ipod_touch_multitouch.h"
#include "qemu/log.h"
#include "qemu/bswap.h"
static void prepare_interface_version_response(IPodTouchMultitouchState *s) {
memset(s->out_buffer + 1, 0, 15);
@@ -62,7 +64,9 @@ static void prepare_report_info_response(IPodTouchMultitouchState *s, uint8_t re
report_length = MT_REPORT_SENSOR_DIMENSIONS_SIZE;
}
else {
hw_error("Unknown report ID 0x%02x\n", report_id);
qemu_log_mask(LOG_GUEST_ERROR, "%s: rapport inconnu 0x%02x\n",
__func__, report_id);
s->out_buffer[2] = 1;
}
s->out_buffer[3] = (report_length & 0xFF);
@@ -98,12 +102,13 @@ static void prepare_short_control_response(IPodTouchMultitouchState *s, uint8_t
s->out_buffer[3] = MT_SENSOR_REGION_PARAM;
}
else if(report_id == MT_REPORT_SENSOR_DIMENSIONS) {
uint32_t *ob_int32 = (uint32_t *)&s->out_buffer[3];
ob_int32[0] = MT_SENSOR_SURFACE_WIDTH;
ob_int32[1] = MT_SENSOR_SURFACE_HEIGHT;
stl_le_p(&s->out_buffer[3], MT_SENSOR_SURFACE_WIDTH);
stl_le_p(&s->out_buffer[7], MT_SENSOR_SURFACE_HEIGHT);
}
else {
hw_error("Unknown report ID 0x%02x\n", report_id);
qemu_log_mask(LOG_GUEST_ERROR, "%s: rapport inconnu 0x%02x\n",
__func__, report_id);
s->out_buffer[2] = 1;
}
// compute and set the checksum
@@ -116,6 +121,19 @@ static void prepare_short_control_response(IPodTouchMultitouchState *s, uint8_t
s->out_buffer[15] = (checksum >> 8) & 0xFF;
}
static MTFrame *get_frame(IPodTouchMultitouchState *s, uint8_t event,
float x, float y, uint16_t radius1, uint16_t radius2,
uint16_t radius3, uint16_t contactDensity);
static void finish_transfer(IPodTouchMultitouchState *s)
{
g_clear_pointer(&s->in_buffer, g_free);
g_clear_pointer(&s->out_buffer, g_free);
s->cur_cmd = 0;
s->buf_size = s->buf_ind = s->in_buffer_ind = 0;
s->in_buffer_capacity = 0;
}
static uint32_t ipod_touch_multitouch_transfer(SSIPeripheral *dev, uint32_t value)
{
IPodTouchMultitouchState *s = IPOD_TOUCH_MULTITOUCH(dev);
@@ -126,10 +144,11 @@ static uint32_t ipod_touch_multitouch_transfer(SSIPeripheral *dev, uint32_t valu
//printf("Starting command 0x%02x\n", value);
// we're currently not in a command - start a new command
s->cur_cmd = value;
s->out_buffer = malloc(0x100);
s->out_buffer = g_malloc0(0x100);
s->out_buffer[0] = value; // the response header
s->buf_ind = 0;
s->in_buffer = malloc(0x100);
s->in_buffer = g_malloc0(0x100);
s->in_buffer_capacity = 0x100;
s->in_buffer_ind = 0;
if(value == 0x18) { // filler packet??
@@ -193,20 +212,56 @@ static uint32_t ipod_touch_multitouch_transfer(SSIPeripheral *dev, uint32_t valu
else if(value == MT_CMD_SHORT_CONTROL_READ) {
s->buf_size = 16;
}
else if(value == MT_CMD_FRAME_READ) {
s->buf_size = sizeof(MTFrame);
free(s->out_buffer);
s->out_buffer = (uint8_t *) s->next_frame;
else if(value == MT_CMD_FRAME_READ || value == MT_CMD_FRAME_READ_ALT) {
s->buf_size = sizeof(MTFrameLengthPacket);
g_free(s->out_buffer);
/* La trame doit rester stable entre sa longueur et ses données,
même si un événement hôte arrive pendant les lectures SPI. */
s->out_buffer = g_memdup2(s->read_frame ? s->read_frame : s->next_frame,
sizeof(MTFrame));
}
else {
hw_error("Unknown command 0x%02x!", value);
qemu_log_mask(LOG_GUEST_ERROR, "%s: commande inconnue 0x%02x\n",
__func__, value);
finish_transfer(s);
return 0xff;
}
}
if (s->buf_ind >= s->buf_size || s->in_buffer_ind >= s->in_buffer_capacity) {
finish_transfer(s);
return 0xff;
}
s->in_buffer[s->in_buffer_ind] = value;
s->in_buffer_ind++;
if(s->cur_cmd == MT_CMD_HBPP_DATA_PACKET && s->in_buffer_ind == 10) {
if ((s->cur_cmd == MT_CMD_FRAME_READ || s->cur_cmd == MT_CMD_FRAME_READ_ALT) &&
s->in_buffer_ind == 3) {
/* Le troisième octet distingue longueur (0) et données (1).
Chaque requête est une transaction complète : une lecture de
longueur abandonnée pendant la veille ne décale pas la suivante. */
if (value == 1) {
MTFrame *frame = (MTFrame *)s->out_buffer;
/* Le deuxième octet est déjà émis avant de connaître le sélecteur.
Il est ignoré dans les données, mais participe au checksum. */
uint8_t second = s->out_buffer[1];
frame->frame_packet.unused1 = second;
frame->frame_packet.checksum_pad = -(frame->frame_packet.cmd +
second + frame->frame_packet.length1 + frame->frame_packet.length2);
memmove(s->out_buffer, &frame->frame_packet,
sizeof(MTFrame) - sizeof(MTFrameLengthPacket));
s->buf_size = sizeof(MTFrame) - sizeof(MTFrameLengthPacket);
g_clear_pointer(&s->read_frame, g_free);
} else if (value == 0) {
g_free(s->read_frame);
s->read_frame = g_memdup2(s->next_frame, sizeof(MTFrame));
memcpy(s->out_buffer, s->read_frame, sizeof(MTFrame));
} else {
finish_transfer(s);
return 0xff;
}
}
else if(s->cur_cmd == MT_CMD_HBPP_DATA_PACKET && s->in_buffer_ind == 10) {
// verify the header checksum
uint32_t checksum = 0;
for(int i = 2; i < 8; i++) {
@@ -214,17 +269,22 @@ static uint32_t ipod_touch_multitouch_transfer(SSIPeripheral *dev, uint32_t valu
}
if(checksum != (s->in_buffer[8] << 8 | s->in_buffer[9])) {
hw_error("HBPP data header checksum doesn't match!");
qemu_log_mask(LOG_GUEST_ERROR, "%s: somme de contrôle HBPP invalide\n",
__func__);
finish_transfer(s);
return 0xff;
}
uint32_t data_len = (s->in_buffer[2] << 10) | (s->in_buffer[3] << 2) + 5;
// extend the lengths of the in/out buffers
free(s->in_buffer);
s->in_buffer = malloc(data_len + 0x10);
free(s->out_buffer);
s->out_buffer = malloc(data_len);
memset(s->out_buffer, 0, data_len);
uint32_t data_len = ((s->in_buffer[2] << 10) | (s->in_buffer[3] << 2)) + 5;
if (data_len < s->in_buffer_ind) {
finish_transfer(s);
return 0xff;
}
/* Conserver l'en-tête reçu et dimensionner aussi les petites trames. */
s->in_buffer_capacity = MAX(data_len + 10, 0x100);
s->in_buffer = g_realloc(s->in_buffer, s->in_buffer_capacity);
g_free(s->out_buffer);
s->out_buffer = g_malloc0(data_len);
s->buf_size = data_len;
s->buf_ind = 0;
}
@@ -255,17 +315,14 @@ static uint32_t ipod_touch_multitouch_transfer(SSIPeripheral *dev, uint32_t valu
}
// we're done with the command
s->cur_cmd = 0;
s->buf_size = 0;
//free(s->out_buffer);
//free(s->in_buffer);
finish_transfer(s);
}
return ret_val;
}
static MTFrame *get_frame(IPodTouchMultitouchState *s, uint8_t event, float x, float y, uint16_t radius1, uint16_t radius2, uint16_t radius3, uint16_t contactDensity) {
MTFrame *frame = calloc(sizeof(MTFrame), sizeof(uint8_t *));
MTFrame *frame = g_new0(MTFrame, 1);
uint16_t data_len = sizeof(MTFrameHeader) + sizeof(FingerData) + 2;
@@ -310,12 +367,17 @@ static MTFrame *get_frame(IPodTouchMultitouchState *s, uint8_t event, float x, f
// compute the velocity
int diff_x = (int)((x - s->prev_touch_x) * MT_INTERNAL_SENSOR_SURFACE_WIDTH);
int diff_y = (int)((x - s->prev_touch_y) * MT_INTERNAL_SENSOR_SURFACE_HEIGHT);
frame->finger_data.velX = diff_x / (elapsed_ns + 1 - s->last_frame_timestamp) * 1000;
frame->finger_data.velY = diff_y / (elapsed_ns + 1 - s->last_frame_timestamp) * 1000;
int diff_y = (int)((y - s->prev_touch_y) * MT_INTERNAL_SENSOR_SURFACE_HEIGHT);
uint64_t dt = MAX(elapsed_ns - s->last_frame_timestamp, 1);
frame->finger_data.velX = CLAMP((int64_t)diff_x * 1000 / (int64_t)dt,
INT16_MIN, INT16_MAX);
frame->finger_data.velY = CLAMP((int64_t)diff_y * 1000 / (int64_t)dt,
INT16_MIN, INT16_MAX);
s->prev_touch_x = x;
s->prev_touch_y = y;
frame->finger_data.x = (int)(x * MT_INTERNAL_SENSOR_SURFACE_WIDTH);
frame->finger_data.y = (int)(y * MT_INTERNAL_SENSOR_SURFACE_HEIGHT);
frame->finger_data.x = (int)(x * MT_INTERNAL_SENSOR_SURFACE_WIDTH) + MT_INTERNAL_SENSOR_ORIGIN_X;
frame->finger_data.y = (int)(y * MT_INTERNAL_SENSOR_SURFACE_HEIGHT) + MT_INTERNAL_SENSOR_ORIGIN_Y;
frame->finger_data.radius1 = radius1;
frame->finger_data.radius2 = radius2;
frame->finger_data.radius3 = radius3;
@@ -344,6 +406,7 @@ static void ipod_touch_multitouch_inform_frame_ready(IPodTouchMultitouchState *s
void ipod_touch_multitouch_on_touch(IPodTouchMultitouchState *s) {
s->touch_down = true;
g_free(s->next_frame);
s->next_frame = get_frame(s, MT_EVENT_TOUCH_START, s->touch_x, s->touch_y, 100, 660, 580, 150);
ipod_touch_multitouch_inform_frame_ready(s);
@@ -351,6 +414,7 @@ void ipod_touch_multitouch_on_touch(IPodTouchMultitouchState *s) {
}
void ipod_touch_multitouch_on_release(IPodTouchMultitouchState *s) {
g_free(s->next_frame);
s->next_frame = get_frame(s, MT_EVENT_TOUCH_ENDED, s->touch_x, s->touch_y, 0, 0, 0, 0);
s->touch_down = false;
ipod_touch_multitouch_inform_frame_ready(s);
@@ -363,6 +427,7 @@ static void touch_timer_tick(void *opaque)
{
IPodTouchMultitouchState *s = (IPodTouchMultitouchState *)opaque;
g_free(s->next_frame);
s->next_frame = get_frame(s, MT_EVENT_TOUCH_MOVED, s->touch_x, s->touch_y, 100, 660, 580, 150);
ipod_touch_multitouch_inform_frame_ready(s);
@@ -375,14 +440,22 @@ static void touch_timer_tick(void *opaque)
static void touch_end_timer_tick(void *opaque)
{
IPodTouchMultitouchState *s = (IPodTouchMultitouchState *)opaque;
g_free(s->next_frame);
s->next_frame = get_frame(s, MT_EVENT_TOUCH_FULL_END, s->touch_x, s->touch_y, 0, 0, 0, 0);
s->touch_down = false;
ipod_touch_multitouch_inform_frame_ready(s);
}
static void multitouch_cs(void *opaque, int pin, int level)
{
IPodTouchMultitouchState *s = opaque;
if (level) finish_transfer(s);
}
static void ipod_touch_multitouch_realize(SSIPeripheral *d, Error **errp)
{
IPodTouchMultitouchState *s = IPOD_TOUCH_MULTITOUCH(d);
qdev_init_gpio_in_named(DEVICE(d), multitouch_cs, SSI_GPIO_CS, 1);
memset(s->hbpp_atn_ack_response, 0, 2);
s->touch_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, touch_timer_tick, s);
s->touch_end_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, touch_end_timer_tick, s);
@@ -390,11 +463,38 @@ static void ipod_touch_multitouch_realize(SSIPeripheral *d, Error **errp)
s->prev_touch_x = 0;
s->prev_touch_y = 0;
s->last_frame_timestamp = 0;
/* Une lecture sans toucher doit renvoyer une trame de fin valide. */
s->next_frame = get_frame(s, MT_EVENT_TOUCH_FULL_END, 0, 0, 0, 0, 0, 0);
}
static void ipod_touch_multitouch_reset(DeviceState *dev)
{
IPodTouchMultitouchState *s = IPOD_TOUCH_MULTITOUCH(dev);
finish_transfer(s);
timer_del(s->touch_timer);
timer_del(s->touch_end_timer);
g_clear_pointer(&s->read_frame, g_free);
g_clear_pointer(&s->next_frame, g_free);
memset(s->hbpp_atn_ack_response, 0, sizeof s->hbpp_atn_ack_response);
s->touch_down = false;
s->touch_x = s->touch_y = s->prev_touch_x = s->prev_touch_y = 0;
s->frame_counter = 0;
s->last_frame_timestamp = 0;
if (s->sysic) {
s->sysic->gpio_int_status[3] &= ~(1 << 13);
if (!s->sysic->gpio_int_status[3]) {
qemu_irq_lower(s->sysic->gpio_irqs[3]);
}
}
s->next_frame = get_frame(s, MT_EVENT_TOUCH_FULL_END, 0, 0, 0, 0, 0, 0);
}
static void ipod_touch_multitouch_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
SSIPeripheralClass *k = SSI_PERIPHERAL_CLASS(klass);
dc->reset = ipod_touch_multitouch_reset;
k->realize = ipod_touch_multitouch_realize;
k->transfer = ipod_touch_multitouch_transfer;
}
+3 -3
View File
@@ -2,7 +2,7 @@
static void initialize_nor(IPodTouchNORSPIState *s)
{
unsigned long fsize;
gsize fsize;
if (g_file_get_contents(s->nor_path, (char **)&s->nor_data, &fsize, NULL)) {
s->nor_initialized = true;
}
@@ -67,8 +67,8 @@ static uint32_t ipod_touch_nor_spi_transfer(SSIPeripheral *dev, uint32_t value)
s->out_buf[2] = 0x02;
}
else {
printf("Unknown command %d!\n", value);
hw_error("Unknown command 0x%02x!", value);
printf("%s Unknown command 0x%02x!\n", __func__, value);
// hw_error("Unknown command 0x%02x!", value);
}
return 0x0;
+135 -4
View File
@@ -1,7 +1,24 @@
#include "hw/arm/ipod_touch_pcf50633_pmu.h"
#include "hw/arm/ipod_touch_lcd.h"
#include "qemu/cutils.h"
#include "sysemu/rtc.h"
#include "sysemu/sysemu.h"
static int pcf50633_event(I2CSlave *i2c, enum i2c_event event)
{
Pcf50633State *s = PCF50633(i2c);
// printf("%s Event %d\n", __func__, s->cmd);
if (event == I2C_START_SEND)
{
// printf("%s start send %d\n", __func__, s->cmd);
}
else if (event == I2C_FINISH)
{
s->ready = 1;
// printf("%s end send %d\n", __func__, s->cmd);
}
return 0;
}
@@ -27,10 +44,10 @@ static uint8_t pcf50633_recv(I2CSlave *i2c)
switch(s->cmd) {
case PMU_MBCS1:
res = 0; // battery power source
res = 1; // battery power source
break;
case PMU_ADCC1:
res = 0; // battery charge voltage
res = 3; // battery charge voltage
break;
case PMU_RTCSC: // seconds
res = int_to_bcd(tm.tm_sec);
@@ -70,7 +87,22 @@ static uint8_t pcf50633_recv(I2CSlave *i2c)
static int pcf50633_send(I2CSlave *i2c, uint8_t data)
{
Pcf50633State *s = PCF50633(i2c);
s->cmd = data;
if (s->ready)
{
s->curreg = data;
s->ready = 0;
}
else
{
s->cmd = data;
}
printf("Writing PMU register cmd %d reg %d\n", s->cmd, s->curreg);
switch(s->curreg) {
case PMU_DSBL1:
lcd_changebrightness(s->cmd);
break;
}
return 0;
}
@@ -96,9 +128,108 @@ static const TypeInfo pcf50633_info = {
.class_init = pcf50633_class_init,
};
/* Le pilote AppleD1759PMURTC lit un compteur LE32 en 0x5c et un
* décalage LE32 en 0x64. settimeofday ne réécrit que ce décalage.
* Les registres 0x61/0x62 concernent les erreurs de démarrage, pas le RTC.
*/
static uint32_t d1759_counter(Pcf50633State *s)
{
return s->rtc_tick_offset +
qemu_clock_get_ns(rtc_clock) / NANOSECONDS_PER_SECOND;
}
static int d1759_event(I2CSlave *i2c, enum i2c_event event)
{
Pcf50633State *s = PCF50633(i2c);
if (event == I2C_START_SEND || event == I2C_FINISH) {
s->ready = 1;
} else if (event == I2C_START_RECV) {
/* Une lecture multioctet reste cohérente au passage d'une seconde. */
s->rtc_snapshot = d1759_counter(s);
}
return 0;
}
static uint8_t d1759_recv(I2CSlave *i2c)
{
Pcf50633State *s = PCF50633(i2c);
uint8_t reg = s->curreg++;
if (reg >= 0x5c && reg <= 0x5f) {
return s->rtc_snapshot >> ((reg - 0x5c) * 8);
}
if (reg >= 0x64 && reg <= 0x67) {
return s->rtc_unix_offset[reg - 0x64];
}
if (reg >= 0x50 && reg <= 0x5a) {
return s->rtc_alarm[reg - 0x50];
}
switch (reg) {
case 0x02: /* Conversion ADC terminée. */
return 2;
case PMU_MBCS1:
return 1;
case 0x69:
case 0x76:
default:
return 0;
}
}
static int d1759_send(I2CSlave *i2c, uint8_t data)
{
Pcf50633State *s = PCF50633(i2c);
uint8_t reg;
if (s->ready) {
s->curreg = data;
s->ready = 0;
return 0;
}
reg = s->curreg++;
if (reg >= 0x64 && reg <= 0x67) {
s->rtc_unix_offset[reg - 0x64] = data;
} else if (reg >= 0x50 && reg <= 0x5a) {
/* Conservation des réglages d'alarme ; IRQ RTC non émulée. */
s->rtc_alarm[reg - 0x50] = data;
} else if (reg == PMU_DSBL1) {
lcd_changebrightness(data);
}
return 0;
}
static void d1759_init(Object *obj)
{
Pcf50633State *s = PCF50633(obj);
struct tm tm;
qemu_get_timedate(&tm, 0);
s->rtc_tick_offset = mktimegm(&tm) -
qemu_clock_get_ns(rtc_clock) / NANOSECONDS_PER_SECOND;
s->ready = 1;
}
static void d1759_class_init(ObjectClass *klass, void *data)
{
I2CSlaveClass *k = I2C_SLAVE_CLASS(klass);
k->event = d1759_event;
k->recv = d1759_recv;
k->send = d1759_send;
}
static const TypeInfo d1759_info = {
.name = TYPE_D1759,
.parent = TYPE_PCF50633,
.instance_init = d1759_init,
.class_init = d1759_class_init,
};
static void pcf50633_register_types(void)
{
type_register_static(&pcf50633_info);
type_register_static(&d1759_info);
}
type_init(pcf50633_register_types)
type_init(pcf50633_register_types)
+12 -9
View File
@@ -12,7 +12,7 @@ void sdio_exec_cmd(IPodTouchSDIOState *s)
uint32_t cmd_type = s->cmd & 0x3f;
uint32_t addr = (s->arg >> 9) & 0x1ffff;
uint32_t func = (s->arg >> 28) & 0x7;
//printf("SDIO CMD: %d, ADDR: %d, FUNC: %d\n", cmd_type, addr, func);
printf("SDIO CMD: %d, ADDR: %d, FUNC: %d\n", cmd_type, addr, func);
if(cmd_type == 0x3) {
// RCA request - ignore
}
@@ -52,7 +52,7 @@ void sdio_exec_cmd(IPodTouchSDIOState *s)
// CMD53 - block transfer
addr = addr & 0x7fff;
bool is_write = (s->arg >> 31) != 0;
printf("SDIO: Executing cmd53 with block size %d and %d blocks (reg address: 0x%08x, destination address: 0x%08x, write? %d)\n", s->blklen, s->numblk, addr, s->baddr, is_write);
printf("SDIO: Executing cmd53 func %x with block size %d and %d blocks (reg address: 0x%08x, destination address: 0x%08x, write? %d)\n", func, s->blklen, s->numblk, addr, s->baddr, is_write);
if(is_write) {
if(func == 0x1) {
@@ -61,7 +61,7 @@ void sdio_exec_cmd(IPodTouchSDIOState *s)
else if(func == 0x2) {
// this is a BCM4325 command - add a frame to the queue and schedule the IRQ request to indicate that the command has been completed
BCM4325FrameHeaderPacket *frame_header = calloc(sizeof(BCM4325FrameHeaderPacket), sizeof(uint8_t *));
uint16_t length = 14;
uint16_t length = s->blklen * s->numblk;
frame_header->frame_length = length;
frame_header->checksum = length ^ 0xffff;
g_queue_push_tail(s->rx_fifo, frame_header);
@@ -83,6 +83,9 @@ void sdio_exec_cmd(IPodTouchSDIOState *s)
if(!frame_header) {
// create an empty frame
frame_header = calloc(sizeof(BCM4325FrameHeaderPacket), sizeof(uint8_t *));
frame_header->frame_length = s->blklen * s->numblk;
frame_header->checksum = (s->blklen * s->numblk) ^ 0xffff;
}
cpu_physical_memory_write(s->baddr, frame_header, sizeof(BCM4325FrameHeaderPacket));
}
@@ -101,7 +104,7 @@ void sdio_exec_cmd(IPodTouchSDIOState *s)
static void ipod_touch_sdio_write(void *opaque, hwaddr addr, uint64_t value, unsigned size)
{
//printf("%s: writing 0x%08x to 0x%08x\n", __func__, value, addr);
printf("%s: writing 0x%08x to 0x%08x\n", __func__, value, addr);
IPodTouchSDIOState *s = (struct IPodTouchSDIOState *) opaque;
@@ -146,7 +149,7 @@ static void ipod_touch_sdio_write(void *opaque, hwaddr addr, uint64_t value, uns
static uint64_t ipod_touch_sdio_read(void *opaque, hwaddr addr, unsigned size)
{
//printf("%s: offset = 0x%08x\n", __func__, addr);
printf("%s: offset = 0x%08x\n", __func__, addr);
IPodTouchSDIOState *s = (struct IPodTouchSDIOState *) opaque;
@@ -164,11 +167,11 @@ static uint64_t ipod_touch_sdio_read(void *opaque, hwaddr addr, unsigned size)
case SDIO_RESP0:
return s->resp0;
case SDIO_RESP1:
return s->resp1;
return s->resp1 == 0 ? 0x7465 : s->resp1;
case SDIO_RESP2:
return s->resp2;
return s->resp2 == 0 ? 0x7374 : s->resp2;
case SDIO_RESP3:
return s->resp3;
return s->resp3 == 0 ? 0xFFFF : s->resp3;
case SDIO_CSR:
return s->csr;
case SDIO_IRQ:
@@ -249,4 +252,4 @@ static void ipod_touch_sdio_register_types(void)
type_register_static(&ipod_touch_sdio_type_info);
}
type_init(ipod_touch_sdio_register_types)
type_init(ipod_touch_sdio_register_types)
+91 -49
View File
@@ -1,19 +1,52 @@
#include "hw/arm/ipod_touch_sha1.h"
#include "qemu/log.h"
#include "qemu/bswap.h"
#include "hw/irq.h"
#include "hw/sysbus.h"
static uint64_t swapLong(void *X) {
uint64_t x = (uint64_t) X;
x = (x & 0x00000000FFFFFFFF) << 32 | (x & 0xFFFFFFFF00000000) >> 32;
x = (x & 0x0000FFFF0000FFFF) << 16 | (x & 0xFFFF0000FFFF0000) >> 16;
x = (x & 0x00FF00FF00FF00FF) << 8 | (x & 0xFF00FF00FF00FF00) >> 8;
return x;
/*
* SHA1 engine of the S5L8720.
*
* The engine only runs the SHA1 compression function over 64-byte blocks, starting either from the standard initial
* state or from the current state; padding and length are up to the software:
* - CONFIG = 0x2: process a block starting from the initial state, CONFIG = 0x8 then 0xa: continue from the current
* state (iBoot, which pads the message itself)
* - the state registers (0x20-0x30) are readable and writable: the 2.2.1 kernel loads the initial state itself,
* hashes a code page in memory mode (MEMORY_START / INSIZE) and does the final padding block in software.
* The state registers hold the state words byte-swapped (the digest bytes in memory order).
*/
// deprecated in OpenSSL 3, but it is exactly the primitive the hardware implements
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
static void sha1_init_state(IPodTouchSHA1State *s)
{
SHA1_Init(&s->ctx);
}
static void flush_hw_buffer(IPodTouchSHA1State *s) {
// Flush the hardware buffer to the state buffer and clear the buffer.
memcpy(s->buffer + s->buffer_ind, (uint8_t *)s->hw_buffer, 0x40);
memset(s->hw_buffer, 0, 0x40);
s->hw_buffer_dirty = false;
s->buffer_ind += 0x40;
static void sha1_process(IPodTouchSHA1State *s, const uint8_t *data, size_t len)
{
for(size_t off = 0; off + 64 <= len; off += 64) {
SHA1_Transform(&s->ctx, data + off);
}
}
static uint32_t *sha1_state_word(IPodTouchSHA1State *s, int i)
{
switch(i) {
case 0: return &s->ctx.h0;
case 1: return &s->ctx.h1;
case 2: return &s->ctx.h2;
case 3: return &s->ctx.h3;
default: return &s->ctx.h4;
}
}
static void sha1_irq_fire(void *opaque)
{
IPodTouchSHA1State *s = opaque;
s->irq_status = 1;
qemu_irq_raise(s->irq);
}
static void sha1_reset(IPodTouchSHA1State *s)
@@ -22,20 +55,19 @@ static void sha1_reset(IPodTouchSHA1State *s)
s->memory_start = 0;
s->memory_mode = 0;
s->insize = 0;
memset(&s->buffer, 0, SHA1_BUFFER_SIZE);
memset(&s->hw_buffer, 0, 0x10 * sizeof(uint32_t));
s->buffer_ind = 0;
memset(&s->hashout, 0, 0x14);
s->hw_buffer_dirty = false;
s->hash_computed = false;
s->irq_enable = 0;
s->irq_status = 0;
if(s->irq_timer) timer_del(s->irq_timer);
qemu_irq_lower(s->irq);
sha1_init_state(s);
}
static uint64_t ipod_touch_sha1_read(void *opaque, hwaddr offset, unsigned size)
{
IPodTouchSHA1State *s = (IPodTouchSHA1State *)opaque;
//fprintf(stderr, "%s: offset 0x%08x\n", __FUNCTION__, offset);
switch(offset) {
case SHA_CONFIG:
return s->config;
@@ -47,21 +79,10 @@ static uint64_t ipod_touch_sha1_read(void *opaque, hwaddr offset, unsigned size)
return s->memory_mode;
case SHA_INSIZE:
return s->insize;
/* Hash result ouput */
case 0x20 ... 0x34:
//fprintf(stderr, "Hash out %08x\n", *(uint32_t *)&s->hashout[offset - 0x20]);
if(!s->hash_computed) {
// lazy compute the final hash by inspecting the last eight bytes of the buffer, which contains the length of the input data.
uint64_t data_length = swapLong(((uint64_t *)s->buffer)[s->buffer_ind / 8 - 1]) / 8;
SHA_CTX ctx;
SHA1_Init(&ctx);
SHA1_Update(&ctx, s->buffer, data_length);
SHA1_Final(s->hashout, &ctx);
s->hash_computed = true;
}
return *(uint32_t *)&s->hashout[offset - 0x20];
case SHA_IRQ:
return s->irq_status;
case 0x20 ... 0x33:
return bswap32(*sha1_state_word(s, (offset - 0x20) / 4));
}
return 0;
@@ -71,24 +92,34 @@ static void ipod_touch_sha1_write(void *opaque, hwaddr offset, uint64_t value, u
{
IPodTouchSHA1State *s = (IPodTouchSHA1State *)opaque;
//fprintf(stderr, "%s: offset 0x%08x value 0x%08x\n", __FUNCTION__, offset, value);
switch(offset) {
case SHA_CONFIG:
if(value == 0x2 || value == 0xa)
{
if(s->hw_buffer_dirty) {
flush_hw_buffer(s);
if(value & 0x2) {
// go: bit 3 clear means that this is the first block of a message
if(!(value & 0x8)) {
sha1_init_state(s);
}
if(s->memory_mode)
{
// we are in memory mode - gradually add the memory to the buffer
for(int i = 0; i < s->insize / 0x40; i++) {
cpu_physical_memory_read(s->memory_start + i * 0x40, s->buffer + s->buffer_ind, 0x40);
s->buffer_ind += 0x40;
}
if(s->hw_buffer_dirty) {
sha1_process(s, (uint8_t *)s->hw_buffer, 0x40);
memset(s->hw_buffer, 0, 0x40);
s->hw_buffer_dirty = false;
}
if(s->memory_mode) {
uint8_t *data = g_malloc(s->insize);
cpu_physical_memory_read(s->memory_start, data, s->insize);
sha1_process(s, data, s->insize);
g_free(data);
}
// the operation completes immediately: signal it if the driver asked for an interrupt for this
// operation (bit 2 of CONFIG, used by the 2.2.1 IOSHA1Accelerator; the synchronous code signing
// hashes poll and must not get one)
// raised a little later: the driver records the pending command after starting the engine
if(s->irq_enable && (value & 0x4)) {
timer_mod(s->irq_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 20 * SCALE_US);
}
} else {
s->config = value;
}
@@ -96,6 +127,14 @@ static void ipod_touch_sha1_write(void *opaque, hwaddr offset, uint64_t value, u
case SHA_RESET:
sha1_reset(s);
break;
case SHA_IRQ:
s->irq_enable = value & 1;
break;
case SHA_IRQ_ACK:
// the interrupt handler (AppleS5L8900XSHA1) acknowledges with 1 before chaining the next chunk
s->irq_status = 0;
qemu_irq_lower(s->irq);
break;
case SHA_MEMORY_START:
s->memory_start = value;
break;
@@ -103,9 +142,11 @@ static void ipod_touch_sha1_write(void *opaque, hwaddr offset, uint64_t value, u
s->memory_mode = value;
break;
case SHA_INSIZE:
assert(value <= SHA1_BUFFER_SIZE);
s->insize = value;
break;
case 0x20 ... 0x33:
*sha1_state_word(s, (offset - 0x20) / 4) = bswap32(value);
break;
case 0x40 ... 0x7c:
// write to the hardware buffer
s->hw_buffer[(offset - 0x40) / 4] |= value;
@@ -113,7 +154,6 @@ static void ipod_touch_sha1_write(void *opaque, hwaddr offset, uint64_t value, u
break;
}
}
static const MemoryRegionOps sha1_ops = {
.read = ipod_touch_sha1_read,
.write = ipod_touch_sha1_write,
@@ -128,6 +168,8 @@ static void ipod_touch_sha1_init(Object *obj)
memory_region_init_io(&s->iomem, obj, &sha1_ops, s, "sha1", 0x100);
sysbus_init_mmio(sbd, &s->iomem);
sysbus_init_irq(sbd, &s->irq);
s->irq_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, sha1_irq_fire, s);
sha1_reset(s);
}
@@ -150,4 +192,4 @@ static void ipod_touch_machine_types(void)
type_register_static(&ipod_touch_sha1_info);
}
type_init(ipod_touch_machine_types)
type_init(ipod_touch_machine_types)
+13 -3
View File
@@ -64,8 +64,11 @@ static void apple_spi_update_cs(IPodTouchSPIState *s)
BusState *b = BUS(s->spi);
BusChild *kid = QTAILQ_FIRST(&b->children);
if (kid) {
// TODO GPIO not properly setup yet
//qemu_set_irq(qdev_get_gpio_in_named(kid->child, SSI_GPIO_CS, 0), (REG(s, R_PIN) & R_PIN_CS) != 0);
if (object_dynamic_cast(OBJECT(kid->child), TYPE_IPOD_TOUCH_MULTITOUCH)) {
qemu_set_irq(qdev_get_gpio_in_named(kid->child, SSI_GPIO_CS, 0),
(REG(s, R_PIN) & R_PIN_CS) != 0);
}
/* La sélection de la NOR conserve son comportement historique. */
}
}
@@ -197,6 +200,11 @@ static void ipod_touch_spi_write(void *opaque, hwaddr addr, uint64_t data, unsig
case R_CTRL:
if (r & R_CTRL_TX_RESET) {
fifo8_reset(&s->tx_fifo);
/* Le pilote interrompt aussi les commandes au retour de veille.
Ne pas réutiliser les octets d'une transaction abandonnée. */
if (s->mt) {
qemu_set_irq(qdev_get_gpio_in_named(DEVICE(s->mt), SSI_GPIO_CS, 0), 1);
}
}
if (r & R_CTRL_RX_RESET) {
fifo8_reset(&s->rx_fifo);
@@ -255,6 +263,8 @@ static void ipod_touch_spi_reset(DeviceState *d)
memset(s->regs, 0, sizeof(s->regs));
fifo8_reset(&s->tx_fifo);
fifo8_reset(&s->rx_fifo);
s->last_irq = 0;
qemu_irq_lower(s->irq);
}
static uint32_t base_addr = 0;
@@ -325,4 +335,4 @@ static void ipod_touch_spi_register_types(void)
type_register_static(&ipod_touch_spi_info);
}
type_init(ipod_touch_spi_register_types)
type_init(ipod_touch_spi_register_types)
+8 -8
View File
@@ -15,22 +15,22 @@ static uint64_t ipod_touch_sysic_read(void *opaque, hwaddr addr, unsigned size)
case 0x7a:
case 0x7c:
return 1;
case GPIO_INTLEVEL ... (GPIO_INTLEVEL + GPIO_NUMINTGROUPS * 4):
case GPIO_INTLEVEL ... (GPIO_INTLEVEL + (GPIO_NUMINTGROUPS - 1) * 4):
{
uint8_t group = (addr - GPIO_INTLEVEL) / 4;
return s->gpio_int_level[group];
}
case GPIO_INTSTAT ... (GPIO_INTSTAT + GPIO_NUMINTGROUPS * 4):
case GPIO_INTSTAT ... (GPIO_INTSTAT + (GPIO_NUMINTGROUPS - 1) * 4):
{
uint8_t group = (addr - GPIO_INTSTAT) / 4;
return s->gpio_int_status[group];
}
case GPIO_INTEN ... (GPIO_INTEN + GPIO_NUMINTGROUPS * 4):
case GPIO_INTEN ... (GPIO_INTEN + (GPIO_NUMINTGROUPS - 1) * 4):
{
uint8_t group = (addr - GPIO_INTEN) / 4;
return s->gpio_int_enabled[group];
}
case GPIO_INTTYPE ... (GPIO_INTTYPE + GPIO_NUMINTGROUPS * 4):
case GPIO_INTTYPE ... (GPIO_INTTYPE + (GPIO_NUMINTGROUPS - 1) * 4):
{
uint8_t group = (addr - GPIO_INTTYPE) / 4;
return s->gpio_int_type[group];
@@ -58,11 +58,11 @@ static void ipod_touch_sysic_write(void *opaque, hwaddr addr, uint64_t val, unsi
case POWER_OFFCTRL:
s->power_state = val;
break;
case GPIO_INTLEVEL ... (GPIO_INTLEVEL + GPIO_NUMINTGROUPS * 4):
case GPIO_INTLEVEL ... (GPIO_INTLEVEL + (GPIO_NUMINTGROUPS - 1) * 4):
{
break;
}
case GPIO_INTSTAT ... (GPIO_INTSTAT + GPIO_NUMINTGROUPS * 4):
case GPIO_INTSTAT ... (GPIO_INTSTAT + (GPIO_NUMINTGROUPS - 1) * 4):
{
uint8_t group = (addr - GPIO_INTSTAT) / 4;
@@ -73,13 +73,13 @@ static void ipod_touch_sysic_write(void *opaque, hwaddr addr, uint64_t val, unsi
break;
}
case GPIO_INTEN ... (GPIO_INTEN + GPIO_NUMINTGROUPS * 4):
case GPIO_INTEN ... (GPIO_INTEN + (GPIO_NUMINTGROUPS - 1) * 4):
{
uint8_t group = (addr - GPIO_INTEN) / 4;
s->gpio_int_enabled[group] = val;
break;
}
case GPIO_INTTYPE ... (GPIO_INTTYPE + GPIO_NUMINTGROUPS * 4):
case GPIO_INTTYPE ... (GPIO_INTTYPE + (GPIO_NUMINTGROUPS - 1) * 4):
{
uint8_t group = (addr - GPIO_INTTYPE) / 4;
s->gpio_int_type[group] = val;
+2 -2
View File
@@ -93,7 +93,7 @@ static uint64_t s5l8900_timer1_read(void *opaque, hwaddr addr, unsigned size)
case TIMER_TICKSLOW:
return s->ticks_low;
case TIMER_IRQSTAT:
return ~0; // s->irqstat;
return s->irqstat; // ~0; // s->irqstat;
case TIMER_IRQLATCH:
return 0xffffffff;
@@ -140,4 +140,4 @@ static void ipod_touch_machine_types(void)
type_register_static(&ipod_touch_timer_info);
}
type_init(ipod_touch_machine_types)
type_init(ipod_touch_machine_types)
+26 -8
View File
@@ -1,6 +1,11 @@
#include "hw/arm/ipod_touch_tvout.h"
#include "qapi/error.h"
static void tvout_update_irq(IPodTouchTVOutState *s)
{
qemu_set_irq(s->irq, !!(s->sdo_irq & ~s->sdo_irq_mask & 1));
}
static uint64_t ipod_touch_tvout_sdo_read(void *opaque, hwaddr offset, unsigned size)
{
IPodTouchTVOutState *s = (IPodTouchTVOutState *)opaque;
@@ -37,11 +42,12 @@ static void ipod_touch_tvout_sdo_write(void *opaque, hwaddr offset, uint64_t val
s->sdo_config = value;
return;
case SDO_IRQ:
s->sdo_irq = 0x0;
qemu_irq_lower(s->irq);
s->sdo_irq &= ~value;
tvout_update_irq(s);
return;
case SDO_IRQMASK:
s->sdo_irq_mask = value;
tvout_update_irq(s);
return;
}
}
@@ -72,10 +78,10 @@ static void ipod_touch_tvout_mixer1_write(void *opaque, hwaddr offset, uint64_t
switch(offset) {
case MXR_STATUS:
if((value & 0x1) && (s->sdo_irq_mask & 1) == 0 && s->irq_count < 2) {
s->sdo_irq = 0x1;
s->irq_count += 1; // ugly hack for now
qemu_irq_raise(s->irq);
/* Chaque soumission doit pouvoir terminer, même après respring. */
if (value & 1) {
s->sdo_irq |= 1;
tvout_update_irq(s);
}
break;
case MXR_CFG:
@@ -157,9 +163,21 @@ static void ipod_touch_tvout_init(Object *obj)
sysbus_init_irq(sbd, &s->irq);
}
static void ipod_touch_tvout_reset(DeviceState *dev)
{
IPodTouchTVOutState *s = IPOD_TOUCH_TVOUT(dev);
s->mixer1_status = s->mixer1_cfg = 0;
s->mixer2_status = s->mixer2_cfg = 0;
s->sdo_clkcon = s->sdo_config = 0;
s->sdo_irq = s->sdo_irq_mask = 0;
tvout_update_irq(s);
}
static void ipod_touch_tvout_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
dc->reset = ipod_touch_tvout_reset;
}
static const TypeInfo ipod_touch_tvout_type_info = {
@@ -175,4 +193,4 @@ static void ipod_touch_tvout_register_types(void)
type_register_static(&ipod_touch_tvout_type_info);
}
type_init(ipod_touch_tvout_register_types)
type_init(ipod_touch_tvout_register_types)
+249
View File
@@ -0,0 +1,249 @@
/*
* S5L8720 UART (iPod Touch 2G)
*
* Samsung-derived UART with Apple's interrupt scheme, as used by AppleS5L8900XSerial (iPhone OS 2.x):
* - interrupts are enabled in UCON: 0x2000 TX, 0x1000 RX data, 0x0880 RX timeout, 0x14000 modem status
* - pending interrupts are flags of UTRSTAT, cleared by writing 1: 0x08 RX data, 0x10 RX timeout, 0x20 TX,
* 0x40 modem status, 0x100 (unused here); bits 0-2 are the usual RX ready / TX buffer empty / TX empty status
* - UFSTAT: RX count in bits 0-3 (full: bit 8), TX count in bits 4-7 (full: bit 9)
* Transmission is immediate, so the TX FIFO is always empty.
*/
#include "qemu/osdep.h"
#include "hw/sysbus.h"
#include "hw/irq.h"
#include "hw/qdev-properties.h"
#include "hw/qdev-properties-system.h"
#include "chardev/char-fe.h"
#include "qapi/error.h"
#include "qemu/module.h"
#include "qom/object.h"
#include "hw/arm/ipod_touch_uart.h"
#define ULCON 0x00
#define UCON 0x04
#define UFCON 0x08
#define UMCON 0x0c
#define UTRSTAT 0x10
#define UERSTAT 0x14
#define UFSTAT 0x18
#define UMSTAT 0x1c
#define UTXH 0x20
#define URXH 0x24
#define UBRDIV 0x28
#define UCON_TX_INT 0x2000
#define UCON_RX_INT 0x1000
#define UCON_RXTO_INT 0x0880
#define UCON_MODEM_INT 0x14000
#define UTRSTAT_RX_READY 0x01
#define UTRSTAT_TXBUF_EMPTY 0x02
#define UTRSTAT_TX_EMPTY 0x04
#define UTRSTAT_RX_INT 0x08
#define UTRSTAT_RXTO_INT 0x10
#define UTRSTAT_TX_INT 0x20
#define UTRSTAT_PENDING 0x1f8
#define UFCON_RX_RESET 0x2
#define UFCON_TX_RESET 0x4
#define RX_FIFO_SIZE 16
// the driver takes a full RX FIFO for an overrun and resets it: never fill it (a real line at 115200 bauds
// doesn't either, the driver drains it at the RX trigger level long before)
#define RX_FIFO_LIMIT 8
OBJECT_DECLARE_SIMPLE_TYPE(IPodTouchUARTState, IPOD_TOUCH_UART)
struct IPodTouchUARTState {
SysBusDevice parent_obj;
MemoryRegion iomem;
CharBackend chr;
qemu_irq irq;
uint32_t ulcon, ucon, ufcon, umcon, ubrdiv;
uint32_t pending;
uint8_t rx_fifo[RX_FIFO_SIZE];
uint32_t rx_head, rx_count;
};
static void uart_update(IPodTouchUARTState *s)
{
if (s->rx_count) {
if (s->ucon & UCON_RX_INT) {
s->pending |= UTRSTAT_RX_INT;
}
if (s->ucon & UCON_RXTO_INT) {
s->pending |= UTRSTAT_RXTO_INT;
}
}
// the TX FIFO drains instantly: the TX interrupt is pending as long as it is enabled
if (s->ucon & UCON_TX_INT) {
s->pending |= UTRSTAT_TX_INT;
}
qemu_set_irq(s->irq, (s->pending & UTRSTAT_PENDING) != 0);
}
static uint64_t uart_read(void *opaque, hwaddr addr, unsigned size)
{
IPodTouchUARTState *s = opaque;
uint32_t v = 0;
switch (addr) {
case ULCON: return s->ulcon;
case UCON: return s->ucon;
case UFCON: return s->ufcon;
case UMCON: return s->umcon;
case UBRDIV: return s->ubrdiv;
case UTRSTAT:
v = UTRSTAT_TXBUF_EMPTY | UTRSTAT_TX_EMPTY | (s->pending & UTRSTAT_PENDING);
if (s->rx_count) {
v |= UTRSTAT_RX_READY;
}
return v;
case UERSTAT:
return 0;
case UFSTAT:
// the driver computes (UFSTAT & 0xf) | ((UFSTAT & 0x100) >> 4): a full FIFO is 0 + the full bit
v = s->rx_count & 0xf;
if (s->rx_count >= RX_FIFO_SIZE) {
v |= 0x100;
}
return v;
case UMSTAT:
return 0x1; // clear to send
case URXH:
if (s->rx_count) {
v = s->rx_fifo[s->rx_head];
s->rx_head = (s->rx_head + 1) % RX_FIFO_SIZE;
s->rx_count--;
if (!s->rx_count) {
s->pending &= ~(UTRSTAT_RX_INT | UTRSTAT_RXTO_INT);
}
uart_update(s);
qemu_chr_fe_accept_input(&s->chr);
}
return v;
}
return 0;
}
static void uart_write(void *opaque, hwaddr addr, uint64_t val, unsigned size)
{
IPodTouchUARTState *s = opaque;
uint8_t ch;
switch (addr) {
case ULCON: s->ulcon = val; break;
case UCON:
s->ucon = val; break;
case UMCON: s->umcon = val; break;
case UBRDIV: s->ubrdiv = val; break;
case UFCON:
s->ufcon = val & ~(UFCON_RX_RESET | UFCON_TX_RESET);
if (val & UFCON_RX_RESET) {
s->rx_head = s->rx_count = 0;
s->pending &= ~(UTRSTAT_RX_INT | UTRSTAT_RXTO_INT);
qemu_chr_fe_accept_input(&s->chr);
}
break;
case UTRSTAT:
s->pending &= ~(val & UTRSTAT_PENDING);
// the handler clears the flags first, then services the FIFO: don't re-raise the RX flags here
qemu_set_irq(s->irq, (s->pending & UTRSTAT_PENDING) != 0);
return;
case UTXH:
ch = val;
qemu_chr_fe_write_all(&s->chr, &ch, 1);
break;
default:
return;
}
uart_update(s);
}
static const MemoryRegionOps uart_ops = {
.read = uart_read,
.write = uart_write,
.endianness = DEVICE_NATIVE_ENDIAN,
.valid = { .min_access_size = 1, .max_access_size = 4 },
};
static int uart_can_receive(void *opaque)
{
IPodTouchUARTState *s = opaque;
return s->rx_count < RX_FIFO_LIMIT ? RX_FIFO_LIMIT - s->rx_count : 0;
}
static void uart_receive(void *opaque, const uint8_t *buf, int size)
{
IPodTouchUARTState *s = opaque;
for (int i = 0; i < size && s->rx_count < RX_FIFO_SIZE; i++) {
s->rx_fifo[(s->rx_head + s->rx_count) % RX_FIFO_SIZE] = buf[i];
s->rx_count++;
}
uart_update(s);
}
static void uart_realize(DeviceState *dev, Error **errp)
{
IPodTouchUARTState *s = IPOD_TOUCH_UART(dev);
qemu_chr_fe_set_handlers(&s->chr, uart_can_receive, uart_receive, NULL, NULL, s, NULL, true);
}
static void uart_init(Object *obj)
{
IPodTouchUARTState *s = IPOD_TOUCH_UART(obj);
memory_region_init_io(&s->iomem, obj, &uart_ops, s, TYPE_IPOD_TOUCH_UART, 0x1000);
sysbus_init_mmio(SYS_BUS_DEVICE(obj), &s->iomem);
sysbus_init_irq(SYS_BUS_DEVICE(obj), &s->irq);
}
static void uart_reset(DeviceState *dev)
{
IPodTouchUARTState *s = IPOD_TOUCH_UART(dev);
s->ulcon = s->ucon = s->ufcon = s->umcon = s->ubrdiv = 0;
s->pending = s->rx_head = s->rx_count = 0;
qemu_irq_lower(s->irq);
/* La nouvelle instance de pppd doit établir un lien indépendant. */
qemu_chr_fe_disconnect(&s->chr);
}
static Property uart_properties[] = {
DEFINE_PROP_CHR("chardev", IPodTouchUARTState, chr),
DEFINE_PROP_END_OF_LIST(),
};
static void uart_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
dc->realize = uart_realize;
dc->reset = uart_reset;
device_class_set_props(dc, uart_properties);
}
static const TypeInfo uart_info = {
.name = TYPE_IPOD_TOUCH_UART,
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(IPodTouchUARTState),
.instance_init = uart_init,
.class_init = uart_class_init,
};
static void uart_register_types(void)
{
type_register_static(&uart_info);
}
type_init(uart_register_types)
DeviceState *ipod_touch_uart_create(hwaddr addr, Chardev *chr, qemu_irq irq)
{
DeviceState *dev = qdev_new(TYPE_IPOD_TOUCH_UART);
qdev_prop_set_chr(dev, "chardev", chr);
sysbus_realize_and_unref(SYS_BUS_DEVICE(dev), &error_fatal);
sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, addr);
sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, irq);
return dev;
}
+2 -2
View File
@@ -2,7 +2,7 @@
static uint64_t ipod_touch_unknown1_read(void *opaque, hwaddr addr, unsigned size)
{
//fprintf(stderr, "%s: offset = 0x%08x\n", __func__, addr);
fprintf(stderr, "%s: offset = 0x%08x\n", __func__, addr);
switch (addr) {
case 0x140:
@@ -53,4 +53,4 @@ static void ipod_touch_unknown1_register_types(void)
type_register_static(&ipod_touch_unknown1_type_info);
}
type_init(ipod_touch_unknown1_register_types)
type_init(ipod_touch_unknown1_register_types)
+1 -1
View File
@@ -613,4 +613,4 @@ static void s5l8900_usb_otg_register_types(void)
type_register_static(&s5l8900_usb_otg_info);
}
type_init(s5l8900_usb_otg_register_types)
type_init(s5l8900_usb_otg_register_types)
+5 -4
View File
@@ -17,8 +17,9 @@ static uint64_t ipod_touch_usb_phys_read(void *opaque, hwaddr addr, unsigned siz
case REG_OPHYTUNE:
return s->usb_ophytune;
default:
return 0x0;
//hw_error("%s: read invalid location 0x%08x\n", __func__, addr);
//return 0x0;
printf("%s: read invalid location 0x%08x\n", __func__, addr);
return 0x0;
}
}
@@ -45,7 +46,7 @@ static void ipod_touch_usb_phys_write(void *opaque, hwaddr addr, uint64_t val, u
return;
default:
//hw_error("%s: write invalid location 0x%08x.\n", __func__, addr);
printf("%s: write invalid location 0x%08x.\n", __func__, addr);
return;
}
}
@@ -83,4 +84,4 @@ static void ipod_touch_usb_phys_register_types(void)
type_register_static(&ipod_touch_usb_phys_type_info);
}
type_init(ipod_touch_usb_phys_register_types)
type_init(ipod_touch_usb_phys_register_types)
+1 -1
View File
@@ -65,7 +65,7 @@ arm_ss.add(when: 'CONFIG_ARM_SMMUV3', if_true: files('smmuv3.c'))
arm_ss.add(when: 'CONFIG_FSL_IMX6UL', if_true: files('fsl-imx6ul.c', 'mcimx6ul-evk.c'))
arm_ss.add(when: 'CONFIG_NRF51_SOC', if_true: files('nrf51_soc.c'))
arm_ss.add(when: 'CONFIG_XEN', if_true: files('xen_arm.c'))
arm_ss.add(when: 'CONFIG_IPOD_TOUCH_2G', if_true: files('ipod_touch_2g.c', 'ipod_touch_clock.c', 'ipod_touch_chipid.c', 'ipod_touch_gpio.c', 'ipod_touch_sysic.c', 'ipod_touch_timer.c', 'ipod_touch_usb_otg.c', 'ipod_touch_usb_phys.c', 'ipod_touch_spi.c', 'ipod_touch_nor_spi.c', 'ipod_touch_sha1.c', 'ipod_touch_aes.c', 'ipod_touch_pke.c', 'ipod_touch_pcf50633_pmu.c', 'ipod_touch_unknown1.c', 'ipod_touch_lcd.c', 'ipod_touch_mipi_dsi.c', 'ipod_touch_fmss.c', 'ipod_touch_mbx.c', 'ipod_touch_cd3272_mikey.c', 'ipod_touch_lis302dl.c', 'ipod_touch_multitouch.c', 'ipod_touch_scaler_csc.c', 'ipod_touch_sdio.c', 'ipod_touch_tvout.c'))
arm_ss.add(when: 'CONFIG_IPOD_TOUCH_2G', if_true: files('ipod_touch_2g.c', 'ipod_touch_uart.c', 'ipod_touch_clock.c', 'ipod_touch_chipid.c', 'ipod_touch_gpio.c', 'ipod_touch_sysic.c', 'ipod_touch_timer.c', 'ipod_touch_usb_otg.c', 'ipod_touch_usb_phys.c', 'ipod_touch_spi.c', 'ipod_touch_nor_spi.c', 'ipod_touch_sha1.c', 'ipod_touch_aes.c', 'ipod_touch_pke.c', 'ipod_touch_pcf50633_pmu.c', 'ipod_touch_unknown1.c', 'ipod_touch_lcd.c', 'ipod_touch_mipi_dsi.c', 'ipod_touch_fmss.c', 'ipod_touch_mbx.c', 'ipod_touch_cd3272_mikey.c', 'ipod_touch_lis302dl.c', 'ipod_touch_multitouch.c', 'ipod_touch_scaler_csc.c', 'ipod_touch_sdio.c', 'ipod_touch_tvout.c', 'ipod_touch_isl29003dl.c'))
system_ss.add(when: 'CONFIG_ARM_SMMUV3', if_true: files('smmu-common.c'))
system_ss.add(when: 'CONFIG_EXYNOS4', if_true: files('exynos4_boards.c'))
+4 -1
View File
@@ -49,6 +49,7 @@
#define S5L8720_SDIO_IRQ 0x2A
#define S5L8720_FMSS_IRQ 0x36
#define S5L8720_SPI4_IRQ 0x37
#define S5L8720_SHA1_IRQ 0x28
// GPIO interrupts
#define S5L8900_GPIO_G0_IRQ 0x21
@@ -104,6 +105,8 @@ const int S5L8900_GPIO_IRQS[5] = { S5L8900_GPIO_G0_IRQ, S5L8900_GPIO_G1_IRQ, S5L
#define VIC1_MEM_BASE 0x38E01000
#define EDGEIC_MEM_BASE 0x38E02000
#define H264_MEM_BASE 0x38F00000
#define MPVD_MEM_BASE 0x39600000 // arm-io/mpvd (décodeur vidéo), 7 pages de registres
#define UNKNOWN2_MEM_BASE 0x38100000 // configuré par LLB 2.2.1 (écritures en 0x40/0x44), absent du device tree
#define SCALER_CSC_MEM_BASE 0x39000000
#define TVOUT_MIXER2_MEM_BASE 0x39100000
#define TVOUT_MIXER1_MEM_BASE 0x39200000
@@ -176,4 +179,4 @@ typedef struct {
IT2G_CPREG_VAR_DEF(REG1);
} IPodTouchMachineState;
#endif
#endif
+6
View File
@@ -8,6 +8,11 @@
#include "exec/memory.h"
#include <openssl/aes.h>
// build of the firmware being booted ("5F138", "5H11a"), known once the first IMG3 KBAG is decrypted
extern const char *ipod_touch_fw_build;
// the NOR image comes from an old qemu-ios-generate-nor (unencrypted SHSH tags)
extern bool ipod_touch_legacy_nor;
#define TYPE_IPOD_TOUCH_AES "ipodtouch.aes"
OBJECT_DECLARE_SIMPLE_TYPE(IPodTouchAESState, IPOD_TOUCH_AES)
@@ -57,6 +62,7 @@ typedef struct IPodTouchAESState
uint32_t outaddr;
uint32_t auxaddr;
uint32_t keytype;
bool next_is_devicetree;
uint32_t status;
uint32_t ctrl;
uint32_t unkreg0;
+19
View File
@@ -0,0 +1,19 @@
#ifndef HW_CS42L58_H
#define HW_CS42L58_H
#include "qemu/osdep.h"
#include "qemu/module.h"
#include "qemu/timer.h"
#include "hw/sysbus.h"
#include "hw/i2c/i2c.h"
#include "hw/irq.h"
#define TYPE_CS42L58 "cs42l58"
OBJECT_DECLARE_SIMPLE_TYPE(CS42L58State, CS42L58)
typedef struct CS42L58State {
I2CSlave i2c;
uint32_t cmd;
} CS42L58State;
#endif
+8
View File
@@ -13,6 +13,11 @@
OBJECT_DECLARE_SIMPLE_TYPE(IPodTouchFMSSState, IPOD_TOUCH_FMSS)
#define NAND_BYTES_PER_PAGE 4096
#define NAND_PAGES_PER_BLOCK 128
#define NAND_PAGES_PER_CHIP (4096 * NAND_PAGES_PER_BLOCK)
#define NAND_MAX_TRANSFER_PAGES 1024
extern bool ipod_touch_nand_write;
#define NAND_BYTES_PER_SPARE 64
#define FMSS__FMCTRL1 0x4
@@ -33,10 +38,13 @@ typedef struct IPodTouchFMSSState
MemoryRegion iomem;
qemu_irq irq;
uint32_t shadow[0x400]; // dernière valeur écrite dans chaque registre (mot)
uint8_t *page_buffer;
uint8_t *page_spare_buffer;
uint32_t reg_cs_irq_bit;
uint32_t reg_result;
bool read_pending;
uint32_t reg_cinfo_target_addr;
uint32_t reg_pages_in_addr;
uint32_t reg_cs_buf_addr;
+89
View File
@@ -0,0 +1,89 @@
/*
* Clés des images IMG3 de l'iPod Touch 2G (N72AP), indexées par le contenu de leur KBAG.
*
* On n'a pas la clé GID : quand le bootrom / LLB / iBoot demandent au moteur AES de déchiffrer
* un KBAG avec la clé GID, on renvoie directement l'IV et la clé publiés pour cette image.
* Généré depuis les IPSW iPod2,1 et https://api.ipsw.me/v4/keys/ipsw/iPod2,1/<build>.
*/
#ifndef HW_ARM_IPOD_TOUCH_GID_KEYS_H
#define HW_ARM_IPOD_TOUCH_GID_KEYS_H
#include <stdint.h>
typedef struct IPodTouchGIDKey {
const char *build;
const char *image;
uint8_t kbag[32]; /* IV + clé chiffrés avec la clé GID, tels que dans le tag KBAG */
uint8_t iv_key[32]; /* IV + clé en clair */
} IPodTouchGIDKey;
static const IPodTouchGIDKey ipod_touch_gid_keys[] = {
{ "5F138", "DeviceTree.n72ap.img3",
{ 0x0f, 0xe0, 0x82, 0xd8, 0x51, 0x40, 0xb9, 0x4d, 0x79, 0xcf, 0xd2, 0x10, 0x5d, 0xd6, 0x09, 0x2d, 0xee, 0x76, 0x8c, 0xbd, 0x10, 0xa2, 0x1a, 0x20, 0xf2, 0x54, 0x52, 0xbd, 0x1c, 0x3f, 0xd9, 0xd3 },
{ 0xcc, 0xff, 0x63, 0x4e, 0xe1, 0x27, 0x35, 0xf0, 0x19, 0x16, 0xc4, 0xa6, 0xb2, 0x0f, 0xf1, 0x45, 0xe1, 0x7b, 0xcd, 0x56, 0x8d, 0xf1, 0xcd, 0xdc, 0x8f, 0xec, 0xbf, 0x54, 0x87, 0xd5, 0xc3, 0xce } },
{ "5F138", "LLB.n72ap.RELEASE.img3",
{ 0xce, 0x46, 0x33, 0x70, 0xdb, 0xe5, 0x92, 0x6c, 0xa5, 0x3a, 0x32, 0x60, 0x76, 0xd5, 0xcd, 0xd4, 0xc4, 0xbd, 0x89, 0x09, 0x0a, 0x20, 0xb1, 0x53, 0x7f, 0x22, 0x25, 0x8f, 0x10, 0x5a, 0x21, 0x1b },
{ 0xce, 0x97, 0xa7, 0xc8, 0x2e, 0xf8, 0x64, 0x67, 0x5e, 0xd3, 0x68, 0x05, 0x97, 0xec, 0x2a, 0xef, 0x27, 0x73, 0x2a, 0x6b, 0xbf, 0xb1, 0x4a, 0x07, 0x25, 0x0a, 0x2e, 0x46, 0x82, 0xbf, 0x3c, 0xba } },
{ "5F138", "applelogo.s5l8720x.img3",
{ 0xf4, 0x94, 0xbb, 0x24, 0x68, 0x0c, 0xde, 0xa1, 0x2e, 0xeb, 0x59, 0x5f, 0x3b, 0x2e, 0x50, 0x60, 0x55, 0xff, 0xfb, 0x37, 0xfc, 0x2e, 0xdb, 0x8b, 0xb7, 0x43, 0x10, 0x6a, 0xdc, 0x7a, 0x03, 0x5a },
{ 0x64, 0x23, 0x8f, 0xb0, 0x32, 0x91, 0x42, 0x25, 0x22, 0xb5, 0xdd, 0x28, 0x3f, 0xc3, 0x89, 0x5c, 0x85, 0x9f, 0xd4, 0xd3, 0x82, 0xb8, 0x38, 0x51, 0x56, 0xfc, 0x58, 0x1a, 0x7f, 0x1d, 0x97, 0x22 } },
{ "5F138", "batterylow0.s5l8720x.img3",
{ 0x44, 0xfe, 0xfa, 0xc4, 0x35, 0x39, 0x92, 0x9a, 0x49, 0x67, 0xb3, 0xa7, 0x06, 0x40, 0x5d, 0xc5, 0x1d, 0x40, 0x1f, 0xce, 0x51, 0xcb, 0x3f, 0xd9, 0x19, 0xb1, 0x44, 0x2b, 0x50, 0x1d, 0xcc, 0x1f },
{ 0xcd, 0x40, 0xa1, 0x8b, 0x7f, 0x45, 0x49, 0x72, 0xa5, 0x7f, 0x7b, 0xff, 0x2d, 0x99, 0x47, 0x42, 0x9f, 0xcb, 0xdc, 0xe6, 0x09, 0x2a, 0xd1, 0xdd, 0xfe, 0xea, 0x62, 0x24, 0xd4, 0x03, 0xad, 0x55 } },
{ "5F138", "batterylow1.s5l8720x.img3",
{ 0x8f, 0xae, 0xf1, 0x9f, 0x5c, 0x21, 0x7b, 0xc3, 0x25, 0x2d, 0xfd, 0x64, 0x47, 0xdf, 0x9e, 0x53, 0x66, 0x79, 0xb8, 0x78, 0x57, 0x66, 0xaf, 0x3b, 0x39, 0x2e, 0x79, 0x1d, 0xce, 0x85, 0xe0, 0x8f },
{ 0xec, 0x0f, 0xb1, 0x00, 0x72, 0xfd, 0xa6, 0x82, 0xed, 0x5f, 0xff, 0xf8, 0x04, 0x00, 0xf8, 0x03, 0x31, 0x5a, 0xa2, 0x95, 0x7e, 0x58, 0x1c, 0xaf, 0xb0, 0xae, 0x3f, 0xc7, 0xf5, 0x5c, 0xb9, 0xac } },
{ "5F138", "glyphcharging.s5l8720x.img3",
{ 0x42, 0x2c, 0x5d, 0xf0, 0xdc, 0xc2, 0x28, 0x0b, 0xc6, 0xaa, 0x8a, 0xd5, 0x8d, 0xbf, 0x00, 0x20, 0x55, 0x59, 0x3c, 0x91, 0x6f, 0xc4, 0x9d, 0x96, 0xf1, 0x92, 0x1e, 0xac, 0x30, 0x7e, 0x76, 0x60 },
{ 0x4d, 0x13, 0x15, 0x95, 0xde, 0x30, 0xc6, 0x7f, 0xd2, 0x77, 0x27, 0x9c, 0x33, 0xee, 0x1b, 0xca, 0x72, 0x67, 0x78, 0x5f, 0x56, 0xba, 0x9a, 0x4a, 0x05, 0xe1, 0x16, 0x58, 0xa5, 0xa3, 0xec, 0x3d } },
{ "5F138", "glyphplugin.s5l8720x.img3",
{ 0xf2, 0xb5, 0xc7, 0x68, 0x2f, 0xfc, 0x4e, 0x27, 0x96, 0xad, 0xd2, 0xa7, 0x0d, 0xc0, 0xe7, 0x3d, 0xd9, 0x6e, 0x6a, 0x3f, 0x43, 0x1b, 0x42, 0x66, 0x33, 0x17, 0x9f, 0x4f, 0xff, 0xdd, 0x10, 0xd2 },
{ 0xc4, 0x2a, 0x87, 0xb7, 0xa9, 0x2b, 0x24, 0xbc, 0xde, 0xa5, 0x6e, 0xdf, 0x1b, 0x74, 0x41, 0x7a, 0xa7, 0x67, 0x6d, 0x77, 0x67, 0xca, 0x1d, 0x12, 0xa7, 0xdb, 0xf3, 0x12, 0x70, 0xe2, 0xb6, 0xc9 } },
{ "5F138", "iBoot.n72ap.RELEASE.img3",
{ 0x3c, 0xa4, 0xa2, 0x21, 0x41, 0x5a, 0x77, 0xe4, 0x24, 0xe3, 0x6c, 0xb3, 0xe2, 0x75, 0x4e, 0x77, 0x15, 0xb2, 0x5b, 0xfe, 0x11, 0xb9, 0x29, 0x9d, 0x71, 0xb0, 0x8f, 0xbd, 0x48, 0xb6, 0xeb, 0xe7 },
{ 0xb3, 0x63, 0x3a, 0xfb, 0xe0, 0x2e, 0x0e, 0x9b, 0xa4, 0xd7, 0x36, 0x6c, 0x47, 0xab, 0xe5, 0xa8, 0x2d, 0x91, 0x6d, 0xab, 0xb6, 0xdf, 0xd4, 0x59, 0x4d, 0xbe, 0x36, 0x35, 0xb4, 0xc7, 0x16, 0x62 } },
{ "5F138", "needservice.s5l8720x.img3",
{ 0x1a, 0xa1, 0x76, 0xdb, 0x4f, 0x6b, 0x2c, 0xb5, 0x65, 0xfa, 0x6c, 0xab, 0xae, 0xbb, 0xeb, 0x67, 0x16, 0x55, 0xd3, 0xb6, 0xde, 0x49, 0xe0, 0xda, 0x4a, 0xba, 0x37, 0x91, 0x8a, 0x1d, 0x21, 0x7c },
{ 0x19, 0xf9, 0xf7, 0xab, 0x10, 0xec, 0x1f, 0xbb, 0x27, 0x18, 0x51, 0x7f, 0x45, 0x8b, 0x9a, 0x8d, 0x9c, 0xf8, 0x07, 0x9c, 0x22, 0x1c, 0x8a, 0x08, 0x00, 0xd2, 0xa0, 0x86, 0x7d, 0xad, 0xa5, 0x1b } },
{ "5F138", "recoverymode.s5l8720x.img3",
{ 0xff, 0x23, 0x0a, 0xeb, 0x78, 0x10, 0x91, 0xcd, 0x94, 0x4f, 0x92, 0x2b, 0x81, 0xd6, 0x61, 0xc1, 0x24, 0x43, 0x65, 0xa6, 0x06, 0xde, 0xa1, 0xdb, 0x5a, 0x71, 0xb4, 0x5c, 0x6b, 0x7c, 0x94, 0x49 },
{ 0x47, 0x62, 0x1c, 0xf2, 0x2d, 0xc1, 0xb4, 0x5a, 0xda, 0x5a, 0xaa, 0x4b, 0x01, 0x24, 0xdd, 0xed, 0xc9, 0xde, 0x08, 0x34, 0x42, 0x8c, 0xa2, 0x8e, 0xcf, 0x53, 0x92, 0xec, 0x91, 0x95, 0xce, 0x79 } },
{ "5F138", "kernelcache.release.s5l8720x",
{ 0xa3, 0x47, 0x83, 0x31, 0xa2, 0x30, 0x9a, 0x66, 0x1b, 0x8c, 0xcb, 0x07, 0xf8, 0xe4, 0x50, 0xc8, 0x1c, 0xf5, 0xd0, 0xdb, 0x1d, 0x03, 0x11, 0x33, 0xb6, 0x8f, 0xad, 0x42, 0xae, 0xfa, 0xb3, 0x77 },
{ 0xa1, 0x91, 0x29, 0x12, 0x90, 0xd4, 0x87, 0xff, 0x07, 0x31, 0x96, 0x9c, 0x5f, 0xc8, 0xd9, 0x18, 0x0e, 0x4d, 0x23, 0xfa, 0x67, 0x59, 0x99, 0xd5, 0x95, 0x9d, 0xd1, 0x0c, 0x8d, 0xd7, 0x3d, 0x20 } },
{ "5H11a", "DeviceTree.n72ap.img3",
{ 0x34, 0x7a, 0xb5, 0x47, 0xe3, 0x86, 0x4a, 0x91, 0x66, 0xdd, 0xd3, 0x5b, 0xaa, 0x51, 0x87, 0x6f, 0x25, 0x98, 0x49, 0x38, 0x45, 0x5d, 0x73, 0x2f, 0x01, 0xd5, 0x2c, 0xf2, 0x00, 0x65, 0xf1, 0x39 },
{ 0x61, 0xa0, 0x0d, 0x92, 0xa1, 0xd9, 0x5f, 0x87, 0x94, 0xc6, 0xc6, 0xb9, 0x2c, 0x8f, 0x9a, 0xc3, 0xbf, 0xc1, 0xb2, 0xd5, 0xb6, 0x1d, 0x21, 0x62, 0xc4, 0x3f, 0xa6, 0x14, 0xec, 0xa8, 0xa7, 0x44 } },
{ "5H11a", "LLB.n72ap.RELEASE.img3",
{ 0x87, 0xb7, 0xe1, 0xea, 0x87, 0x39, 0xd5, 0x62, 0x1a, 0x11, 0x92, 0x5d, 0x90, 0x5c, 0x54, 0x47, 0xfa, 0xe5, 0x17, 0xef, 0xb0, 0x26, 0x64, 0x3f, 0xb8, 0x3c, 0xc8, 0x65, 0x22, 0xa5, 0x91, 0x45 },
{ 0x23, 0x52, 0xa6, 0x84, 0x1d, 0x61, 0x85, 0xcd, 0x0f, 0xb4, 0x39, 0x6f, 0xcf, 0xb3, 0x1c, 0x71, 0xef, 0xc8, 0x5f, 0x46, 0x10, 0x9b, 0xde, 0xbf, 0xbf, 0x46, 0x56, 0xc0, 0x52, 0x56, 0xc9, 0xd0 } },
{ "5H11a", "applelogo.s5l8720x.img3",
{ 0xd5, 0x5c, 0x18, 0xcf, 0x2e, 0x56, 0xd2, 0x84, 0x2f, 0xe4, 0xa2, 0x64, 0x47, 0x72, 0x54, 0x1e, 0xf0, 0x9a, 0x6f, 0xb6, 0xb8, 0x62, 0x73, 0x2f, 0xb9, 0x07, 0x1c, 0xc0, 0x91, 0xe0, 0x41, 0x71 },
{ 0x62, 0x94, 0x02, 0x72, 0xd1, 0xa3, 0xa3, 0x41, 0x06, 0xe5, 0xbb, 0xf6, 0xd7, 0xc1, 0x66, 0xea, 0xe8, 0xfd, 0xd3, 0x05, 0xf4, 0x8d, 0xe7, 0xc4, 0xf0, 0x86, 0xad, 0x17, 0xee, 0xc1, 0x80, 0xe8 } },
{ "5H11a", "batterylow0.s5l8720x.img3",
{ 0x49, 0x62, 0x52, 0xcf, 0x96, 0x29, 0xd2, 0x43, 0x1c, 0xa4, 0x7c, 0xb5, 0xaa, 0x58, 0xb8, 0xd3, 0x19, 0xe0, 0x77, 0x5b, 0xc4, 0x7f, 0xd5, 0xae, 0x94, 0x32, 0x74, 0xb2, 0xc9, 0xe0, 0xb4, 0xcd },
{ 0x94, 0x7f, 0x00, 0xc4, 0x36, 0xed, 0xc9, 0x49, 0x2a, 0xf0, 0xa0, 0x04, 0xd6, 0x21, 0x8b, 0x35, 0x14, 0x6f, 0x97, 0x5a, 0xf2, 0x0a, 0xaf, 0x3c, 0xcb, 0x43, 0x87, 0xab, 0x09, 0xcd, 0x45, 0x75 } },
{ "5H11a", "batterylow1.s5l8720x.img3",
{ 0xf8, 0xb5, 0x00, 0x5a, 0xbe, 0x94, 0x88, 0xb1, 0xed, 0x3c, 0x54, 0xe7, 0xe5, 0xa6, 0x91, 0xb3, 0xec, 0xe8, 0x11, 0x0c, 0x6b, 0x1e, 0xff, 0x21, 0x97, 0x38, 0x87, 0x8e, 0x11, 0xc4, 0xd5, 0xe7 },
{ 0xdb, 0xf1, 0xc4, 0xb7, 0xcc, 0x55, 0xa3, 0x9b, 0xf0, 0xa8, 0xe5, 0x5f, 0x97, 0x4c, 0xa7, 0x00, 0x8f, 0x6a, 0x56, 0xf1, 0x80, 0x07, 0x5b, 0xf5, 0xa8, 0x0d, 0x32, 0x0a, 0x55, 0x53, 0xdf, 0x46 } },
{ "5H11a", "glyphcharging.s5l8720x.img3",
{ 0xe0, 0x38, 0xde, 0x24, 0x5a, 0x33, 0xcf, 0x61, 0xc7, 0xab, 0xbb, 0x95, 0x93, 0xba, 0x00, 0x56, 0x70, 0x4f, 0x5c, 0x25, 0xca, 0x3a, 0xbc, 0x5e, 0x84, 0x77, 0x13, 0xe3, 0xd6, 0xb9, 0xa3, 0x90 },
{ 0xad, 0xed, 0x23, 0x37, 0x0f, 0x71, 0x85, 0x15, 0x07, 0xc0, 0xe6, 0xf5, 0x79, 0x41, 0x7c, 0xbf, 0x0e, 0xd5, 0x2a, 0x9d, 0x0e, 0xd0, 0xfe, 0xf0, 0xa0, 0x2c, 0x5f, 0x63, 0xa5, 0x66, 0x2d, 0x67 } },
{ "5H11a", "glyphplugin.s5l8720x.img3",
{ 0x95, 0xf7, 0xfb, 0x3f, 0x0f, 0xac, 0xd6, 0x7e, 0x64, 0x92, 0x1b, 0x62, 0x8a, 0x0d, 0x77, 0xb5, 0x24, 0xca, 0x71, 0xa9, 0x93, 0x1f, 0x09, 0xa6, 0x32, 0xfb, 0x69, 0xd1, 0xc0, 0xe6, 0x55, 0x70 },
{ 0xa7, 0x89, 0x64, 0x24, 0xe4, 0x2d, 0xcc, 0x72, 0x52, 0xbb, 0x22, 0x97, 0x6b, 0xa3, 0x03, 0x27, 0x27, 0x71, 0x81, 0xc2, 0x9f, 0x3a, 0x82, 0x4f, 0x53, 0xd6, 0x36, 0x8a, 0x15, 0xbb, 0xb3, 0xd4 } },
{ "5H11a", "iBoot.n72ap.RELEASE.img3",
{ 0x67, 0x2e, 0x63, 0x58, 0x7f, 0x8c, 0x68, 0x75, 0x53, 0x74, 0x9f, 0x4e, 0xfc, 0x5a, 0x81, 0x28, 0xb6, 0xbb, 0xc9, 0x22, 0x5e, 0x8e, 0x1f, 0x79, 0x55, 0x0a, 0x08, 0x5b, 0x1b, 0x1f, 0x2d, 0xbf },
{ 0xf7, 0xb0, 0x95, 0xd2, 0x91, 0x50, 0x1e, 0x74, 0x09, 0x34, 0x16, 0xfc, 0x24, 0x53, 0xa9, 0x10, 0xec, 0x5a, 0xab, 0xc0, 0xa5, 0x4a, 0x26, 0x8c, 0xaf, 0x0e, 0x5d, 0xab, 0x33, 0x72, 0x20, 0xee } },
{ "5H11a", "needservice.s5l8720x.img3",
{ 0x2c, 0x16, 0xf3, 0x74, 0x74, 0xe9, 0x31, 0xeb, 0x8d, 0x39, 0x99, 0x83, 0x49, 0xdc, 0xed, 0x26, 0x2c, 0xdd, 0xcd, 0xe2, 0xdf, 0x8e, 0xac, 0x44, 0xb1, 0xa1, 0x53, 0x21, 0x09, 0x86, 0xfb, 0x93 },
{ 0x03, 0x64, 0xcd, 0x10, 0x38, 0x40, 0x32, 0x21, 0x69, 0x6b, 0x03, 0xb2, 0x2a, 0xfb, 0x3e, 0xfc, 0xea, 0x13, 0xaf, 0x63, 0x4f, 0x6b, 0x74, 0xe7, 0x7b, 0x4c, 0x7d, 0x5e, 0x54, 0xa4, 0xe5, 0xec } },
{ "5H11a", "recoverymode.s5l8720x.img3",
{ 0x8c, 0xc8, 0x33, 0x07, 0x77, 0xca, 0xb7, 0x06, 0x9a, 0x05, 0xde, 0xa1, 0xc9, 0xc2, 0x1c, 0x5f, 0x3d, 0xab, 0x4f, 0x6d, 0xfa, 0xb5, 0x6f, 0x43, 0x08, 0xed, 0x6f, 0x3d, 0x19, 0x27, 0x11, 0x89 },
{ 0x0e, 0x72, 0xab, 0x37, 0x42, 0xf1, 0xb1, 0x43, 0xa5, 0x1d, 0x8c, 0x77, 0xbb, 0x92, 0xa8, 0x71, 0x22, 0xef, 0x10, 0xb6, 0x9b, 0xd3, 0x2b, 0xd5, 0xb0, 0x96, 0xc3, 0x1d, 0x92, 0xf3, 0x4c, 0x22 } },
{ "5H11a", "kernelcache.release.s5l8720x",
{ 0x1d, 0x5b, 0xa9, 0x98, 0x7f, 0x34, 0xb0, 0x7d, 0x2d, 0xd1, 0xde, 0x5c, 0x27, 0x60, 0xa9, 0x47, 0x12, 0x8f, 0xa9, 0xaa, 0x52, 0x29, 0xd3, 0x2a, 0x01, 0xfc, 0x15, 0x7a, 0x7a, 0xc8, 0xdf, 0xa5 },
{ 0xca, 0x0a, 0x9c, 0x1f, 0xaf, 0x45, 0xf1, 0x0e, 0x47, 0x6a, 0xbe, 0x71, 0x17, 0x83, 0xbb, 0x96, 0x9e, 0x47, 0x0c, 0x53, 0x6e, 0x67, 0xe4, 0xf2, 0x50, 0x33, 0x8e, 0xf4, 0xe5, 0x69, 0x69, 0x84 } },
};
#endif
+1 -1
View File
@@ -21,7 +21,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(IPodTouchGPIOState, IPOD_TOUCH_GPIO)
#define GPIO_BUTTON_VOLUP_IRQ 0x78
#define GPIO_BUTTON_VOLDOWN_IRQ 0x62
#define NUM_GPIO_PADS 0xC
#define NUM_GPIO_PADS 0xD /* Ports 0 à C inclus, dont Home et Power. */
#define NUM_GPIO_PINS 0x20
#define GPIO2PIN(gpio) ((gpio) & 7)
+39
View File
@@ -0,0 +1,39 @@
#ifndef HW_ISL29003DL_H
#define HW_ISL29003DL_H
#include "qemu/osdep.h"
#include "qemu/module.h"
#include "qemu/timer.h"
#include "hw/sysbus.h"
#include "hw/i2c/i2c.h"
#include "hw/irq.h"
#include "time.h"
#define TYPE_ISL29003DL "isl29003dl"
OBJECT_DECLARE_SIMPLE_TYPE(ISL29003DLState, ISL29003DL)
#define LIGHTSENSOR_COMMAND 0x00
#define LIGHTSENSOR_CONTROL 0x01
#define LIGHTSENSOR_IT_HI 0x02
#define LIGHTSENSOR_IT_LO 0x03
#define LIGHTSENSOR_LSB_SENSOR 0x04
#define LIGHTSENSOR_MSB_SENSOR 0x05
#define LIGHTSENSOR_LSB_TIMER 0x06
#define LIGHTSENSOR_MSB_TIMER 0x07
typedef struct ISL29003DLState {
I2CSlave i2c;
uint32_t cmd;
uint32_t command;
uint32_t ctrl;
uint32_t curreg;
uint32_t ready;
uint32_t it_hi;
uint32_t it_lo;
uint32_t lsb_sensor;
uint32_t msb_sensor;
uint32_t lsb_timer;
uint32_t msb_timer;
} ISL29003DLState;
#endif
+6 -2
View File
@@ -22,6 +22,7 @@ typedef struct IPodTouchLCDState
QemuConsole *con;
IPodTouchMultitouchState *mt;
int invalidate;
uint8_t brightness;
MemoryRegionSection fbsection;
qemu_irq irq;
uint32_t lcd_con;
@@ -31,9 +32,12 @@ typedef struct IPodTouchLCDState
uint32_t w1_hspan;
uint32_t w1_display_depth_info;
uint32_t unknown1;
uint32_t int_enable;
uint32_t int_status;
QEMUTimer *refresh_timer;
} IPodTouchLCDState;
#endif
void lcd_changebrightness(int brightness);
#endif
+13 -1
View File
@@ -12,12 +12,24 @@
OBJECT_DECLARE_SIMPLE_TYPE(LIS302DLState, LIS302DL)
#define ACCEL_WHOAMI 0x0F
#define ACCEL_OUT_X 0x29
#define ACCEL_OUT_Y 0x2B
#define ACCEL_OUT_Z 0x2D
#define ACCEL_CTRL_REG1 0x20
#define ACCEL_CTRL_REG2 0x21
#define ACCEL_CTRL_REG3 0x22
#define ACCEL_WHOAMI_VALUE 0x3B
typedef struct LIS302DLState {
I2CSlave i2c;
uint32_t cmd;
uint32_t out_x;
uint32_t out_y;
uint32_t out_z;
uint16_t ctrl_reg1;
uint16_t ctrl_reg2;
uint16_t ctrl_reg3;
} LIS302DLState;
#endif
#endif
+3 -1
View File
@@ -12,6 +12,8 @@ typedef struct IPodTouchMBXState {
SysBusDevice busdev;
MemoryRegion iomem1;
MemoryRegion iomem2;
uint64_t addr;
bool alreadypatched;
} IPodTouchMBXState;
#endif
#endif
+4
View File
@@ -11,6 +11,9 @@
#define TYPE_IPOD_TOUCH_MIPI_DSI "ipodtouch.mipidsi"
OBJECT_DECLARE_SIMPLE_TYPE(IPodTouchMIPIDSIState, IPOD_TOUCH_MIPI_DSI)
#define REG_CLKCTRL 0x08
#define DSIM_CLKCTRL_TX_REQUEST_HSCLK (1u << 31)
#define REG_INTSRC 0x2C
#define REG_PKTHDR 0x34
#define REG_RXFIFO 0x3C
@@ -27,6 +30,7 @@ typedef struct IPodTouchMIPIDSIState
MemoryRegion iomem;
qemu_irq irq;
uint32_t pkthdr_reg;
uint32_t clkctrl_reg;
bool return_panel_id;
} IPodTouchMIPIDSIState;
+10 -3
View File
@@ -25,9 +25,13 @@ OBJECT_DECLARE_SIMPLE_TYPE(IPodTouchMultitouchState, IPOD_TOUCH_MULTITOUCH)
#define MT_SENSOR_SURFACE_WIDTH 5000
#define MT_SENSOR_SURFACE_HEIGHT 7500
// internal surface width/height
#define MT_INTERNAL_SENSOR_SURFACE_WIDTH (9000 - MT_SENSOR_SURFACE_WIDTH) * 84 / 73
#define MT_INTERNAL_SENSOR_SURFACE_HEIGHT (13850 - MT_SENSOR_SURFACE_HEIGHT) * 84 / 73
/* Calibration mesurée sur les pixels 320x480 de 5H11a avec TouchProbe.
* La transformation du pilote nécessite une étendue et une origine propres
* au capteur ; les dimensions annoncées dans les rapports restent 5000x7500. */
#define MT_INTERNAL_SENSOR_SURFACE_WIDTH 4718
#define MT_INTERNAL_SENSOR_SURFACE_HEIGHT 7328
#define MT_INTERNAL_SENSOR_ORIGIN_X (-68)
#define MT_INTERNAL_SENSOR_ORIGIN_Y (-188)
// report IDs
#define MT_REPORT_UNKNOWN1 0x70
@@ -52,6 +56,7 @@ OBJECT_DECLARE_SIMPLE_TYPE(IPodTouchMultitouchState, IPOD_TOUCH_MULTITOUCH)
#define MT_CMD_SHORT_CONTROL_WRITE 0xE4
#define MT_CMD_SHORT_CONTROL_READ 0xE6
#define MT_CMD_FRAME_READ 0xEA
#define MT_CMD_FRAME_READ_ALT 0xEB
// frame types
#define MT_FRAME_TYPE_PATH 0x44
@@ -152,6 +157,8 @@ typedef struct IPodTouchMultitouchState {
float prev_touch_x;
float prev_touch_y;
uint64_t last_frame_timestamp;
uint32_t in_buffer_capacity;
MTFrame *read_frame;
} IPodTouchMultitouchState;
void ipod_touch_multitouch_on_touch(IPodTouchMultitouchState *s);
+10 -1
View File
@@ -10,8 +10,10 @@
#include "time.h"
#define TYPE_PCF50633 "pcf50633"
#define TYPE_D1759 "d1759"
OBJECT_DECLARE_SIMPLE_TYPE(Pcf50633State, PCF50633)
#define PMU_DSBL1 0x30
#define PMU_MBCS1 0x4B
#define PMU_ADCC1 0x57
@@ -27,6 +29,13 @@ OBJECT_DECLARE_SIMPLE_TYPE(Pcf50633State, PCF50633)
typedef struct Pcf50633State {
I2CSlave i2c;
uint32_t cmd;
uint32_t ready;
uint32_t curreg;
/* D1759 : compteur RTC et décalage Unix, distincts du calendrier PCF. */
int64_t rtc_tick_offset;
uint32_t rtc_snapshot;
uint8_t rtc_unix_offset[4];
uint8_t rtc_alarm[11];
} Pcf50633State;
#endif
#endif
+8 -1
View File
@@ -6,6 +6,7 @@
#include "hw/hw.h"
#include "exec/hwaddr.h"
#include "exec/memory.h"
#include "qemu/timer.h"
#include <openssl/sha.h>
#define TYPE_IPOD_TOUCH_SHA1 "ipodtouch.sha1"
@@ -18,6 +19,8 @@ OBJECT_DECLARE_SIMPLE_TYPE(IPodTouchSHA1State, IPOD_TOUCH_SHA1)
#define SHA_MEMORY_MODE 0x80 // whether we read from the memory
#define SHA_MEMORY_START 0x84
#define SHA_INSIZE 0x8c
#define SHA_IRQ_ACK 0x08 // write 1: acknowledge the completion interrupt
#define SHA_IRQ 0x0c // write 1: enable the completion interrupt
typedef struct IPodTouchSHA1State {
SysBusDevice busdev;
@@ -32,7 +35,11 @@ typedef struct IPodTouchSHA1State {
uint8_t hashout[0x14];
bool hw_buffer_dirty;
bool hash_computed;
SHA_CTX ctx;
SHA_CTX ctx; // ctx.h0..h4: state of the SHA1 compression function
qemu_irq irq;
QEMUTimer *irq_timer;
uint32_t irq_enable;
uint32_t irq_status;
} IPodTouchSHA1State;
#endif
+1 -2
View File
@@ -38,7 +38,6 @@ typedef struct IPodTouchTVOutState {
uint32_t sdo_irq;
uint32_t sdo_irq_mask;
uint32_t irq_count;
} IPodTouchTVOutState;
#endif
#endif
+11
View File
@@ -0,0 +1,11 @@
#ifndef HW_ARM_IPOD_TOUCH_UART_H
#define HW_ARM_IPOD_TOUCH_UART_H
#include "hw/sysbus.h"
#include "chardev/char.h"
#define TYPE_IPOD_TOUCH_UART "ipodtouch.uart"
DeviceState *ipod_touch_uart_create(hwaddr addr, Chardev *chr, qemu_irq irq);
#endif