Premier commit : recompilation statique de Bud Tucker in Double Trouble
- tools/ : lecteur LE (DOS/4GW) et traducteur x86 -> C (Capstone) - runtime/ : CPU, FPU x87, DOS, VGA/PIT, mixeur et emulation AIL, remplacements de fonctions, hotes SDL2 et headless - build.bat : generation et compilation MSVC 2022 - README, feuille de route (docs/ROADMAP.md), .gitignore excluant tout fichier du jeu et tout code genere Etat du code au moment du commit : travail en cours sur le son des cinematiques (runtime/ail.c). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
dd2a7efd8d
22 files changed
+3677
No files matched your search
@@ -0,0 +1,16 @@
|
||||
# Fins de ligne normalisées dans le dépôt
|
||||
* text=auto
|
||||
|
||||
*.c text eol=lf
|
||||
*.h text eol=lf
|
||||
*.py text eol=lf
|
||||
*.md text eol=lf
|
||||
*.txt text eol=lf
|
||||
|
||||
# Scripts Windows : CRLF obligatoire pour cmd.exe
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.gif binary
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
# ---------------------------------------------------------------------------
|
||||
# DoubleTroubleRecomp : AUCUN fichier du jeu ni dérivé du jeu dans le dépôt.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Sortie de compilation : C généré depuis TUCKER.EXE / INTRO.EXE, objets, exécutables,
|
||||
# désassemblages, captures et journaux
|
||||
build/
|
||||
|
||||
# Captures d'écran de test (images du jeu)
|
||||
frames*/
|
||||
captures/
|
||||
*.bmp
|
||||
*.wav
|
||||
|
||||
# Sauvegardes du joueur
|
||||
saves/
|
||||
*.DTA
|
||||
SAVEGM.*
|
||||
|
||||
# Fichiers originaux du jeu (à fournir par l'utilisateur)
|
||||
*.EXE
|
||||
*.exe
|
||||
*.ISO
|
||||
*.iso
|
||||
*.BIN
|
||||
*.CUE
|
||||
*.FLC
|
||||
*.flc
|
||||
*.PCX
|
||||
*.pcx
|
||||
*.SPR
|
||||
*.spr
|
||||
*.PIC
|
||||
*.pic
|
||||
*.RAW
|
||||
*.raw
|
||||
*.ENC
|
||||
|
||||
# Dépendances tierces téléchargées (SDL2, etc.)
|
||||
third_party/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
|
||||
# MSVC / éditeurs
|
||||
*.obj
|
||||
*.lib
|
||||
*.pdb
|
||||
*.ilk
|
||||
*.exp
|
||||
.vs/
|
||||
.vscode/
|
||||
*.user
|
||||
*.suo
|
||||
|
||||
# Système
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
.DS_Store
|
||||
@@ -0,0 +1,121 @@
|
||||
# DoubleTroubleRecomp
|
||||
|
||||
**Recompilation statique de *Bud Tucker in Double Trouble* (Merit Studios, DOS, 1996) en C natif.**
|
||||
|
||||
Plus de DOSBox : le code x86 d'origine est traduit en C, compilé pour Windows et branché sur SDL2.
|
||||
L'objectif est de redonner vie au jeu : beau et fluide sur grand écran, de 1080p à 4K, ouvert aux
|
||||
mods, sans jamais modifier ni redistribuer les fichiers originaux.
|
||||
|
||||
> ⚠️ Projet en cours de développement. **Vous devez posséder le jeu original** : ce dépôt ne
|
||||
> contient aucun fichier du jeu, ni aucun code généré à partir de ses exécutables.
|
||||
|
||||
---
|
||||
|
||||
## État
|
||||
|
||||
| Partie | État |
|
||||
|---|---|
|
||||
| Traduction x86 → C (`TUCKER.EXE` : 960 fonctions, `INTRO.EXE` : 540) | ✅ |
|
||||
| Runtime : CPU, FPU x87, DOS/4GW, VGA, minuterie PIT | ✅ |
|
||||
| Intro (logo Merit, titre, labo) | ✅ |
|
||||
| Jeu : lieux, interface, verbes, déplacements | ✅ jouable, en test |
|
||||
| Son : mixeur SDL2, émulation du pilote AIL (bruitages, musique, voix) | 🚧 |
|
||||
| Cinématiques | 🚧 |
|
||||
| Menu de réglages | 📋 prévu |
|
||||
| Upscale, filtres, pack HD | 📋 prévu |
|
||||
|
||||
La feuille de route complète est dans [docs/ROADMAP.md](docs/ROADMAP.md).
|
||||
|
||||
## Fonctionnement
|
||||
|
||||
```
|
||||
TUCKER.EXE / INTRO.EXE (LE, DOS/4GW, du joueur)
|
||||
│
|
||||
▼ tools/recomp.py (Capstone, descente récursive + relocations)
|
||||
build/gen_*/*.c ─────────► une fonction C par fonction x86
|
||||
│
|
||||
▼ MSVC
|
||||
runtime/ ── cpu, fpu, loader, dos, machine, audio, ail
|
||||
── overrides.c fonctions du jeu réécrites à la main (accroche des mods)
|
||||
── host_sdl.c fenêtre, clavier, souris, son
|
||||
│
|
||||
▼
|
||||
build/tucker.exe
|
||||
```
|
||||
|
||||
- **Traduction fidèle** : chaque instruction devient du C qui agit sur l'état du processeur émulé
|
||||
(registres, pile en mémoire, indicateurs calculés à la demande). Le comportement d'origine est
|
||||
conservé.
|
||||
- **Remplacements** : `runtime/overrides_tucker.txt` et `runtime/overrides_intro.txt` listent les
|
||||
adresses des fonctions remplacées par du C écrit à la main (`overrides.c`). La fonction d'origine
|
||||
reste disponible sous le nom `F_xxxxxxxx_orig`. Le son, les appels système, puis l'affichage et
|
||||
les mods passent par ce mécanisme.
|
||||
|
||||
## Compiler
|
||||
|
||||
### Prérequis
|
||||
|
||||
- Windows 10/11 x64
|
||||
- [Visual Studio Build Tools 2022](https://visualstudio.microsoft.com/downloads/) (outils C++)
|
||||
- Python 3.12 avec `capstone` 5 : `pip install capstone`
|
||||
- [SDL2 2.32.10](https://github.com/libsdl-org/SDL/releases) (archive `SDL2-devel-2.32.10-VC.zip`),
|
||||
décompressée dans `third_party/SDL2-2.32.10/`
|
||||
- Le jeu original (CD ou ISO)
|
||||
|
||||
### Fichiers du jeu
|
||||
|
||||
Par défaut, le projet cherche :
|
||||
|
||||
| Option | Défaut | Contenu |
|
||||
|---|---|---|
|
||||
| `--cd` | `../extracted/iso/TUCKER` | fichiers du CD (dont `TUCKER.EXE`, `INTRO.EXE`) |
|
||||
| `--hd` | `../Install/C/TUCKER` | fichiers installés sur le disque |
|
||||
| `--root` | `../Install/C` | racine du « C: » vu par le jeu |
|
||||
| `--saves` | `saves` | sauvegardes |
|
||||
|
||||
### Compilation
|
||||
|
||||
```bat
|
||||
build.bat :: génère le C depuis les EXE du joueur, puis compile
|
||||
build.bat nogen :: recompile sans régénérer
|
||||
```
|
||||
|
||||
Résultat : `build\tucker.exe` (SDL2) et `build\tucker_headless.exe` (sans affichage, pour les tests).
|
||||
|
||||
## Lancer
|
||||
|
||||
```bat
|
||||
build\tucker.exe --son
|
||||
```
|
||||
|
||||
| Option | Effet |
|
||||
|---|---|
|
||||
| `--son` | active le son |
|
||||
| `--sans-intro` | lance directement le jeu |
|
||||
| `--intro` | ne joue que l'intro |
|
||||
| `--echelle N` | taille de la fenêtre (défaut 3 : 960×720) |
|
||||
| `--plein` | démarre en plein écran |
|
||||
| `-v` | journal détaillé |
|
||||
|
||||
**F11** ou **Alt+Entrée** : plein écran.
|
||||
|
||||
## Arborescence
|
||||
|
||||
```
|
||||
build.bat compilation (MSVC)
|
||||
tools/
|
||||
le.py lecteur du format LE (DOS/4GW)
|
||||
recomp.py traducteur x86 → C
|
||||
runtime/ runtime C (CPU, DOS, matériel, son, hôtes, remplacements)
|
||||
docs/ feuille de route, notes techniques
|
||||
```
|
||||
|
||||
## Cadre légal
|
||||
|
||||
*Bud Tucker in Double Trouble* © 1996 Merit Studios. Ce projet n'est affilié à aucun ayant droit.
|
||||
Il ne contient et ne distribue aucun fichier du jeu, ni aucun code dérivé de ses exécutables : le C
|
||||
est généré localement, à partir de la copie du joueur, dans `build/` (exclu du dépôt).
|
||||
|
||||
## Licence
|
||||
|
||||
À définir.
|
||||
@@ -0,0 +1,27 @@
|
||||
@echo off
|
||||
rem Compile tucker-recomp avec MSVC (Build Tools 2022).
|
||||
rem build.bat -> regenere le C (TUCKER.EXE et INTRO.EXE) puis compile build\tucker.exe et build\tucker_headless.exe
|
||||
rem build.bat nogen -> compile sans regenerer
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
if not defined VCINSTALLDIR call "C:\Program Files (x86)\Microsoft Visual Studio\2022\BuildTools\VC\Auxiliary\Build\vcvars64.bat" >nul || exit /b 1
|
||||
set SDL=third_party\SDL2-2.32.10
|
||||
set ISO=..\extracted\iso\TUCKER
|
||||
|
||||
if /i not "%1"=="nogen" (
|
||||
python -I tools\recomp.py "%ISO%\TUCKER.EXE" build\gen_tucker tucker F || exit /b 1
|
||||
python -I tools\recomp.py "%ISO%\INTRO.EXE" build\gen_intro intro I || exit /b 1
|
||||
)
|
||||
if not exist build\obj mkdir build\obj
|
||||
|
||||
set CFLAGS=/nologo /O2 /GS- /W3 /wd4146 /wd4244 /wd4018 /wd4102 /wd4101 /wd4189 /MP /utf-8 /Iruntime /Ibuild\gen_tucker /Ibuild\gen_intro /I%SDL%\include /D_CRT_SECURE_NO_WARNINGS /Fobuild\obj\
|
||||
cl %CFLAGS% /c runtime\cpu.c runtime\fpu.c runtime\loader.c runtime\dos.c runtime\machine.c runtime\audio.c runtime\ail.c runtime\overrides.c runtime\main.c build\gen_tucker\*.c build\gen_intro\*.c || exit /b 1
|
||||
cl %CFLAGS% /c runtime\host_headless.c runtime\host_sdl.c || exit /b 1
|
||||
|
||||
if not exist build\lib mkdir build\lib
|
||||
lib /nologo /OUT:build\lib\jeu.lib build\obj\cpu.obj build\obj\fpu.obj build\obj\loader.obj build\obj\dos.obj build\obj\machine.obj build\obj\audio.obj build\obj\ail.obj build\obj\overrides.obj build\obj\main.obj build\obj\tucker_*.obj build\obj\intro_*.obj || exit /b 1
|
||||
|
||||
link /nologo /STACK:67108864 /OUT:build\tucker_headless.exe build\obj\host_headless.obj build\lib\jeu.lib || exit /b 1
|
||||
link /nologo /STACK:67108864 /SUBSYSTEM:CONSOLE /OUT:build\tucker.exe build\obj\host_sdl.obj build\lib\jeu.lib %SDL%\lib\x64\SDL2.lib || exit /b 1
|
||||
copy /y %SDL%\lib\x64\SDL2.dll build\ >nul
|
||||
echo OK : build\tucker.exe et build\tucker_headless.exe
|
||||
@@ -0,0 +1,89 @@
|
||||
# DoubleTroubleRecomp : feuille de route
|
||||
|
||||
Recompilation statique de *Bud Tucker in Double Trouble* (DOS, 1996) en C, pour redonner vie au jeu
|
||||
sur les machines et les écrans d'aujourd'hui.
|
||||
|
||||
**Objectif :** un jeu beau et fluide sur grand écran, de 1080p à 4K (1440p minimum visé), à la cadence
|
||||
d'origine (pas de course aux FPS).
|
||||
|
||||
**Règle d'or :** le dépôt ne contient aucun fichier du jeu. Tout ce qui est généré à partir de
|
||||
TUCKER.EXE et INTRO.EXE reste local (`build/`). Les mods remplacent les fichiers à l'exécution, sans
|
||||
jamais modifier les originaux.
|
||||
|
||||
---
|
||||
|
||||
## État actuel (2026-12-05)
|
||||
|
||||
- [x] Traducteur x86 vers C (`tools/recomp.py`) : 960 fonctions pour TUCKER.EXE, 540 pour INTRO.EXE
|
||||
- [x] Runtime : CPU, FPU, DOS/DOS4GW, VGA, PIT, hôtes SDL2 et headless
|
||||
- [x] L'intro (Merit, titre, labo) tourne entièrement
|
||||
- [x] Le jeu tourne : chambre de Bud, interface, verbes, déplacements
|
||||
- [x] Son : mixeur SDL2, remplacement des fonctions AIL (bruitages, musique, voix)
|
||||
- [ ] Cinématiques : son en flux de l'intro, séquences *(en cours)*
|
||||
- [ ] Menu de réglages (volumes, affichage)
|
||||
- [ ] Mod graphique : upscale
|
||||
|
||||
---
|
||||
|
||||
## 1. Visuel : « beau sur grand écran »
|
||||
|
||||
- [ ] **Mise à l'échelle propre** : correction du format 4:3 (×1,2 en hauteur), image centrée,
|
||||
synchronisation verticale ; logique à 46 Hz et affichage au rythme de l'écran
|
||||
- [ ] **Filtres au choix** : pixels nets (facteur entier), lissé (xBRZ, ScaleFX), shader CRT
|
||||
- [ ] **Pack HD** : décors et sprites agrandis par IA puis retouchés, chargés à la place des
|
||||
originaux
|
||||
- [ ] **Basculement original ↔ HD** sur une touche (F1), avec un fondu
|
||||
- [ ] **Écran large sans bandes noires** : bords remplis par le décor flouté ou une illustration
|
||||
- [ ] **Cinématiques FLC agrandies**
|
||||
- [ ] Police HD pour les textes et les sous-titres
|
||||
|
||||
## 2. Son
|
||||
|
||||
- [ ] Musique MIDI en haute qualité : banque de sons (SoundFont), mode Roland MT-32 en option
|
||||
- [ ] Pack de musiques réenregistrées, chargées à la place des originales
|
||||
- [ ] Voix nettoyées (débruitage, agrandissement)
|
||||
- [ ] Volumes séparés : musique, voix, bruitages
|
||||
|
||||
## 3. Confort de jeu moderne
|
||||
|
||||
- [ ] Afficher les zones cliquables en maintenant Espace
|
||||
- [ ] Double-clic sur une sortie pour changer de lieu instantanément
|
||||
- [ ] Passer les dialogues au clic ; accélérer les déplacements de Bud
|
||||
- [ ] Sauvegarde automatique ; emplacements illimités avec miniature
|
||||
- [ ] Manette : curseur au joystick, roue des verbes
|
||||
- [ ] Sous-titres toujours affichés
|
||||
|
||||
## 4. Langues et accessibilité
|
||||
|
||||
- [ ] Choix de la langue au lancement (français, anglais selon la version possédée)
|
||||
- [ ] Traductions de la communauté (textes des fichiers `.C`)
|
||||
- [ ] Polices agrandies, mode contraste élevé
|
||||
|
||||
## 5. Ouvert aux mods
|
||||
|
||||
- [ ] Dossier `mods/` : chaque mod remplace des images, des sons ou des textes ; empilés par
|
||||
ordre de priorité
|
||||
- [ ] Mode développeur (F12) : zones et chemins de marche, variables, saut vers un lieu, captures
|
||||
(repartir de `tucker-viewer`)
|
||||
- [ ] Accès aux fonctions du jeu en C, sur le modèle de `overrides.txt` et `overrides.c`
|
||||
- [ ] Documentation du format des mods
|
||||
|
||||
## 6. Préservation et diffusion
|
||||
|
||||
- [ ] Installation légale : au premier lancement, le moteur demande le CD ou l'ISO, vérifie les
|
||||
empreintes, puis génère et compile
|
||||
- [ ] `.gitignore` strict : `build/`, `frames*/`, `saves/`, `third_party/dl/`, tout ce qui vient de
|
||||
l'ISO
|
||||
- [ ] Version web (Emscripten), jouable avec les fichiers du joueur
|
||||
- [ ] Wiki technique tiré de `ANALYSE_TUCKER.md` (formats, langage des cinématiques, structures)
|
||||
- [ ] README avec une galerie avant/après (curseur glissant, GIF ou vidéo)
|
||||
|
||||
---
|
||||
|
||||
## Top 5 pour la première version publique
|
||||
|
||||
1. Basculement original ↔ HD sur une touche
|
||||
2. Affichage des zones cliquables
|
||||
3. Musique en haute qualité
|
||||
4. Installation à partir du CD de l'utilisateur, sans fichiers du jeu dans le dépôt
|
||||
5. README avec une galerie avant/après
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
/* Émulation de l'API Miles AIL 3 (« Audio Interface Library ») au niveau de ses fonctions publiques.
|
||||
* Le vrai AIL charge un pilote .DIG 16 bits impossible à recompiler ; ici chaque canal (HSAMPLE)
|
||||
* devient une voix du mixeur (audio.c). Convention : cdecl, arguments sur la pile, résultat dans eax,
|
||||
* l'appelant dépile. Les fonctions ail_* lisent les arguments, rendent eax et font le « ret ».
|
||||
*
|
||||
* Programme qui l'utilise : INTRO.EXE (liste des adresses dans overrides_intro.txt). */
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
#define ARG(n) RD32(R(4) + 4 + 4 * (n))
|
||||
#define RET(v) do { R(0) = (uint32_t)(v); R(4) += 4; } while (0)
|
||||
|
||||
#define AIL_DRV 0x03ff0000u /* poignée du pilote numérique (jamais déréférencée) */
|
||||
#define AIL_HBASE 0x03ff1000u /* poignées de canaux : AIL_HBASE + 0x40 * i */
|
||||
#define AIL_NCH (AUDIO_VOICES - AUDIO_AIL_FIRST)
|
||||
|
||||
static int used[AIL_NCH];
|
||||
static int32_t prefs[64];
|
||||
int (*ail_group_hint)(uint32_t hsample);
|
||||
|
||||
void ail_reset(void) {
|
||||
int i;
|
||||
for (i = 0; i < AIL_NCH; i++) if (used[i]) audio_v_free(AUDIO_AIL_FIRST + i);
|
||||
memset(used, 0, sizeof used);
|
||||
memset(prefs, 0, sizeof prefs);
|
||||
ail_group_hint = NULL;
|
||||
}
|
||||
|
||||
/* poignée -> voix du mixeur, ou -1 */
|
||||
static int voice_of(uint32_t h) {
|
||||
uint32_t i = (h - AIL_HBASE) / 0x40;
|
||||
if (h < AIL_HBASE || (h - AIL_HBASE) % 0x40 || i >= AIL_NCH || !used[i]) return -1;
|
||||
return AUDIO_AIL_FIRST + (int)i;
|
||||
}
|
||||
|
||||
static int group_of(uint32_t h, int def) {
|
||||
int g = ail_group_hint ? ail_group_hint(h) : -1;
|
||||
return g >= 0 ? g : def;
|
||||
}
|
||||
|
||||
static void trace(const char *what, uint32_t h, uint32_t a, uint32_t b) {
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[ail] %s(%08x, %u, %u)\n", what, h, a, b);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ système */
|
||||
void ail_startup(void) { RET(0); }
|
||||
void ail_shutdown(void) { ail_reset(); RET(0); }
|
||||
|
||||
void ail_set_preference(void) { /* S32 AIL_set_preference(U32 n, S32 valeur) -> ancienne */
|
||||
uint32_t n = ARG(0) & 63;
|
||||
int32_t old = prefs[n];
|
||||
prefs[n] = (int32_t)ARG(1);
|
||||
RET(old);
|
||||
}
|
||||
|
||||
void ail_install_DIG_INI(void) { RET(AIL_DRV); } /* HDIGDRIVER AIL_install_DIG_INI(void) */
|
||||
|
||||
void ail_minimum_sample_buffer_size(void) { /* S32 (HDIGDRIVER, S32 débit, S32 format) */
|
||||
RET(0x2000);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ canaux */
|
||||
void ail_allocate_sample_handle(void) { /* HSAMPLE AIL_allocate_sample_handle(HDIGDRIVER) */
|
||||
int i;
|
||||
for (i = 0; i < AIL_NCH; i++)
|
||||
if (!used[i]) {
|
||||
used[i] = 1;
|
||||
audio_v_init(AUDIO_AIL_FIRST + i, AUDIO_FX);
|
||||
RET(AIL_HBASE + 0x40u * (uint32_t)i);
|
||||
return;
|
||||
}
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_release_sample_handle(void) {
|
||||
uint32_t h = ARG(0);
|
||||
int v = voice_of(h);
|
||||
if (v >= 0) { audio_v_free(v); used[v - AUDIO_AIL_FIRST] = 0; }
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_init_sample(void) {
|
||||
int v = voice_of(ARG(0));
|
||||
if (v >= 0) audio_v_init(v, AUDIO_FX);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_set_sample_file(void) { /* S32 (HSAMPLE, void *image, S32 bloc) -> 1 si reconnu */
|
||||
uint32_t h = ARG(0), img = ARG(1), len;
|
||||
int v = voice_of(h), ok = 0;
|
||||
if (v >= 0 && RD32(img) == 0x46464952u) { /* "RIFF" */
|
||||
len = RD32(img + 4) + 8;
|
||||
if (len < (64u << 20)) ok = audio_v_load_wav(v, M + (img & MEM_MASK), len);
|
||||
}
|
||||
trace("set_sample_file", h, img, ok);
|
||||
RET(ok);
|
||||
}
|
||||
|
||||
void ail_set_sample_type(void) { /* (HSAMPLE, S32 format, U32 options) */
|
||||
int v = voice_of(ARG(0));
|
||||
uint32_t fmt = ARG(1), flags = ARG(2);
|
||||
if (v >= 0) audio_v_format(v, fmt & 1, (fmt & 2) != 0, flags & 1);
|
||||
trace("set_sample_type", ARG(0), fmt, flags);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_set_sample_playback_rate(void) {
|
||||
int v = voice_of(ARG(0));
|
||||
if (v >= 0 && ARG(1)) audio_v_rate(v, ARG(1));
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_set_sample_volume(void) {
|
||||
int v = voice_of(ARG(0));
|
||||
if (v >= 0) audio_v_volume(v, (int)ARG(1));
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_set_sample_loop_count(void) {
|
||||
int v = voice_of(ARG(0));
|
||||
if (v >= 0) audio_v_loops(v, (int)ARG(1));
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_start_sample(void) {
|
||||
uint32_t h = ARG(0);
|
||||
int v = voice_of(h);
|
||||
if (v >= 0) { audio_v_group(v, group_of(h, AUDIO_FX)); audio_v_start(v); }
|
||||
trace("start_sample", h, 0, 0);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_stop_sample(void) { /* pause : l'état devient SMP_STOPPED */
|
||||
int v = voice_of(ARG(0));
|
||||
if (v >= 0) audio_v_pause(v, 1);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_resume_sample(void) {
|
||||
int v = voice_of(ARG(0));
|
||||
if (v >= 0) audio_v_pause(v, 0);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_end_sample(void) {
|
||||
int v = voice_of(ARG(0));
|
||||
if (v >= 0) audio_v_end(v);
|
||||
RET(0);
|
||||
}
|
||||
|
||||
void ail_sample_status(void) { /* SMP_FREE 1, SMP_DONE 2, SMP_PLAYING 4, SMP_STOPPED 8 */
|
||||
int v = voice_of(ARG(0));
|
||||
RET(v < 0 ? 1 : audio_v_status(v));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ double tampon (lecture en flux) */
|
||||
void ail_sample_buffer_ready(void) { /* S32 (HSAMPLE) -> 0 ou 1 = tampon à remplir, -1 sinon */
|
||||
int v = voice_of(ARG(0));
|
||||
RET(v < 0 ? -1 : audio_v_ready(v));
|
||||
}
|
||||
|
||||
void ail_load_sample_buffer(void) { /* (HSAMPLE, U32 n°, void *données, U32 taille) ; démarre la lecture */
|
||||
uint32_t h = ARG(0), n = ARG(1), p = ARG(2), len = ARG(3);
|
||||
int v = voice_of(h);
|
||||
if (v >= 0) {
|
||||
audio_v_group(v, group_of(h, AUDIO_SPEECH));
|
||||
audio_v_queue(v, (int)n, M + (p & MEM_MASK), len > (16u << 20) ? 0 : len);
|
||||
}
|
||||
if (rt_cfg.verbose) {
|
||||
static int shown;
|
||||
if (shown++ < 6) fprintf(stderr, "[ail] load_sample_buffer(%08x, %u, %08x, %u) %02x %02x %02x %02x %02x %02x %02x %02x\n",
|
||||
h, n, p, len, RD8(p), RD8(p + 1), RD8(p + 2), RD8(p + 3), RD8(p + 4), RD8(p + 5), RD8(p + 6), RD8(p + 7));
|
||||
}
|
||||
RET(0);
|
||||
}
|
||||
+355
@@ -0,0 +1,355 @@
|
||||
/* Mixeur audio : remplace Miles AIL. Indépendant de l'hôte : l'hôte appelle audio_mix() depuis
|
||||
* son fil audio (SDL) ou à chaque image (sans fenêtre), et fournit host_audio_lock/unlock.
|
||||
*
|
||||
* Voix 0..36 : module son de TUCKER.EXE (overrides.c)
|
||||
* bruitages : 32 voix, « en cours » en [0x46644 + 4n] (n < 7)
|
||||
* musiques : 4 voix, « en cours » en [0x4663c + 4n] (n < 2)
|
||||
* voix : 1 voix, speech\samNNNN.wav lu sur le CD, « en cours » en [0x46638]
|
||||
* Voix 40..63 : canaux AIL émulés (ail.c), utilisés par INTRO.EXE ; double tampon possible. */
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
typedef struct {
|
||||
int16_t *pcm; /* échantillons 16 bits, entrelacés si stéréo */
|
||||
uint32_t frames;
|
||||
} Chunk;
|
||||
|
||||
typedef struct {
|
||||
Chunk main; /* son entier (fichier) */
|
||||
Chunk buf[2]; /* double tampon (flux) */
|
||||
int streaming, play_buf, buf_full[2], next_load, stream_end;
|
||||
int chans; /* 1 ou 2 */
|
||||
int bits16, sign8; /* format des données brutes chargées en flux */
|
||||
uint32_t rate;
|
||||
uint64_t pos, step; /* position et pas en 32.32 */
|
||||
int vol; /* 0..127, volume demandé par le jeu */
|
||||
int loops; /* 0 = infini, sinon nombre de passages restants */
|
||||
int group;
|
||||
int active, paused, ended;
|
||||
uint32_t flag_addr; /* indicateur du jeu remis à 0 en fin de lecture (0 = aucun) */
|
||||
} Voice;
|
||||
|
||||
static Voice voices[AUDIO_VOICES];
|
||||
int audio_volume[AUDIO_GROUPS] = {100, 100, 100}; /* réglages utilisateur, en % */
|
||||
int audio_master = 100;
|
||||
|
||||
static int fixed_voice(int group, int ch) {
|
||||
return group == AUDIO_FX ? ch : group == AUDIO_MUSIC ? AUDIO_FX_CH + ch : AUDIO_FX_CH + AUDIO_MUS_CH;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ WAV → PCM 16 bits */
|
||||
static int16_t *to_pcm16(const uint8_t *d, uint32_t len, int bits16, int sign8, uint32_t *samples) {
|
||||
uint32_t i, n = bits16 ? len / 2 : len;
|
||||
int16_t *p = (int16_t *)malloc((n ? n : 1) * sizeof(int16_t));
|
||||
if (!p) return NULL;
|
||||
for (i = 0; i < n; i++)
|
||||
p[i] = bits16 ? (int16_t)(d[2 * i] | d[2 * i + 1] << 8)
|
||||
: (int16_t)(sign8 ? (int8_t)d[i] << 8 : (d[i] - 128) << 8);
|
||||
*samples = n;
|
||||
return p;
|
||||
}
|
||||
|
||||
static int wav_decode(const uint8_t *d, uint32_t len, Chunk *c, int *chans, uint32_t *rate) {
|
||||
uint32_t p = 12, fmt_ch = 0, bits = 0, data_off = 0, data_len = 0, n;
|
||||
uint16_t tag = 1;
|
||||
if (len < 12 || memcmp(d, "RIFF", 4) || memcmp(d + 8, "WAVE", 4)) return 0;
|
||||
*rate = 0;
|
||||
while (p + 8 <= len) {
|
||||
uint32_t sz = d[p + 4] | d[p + 5] << 8 | d[p + 6] << 16 | (uint32_t)d[p + 7] << 24;
|
||||
if (!memcmp(d + p, "fmt ", 4) && p + 24 <= len) {
|
||||
tag = (uint16_t)(d[p + 8] | d[p + 9] << 8);
|
||||
fmt_ch = d[p + 10] | d[p + 11] << 8;
|
||||
*rate = d[p + 12] | d[p + 13] << 8 | d[p + 14] << 16 | (uint32_t)d[p + 15] << 24;
|
||||
bits = d[p + 22] | d[p + 23] << 8;
|
||||
} else if (!memcmp(d + p, "data", 4)) {
|
||||
data_off = p + 8;
|
||||
data_len = sz;
|
||||
if (data_off + data_len > len) data_len = len - data_off;
|
||||
break;
|
||||
}
|
||||
p += 8 + sz + (sz & 1);
|
||||
}
|
||||
if (tag != 1 || !data_off || !*rate || (bits != 8 && bits != 16) || fmt_ch < 1 || fmt_ch > 2) return 0;
|
||||
c->pcm = to_pcm16(d + data_off, data_len, bits == 16, 0, &n);
|
||||
if (!c->pcm) return 0;
|
||||
*chans = (int)fmt_ch;
|
||||
c->frames = n / fmt_ch;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void chunk_free(Chunk *c) { free(c->pcm); c->pcm = NULL; c->frames = 0; }
|
||||
|
||||
static void voice_clear(Voice *v) {
|
||||
chunk_free(&v->main); chunk_free(&v->buf[0]); chunk_free(&v->buf[1]);
|
||||
memset(v, 0, sizeof *v);
|
||||
}
|
||||
|
||||
static void set_step(Voice *v) { v->step = v->rate ? ((uint64_t)v->rate << 32) / AUDIO_RATE : 0; }
|
||||
|
||||
/* ------------------------------------------------------------------ mixage (fil audio) */
|
||||
static const Chunk *cur_chunk(Voice *v) {
|
||||
return v->streaming ? &v->buf[v->play_buf] : &v->main;
|
||||
}
|
||||
|
||||
void audio_mix(int16_t *out, int frames) {
|
||||
int i, k;
|
||||
static int32_t acc[2 * 4096];
|
||||
while (frames > 0) {
|
||||
int n = frames > 4096 ? 4096 : frames;
|
||||
memset(acc, 0, (size_t)n * 2 * sizeof(int32_t));
|
||||
for (k = 0; k < AUDIO_VOICES; k++) {
|
||||
Voice *v = &voices[k];
|
||||
int32_t gain;
|
||||
if (!v->active || v->paused) continue;
|
||||
gain = v->vol * audio_volume[v->group] * audio_master / 100; /* 0..12700 */
|
||||
for (i = 0; i < n; i++) {
|
||||
const Chunk *c = cur_chunk(v);
|
||||
uint32_t f = (uint32_t)(v->pos >> 32), f2;
|
||||
int32_t frac = (int32_t)((v->pos >> 16) & 0xffff), l, r;
|
||||
if (f >= c->frames) {
|
||||
if (v->streaming) { /* tampon fini : on passe à l'autre */
|
||||
if (c->frames) { v->buf_full[v->play_buf] = 0; v->play_buf ^= 1; v->pos = 0; }
|
||||
if (!v->buf_full[v->play_buf]) {
|
||||
if (v->stream_end) { v->active = 0; v->ended = 1; }
|
||||
break; /* famine : silence en attendant */
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (v->loops != 1) {
|
||||
if (v->loops > 1) v->loops--;
|
||||
v->pos -= (uint64_t)c->frames << 32;
|
||||
if ((uint32_t)(v->pos >> 32) >= c->frames) v->pos = 0;
|
||||
f = (uint32_t)(v->pos >> 32);
|
||||
} else { v->active = 0; v->ended = 1; break; }
|
||||
}
|
||||
f2 = f + 1 < c->frames ? f + 1 : f;
|
||||
if (v->chans == 1) {
|
||||
int32_t a = c->pcm[f], b = c->pcm[f2];
|
||||
l = r = a + ((b - a) * frac >> 16);
|
||||
} else {
|
||||
int32_t a = c->pcm[2 * f], b = c->pcm[2 * f2], cc = c->pcm[2 * f + 1], d = c->pcm[2 * f2 + 1];
|
||||
l = a + ((b - a) * frac >> 16);
|
||||
r = cc + ((d - cc) * frac >> 16);
|
||||
}
|
||||
acc[2 * i] += l * gain / 12700;
|
||||
acc[2 * i + 1] += r * gain / 12700;
|
||||
v->pos += v->step;
|
||||
}
|
||||
}
|
||||
for (i = 0; i < 2 * n; i++) out[i] = (int16_t)(acc[i] > 32767 ? 32767 : acc[i] < -32768 ? -32768 : acc[i]);
|
||||
out += 2 * n;
|
||||
frames -= n;
|
||||
}
|
||||
}
|
||||
|
||||
/* fil principal : fin de lecture → remise à zéro des indicateurs du jeu */
|
||||
void audio_update(void) {
|
||||
int k;
|
||||
host_audio_lock();
|
||||
for (k = 0; k < AUDIO_VOICES; k++) {
|
||||
Voice *v = &voices[k];
|
||||
if (v->ended && v->flag_addr) { WR32(v->flag_addr, 0); v->flag_addr = 0; }
|
||||
}
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_reset(void) {
|
||||
int k;
|
||||
host_audio_lock();
|
||||
for (k = 0; k < AUDIO_VOICES; k++) voice_clear(&voices[k]);
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ voix génériques (ail.c) */
|
||||
void audio_v_init(int k, int group) {
|
||||
host_audio_lock();
|
||||
voice_clear(&voices[k]);
|
||||
voices[k].group = group;
|
||||
voices[k].vol = 127;
|
||||
voices[k].loops = 1;
|
||||
voices[k].chans = 1;
|
||||
voices[k].rate = 11025;
|
||||
set_step(&voices[k]);
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
int audio_v_load_wav(int k, const uint8_t *wav, uint32_t len) {
|
||||
Voice *v = &voices[k];
|
||||
Chunk c = {0};
|
||||
int chans;
|
||||
uint32_t rate;
|
||||
if (!wav_decode(wav, len, &c, &chans, &rate)) return 0;
|
||||
host_audio_lock();
|
||||
chunk_free(&v->main); chunk_free(&v->buf[0]); chunk_free(&v->buf[1]);
|
||||
v->main = c; v->chans = chans; v->rate = rate; set_step(v);
|
||||
v->streaming = 0; v->active = 0; v->ended = 0; v->pos = 0;
|
||||
host_audio_unlock();
|
||||
return 1;
|
||||
}
|
||||
|
||||
void audio_v_format(int k, int bits16, int stereo, int sign8) {
|
||||
Voice *v = &voices[k];
|
||||
host_audio_lock();
|
||||
v->bits16 = bits16; v->chans = stereo ? 2 : 1; v->sign8 = sign8;
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_v_rate(int k, uint32_t rate) {
|
||||
host_audio_lock();
|
||||
voices[k].rate = rate; set_step(&voices[k]);
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_v_volume(int k, int vol) {
|
||||
host_audio_lock();
|
||||
voices[k].vol = vol < 0 ? 0 : vol > 127 ? 127 : vol;
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_v_loops(int k, int loops) {
|
||||
host_audio_lock();
|
||||
voices[k].loops = loops < 0 ? 1 : loops;
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_v_group(int k, int group) { voices[k].group = group; }
|
||||
|
||||
void audio_v_start(int k) {
|
||||
Voice *v = &voices[k];
|
||||
host_audio_lock();
|
||||
if (!v->streaming) { v->pos = 0; v->active = v->main.frames != 0; }
|
||||
else v->active = 1;
|
||||
v->paused = 0; v->ended = 0;
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_v_pause(int k, int paused) {
|
||||
host_audio_lock();
|
||||
voices[k].paused = paused;
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_v_end(int k) {
|
||||
Voice *v = &voices[k];
|
||||
host_audio_lock();
|
||||
v->active = 0; v->ended = 1; v->paused = 0;
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_v_free(int k) {
|
||||
host_audio_lock();
|
||||
voice_clear(&voices[k]);
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
/* AIL : SMP_FREE 1, SMP_DONE 2, SMP_PLAYING 4, SMP_STOPPED 8 */
|
||||
int audio_v_status(int k) {
|
||||
Voice *v = &voices[k];
|
||||
if (v->active) return v->paused ? 8 : 4;
|
||||
return 2;
|
||||
}
|
||||
|
||||
/* double tampon : indice du tampon à remplir, ou -1 */
|
||||
int audio_v_ready(int k) {
|
||||
Voice *v = &voices[k];
|
||||
int r;
|
||||
host_audio_lock();
|
||||
if (!v->streaming) { v->streaming = 1; v->play_buf = 0; v->next_load = 0; v->buf_full[0] = v->buf_full[1] = 0; v->stream_end = 0; }
|
||||
r = v->buf_full[v->next_load] ? -1 : v->next_load;
|
||||
host_audio_unlock();
|
||||
return r;
|
||||
}
|
||||
|
||||
void audio_v_queue(int k, int slot, const uint8_t *data, uint32_t len) {
|
||||
Voice *v = &voices[k];
|
||||
uint32_t n = 0;
|
||||
int16_t *p = len ? to_pcm16(data, len, v->bits16, v->sign8, &n) : NULL;
|
||||
host_audio_lock();
|
||||
slot &= 1;
|
||||
if (!v->streaming) { v->streaming = 1; v->play_buf = slot; v->buf_full[0] = v->buf_full[1] = 0; v->stream_end = 0; v->pos = 0; }
|
||||
chunk_free(&v->buf[slot]);
|
||||
if (p && n >= (uint32_t)v->chans) {
|
||||
v->buf[slot].pcm = p; v->buf[slot].frames = n / (uint32_t)v->chans;
|
||||
v->buf_full[slot] = 1;
|
||||
if (!v->active) { v->active = 1; v->ended = 0; if (!v->buf_full[v->play_buf]) v->play_buf = slot; }
|
||||
} else {
|
||||
free(p);
|
||||
v->stream_end = 1; /* tampon vide : fin du flux */
|
||||
}
|
||||
v->next_load = slot ^ 1;
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ API du module son de TUCKER.EXE */
|
||||
static uint32_t wav_size(uint32_t a) { /* taille d'une image RIFF en mémoire du jeu */
|
||||
if (RD32(a) != 0x46464952u) return 0; /* "RIFF" */
|
||||
return RD32(a + 4) + 8;
|
||||
}
|
||||
|
||||
static int start_fixed(int group, int ch, const uint8_t *wav, uint32_t len, int vol, int loop, uint32_t flag) {
|
||||
int k = fixed_voice(group, ch);
|
||||
audio_v_init(k, group);
|
||||
if (!audio_v_load_wav(k, wav, len)) {
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[son] WAV illisible (groupe %d, canal %d)\n", group, ch);
|
||||
if (flag) WR32(flag, 0);
|
||||
return 0;
|
||||
}
|
||||
if (rt_cfg.verbose)
|
||||
fprintf(stderr, "[son] groupe %d canal %d : %u Hz, %d voie(s), %.2f s, volume %d%s\n", group, ch,
|
||||
voices[k].rate, voices[k].chans, voices[k].main.frames / (double)voices[k].rate, vol,
|
||||
loop ? ", en boucle" : "");
|
||||
audio_v_volume(k, vol);
|
||||
audio_v_loops(k, loop ? 0 : 1);
|
||||
host_audio_lock();
|
||||
voices[k].flag_addr = flag;
|
||||
host_audio_unlock();
|
||||
audio_v_start(k);
|
||||
if (flag) WR32(flag, 1);
|
||||
return 1;
|
||||
}
|
||||
|
||||
void audio_play_mem(int group, int ch, uint32_t addr, int vol, int loop, uint32_t flag) {
|
||||
uint32_t len = wav_size(addr);
|
||||
if (!len || len > 64u << 20) {
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[son] pas de WAV en %08x\n", addr);
|
||||
if (flag) WR32(flag, 0);
|
||||
return;
|
||||
}
|
||||
start_fixed(group, ch, M + (addr & MEM_MASK), len, vol, loop, flag);
|
||||
}
|
||||
|
||||
int audio_play_file(int group, int ch, const char *dos_name, int vol, uint32_t flag) {
|
||||
char path[600];
|
||||
FILE *f;
|
||||
long len;
|
||||
uint8_t *buf;
|
||||
int ok = 0;
|
||||
if (!dos_map_path(dos_name, path, sizeof path, 0) || !(f = fopen(path, "rb"))) {
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[son] introuvable : %s\n", dos_name);
|
||||
return 0;
|
||||
}
|
||||
fseek(f, 0, SEEK_END);
|
||||
len = ftell(f);
|
||||
fseek(f, 0, SEEK_SET);
|
||||
buf = (uint8_t *)malloc(len > 0 ? (size_t)len : 1);
|
||||
if (buf && fread(buf, 1, (size_t)len, f) == (size_t)len)
|
||||
ok = start_fixed(group, ch, buf, (uint32_t)len, vol, 0, flag);
|
||||
free(buf);
|
||||
fclose(f);
|
||||
return ok;
|
||||
}
|
||||
|
||||
void audio_stop(int group, int ch) {
|
||||
int k = fixed_voice(group, ch);
|
||||
host_audio_lock();
|
||||
if (voices[k].flag_addr) WR32(voices[k].flag_addr, 0);
|
||||
voice_clear(&voices[k]);
|
||||
host_audio_unlock();
|
||||
}
|
||||
|
||||
void audio_set_volume(int group, int ch, int vol) { audio_v_volume(fixed_voice(group, ch), vol); }
|
||||
|
||||
int audio_playing(int group, int ch) { return voices[fixed_voice(group, ch)].active; }
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
/* Primitives du processeur émulé : indicateurs, décalages, divisions, chaînes, appels indirects. */
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
const FnEntry *cur_fn_table;
|
||||
unsigned cur_fn_count;
|
||||
|
||||
Cpu cpu;
|
||||
uint8_t *M;
|
||||
|
||||
void PUSHAD(void) {
|
||||
uint32_t sp = R(4);
|
||||
PUSH32(R(0)); PUSH32(R(1)); PUSH32(R(2)); PUSH32(R(3));
|
||||
PUSH32(sp); PUSH32(R(5)); PUSH32(R(6)); PUSH32(R(7));
|
||||
}
|
||||
|
||||
void POPAD(void) {
|
||||
R(7) = POP32(); R(6) = POP32(); R(5) = POP32(); (void)POP32();
|
||||
R(3) = POP32(); R(2) = POP32(); R(1) = POP32(); R(0) = POP32();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ indicateurs */
|
||||
uint32_t get_eflags(void) {
|
||||
return (uint32_t)cCF() | ((uint32_t)cPF() << 2) | ((uint32_t)cAF() << 4) | ((uint32_t)cZF() << 6)
|
||||
| ((uint32_t)cSF() << 7) | (cpu.df << 10) | ((uint32_t)cOF() << 11) | 0x202u;
|
||||
}
|
||||
|
||||
void set_eflags(uint32_t v) {
|
||||
cpu.lf_op = LF_FIXED;
|
||||
cpu.lf_flags = v;
|
||||
cpu.df = (v >> 10) & 1u;
|
||||
}
|
||||
|
||||
void LF_MULFLAGS(int cf_of) {
|
||||
uint32_t f = get_eflags() & ~0x801u;
|
||||
if (cf_of) f |= 0x801u;
|
||||
set_eflags(f);
|
||||
}
|
||||
|
||||
void LF_ZF(int z) {
|
||||
uint32_t f = get_eflags() & ~0x40u;
|
||||
if (z) f |= 0x40u;
|
||||
set_eflags(f);
|
||||
}
|
||||
|
||||
static uint32_t parity(uint32_t r) {
|
||||
r &= 0xffu; r ^= r >> 4; r ^= r >> 2; r ^= r >> 1;
|
||||
return (~r) & 1u;
|
||||
}
|
||||
|
||||
/* résultat d'un décalage : CF et OF donnés, ZF/SF/PF d'après r */
|
||||
static void set_shift_flags(uint32_t r, int sz, uint32_t cf, uint32_t of) {
|
||||
uint32_t sign = 1u << (sz - 1);
|
||||
uint32_t f = (cpu.df << 10) | 0x202u;
|
||||
f |= cf & 1u;
|
||||
f |= parity(r) << 2;
|
||||
if (r == 0) f |= 0x40u;
|
||||
if (r & sign) f |= 0x80u;
|
||||
if (of) f |= 0x800u;
|
||||
cpu.lf_op = LF_FIXED;
|
||||
cpu.lf_flags = f;
|
||||
}
|
||||
|
||||
static void set_cf_of(uint32_t cf, uint32_t of) {
|
||||
uint32_t f = get_eflags() & ~0x801u;
|
||||
f |= cf & 1u;
|
||||
if (of) f |= 0x800u;
|
||||
set_eflags(f);
|
||||
}
|
||||
|
||||
#define MASK(sz) ((sz) == 32 ? 0xffffffffu : ((1u << (sz)) - 1u))
|
||||
#define MSB(v, sz) (((v) >> ((sz) - 1)) & 1u)
|
||||
|
||||
#define SHIFTS(sz) \
|
||||
uint32_t SHL##sz(uint32_t a, uint32_t n) { \
|
||||
uint32_t r, cf; \
|
||||
if (!n) return a; \
|
||||
r = n >= 32 ? 0 : (a << n) & MASK(sz); \
|
||||
cf = n <= sz ? (uint32_t)(((uint64_t)a >> (sz - n)) & 1u) : 0; \
|
||||
set_shift_flags(r, sz, cf, MSB(r, sz) ^ cf); \
|
||||
return r; \
|
||||
} \
|
||||
uint32_t SHR##sz(uint32_t a, uint32_t n) { \
|
||||
uint32_t r, cf; \
|
||||
if (!n) return a; \
|
||||
r = n >= 32 ? 0 : (a >> n); \
|
||||
cf = n <= 32 ? (uint32_t)(((uint64_t)a >> (n - 1)) & 1u) : 0; \
|
||||
set_shift_flags(r, sz, cf, n == 1 ? MSB(a, sz) : 0); \
|
||||
return r; \
|
||||
} \
|
||||
uint32_t SAR##sz(uint32_t a, uint32_t n) { \
|
||||
int64_t s; \
|
||||
uint32_t r, cf; \
|
||||
if (!n) return a; \
|
||||
s = (int64_t)(a & MASK(sz)); \
|
||||
if (MSB(a, sz)) s -= ((int64_t)1 << sz); \
|
||||
r = (uint32_t)((s >> (n > sz ? sz : n)) & MASK(sz)); \
|
||||
cf = (uint32_t)((s >> (n - 1 > sz ? sz : n - 1)) & 1); \
|
||||
set_shift_flags(r, sz, cf, 0); \
|
||||
return r; \
|
||||
} \
|
||||
uint32_t ROL##sz(uint32_t a, uint32_t n) { \
|
||||
uint32_t k = n % sz, r; \
|
||||
if (!n) return a; \
|
||||
r = k ? ((a << k) | (a >> (sz - k))) & MASK(sz) : a; \
|
||||
set_cf_of(r & 1u, MSB(r, sz) ^ (r & 1u)); \
|
||||
return r; \
|
||||
} \
|
||||
uint32_t ROR##sz(uint32_t a, uint32_t n) { \
|
||||
uint32_t k = n % sz, r; \
|
||||
if (!n) return a; \
|
||||
r = k ? ((a >> k) | (a << (sz - k))) & MASK(sz) : a; \
|
||||
set_cf_of(MSB(r, sz), MSB(r, sz) ^ MSB(r << 1, sz)); \
|
||||
return r; \
|
||||
} \
|
||||
uint32_t RCL##sz(uint32_t a, uint32_t n) { \
|
||||
uint32_t k = n % (sz + 1), cf = (uint32_t)cCF(), i; \
|
||||
if (!k) return a; \
|
||||
for (i = 0; i < k; i++) { \
|
||||
uint32_t out = MSB(a, sz); \
|
||||
a = ((a << 1) | cf) & MASK(sz); \
|
||||
cf = out; \
|
||||
} \
|
||||
set_cf_of(cf, MSB(a, sz) ^ cf); \
|
||||
return a; \
|
||||
} \
|
||||
uint32_t RCR##sz(uint32_t a, uint32_t n) { \
|
||||
uint32_t k = n % (sz + 1), cf = (uint32_t)cCF(), i, of; \
|
||||
if (!k) return a; \
|
||||
of = MSB(a, sz) ^ cf; \
|
||||
for (i = 0; i < k; i++) { \
|
||||
uint32_t out = a & 1u; \
|
||||
a = (a >> 1) | (cf << (sz - 1)); \
|
||||
cf = out; \
|
||||
} \
|
||||
set_cf_of(cf, of); \
|
||||
return a; \
|
||||
}
|
||||
|
||||
SHIFTS(8)
|
||||
SHIFTS(16)
|
||||
SHIFTS(32)
|
||||
|
||||
/* ------------------------------------------------------------------ divisions */
|
||||
static void div_error(uint32_t at) {
|
||||
fprintf(stderr, "division par zéro (ou dépassement) à 0x%x\n", at);
|
||||
rt_fatal("division");
|
||||
}
|
||||
|
||||
void DIV8(uint32_t v, uint32_t at) {
|
||||
uint32_t n = W(0);
|
||||
if (!(v & 0xffu) || n / (v & 0xffu) > 0xffu) div_error(at);
|
||||
BL_(0) = (uint8_t)(n / (v & 0xffu)); BH_(0) = (uint8_t)(n % (v & 0xffu));
|
||||
}
|
||||
void DIV16(uint32_t v, uint32_t at) {
|
||||
uint32_t n = ((uint32_t)W(2) << 16) | W(0), d = v & 0xffffu;
|
||||
if (!d || n / d > 0xffffu) div_error(at);
|
||||
W(0) = (uint16_t)(n / d); W(2) = (uint16_t)(n % d);
|
||||
}
|
||||
void DIV32(uint32_t v, uint32_t at) {
|
||||
uint64_t n = ((uint64_t)R(2) << 32) | R(0);
|
||||
if (!v || n / v > 0xffffffffu) div_error(at);
|
||||
R(0) = (uint32_t)(n / v); R(2) = (uint32_t)(n % v);
|
||||
}
|
||||
void IDIV8(uint32_t v, uint32_t at) {
|
||||
int32_t n = (int16_t)W(0), d = (int8_t)v, q;
|
||||
if (!d) div_error(at);
|
||||
q = n / d;
|
||||
if (q > 127 || q < -128) div_error(at);
|
||||
BL_(0) = (uint8_t)q; BH_(0) = (uint8_t)(n % d);
|
||||
}
|
||||
void IDIV16(uint32_t v, uint32_t at) {
|
||||
int32_t n = (int32_t)(((uint32_t)W(2) << 16) | W(0)), d = (int16_t)v, q;
|
||||
if (!d) div_error(at);
|
||||
q = n / d;
|
||||
if (q > 32767 || q < -32768) div_error(at);
|
||||
W(0) = (uint16_t)q; W(2) = (uint16_t)(n % d);
|
||||
}
|
||||
void IDIV32(uint32_t v, uint32_t at) {
|
||||
int64_t n = (int64_t)(((uint64_t)R(2) << 32) | R(0)), d = (int32_t)v, q;
|
||||
if (!d) div_error(at);
|
||||
q = n / d;
|
||||
if (q > 2147483647LL || q < -2147483648LL) div_error(at);
|
||||
R(0) = (uint32_t)q; R(2) = (uint32_t)(n % d);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ chaînes */
|
||||
#define STEP(sz) (cpu.df ? (uint32_t)-(int32_t)((sz) / 8) : (uint32_t)((sz) / 8))
|
||||
#define SRC (SB(S_DS) + R(6))
|
||||
#define DST (SB(S_ES) + R(7))
|
||||
|
||||
#define STRINGS(sz) \
|
||||
void MOVS##sz(void) { WR##sz(DST, RD##sz(SRC)); R(6) += STEP(sz); R(7) += STEP(sz); } \
|
||||
void REP_MOVS##sz(void) { while (R(1)) { MOVS##sz(); R(1)--; } } \
|
||||
void STOS##sz(void) { WR##sz(DST, R(0)); R(7) += STEP(sz); } \
|
||||
void REP_STOS##sz(void) { while (R(1)) { STOS##sz(); R(1)--; } } \
|
||||
void LODS##sz(void) { uint32_t v = RD##sz(SRC); R(6) += STEP(sz); \
|
||||
if (sz == 8) BL_(0) = (uint8_t)v; else if (sz == 16) W(0) = (uint16_t)v; else R(0) = v; } \
|
||||
void REP_LODS##sz(void) { while (R(1)) { LODS##sz(); R(1)--; } } \
|
||||
void CMPS##sz(void) { uint32_t a = RD##sz(SRC), b = RD##sz(DST); \
|
||||
LF(LF_SUB, sz, a, b, (a - b) & MASK(sz), 0); R(6) += STEP(sz); R(7) += STEP(sz); } \
|
||||
void SCAS##sz(void) { uint32_t a = R(0) & MASK(sz), b = RD##sz(DST); \
|
||||
LF(LF_SUB, sz, a, b, (a - b) & MASK(sz), 0); R(7) += STEP(sz); } \
|
||||
void REPE_CMPS##sz(void) { while (R(1)) { CMPS##sz(); R(1)--; if (!cZF()) break; } } \
|
||||
void REPNE_CMPS##sz(void) { while (R(1)) { CMPS##sz(); R(1)--; if (cZF()) break; } } \
|
||||
void REPE_SCAS##sz(void) { while (R(1)) { SCAS##sz(); R(1)--; if (!cZF()) break; } } \
|
||||
void REPNE_SCAS##sz(void) { while (R(1)) { SCAS##sz(); R(1)--; if (cZF()) break; } }
|
||||
|
||||
STRINGS(8)
|
||||
STRINGS(16)
|
||||
STRINGS(32)
|
||||
|
||||
/* ------------------------------------------------------------------ appels indirects */
|
||||
static RecompFn find_fn(uint32_t addr) {
|
||||
unsigned lo = 0, hi = cur_fn_count;
|
||||
while (lo < hi) {
|
||||
unsigned mid = (lo + hi) / 2;
|
||||
if (cur_fn_table[mid].addr == addr) return cur_fn_table[mid].fn;
|
||||
if (cur_fn_table[mid].addr < addr) lo = mid + 1; else hi = mid;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
void rt_call(uint32_t addr) {
|
||||
RecompFn f = find_fn(addr);
|
||||
if (!f) {
|
||||
fprintf(stderr, "appel indirect vers 0x%x : pas de fonction connue\n", addr);
|
||||
rt_fatal("appel indirect");
|
||||
}
|
||||
f();
|
||||
}
|
||||
|
||||
void TRAP(uint32_t addr) {
|
||||
fprintf(stderr, "instruction non traduite exécutée à 0x%x\n", addr);
|
||||
rt_fatal("instruction non traduite");
|
||||
}
|
||||
|
||||
/* jmp far [m16:32] : en pratique un gestionnaire d'interruption qui chaîne vers l'ancien vecteur
|
||||
* (sauvé par int 21h/35h). Sans ancien gestionnaire (vecteur 0, celui du BIOS), on fait son travail :
|
||||
* rien, puis iretd. */
|
||||
void JUMP_FAR(uint32_t ea) {
|
||||
uint32_t off = RD32(ea);
|
||||
void (*fn)(void) = off ? find_fn(off) : NULL;
|
||||
if (fn) { fn(); return; }
|
||||
R(4) += 12; /* iretd : eip, cs, eflags */
|
||||
}
|
||||
|
||||
void CALL_FAR(uint32_t ea, uint32_t ret) {
|
||||
uint32_t off = RD32(ea);
|
||||
void (*fn)(void) = off ? find_fn(off) : NULL;
|
||||
if (!fn) { TRAP(off); return; }
|
||||
PUSH32(SEL_CODE);
|
||||
PUSH32(ret);
|
||||
fn();
|
||||
}
|
||||
+183
@@ -0,0 +1,183 @@
|
||||
/* État du processeur x86 émulé et primitives utilisées par le code traduit (build/gen/*.c).
|
||||
*
|
||||
* Mémoire : un seul tableau M, adressé par les adresses linéaires du jeu (modèle plat de
|
||||
* DOS/4GW : code 0x10000, données 0x40000, écran VGA 0xA0000, tas au-delà de 1 Mo).
|
||||
* Indicateurs : paresseux. Chaque instruction qui les modifie note (opération, taille, a, b,
|
||||
* résultat) ; on ne calcule CF, ZF, etc. que si quelqu'un les lit.
|
||||
*/
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef union {
|
||||
uint32_t d;
|
||||
uint16_t w;
|
||||
struct { uint8_t l, h; } b;
|
||||
} Reg;
|
||||
|
||||
enum { LF_ADD, LF_ADC, LF_SUB, LF_SBB, LF_LOGIC, LF_INC, LF_DEC, LF_NEG, LF_FIXED };
|
||||
enum { S_ES, S_CS, S_SS, S_DS, S_FS, S_GS };
|
||||
|
||||
typedef struct {
|
||||
Reg r[8]; /* eax ecx edx ebx esp ebp esi edi */
|
||||
uint32_t lf_op, lf_sz, lf_a, lf_b, lf_r, lf_c, lf_flags;
|
||||
uint32_t df;
|
||||
uint16_t seg[6];
|
||||
uint32_t sb[6]; /* bases des segments (0 en modèle plat) */
|
||||
} Cpu;
|
||||
|
||||
typedef void (*RecompFn)(void);
|
||||
typedef struct { uint32_t addr; RecompFn fn; } FnEntry;
|
||||
|
||||
extern Cpu cpu;
|
||||
extern uint8_t *M;
|
||||
extern const FnEntry *cur_fn_table; /* table du programme en cours (jeu ou intro) */
|
||||
extern unsigned cur_fn_count;
|
||||
|
||||
#define MEM_SIZE (64u << 20)
|
||||
#define MEM_MASK (MEM_SIZE - 1u)
|
||||
|
||||
#define R(n) cpu.r[n].d
|
||||
#define W(n) cpu.r[n].w
|
||||
#define BL_(n) cpu.r[n].b.l
|
||||
#define BH_(n) cpu.r[n].b.h
|
||||
#define SEGR(n) cpu.seg[n]
|
||||
#define SB(n) cpu.sb[n]
|
||||
|
||||
/* ------------------------------------------------------------------ mémoire */
|
||||
static inline uint8_t RD8(uint32_t a) { return M[a & MEM_MASK]; }
|
||||
static inline uint16_t RD16(uint32_t a) { uint16_t v; memcpy(&v, M + (a & MEM_MASK), 2); return v; }
|
||||
static inline uint32_t RD32(uint32_t a) { uint32_t v; memcpy(&v, M + (a & MEM_MASK), 4); return v; }
|
||||
static inline void WR8(uint32_t a, uint32_t v) { M[a & MEM_MASK] = (uint8_t)v; }
|
||||
static inline void WR16(uint32_t a, uint32_t v) { uint16_t x = (uint16_t)v; memcpy(M + (a & MEM_MASK), &x, 2); }
|
||||
static inline void WR32(uint32_t a, uint32_t v) { memcpy(M + (a & MEM_MASK), &v, 4); }
|
||||
|
||||
static inline void PUSH32(uint32_t v) { R(4) -= 4; WR32(SB(S_SS) + R(4), v); }
|
||||
static inline uint32_t POP32(void) { uint32_t v = RD32(SB(S_SS) + R(4)); R(4) += 4; return v; }
|
||||
static inline void PUSH16(uint32_t v) { R(4) -= 2; WR16(SB(S_SS) + R(4), v); }
|
||||
static inline uint16_t POP16(void) { uint16_t v = RD16(SB(S_SS) + R(4)); R(4) += 2; return v; }
|
||||
|
||||
void PUSHAD(void);
|
||||
void POPAD(void);
|
||||
|
||||
/* ------------------------------------------------------------------ indicateurs */
|
||||
#define LF(op, sz, a, b, r, c) (cpu.lf_op = (op), cpu.lf_sz = (sz), cpu.lf_a = (a), cpu.lf_b = (b), \
|
||||
cpu.lf_r = (r), cpu.lf_c = (c))
|
||||
|
||||
static inline uint32_t lf_sign(void) { return 1u << (cpu.lf_sz - 1); }
|
||||
|
||||
static inline int cCF(void) {
|
||||
switch (cpu.lf_op) {
|
||||
case LF_ADD: return cpu.lf_r < cpu.lf_a;
|
||||
case LF_ADC: return cpu.lf_c ? cpu.lf_r <= cpu.lf_a : cpu.lf_r < cpu.lf_a;
|
||||
case LF_SUB: return cpu.lf_a < cpu.lf_b;
|
||||
case LF_SBB: return cpu.lf_c ? cpu.lf_a <= cpu.lf_b : cpu.lf_a < cpu.lf_b;
|
||||
case LF_LOGIC: return 0;
|
||||
case LF_INC: case LF_DEC: return (int)cpu.lf_c;
|
||||
case LF_NEG: return cpu.lf_a != 0;
|
||||
default: return (int)(cpu.lf_flags & 1u);
|
||||
}
|
||||
}
|
||||
static inline int cZF(void) { return cpu.lf_op == LF_FIXED ? (int)((cpu.lf_flags >> 6) & 1u) : cpu.lf_r == 0; }
|
||||
static inline int cSF(void) { return cpu.lf_op == LF_FIXED ? (int)((cpu.lf_flags >> 7) & 1u) : (cpu.lf_r & lf_sign()) != 0; }
|
||||
static inline int cOF(void) {
|
||||
uint32_t s = lf_sign();
|
||||
switch (cpu.lf_op) {
|
||||
case LF_ADD: case LF_ADC: return ((cpu.lf_a ^ cpu.lf_r) & (cpu.lf_b ^ cpu.lf_r) & s) != 0;
|
||||
case LF_SUB: case LF_SBB: return ((cpu.lf_a ^ cpu.lf_b) & (cpu.lf_a ^ cpu.lf_r) & s) != 0;
|
||||
case LF_INC: return cpu.lf_r == s;
|
||||
case LF_DEC: return cpu.lf_a == s;
|
||||
case LF_NEG: return cpu.lf_a == s;
|
||||
case LF_LOGIC: return 0;
|
||||
default: return (int)((cpu.lf_flags >> 11) & 1u);
|
||||
}
|
||||
}
|
||||
static inline int cPF(void) {
|
||||
uint32_t v;
|
||||
if (cpu.lf_op == LF_FIXED) return (int)((cpu.lf_flags >> 2) & 1u);
|
||||
v = cpu.lf_r & 0xffu;
|
||||
v ^= v >> 4; v ^= v >> 2; v ^= v >> 1;
|
||||
return !(v & 1u);
|
||||
}
|
||||
static inline int cAF(void) {
|
||||
switch (cpu.lf_op) {
|
||||
case LF_ADD: case LF_ADC: case LF_SUB: case LF_SBB: return ((cpu.lf_a ^ cpu.lf_b ^ cpu.lf_r) & 0x10u) != 0;
|
||||
case LF_INC: return (cpu.lf_r & 0xfu) == 0;
|
||||
case LF_DEC: return (cpu.lf_r & 0xfu) == 0xfu;
|
||||
case LF_NEG: return (cpu.lf_a & 0xfu) != 0;
|
||||
case LF_LOGIC: return 0;
|
||||
default: return (int)((cpu.lf_flags >> 4) & 1u);
|
||||
}
|
||||
}
|
||||
uint32_t get_eflags(void);
|
||||
void set_eflags(uint32_t v);
|
||||
void LF_MULFLAGS(int cf_of);
|
||||
void LF_ZF(int z);
|
||||
|
||||
/* ------------------------------------------------------------------ décalages */
|
||||
uint32_t SHL8(uint32_t a, uint32_t n); uint32_t SHL16(uint32_t a, uint32_t n); uint32_t SHL32(uint32_t a, uint32_t n);
|
||||
uint32_t SHR8(uint32_t a, uint32_t n); uint32_t SHR16(uint32_t a, uint32_t n); uint32_t SHR32(uint32_t a, uint32_t n);
|
||||
uint32_t SAR8(uint32_t a, uint32_t n); uint32_t SAR16(uint32_t a, uint32_t n); uint32_t SAR32(uint32_t a, uint32_t n);
|
||||
uint32_t ROL8(uint32_t a, uint32_t n); uint32_t ROL16(uint32_t a, uint32_t n); uint32_t ROL32(uint32_t a, uint32_t n);
|
||||
uint32_t ROR8(uint32_t a, uint32_t n); uint32_t ROR16(uint32_t a, uint32_t n); uint32_t ROR32(uint32_t a, uint32_t n);
|
||||
uint32_t RCL8(uint32_t a, uint32_t n); uint32_t RCL16(uint32_t a, uint32_t n); uint32_t RCL32(uint32_t a, uint32_t n);
|
||||
uint32_t RCR8(uint32_t a, uint32_t n); uint32_t RCR16(uint32_t a, uint32_t n); uint32_t RCR32(uint32_t a, uint32_t n);
|
||||
|
||||
/* ------------------------------------------------------------------ divisions */
|
||||
void DIV8(uint32_t v, uint32_t at); void DIV16(uint32_t v, uint32_t at); void DIV32(uint32_t v, uint32_t at);
|
||||
void IDIV8(uint32_t v, uint32_t at); void IDIV16(uint32_t v, uint32_t at); void IDIV32(uint32_t v, uint32_t at);
|
||||
|
||||
/* ------------------------------------------------------------------ chaînes */
|
||||
#define STR_DECL(op) void op##8(void); void op##16(void); void op##32(void); \
|
||||
void REP_##op##8(void); void REP_##op##16(void); void REP_##op##32(void);
|
||||
STR_DECL(MOVS) STR_DECL(STOS) STR_DECL(LODS)
|
||||
void CMPS8(void); void CMPS16(void); void CMPS32(void);
|
||||
void SCAS8(void); void SCAS16(void); void SCAS32(void);
|
||||
void REPE_CMPS8(void); void REPE_CMPS16(void); void REPE_CMPS32(void);
|
||||
void REPNE_CMPS8(void); void REPNE_CMPS16(void); void REPNE_CMPS32(void);
|
||||
void REPE_SCAS8(void); void REPE_SCAS16(void); void REPE_SCAS32(void);
|
||||
void REPNE_SCAS8(void); void REPNE_SCAS16(void); void REPNE_SCAS32(void);
|
||||
|
||||
/* ------------------------------------------------------------------ segments, flot */
|
||||
void set_seg(int s, uint16_t sel);
|
||||
void rt_call(uint32_t addr);
|
||||
#define CALL_INDIRECT(t) rt_call(t)
|
||||
#define JUMP_INDIRECT(t) rt_call(t)
|
||||
void JUMP_FAR(uint32_t ea); /* jmp far [m16:32] : chaînage vers un ancien gestionnaire */
|
||||
void CALL_FAR(uint32_t ea, uint32_t ret); /* call far [m16:32] */
|
||||
void TRAP(uint32_t addr);
|
||||
|
||||
extern uint32_t poll_counter;
|
||||
void rt_poll(void);
|
||||
#define POLL_EVERY 256u
|
||||
#define POLL() do { if (++poll_counter >= POLL_EVERY) rt_poll(); } while (0)
|
||||
|
||||
/* ------------------------------------------------------------------ DOS, BIOS, ports */
|
||||
void rt_int(uint32_t n);
|
||||
uint32_t rt_in(uint32_t port, int size);
|
||||
void rt_out(uint32_t port, uint32_t v, int size);
|
||||
|
||||
/* ------------------------------------------------------------------ FPU */
|
||||
typedef struct { int k; uint32_t a; } FpuOp; /* k : 16/32/64/80 mémoire, 100+i st(i), 200 ax */
|
||||
#define MEM16(a) ((FpuOp){16, (a)})
|
||||
#define MEM32(a) ((FpuOp){32, (a)})
|
||||
#define MEM64(a) ((FpuOp){64, (a)})
|
||||
#define MEM80(a) ((FpuOp){80, (a)})
|
||||
#define ST_REG(i) ((FpuOp){100 + (i), 0})
|
||||
#define REG_ax ((FpuOp){200, 0})
|
||||
void FPU_FLD(FpuOp o); void FPU_FILD(FpuOp o); void FPU_FST(FpuOp o); void FPU_FSTP(FpuOp o);
|
||||
void FPU_FIST(FpuOp o); void FPU_FISTP(FpuOp o);
|
||||
void FPU_FLDZ(void); void FPU_FLD1(void); void FPU_FLDLG2(void);
|
||||
void FPU_FADD(FpuOp o); void FPU_FSUB(FpuOp o); void FPU_FSUBR(FpuOp o); void FPU_FMUL(FpuOp o);
|
||||
void FPU_FDIV(FpuOp o); void FPU_FDIVR(FpuOp o);
|
||||
void FPU_FIADD(FpuOp o); void FPU_FISUB(FpuOp o); void FPU_FIMUL(FpuOp o); void FPU_FIDIV(FpuOp o);
|
||||
void FPU_FDIVP(FpuOp o); void FPU_FMULP(FpuOp o); void FPU_FADDP(FpuOp o); void FPU_FSUBP(FpuOp o);
|
||||
void FPU_FCOMP(FpuOp o); void FPU_FCOM(FpuOp o); void FPU_FCOMPP(void);
|
||||
void FPU_FCHS(void); void FPU_FABS(void); void FPU_FRNDINT(void); void FPU_FYL2X(void);
|
||||
void FPU_FXCH(FpuOp a, FpuOp b);
|
||||
void FPU_FNSTSW(FpuOp o); void FPU_FNSTCW(FpuOp o); void FPU_FLDCW(FpuOp o);
|
||||
void FPU_FNINIT(void); void FPU_FNSAVE(FpuOp o); void FPU_FRSTOR(FpuOp o);
|
||||
/* formes à deux opérandes st(i), st(j) */
|
||||
void FPU_FADD2(FpuOp a, FpuOp b); void FPU_FSUB2(FpuOp a, FpuOp b); void FPU_FSUBR2(FpuOp a, FpuOp b);
|
||||
void FPU_FMUL2(FpuOp a, FpuOp b); void FPU_FDIV2(FpuOp a, FpuOp b); void FPU_FDIVR2(FpuOp a, FpuOp b);
|
||||
void FPU_FSUBRP(FpuOp o); void FPU_FDIVRP(FpuOp o);
|
||||
+487
@@ -0,0 +1,487 @@
|
||||
/* DOS (int 21h, version DOS/4GW 32 bits), DPMI (int 31h), BIOS (10h, 16h), souris (33h), MSCDEX (2Fh).
|
||||
*
|
||||
* Fichiers : les chemins du jeu (« d:\tucker\speech\sam0001.wav », « loc01.pcx », « c:\g.in ») sont
|
||||
* ramenés au dossier du CD, au dossier installé ou à la racine C:, en lecture seule. Seules les
|
||||
* sauvegardes (savegm.NN, nofiles.dta) sont écrites, dans un dossier à part.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
RtConfig rt_cfg;
|
||||
|
||||
static void set_cf(int c) { set_eflags((get_eflags() & ~1u) | (c ? 1u : 0u)); }
|
||||
static void dos_error(uint16_t code) { R(0) = code; set_cf(1); }
|
||||
#define LIN(seg, off) (SB(seg) + (off))
|
||||
|
||||
/* ------------------------------------------------------------------ sélecteurs */
|
||||
#define NSEL 1024
|
||||
static uint32_t sel_tab_base[NSEL];
|
||||
static uint8_t sel_used[NSEL];
|
||||
|
||||
uint32_t sel_base(uint16_t sel) {
|
||||
unsigned i = sel >> 3;
|
||||
return i < NSEL ? sel_tab_base[i] : 0;
|
||||
}
|
||||
|
||||
uint16_t sel_alloc(uint32_t base, uint32_t limit) {
|
||||
unsigned i;
|
||||
(void)limit;
|
||||
for (i = 0x40; i < NSEL; i++)
|
||||
if (!sel_used[i]) { sel_used[i] = 1; sel_tab_base[i] = base; return (uint16_t)(i << 3 | 7); }
|
||||
rt_fatal("plus de sélecteurs");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void sel_fixed(uint16_t sel, uint32_t base) { sel_used[sel >> 3] = 1; sel_tab_base[sel >> 3] = base; }
|
||||
|
||||
void set_seg(int s, uint16_t sel) { cpu.seg[s] = sel; cpu.sb[s] = sel_base(sel); }
|
||||
|
||||
/* ------------------------------------------------------------------ fichiers */
|
||||
#define NFILES 40
|
||||
static FILE *files[NFILES];
|
||||
static int file_writable[NFILES];
|
||||
static uint32_t dta = 0;
|
||||
|
||||
static void read_str(uint32_t a, char *out, size_t n) {
|
||||
size_t i;
|
||||
for (i = 0; i + 1 < n; i++) { out[i] = (char)RD8(a + (uint32_t)i); if (!out[i]) break; }
|
||||
out[n - 1] = 0;
|
||||
}
|
||||
|
||||
static int is_save_name(const char *base) {
|
||||
return !strncmp(base, "SAVEGM.", 7) || !strcmp(base, "NOFILES.DTA");
|
||||
}
|
||||
|
||||
/* nom DOS -> chemin hôte ; renvoie 0 si introuvable (lecture) */
|
||||
int dos_map_path(const char *dos, char *out, size_t n, int for_write) {
|
||||
char p[260], *s, *base;
|
||||
const char *dirs[3];
|
||||
int i;
|
||||
size_t k;
|
||||
for (k = 0; dos[k] && k + 1 < sizeof p; k++) p[k] = (char)toupper((unsigned char)(dos[k] == '/' ? '\\' : dos[k]));
|
||||
p[k] = 0;
|
||||
s = p;
|
||||
if (s[0] && s[1] == ':') s += 2;
|
||||
while (*s == '\\') s++;
|
||||
if (!strncmp(s, "TUCKER\\", 7)) s += 7;
|
||||
base = strrchr(s, '\\');
|
||||
base = base ? base + 1 : s;
|
||||
if (is_save_name(base)) {
|
||||
snprintf(out, n, "%s/%s", rt_cfg.save_dir, base);
|
||||
return 1;
|
||||
}
|
||||
if (for_write) return 0;
|
||||
if (!strcmp(s, "G.IN") && rt_cfg.mute) return 0;
|
||||
dirs[0] = rt_cfg.hd_dir; dirs[1] = rt_cfg.cd_dir; dirs[2] = rt_cfg.root_dir;
|
||||
for (i = 0; i < 3; i++) {
|
||||
FILE *f;
|
||||
if (!dirs[i]) continue;
|
||||
snprintf(out, n, "%s/%s", dirs[i], s);
|
||||
for (k = 0; out[k]; k++) if (out[k] == '\\') out[k] = '/';
|
||||
f = fopen(out, "rb");
|
||||
if (f) { fclose(f); return 1; }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int alloc_handle(FILE *f, int w) {
|
||||
int h;
|
||||
for (h = 5; h < NFILES; h++) if (!files[h]) { files[h] = f; file_writable[h] = w; return h; }
|
||||
fclose(f);
|
||||
return -1;
|
||||
}
|
||||
|
||||
static void dos_open(int create) {
|
||||
char name[260], path[300];
|
||||
FILE *f;
|
||||
int h, mode = BL_(0) & 3;
|
||||
read_str(LIN(S_DS, R(2)), name, sizeof name);
|
||||
if (create || mode != 0) {
|
||||
if (!dos_map_path(name, path, sizeof path, 1)) {
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[dos] écriture refusée : %s\n", name);
|
||||
dos_error(5); return;
|
||||
}
|
||||
f = fopen(path, create ? "wb+" : "rb+");
|
||||
if (!f && !create) f = fopen(path, "wb+");
|
||||
} else {
|
||||
if (!dos_map_path(name, path, sizeof path, 0)) {
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[dos] introuvable : %s\n", name);
|
||||
dos_error(2); return;
|
||||
}
|
||||
f = fopen(path, "rb");
|
||||
}
|
||||
if (!f) { dos_error(2); return; }
|
||||
h = alloc_handle(f, create || mode != 0);
|
||||
if (h < 0) { dos_error(4); return; }
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[dos] ouvre %s -> %d\n", name, h);
|
||||
R(0) = (uint32_t)h;
|
||||
set_cf(0);
|
||||
}
|
||||
|
||||
static FILE *handle(int h) { return (h >= 0 && h < NFILES) ? files[h] : NULL; }
|
||||
|
||||
/* recherche de fichiers (4Eh/4Fh) : seulement les sauvegardes et les noms exacts */
|
||||
static void find_file(int first) {
|
||||
char spec[260], path[300];
|
||||
FILE *f;
|
||||
long size;
|
||||
const char *base;
|
||||
if (!first) { dos_error(18); return; }
|
||||
read_str(LIN(S_DS, R(2)), spec, sizeof spec);
|
||||
if (strchr(spec, '*') || strchr(spec, '?') || !dos_map_path(spec, path, sizeof path, 0)) { dos_error(18); return; }
|
||||
f = fopen(path, "rb");
|
||||
if (!f) { dos_error(18); return; }
|
||||
fseek(f, 0, SEEK_END); size = ftell(f); fclose(f);
|
||||
base = strrchr(spec, '\\'); base = base ? base + 1 : spec;
|
||||
WR8(dta + 0x15, 0x20);
|
||||
WR16(dta + 0x16, 0); WR16(dta + 0x18, (16 << 9) | (1 << 5) | 1);
|
||||
WR32(dta + 0x1a, (uint32_t)size);
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < 12 && base[i]; i++) WR8(dta + 0x1e + (uint32_t)i, (uint8_t)toupper((unsigned char)base[i]));
|
||||
WR8(dta + 0x1e + (uint32_t)i, 0);
|
||||
}
|
||||
R(0) = 0; set_cf(0);
|
||||
}
|
||||
|
||||
void dos_init(const char *exe_dos) {
|
||||
static const char env_head[] = "PATH=C:\\\0COMSPEC=C:\\COMMAND.COM\0DOS4G=QUIET\0\0\1\0";
|
||||
char env[160];
|
||||
size_t n = sizeof env_head - 1, m = strlen(exe_dos);
|
||||
memcpy(env, env_head, n);
|
||||
if (m > sizeof env - n - 1) m = sizeof env - n - 1;
|
||||
memcpy(env + n, exe_dos, m);
|
||||
env[n + m] = 0;
|
||||
sel_fixed(SEL_CODE, 0); sel_fixed(SEL_DATA, 0);
|
||||
sel_fixed(SEL_PSP, PSP_BASE); sel_fixed(SEL_ENV, ENV_BASE);
|
||||
memset(M + PSP_BASE, 0, 256);
|
||||
WR16(PSP_BASE, 0x20cd);
|
||||
WR16(PSP_BASE + 0x2c, SEL_ENV);
|
||||
WR32(PSP_BASE + 0x5c, HEAP_BASE);
|
||||
WR8(PSP_BASE + 0x80, 0); WR8(PSP_BASE + 0x81, '\r');
|
||||
memcpy(M + ENV_BASE, env, n + m + 1);
|
||||
dta = PSP_BASE + 0x80;
|
||||
{
|
||||
time_t t = time(NULL);
|
||||
(void)t;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ int 21h */
|
||||
void dos_int21(void) {
|
||||
uint8_t ah = BH_(0), al = BL_(0);
|
||||
FILE *f;
|
||||
switch (ah) {
|
||||
case 0x02: putchar(BL_(2)); break;
|
||||
case 0x06: if (BL_(2) == 0xff) { BL_(0) = 0; LF_ZF(1); } else putchar(BL_(2)); break;
|
||||
case 0x09: { uint32_t a = LIN(S_DS, R(2)); while (RD8(a) != '$') putchar(RD8(a++)); break; }
|
||||
case 0x0b: BL_(0) = 0; break;
|
||||
case 0x0e: BL_(0) = 26; break;
|
||||
case 0x19: BL_(0) = 2; break; /* C: */
|
||||
case 0x1a: dta = LIN(S_DS, R(2)); break;
|
||||
case 0x25: pm_vec_off[al] = R(2); pm_vec_sel[al] = SEGR(S_DS);
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[dos] vecteur %02x -> %08x\n", al, R(2)); break;
|
||||
case 0x2a: { time_t t = time(NULL); struct tm *tm = localtime(&t);
|
||||
W(1) = (uint16_t)(tm->tm_year + 1900); BH_(2) = (uint8_t)(tm->tm_mon + 1); BL_(2) = (uint8_t)tm->tm_mday;
|
||||
BL_(0) = (uint8_t)tm->tm_wday; break; }
|
||||
case 0x2c: { uint64_t us = host_time_us(); time_t t = time(NULL); struct tm *tm = localtime(&t);
|
||||
BH_(1) = (uint8_t)tm->tm_hour; BL_(1) = (uint8_t)tm->tm_min; BH_(2) = (uint8_t)tm->tm_sec;
|
||||
BL_(2) = (uint8_t)((us / 10000) % 100); break; }
|
||||
case 0x2f: set_seg(S_ES, SEL_DATA); R(3) = dta; break;
|
||||
case 0x30: R(0) = 0x0005u; break; /* DOS 5.0, pas Phar Lap */
|
||||
case 0x35: R(3) = pm_vec_off[al]; set_seg(S_ES, pm_vec_sel[al] ? pm_vec_sel[al] : SEL_CODE); break;
|
||||
case 0x36: W(0) = 8; W(3) = 0x4000; W(1) = 512; W(2) = 0x8000; break;
|
||||
case 0x3b: set_cf(0); break;
|
||||
case 0x3c: dos_open(1); return;
|
||||
case 0x3d: dos_open(0); return;
|
||||
case 0x3e:
|
||||
f = handle(W(3));
|
||||
if (W(3) < 5) { set_cf(0); return; }
|
||||
if (!f) { dos_error(6); return; }
|
||||
fclose(f); files[W(3)] = NULL; set_cf(0); return;
|
||||
case 0x3f: {
|
||||
size_t got;
|
||||
f = handle(W(3));
|
||||
if (!f) { if (W(3) == 0) { R(0) = 0; set_cf(0); } else dos_error(6); return; }
|
||||
got = fread(M + (LIN(S_DS, R(2)) & MEM_MASK), 1, R(1), f);
|
||||
R(0) = (uint32_t)got; set_cf(0); return;
|
||||
}
|
||||
case 0x40: {
|
||||
uint32_t a = LIN(S_DS, R(2)), i;
|
||||
if (W(3) == 1 || W(3) == 2) {
|
||||
for (i = 0; i < R(1); i++) fputc(RD8(a + i), W(3) == 1 ? stdout : stderr);
|
||||
R(0) = R(1); set_cf(0); return;
|
||||
}
|
||||
f = handle(W(3));
|
||||
if (!f || !file_writable[W(3)]) { dos_error(5); return; }
|
||||
R(0) = (uint32_t)fwrite(M + (a & MEM_MASK), 1, R(1), f); fflush(f);
|
||||
set_cf(0); return;
|
||||
}
|
||||
case 0x41: dos_error(5); return;
|
||||
case 0x42: {
|
||||
long off = (long)(((uint32_t)W(1) << 16) | W(2));
|
||||
f = handle(W(3));
|
||||
if (!f) { dos_error(6); return; }
|
||||
fseek(f, off, al == 0 ? SEEK_SET : al == 1 ? SEEK_CUR : SEEK_END);
|
||||
off = ftell(f);
|
||||
W(0) = (uint16_t)off; W(2) = (uint16_t)((uint32_t)off >> 16);
|
||||
set_cf(0); return;
|
||||
}
|
||||
case 0x43: {
|
||||
char name[260], path[300];
|
||||
read_str(LIN(S_DS, R(2)), name, sizeof name);
|
||||
if (dos_map_path(name, path, sizeof path, 0)) { W(1) = 0x20; set_cf(0); } else dos_error(2);
|
||||
return;
|
||||
}
|
||||
case 0x44:
|
||||
if (al == 0) { W(2) = W(3) < 3 ? 0x80d3 : 0x0002; set_cf(0); return; }
|
||||
if (al == 8) { R(0) = 1; set_cf(0); return; }
|
||||
dos_error(1); return;
|
||||
case 0x47: { const char *cwd = "TUCKER"; uint32_t a = LIN(S_DS, R(6)), i;
|
||||
for (i = 0; i <= strlen(cwd); i++) WR8(a + i, (uint8_t)cwd[i]);
|
||||
set_cf(0); return; }
|
||||
case 0x48: dos_error(8); return;
|
||||
case 0x49: set_cf(0); return;
|
||||
case 0x4a: set_cf(0); return;
|
||||
case 0x4c: rt_exit(al); return;
|
||||
case 0x4e: find_file(1); return;
|
||||
case 0x4f: find_file(0); return;
|
||||
case 0x57: W(1) = 0; W(2) = (16 << 9) | (1 << 5) | 1; set_cf(0); return;
|
||||
case 0xff:
|
||||
if (W(0) == 0xff00 && W(2) == 0x78) { R(0) = 0x4734ff47u; return; } /* DOS/4G présent */
|
||||
break;
|
||||
default:
|
||||
fprintf(stderr, "[dos] int 21h AH=%02Xh non géré (EAX=%08x)\n", ah, R(0));
|
||||
dos_error(1);
|
||||
return;
|
||||
}
|
||||
set_cf(0);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ DPMI */
|
||||
uint32_t pm_vec_off[256];
|
||||
uint16_t pm_vec_sel[256];
|
||||
static uint32_t rm_vec[256];
|
||||
static uint32_t heap_top = HEAP_BASE;
|
||||
static uint32_t low_top = LOWMEM_BASE;
|
||||
|
||||
static uint32_t heap_alloc(uint32_t size) {
|
||||
uint32_t a = (heap_top + 0xfffu) & ~0xfffu;
|
||||
if (a + size > MEM_SIZE - 0x10000u) return 0;
|
||||
heap_top = a + size;
|
||||
return a;
|
||||
}
|
||||
|
||||
static void real_mode_int(uint8_t n, uint32_t rs);
|
||||
|
||||
void dpmi_int31(void) {
|
||||
uint16_t ax = W(0);
|
||||
set_cf(0);
|
||||
switch (ax) {
|
||||
case 0x0000: { unsigned i; uint16_t first = 0;
|
||||
for (i = 0; i < W(1); i++) { uint16_t s = sel_alloc(0, 0xffffffffu); if (!i) first = s; }
|
||||
W(0) = first; return; }
|
||||
case 0x0001: return;
|
||||
case 0x0002: W(0) = sel_alloc((uint32_t)W(3) << 4, 0xffff); return;
|
||||
case 0x0003: W(0) = 8; return;
|
||||
case 0x0006: { uint32_t b = sel_base(W(3)); W(1) = (uint16_t)(b >> 16); W(2) = (uint16_t)b; return; }
|
||||
case 0x0007: sel_tab_base[(W(3) >> 3) % NSEL] = ((uint32_t)W(1) << 16) | W(2);
|
||||
{ int s; for (s = 0; s < 6; s++) if (cpu.seg[s] == W(3)) cpu.sb[s] = sel_base(W(3)); }
|
||||
return;
|
||||
case 0x0008: case 0x0009: case 0x000c: return;
|
||||
case 0x000a: W(0) = sel_alloc(sel_base(W(3)), 0xffffffffu); return;
|
||||
case 0x000b: { uint32_t a = LIN(S_ES, R(7)), i; for (i = 0; i < 8; i++) WR8(a + i, 0);
|
||||
WR16(a, 0xffff); WR16(a + 2, (uint16_t)sel_base(W(3))); WR8(a + 4, (uint8_t)(sel_base(W(3)) >> 16));
|
||||
WR8(a + 5, 0xf2); WR8(a + 6, 0xcf); WR8(a + 7, (uint8_t)(sel_base(W(3)) >> 24)); return; }
|
||||
case 0x0100: {
|
||||
uint32_t size = (uint32_t)W(3) << 4, a = (low_top + 15u) & ~15u;
|
||||
if (a + size > LOWMEM_END) { W(0) = 8; W(3) = (uint16_t)((LOWMEM_END - a) >> 4); set_cf(1); return; }
|
||||
low_top = a + size;
|
||||
W(0) = (uint16_t)(a >> 4);
|
||||
W(2) = sel_alloc(a, size);
|
||||
return;
|
||||
}
|
||||
case 0x0101: case 0x0102: return;
|
||||
case 0x0200: W(1) = (uint16_t)(rm_vec[BL_(3)] >> 16); W(2) = (uint16_t)rm_vec[BL_(3)]; return;
|
||||
case 0x0201: rm_vec[BL_(3)] = ((uint32_t)W(1) << 16) | W(2); return;
|
||||
case 0x0202: case 0x0203: return;
|
||||
case 0x0204: W(1) = pm_vec_sel[BL_(3)] ? pm_vec_sel[BL_(3)] : SEL_CODE; R(2) = pm_vec_off[BL_(3)]; return;
|
||||
case 0x0205: pm_vec_sel[BL_(3)] = W(1); pm_vec_off[BL_(3)] = R(2);
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[dpmi] vecteur %02x -> %04x:%08x\n", BL_(3), W(1), R(2));
|
||||
return;
|
||||
case 0x0300: real_mode_int(BL_(3), LIN(S_ES, R(7))); return;
|
||||
case 0x0301: case 0x0302:
|
||||
fprintf(stderr, "[dpmi] appel en mode réel %04x non géré\n", ax); set_cf(1); return;
|
||||
case 0x0303: W(1) = 0xf000; W(2) = 0x0100; return;
|
||||
case 0x0304: return;
|
||||
case 0x0400: W(0) = 0x005a; W(3) = 0x0005; BL_(1) = 4; BH_(2) = 0x08; BL_(2) = 0x70; return;
|
||||
case 0x0500: { uint32_t a = LIN(S_ES, R(7)), i, fr = (MEM_SIZE - heap_top) ;
|
||||
for (i = 0; i < 48; i += 4) WR32(a + i, 0xffffffffu);
|
||||
WR32(a, fr); WR32(a + 4, fr >> 12); WR32(a + 8, fr >> 12); WR32(a + 0x14, fr >> 12);
|
||||
WR32(a + 0x18, MEM_SIZE >> 12); WR32(a + 0x1c, fr >> 12); return; }
|
||||
case 0x0501: {
|
||||
uint32_t size = ((uint32_t)W(3) << 16) | W(1), a = heap_alloc(size);
|
||||
if (!a) { set_cf(1); W(0) = 0x8013; return; }
|
||||
W(3) = (uint16_t)(a >> 16); W(1) = (uint16_t)a; W(6) = (uint16_t)(a >> 16); W(7) = (uint16_t)a;
|
||||
return;
|
||||
}
|
||||
case 0x0502: return;
|
||||
case 0x0503: {
|
||||
uint32_t size = ((uint32_t)W(3) << 16) | W(1), old = ((uint32_t)W(6) << 16) | W(7);
|
||||
uint32_t a = heap_alloc(size);
|
||||
if (!a) { set_cf(1); W(0) = 0x8013; return; }
|
||||
memmove(M + a, M + old, size);
|
||||
W(3) = (uint16_t)(a >> 16); W(1) = (uint16_t)a; W(6) = (uint16_t)(a >> 16); W(7) = (uint16_t)a;
|
||||
return;
|
||||
}
|
||||
case 0x0600: case 0x0601: case 0x0602: case 0x0603: case 0x0702: case 0x0703: return;
|
||||
case 0x0604: W(3) = 0; W(1) = 0x1000; return;
|
||||
case 0x0800: return; /* adresse physique = linéaire */
|
||||
case 0x0801: return;
|
||||
case 0x0900: case 0x0901: case 0x0902: BL_(0) = 1; return;
|
||||
default:
|
||||
fprintf(stderr, "[dpmi] int 31h AX=%04Xh non géré\n", ax);
|
||||
set_cf(1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/* DPMI 0300h : structure d'appel en mode réel */
|
||||
static void real_mode_int(uint8_t n, uint32_t rs) {
|
||||
Cpu saved = cpu;
|
||||
uint32_t es_base;
|
||||
R(7) = RD32(rs); R(6) = RD32(rs + 4); R(5) = RD32(rs + 8);
|
||||
R(3) = RD32(rs + 0x10); R(2) = RD32(rs + 0x14); R(1) = RD32(rs + 0x18); R(0) = RD32(rs + 0x1c);
|
||||
es_base = (uint32_t)RD16(rs + 0x22) << 4;
|
||||
cpu.sb[S_ES] = es_base; cpu.sb[S_DS] = (uint32_t)RD16(rs + 0x24) << 4;
|
||||
set_eflags(0x202);
|
||||
rt_int(n);
|
||||
WR32(rs, R(7)); WR32(rs + 4, R(6)); WR32(rs + 8, R(5));
|
||||
WR32(rs + 0x10, R(3)); WR32(rs + 0x14, R(2)); WR32(rs + 0x18, R(1)); WR32(rs + 0x1c, R(0));
|
||||
WR16(rs + 0x20, (uint16_t)get_eflags());
|
||||
cpu = saved;
|
||||
set_cf(0);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ BIOS */
|
||||
int vga_mode = 3;
|
||||
|
||||
void bios_int10(void) {
|
||||
switch (BH_(0)) {
|
||||
case 0x00: vga_mode = BL_(0) & 0x7f; if (!(BL_(0) & 0x80) && vga_mode == 0x13) memset(M + VGA_BASE, 0, 64000); break;
|
||||
case 0x0f: BL_(0) = (uint8_t)vga_mode; BH_(0) = 40; BH_(3) = 0; break;
|
||||
case 0x10:
|
||||
if (BL_(0) == 0x10) { vga_dac[BL_(3) * 3] = BH_(2) & 63; vga_dac[BL_(3) * 3 + 1] = BH_(1) & 63; vga_dac[BL_(3) * 3 + 2] = BL_(1) & 63; }
|
||||
else if (BL_(0) == 0x12) { uint32_t i, a = LIN(S_ES, R(2));
|
||||
for (i = 0; i < (uint32_t)W(1) * 3 && W(3) * 3 + i < 768; i++) vga_dac[W(3) * 3 + i] = RD8(a + i) & 63; }
|
||||
else if (BL_(0) == 0x17) { uint32_t i, a = LIN(S_ES, R(2));
|
||||
for (i = 0; i < (uint32_t)W(1) * 3 && W(3) * 3 + i < 768; i++) WR8(a + i, vga_dac[W(3) * 3 + i]); }
|
||||
break;
|
||||
case 0x1a: BL_(0) = 0x1a; W(3) = 0x0008; break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
/* le BIOS ne garde que les appuis : on jette les relâchements en tête de file */
|
||||
static int bios_peek(uint8_t *sc) {
|
||||
while (host_key_peek(sc)) {
|
||||
if (!(*sc & 0x80)) return 1;
|
||||
host_key_pop(sc);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static const char kbd_ascii[0x3a] = {
|
||||
0, 27, '1','2','3','4','5','6','7','8','9','0','-','=', 8, 9,
|
||||
'q','w','e','r','t','y','u','i','o','p','[',']', 13, 0, 'a','s',
|
||||
'd','f','g','h','j','k','l',';', 39, '`', 0, 92, 'z','x','c','v',
|
||||
'b','n','m',',','.','/', 0, '*', 0, ' '
|
||||
};
|
||||
|
||||
void bios_int16(void) {
|
||||
uint8_t sc;
|
||||
switch (BH_(0)) {
|
||||
case 0x00: case 0x10:
|
||||
while (!bios_peek(&sc)) { host_pump(); if (host_quit) rt_exit(0); rt_poll(); }
|
||||
host_key_pop(&sc);
|
||||
W(0) = (uint16_t)(sc << 8 | (sc < 0x3a ? (uint8_t)kbd_ascii[sc] : 0)); return;
|
||||
case 0x01: case 0x11:
|
||||
if (bios_peek(&sc)) { W(0) = (uint16_t)(sc << 8 | (sc < 0x3a ? (uint8_t)kbd_ascii[sc] : 0)); LF_ZF(0); }
|
||||
else LF_ZF(1);
|
||||
return;
|
||||
case 0x02: BL_(0) = 0; return;
|
||||
default: return;
|
||||
}
|
||||
}
|
||||
|
||||
static int mouse_minx = 0, mouse_maxx = 639, mouse_miny = 0, mouse_maxy = 199;
|
||||
static int mouse_lastx, mouse_lasty;
|
||||
|
||||
/* Le jeu lit une position absolue en pixels 320x200 (fonction 3, rangée en [0x46880]/[0x46882])
|
||||
* et ne fixe pas de plage : on renvoie donc la position de l'hôte telle quelle, bornée à la plage
|
||||
* éventuelle. La fonction 4 (le jeu bloque le curseur à x <= 307, y <= 195) est sans effet : l'hôte
|
||||
* ne peut pas déplacer le pointeur, et le jeu borne lui-même ce qu'il lit. */
|
||||
static int clampi(int v, int lo, int hi) { return v < lo ? lo : v > hi ? hi : v; }
|
||||
|
||||
void mouse_int33(void) {
|
||||
int x, y, b;
|
||||
host_mouse(&x, &y, &b);
|
||||
x = clampi(x, mouse_minx, mouse_maxx);
|
||||
y = clampi(y, mouse_miny, mouse_maxy);
|
||||
switch (W(0)) {
|
||||
case 0x00: W(0) = 0xffff; W(3) = 2; break;
|
||||
case 0x01: case 0x02: break;
|
||||
case 0x03: W(3) = (uint16_t)b; W(1) = (uint16_t)x; W(2) = (uint16_t)y; break;
|
||||
case 0x04: break;
|
||||
case 0x05: case 0x06: W(0) = (uint16_t)b; W(3) = 0; W(1) = (uint16_t)x; W(2) = (uint16_t)y; break;
|
||||
case 0x07: mouse_minx = (int16_t)W(1); mouse_maxx = (int16_t)W(2); break;
|
||||
case 0x08: mouse_miny = (int16_t)W(1); mouse_maxy = (int16_t)W(2); break;
|
||||
case 0x0b: W(1) = (uint16_t)(x - mouse_lastx); W(2) = (uint16_t)(y - mouse_lasty); mouse_lastx = x; mouse_lasty = y; break;
|
||||
case 0x0c: fprintf(stderr, "[souris] gestionnaire d'événements demandé (non géré)\n"); break;
|
||||
case 0x0f: case 0x1a: case 0x1d: break;
|
||||
case 0x21: W(0) = 0xffff; W(3) = 2; break;
|
||||
case 0x24: W(3) = 0x0626; BH_(1) = 4; BL_(1) = 0; break;
|
||||
default: fprintf(stderr, "[souris] fonction %04x non gérée\n", W(0)); break;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ aiguillage des interruptions */
|
||||
void rt_int(uint32_t n) {
|
||||
switch (n) {
|
||||
case 0x21: dos_int21(); break;
|
||||
case 0x31: dpmi_int31(); break;
|
||||
case 0x10: bios_int10(); break;
|
||||
case 0x16: bios_int16(); break;
|
||||
case 0x33: mouse_int33(); break;
|
||||
case 0x2f:
|
||||
if (W(0) == 0x1500) { W(3) = 1; W(1) = 3; } /* MSCDEX : un lecteur, D: */
|
||||
else if (W(0) == 0x150b) { W(0) = 1; W(3) = 0xadad; }
|
||||
else if (W(0) == 0x1687) { W(0) = 1; } /* pas d'hôte DPMI réel */
|
||||
break;
|
||||
case 0x1a: { uint32_t t = RD32(0x46c); W(1) = (uint16_t)(t >> 16); W(2) = (uint16_t)t; BL_(0) = 0; break; }
|
||||
default:
|
||||
fprintf(stderr, "[int] interruption %02x non gérée (EAX=%08x)\n", n, R(0));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* remet DOS / DPMI / souris dans l'état d'un démarrage, avant de lancer un autre programme */
|
||||
void dos_reset(void) {
|
||||
int i;
|
||||
for (i = 5; i < NFILES; i++) if (files[i]) { fclose(files[i]); files[i] = NULL; }
|
||||
memset(file_writable, 0, sizeof file_writable);
|
||||
memset(sel_tab_base, 0, sizeof sel_tab_base);
|
||||
memset(sel_used, 0, sizeof sel_used);
|
||||
memset(pm_vec_off, 0, sizeof pm_vec_off);
|
||||
memset(pm_vec_sel, 0, sizeof pm_vec_sel);
|
||||
memset(rm_vec, 0, sizeof rm_vec);
|
||||
heap_top = HEAP_BASE;
|
||||
low_top = LOWMEM_BASE;
|
||||
vga_mode = 3;
|
||||
mouse_minx = 0; mouse_maxx = 639; mouse_miny = 0; mouse_maxy = 199;
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
/* Coprocesseur x87 : le sous-ensemble utilisé par TUCKER.EXE (bibliothèque C Watcom). */
|
||||
#include <math.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
static double st[8];
|
||||
static int top;
|
||||
static uint16_t fsw, fcw = 0x037f;
|
||||
|
||||
#define ST(i) st[(top + (i)) & 7]
|
||||
static void push(double v) { top = (top - 1) & 7; st[top] = v; }
|
||||
static double pop(void) { double v = st[top]; top = (top + 1) & 7; return v; }
|
||||
|
||||
static double rd_float(FpuOp o) {
|
||||
if (o.k >= 100 && o.k < 108) return ST(o.k - 100);
|
||||
if (o.k == 32) { uint32_t v = RD32(o.a); float f; memcpy(&f, &v, 4); return f; }
|
||||
if (o.k == 64) { uint64_t v = (uint64_t)RD32(o.a) | (uint64_t)RD32(o.a + 4) << 32; double d; memcpy(&d, &v, 8); return d; }
|
||||
if (o.k == 80) {
|
||||
uint64_t mant = (uint64_t)RD32(o.a) | (uint64_t)RD32(o.a + 4) << 32;
|
||||
uint16_t se = RD16(o.a + 8);
|
||||
int e = (se & 0x7fff) - 16383 - 63;
|
||||
double d = ldexp((double)mant, e);
|
||||
return (se & 0x8000) ? -d : d;
|
||||
}
|
||||
rt_fatal("FPU : opérande flottant inconnu");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static double rd_int(FpuOp o) {
|
||||
if (o.k == 16) return (double)(int16_t)RD16(o.a);
|
||||
if (o.k == 32) return (double)(int32_t)RD32(o.a);
|
||||
if (o.k == 64) return (double)(int64_t)((uint64_t)RD32(o.a) | (uint64_t)RD32(o.a + 4) << 32);
|
||||
rt_fatal("FPU : opérande entier inconnu");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void wr_float(FpuOp o, double v) {
|
||||
if (o.k >= 100 && o.k < 108) { ST(o.k - 100) = v; return; }
|
||||
if (o.k == 32) { float f = (float)v; uint32_t u; memcpy(&u, &f, 4); WR32(o.a, u); return; }
|
||||
if (o.k == 64) { uint64_t u; memcpy(&u, &v, 8); WR32(o.a, (uint32_t)u); WR32(o.a + 4, (uint32_t)(u >> 32)); return; }
|
||||
rt_fatal("FPU : écriture flottante inconnue");
|
||||
}
|
||||
|
||||
static double round_mode(double v) {
|
||||
switch ((fcw >> 10) & 3) {
|
||||
case 0: return nearbyint(v);
|
||||
case 1: return floor(v);
|
||||
case 2: return ceil(v);
|
||||
default: return trunc(v);
|
||||
}
|
||||
}
|
||||
|
||||
static void wr_int(FpuOp o, double v) {
|
||||
v = round_mode(v);
|
||||
if (o.k == 16) { WR16(o.a, (uint16_t)(int16_t)v); return; }
|
||||
if (o.k == 32) { WR32(o.a, (uint32_t)(int32_t)v); return; }
|
||||
if (o.k == 64) { int64_t i = (int64_t)v; WR32(o.a, (uint32_t)i); WR32(o.a + 4, (uint32_t)((uint64_t)i >> 32)); return; }
|
||||
rt_fatal("FPU : écriture entière inconnue");
|
||||
}
|
||||
|
||||
static void compare(double a, double b) {
|
||||
fsw &= ~0x4500u;
|
||||
if (isnan(a) || isnan(b)) fsw |= 0x4500u;
|
||||
else if (a < b) fsw |= 0x0100u;
|
||||
else if (a == b) fsw |= 0x4000u;
|
||||
}
|
||||
|
||||
void FPU_FLD(FpuOp o) { push(rd_float(o)); }
|
||||
void FPU_FILD(FpuOp o) { push(rd_int(o)); }
|
||||
void FPU_FST(FpuOp o) { wr_float(o, ST(0)); }
|
||||
void FPU_FSTP(FpuOp o) { wr_float(o, ST(0)); pop(); }
|
||||
void FPU_FIST(FpuOp o) { wr_int(o, ST(0)); }
|
||||
void FPU_FISTP(FpuOp o) { wr_int(o, ST(0)); pop(); }
|
||||
void FPU_FLDZ(void) { push(0.0); }
|
||||
void FPU_FLD1(void) { push(1.0); }
|
||||
void FPU_FLDLG2(void) { push(0.30102999566398119521); }
|
||||
void FPU_FADD(FpuOp o) { ST(0) += rd_float(o); }
|
||||
void FPU_FSUB(FpuOp o) { ST(0) -= rd_float(o); }
|
||||
void FPU_FSUBR(FpuOp o) { ST(0) = rd_float(o) - ST(0); }
|
||||
void FPU_FMUL(FpuOp o) { ST(0) *= rd_float(o); }
|
||||
void FPU_FDIV(FpuOp o) { ST(0) /= rd_float(o); }
|
||||
void FPU_FDIVR(FpuOp o) { ST(0) = rd_float(o) / ST(0); }
|
||||
void FPU_FIADD(FpuOp o) { ST(0) += rd_int(o); }
|
||||
void FPU_FISUB(FpuOp o) { ST(0) -= rd_int(o); }
|
||||
void FPU_FIMUL(FpuOp o) { ST(0) *= rd_int(o); }
|
||||
void FPU_FIDIV(FpuOp o) { ST(0) /= rd_int(o); }
|
||||
void FPU_FDIVP(FpuOp o) { int i = o.k - 100; ST(i) = ST(i) / ST(0); pop(); }
|
||||
void FPU_FMULP(FpuOp o) { int i = o.k - 100; ST(i) = ST(i) * ST(0); pop(); }
|
||||
void FPU_FADDP(FpuOp o) { int i = o.k - 100; ST(i) = ST(i) + ST(0); pop(); }
|
||||
void FPU_FSUBP(FpuOp o) { int i = o.k - 100; ST(i) = ST(i) - ST(0); pop(); }
|
||||
void FPU_FADD2(FpuOp a, FpuOp b) { ST(a.k - 100) = ST(a.k - 100) + ST(b.k - 100); }
|
||||
void FPU_FSUB2(FpuOp a, FpuOp b) { ST(a.k - 100) = ST(a.k - 100) - ST(b.k - 100); }
|
||||
void FPU_FSUBR2(FpuOp a, FpuOp b) { ST(a.k - 100) = ST(b.k - 100) - ST(a.k - 100); }
|
||||
void FPU_FMUL2(FpuOp a, FpuOp b) { ST(a.k - 100) = ST(a.k - 100) * ST(b.k - 100); }
|
||||
void FPU_FDIV2(FpuOp a, FpuOp b) { ST(a.k - 100) = ST(a.k - 100) / ST(b.k - 100); }
|
||||
void FPU_FDIVR2(FpuOp a, FpuOp b) { ST(a.k - 100) = ST(b.k - 100) / ST(a.k - 100); }
|
||||
void FPU_FSUBRP(FpuOp o) { int i = o.k - 100; ST(i) = ST(0) - ST(i); pop(); }
|
||||
void FPU_FDIVRP(FpuOp o) { int i = o.k - 100; ST(i) = ST(0) / ST(i); pop(); }
|
||||
void FPU_FCOM(FpuOp o) { compare(ST(0), rd_float(o)); }
|
||||
void FPU_FCOMP(FpuOp o) { compare(ST(0), rd_float(o)); pop(); }
|
||||
void FPU_FCOMPP(void) { compare(ST(0), ST(1)); pop(); pop(); }
|
||||
void FPU_FCHS(void) { ST(0) = -ST(0); }
|
||||
void FPU_FABS(void) { ST(0) = fabs(ST(0)); }
|
||||
void FPU_FRNDINT(void) { ST(0) = round_mode(ST(0)); }
|
||||
void FPU_FYL2X(void) { double x = pop(); ST(0) = ST(0) * log2(x); }
|
||||
void FPU_FXCH(FpuOp a, FpuOp b) { double t = ST(a.k - 100); ST(a.k - 100) = ST(b.k - 100); ST(b.k - 100) = t; }
|
||||
void FPU_FNSTSW(FpuOp o) {
|
||||
uint16_t v = (uint16_t)((fsw & ~0x3800u) | ((top & 7) << 11));
|
||||
if (o.k == 200) W(0) = v; else WR16(o.a, v);
|
||||
}
|
||||
void FPU_FNSTCW(FpuOp o) { WR16(o.a, fcw); }
|
||||
void FPU_FLDCW(FpuOp o) { fcw = RD16(o.a); }
|
||||
void FPU_FNINIT(void) { top = 0; fsw = 0; fcw = 0x037f; }
|
||||
void fpu_reset(void) { FPU_FNINIT(); }
|
||||
void FPU_FNSAVE(FpuOp o) { WR16(o.a, fcw); WR16(o.a + 4, fsw); FPU_FNINIT(); }
|
||||
void FPU_FRSTOR(FpuOp o) { fcw = RD16(o.a); fsw = RD16(o.a + 4); }
|
||||
@@ -0,0 +1,108 @@
|
||||
/* Hôte sans fenêtre, pour les essais : temps virtuel déterministe, images écrites en BMP.
|
||||
* --images N arrêt après N images (70 par seconde de jeu), défaut 700
|
||||
* --tous K écrit une image sur K, défaut 70
|
||||
* --dossier D dossier des images, défaut frames
|
||||
* --wav F enregistre le son mixé dans F (WAV 44,1 kHz stéréo)
|
||||
* --clic I,X,Y clic gauche à l'image I en (X, Y) (coordonnées 320×200), répétable
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
int host_quit;
|
||||
static uint64_t vtime;
|
||||
static unsigned frame, max_frames = 700, every = 70;
|
||||
static const char *outdir = "frames";
|
||||
static int mx = 160, my = 100, mb;
|
||||
static struct { unsigned at; int x, y; } clicks[64];
|
||||
static int nclicks;
|
||||
static FILE *wav_out;
|
||||
static uint32_t wav_bytes;
|
||||
|
||||
int host_init(int argc, char **argv) {
|
||||
int i;
|
||||
for (i = 1; i + 1 < argc; i++) {
|
||||
if (!strcmp(argv[i], "--images")) max_frames = (unsigned)atoi(argv[i + 1]);
|
||||
else if (!strcmp(argv[i], "--tous")) every = (unsigned)atoi(argv[i + 1]);
|
||||
else if (!strcmp(argv[i], "--dossier")) outdir = argv[i + 1];
|
||||
else if (!strcmp(argv[i], "--wav")) {
|
||||
static const uint8_t hdr[44] = {0};
|
||||
wav_out = fopen(argv[i + 1], "wb");
|
||||
if (wav_out) fwrite(hdr, 1, 44, wav_out);
|
||||
}
|
||||
else if (!strcmp(argv[i], "--clic") && nclicks < 64) {
|
||||
sscanf(argv[i + 1], "%u,%d,%d", &clicks[nclicks].at, &clicks[nclicks].x, &clicks[nclicks].y);
|
||||
nclicks++;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void put32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24); }
|
||||
|
||||
void host_shutdown(void) {
|
||||
uint8_t h[44];
|
||||
if (!wav_out) return;
|
||||
memcpy(h, "RIFF", 4); put32(h + 4, 36 + wav_bytes); memcpy(h + 8, "WAVEfmt ", 8);
|
||||
put32(h + 16, 16); h[20] = 1; h[21] = 0; h[22] = 2; h[23] = 0;
|
||||
put32(h + 24, AUDIO_RATE); put32(h + 28, AUDIO_RATE * 4); h[32] = 4; h[33] = 0; h[34] = 16; h[35] = 0;
|
||||
memcpy(h + 36, "data", 4); put32(h + 40, wav_bytes);
|
||||
fseek(wav_out, 0, SEEK_SET); fwrite(h, 1, 44, wav_out); fclose(wav_out);
|
||||
}
|
||||
|
||||
uint64_t host_time_us(void) {
|
||||
vtime += 20; /* chaque appel avance le temps virtuel */
|
||||
return vtime;
|
||||
}
|
||||
|
||||
static void write_bmp(const char *path) {
|
||||
FILE *f = fopen(path, "wb");
|
||||
uint8_t hdr[54 + 1024];
|
||||
int y, i;
|
||||
if (!f) return;
|
||||
memset(hdr, 0, sizeof hdr);
|
||||
hdr[0] = 'B'; hdr[1] = 'M';
|
||||
*(uint32_t *)(hdr + 2) = 54 + 1024 + 64000;
|
||||
*(uint32_t *)(hdr + 10) = 54 + 1024;
|
||||
*(uint32_t *)(hdr + 14) = 40;
|
||||
*(int32_t *)(hdr + 18) = 320; *(int32_t *)(hdr + 22) = 200;
|
||||
*(uint16_t *)(hdr + 26) = 1; *(uint16_t *)(hdr + 28) = 8;
|
||||
*(uint32_t *)(hdr + 34) = 64000; *(uint32_t *)(hdr + 46) = 256;
|
||||
for (i = 0; i < 256; i++) {
|
||||
hdr[54 + i * 4 + 0] = (uint8_t)(vga_dac[i * 3 + 2] * 255 / 63);
|
||||
hdr[54 + i * 4 + 1] = (uint8_t)(vga_dac[i * 3 + 1] * 255 / 63);
|
||||
hdr[54 + i * 4 + 2] = (uint8_t)(vga_dac[i * 3 + 0] * 255 / 63);
|
||||
}
|
||||
fwrite(hdr, 1, sizeof hdr, f);
|
||||
for (y = 199; y >= 0; y--) fwrite(M + VGA_BASE + (uint32_t)y * 320, 1, 320, f);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void host_frame(void) {
|
||||
int i;
|
||||
static int16_t snd[2 * (AUDIO_RATE / 70 + 1)];
|
||||
frame++;
|
||||
audio_mix(snd, AUDIO_RATE / 70); /* fait avancer les sons au rythme du jeu */
|
||||
if (wav_out) { fwrite(snd, 4, AUDIO_RATE / 70, wav_out); wav_bytes += 4 * (AUDIO_RATE / 70); }
|
||||
mb = 0;
|
||||
for (i = 0; i < nclicks; i++) {
|
||||
if (frame >= clicks[i].at && frame <= clicks[i].at + 8) { mx = clicks[i].x; my = clicks[i].y; }
|
||||
if (frame > clicks[i].at && frame <= clicks[i].at + 8) mb = 1; /* bouton tenu 8 images */
|
||||
}
|
||||
if (every && frame % every == 0) {
|
||||
char p[512];
|
||||
snprintf(p, sizeof p, "%s/img_%05u.bmp", outdir, frame);
|
||||
write_bmp(p);
|
||||
}
|
||||
if (frame >= max_frames) host_quit = 1;
|
||||
}
|
||||
|
||||
void host_pump(void) {}
|
||||
void host_idle(void) {}
|
||||
void host_audio_lock(void) {}
|
||||
void host_audio_unlock(void) {}
|
||||
int host_key_pop(uint8_t *sc) { (void)sc; return 0; }
|
||||
int host_key_peek(uint8_t *sc) { (void)sc; return 0; }
|
||||
void host_mouse(int *x, int *y, int *b) { *x = mx; *y = my; *b = mb; }
|
||||
@@ -0,0 +1,191 @@
|
||||
/* Hôte SDL2 : fenêtre, temps réel, souris, clavier.
|
||||
* --echelle N taille de la fenêtre (défaut 3 → 960×720)
|
||||
* --plein démarre en plein écran
|
||||
* F11 ou Alt+Entrée : plein écran ; fermer la fenêtre : quitter.
|
||||
* L'image 320×200 est affichée au format 4:3 (pixels plus hauts que larges, comme sur un écran VGA). */
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#define SDL_MAIN_HANDLED
|
||||
#include <SDL.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
int host_quit;
|
||||
static SDL_Window *win;
|
||||
static SDL_Renderer *ren;
|
||||
static SDL_Texture *tex;
|
||||
static SDL_AudioDeviceID adev;
|
||||
static uint64_t t0, freq;
|
||||
static int mx = 160, my = 100, mb;
|
||||
static uint64_t press_until[3]; /* un appui reste visible au moins 80 ms : le jeu lit l'état des boutons à chaque image */
|
||||
|
||||
/* ------------------------------------------------------------------ clavier : SDL → scancodes PC (jeu 1) */
|
||||
static uint8_t keyq[64];
|
||||
static int kq_head, kq_tail;
|
||||
|
||||
static void key_push(uint8_t sc) {
|
||||
int n = (kq_tail + 1) & 63;
|
||||
if (n != kq_head) { keyq[kq_tail] = sc; kq_tail = n; }
|
||||
}
|
||||
int host_key_peek(uint8_t *sc) { if (kq_head == kq_tail) return 0; *sc = keyq[kq_head]; return 1; }
|
||||
int host_key_pop(uint8_t *sc) { if (!host_key_peek(sc)) return 0; kq_head = (kq_head + 1) & 63; return 1; }
|
||||
|
||||
static uint8_t pc_scancode(SDL_Scancode s) {
|
||||
static const struct { SDL_Scancode s; uint8_t pc; } map[] = {
|
||||
{SDL_SCANCODE_ESCAPE, 0x01}, {SDL_SCANCODE_1, 0x02}, {SDL_SCANCODE_2, 0x03}, {SDL_SCANCODE_3, 0x04},
|
||||
{SDL_SCANCODE_4, 0x05}, {SDL_SCANCODE_5, 0x06}, {SDL_SCANCODE_6, 0x07}, {SDL_SCANCODE_7, 0x08},
|
||||
{SDL_SCANCODE_8, 0x09}, {SDL_SCANCODE_9, 0x0a}, {SDL_SCANCODE_0, 0x0b}, {SDL_SCANCODE_MINUS, 0x0c},
|
||||
{SDL_SCANCODE_EQUALS, 0x0d}, {SDL_SCANCODE_BACKSPACE, 0x0e}, {SDL_SCANCODE_TAB, 0x0f},
|
||||
{SDL_SCANCODE_Q, 0x10}, {SDL_SCANCODE_W, 0x11}, {SDL_SCANCODE_E, 0x12}, {SDL_SCANCODE_R, 0x13},
|
||||
{SDL_SCANCODE_T, 0x14}, {SDL_SCANCODE_Y, 0x15}, {SDL_SCANCODE_U, 0x16}, {SDL_SCANCODE_I, 0x17},
|
||||
{SDL_SCANCODE_O, 0x18}, {SDL_SCANCODE_P, 0x19}, {SDL_SCANCODE_LEFTBRACKET, 0x1a},
|
||||
{SDL_SCANCODE_RIGHTBRACKET, 0x1b}, {SDL_SCANCODE_RETURN, 0x1c}, {SDL_SCANCODE_KP_ENTER, 0x1c},
|
||||
{SDL_SCANCODE_LCTRL, 0x1d}, {SDL_SCANCODE_RCTRL, 0x1d},
|
||||
{SDL_SCANCODE_A, 0x1e}, {SDL_SCANCODE_S, 0x1f}, {SDL_SCANCODE_D, 0x20}, {SDL_SCANCODE_F, 0x21},
|
||||
{SDL_SCANCODE_G, 0x22}, {SDL_SCANCODE_H, 0x23}, {SDL_SCANCODE_J, 0x24}, {SDL_SCANCODE_K, 0x25},
|
||||
{SDL_SCANCODE_L, 0x26}, {SDL_SCANCODE_SEMICOLON, 0x27}, {SDL_SCANCODE_APOSTROPHE, 0x28},
|
||||
{SDL_SCANCODE_GRAVE, 0x29}, {SDL_SCANCODE_LSHIFT, 0x2a}, {SDL_SCANCODE_BACKSLASH, 0x2b},
|
||||
{SDL_SCANCODE_Z, 0x2c}, {SDL_SCANCODE_X, 0x2d}, {SDL_SCANCODE_C, 0x2e}, {SDL_SCANCODE_V, 0x2f},
|
||||
{SDL_SCANCODE_B, 0x30}, {SDL_SCANCODE_N, 0x31}, {SDL_SCANCODE_M, 0x32}, {SDL_SCANCODE_COMMA, 0x33},
|
||||
{SDL_SCANCODE_PERIOD, 0x34}, {SDL_SCANCODE_SLASH, 0x35}, {SDL_SCANCODE_RSHIFT, 0x36},
|
||||
{SDL_SCANCODE_KP_MULTIPLY, 0x37}, {SDL_SCANCODE_LALT, 0x38}, {SDL_SCANCODE_SPACE, 0x39},
|
||||
{SDL_SCANCODE_CAPSLOCK, 0x3a}, {SDL_SCANCODE_F1, 0x3b}, {SDL_SCANCODE_F2, 0x3c}, {SDL_SCANCODE_F3, 0x3d},
|
||||
{SDL_SCANCODE_F4, 0x3e}, {SDL_SCANCODE_F5, 0x3f}, {SDL_SCANCODE_F6, 0x40}, {SDL_SCANCODE_F7, 0x41},
|
||||
{SDL_SCANCODE_F8, 0x42}, {SDL_SCANCODE_F9, 0x43}, {SDL_SCANCODE_F10, 0x44},
|
||||
{SDL_SCANCODE_HOME, 0x47}, {SDL_SCANCODE_UP, 0x48}, {SDL_SCANCODE_PAGEUP, 0x49},
|
||||
{SDL_SCANCODE_KP_MINUS, 0x4a}, {SDL_SCANCODE_LEFT, 0x4b}, {SDL_SCANCODE_RIGHT, 0x4d},
|
||||
{SDL_SCANCODE_KP_PLUS, 0x4e}, {SDL_SCANCODE_END, 0x4f}, {SDL_SCANCODE_DOWN, 0x50},
|
||||
{SDL_SCANCODE_PAGEDOWN, 0x51}, {SDL_SCANCODE_INSERT, 0x52}, {SDL_SCANCODE_DELETE, 0x53},
|
||||
{SDL_SCANCODE_KP_7, 0x47}, {SDL_SCANCODE_KP_8, 0x48}, {SDL_SCANCODE_KP_9, 0x49},
|
||||
{SDL_SCANCODE_KP_4, 0x4b}, {SDL_SCANCODE_KP_5, 0x4c}, {SDL_SCANCODE_KP_6, 0x4d},
|
||||
{SDL_SCANCODE_KP_1, 0x4f}, {SDL_SCANCODE_KP_2, 0x50}, {SDL_SCANCODE_KP_3, 0x51},
|
||||
{SDL_SCANCODE_KP_0, 0x52}, {SDL_SCANCODE_KP_PERIOD, 0x53},
|
||||
};
|
||||
size_t i;
|
||||
for (i = 0; i < sizeof map / sizeof map[0]; i++) if (map[i].s == s) return map[i].pc;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ son */
|
||||
static void SDLCALL audio_cb(void *user, Uint8 *stream, int len) {
|
||||
(void)user;
|
||||
audio_mix((int16_t *)stream, len / 4);
|
||||
}
|
||||
void host_audio_lock(void) { if (adev) SDL_LockAudioDevice(adev); }
|
||||
void host_audio_unlock(void) { if (adev) SDL_UnlockAudioDevice(adev); }
|
||||
|
||||
/* ------------------------------------------------------------------ cycle de vie */
|
||||
int host_init(int argc, char **argv) {
|
||||
int i, scale = 3, full = 0;
|
||||
for (i = 1; i < argc; i++) {
|
||||
if (!strcmp(argv[i], "--echelle") && i + 1 < argc) scale = atoi(argv[i + 1]);
|
||||
else if (!strcmp(argv[i], "--plein")) full = 1;
|
||||
}
|
||||
if (scale < 1) scale = 1;
|
||||
SDL_SetMainReady();
|
||||
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO) != 0) {
|
||||
fprintf(stderr, "SDL : %s\n", SDL_GetError());
|
||||
return 0;
|
||||
}
|
||||
SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "0");
|
||||
win = SDL_CreateWindow("Bud Tucker in Double Trouble (recomp)", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
|
||||
320 * scale, 240 * scale, SDL_WINDOW_RESIZABLE | (full ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0));
|
||||
ren = win ? SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED) : NULL;
|
||||
if (!ren) { fprintf(stderr, "SDL : %s\n", SDL_GetError()); return 0; }
|
||||
SDL_RenderSetLogicalSize(ren, 320, 240); /* 4:3 ; souris convertie par SDL */
|
||||
tex = SDL_CreateTexture(ren, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, 320, 200);
|
||||
SDL_ShowCursor(SDL_DISABLE); /* le jeu dessine son propre curseur */
|
||||
{
|
||||
SDL_AudioSpec want, got;
|
||||
SDL_zero(want);
|
||||
want.freq = AUDIO_RATE; want.format = AUDIO_S16SYS; want.channels = 2; want.samples = 1024;
|
||||
want.callback = audio_cb;
|
||||
adev = SDL_OpenAudioDevice(NULL, 0, &want, &got, 0);
|
||||
if (adev) SDL_PauseAudioDevice(adev, 0);
|
||||
else fprintf(stderr, "SDL : pas de sortie audio (%s)\n", SDL_GetError());
|
||||
}
|
||||
freq = SDL_GetPerformanceFrequency();
|
||||
t0 = SDL_GetPerformanceCounter();
|
||||
return 1;
|
||||
}
|
||||
|
||||
void host_shutdown(void) {
|
||||
if (adev) SDL_CloseAudioDevice(adev);
|
||||
if (tex) SDL_DestroyTexture(tex);
|
||||
if (ren) SDL_DestroyRenderer(ren);
|
||||
if (win) SDL_DestroyWindow(win);
|
||||
SDL_Quit();
|
||||
}
|
||||
|
||||
uint64_t host_time_us(void) {
|
||||
return (SDL_GetPerformanceCounter() - t0) * 1000000u / freq;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ image */
|
||||
void host_frame(void) {
|
||||
uint32_t pal[256];
|
||||
void *pixels;
|
||||
int pitch, x, y, i;
|
||||
for (i = 0; i < 256; i++) {
|
||||
uint32_t r = vga_dac[i * 3] & 63, g = vga_dac[i * 3 + 1] & 63, b = vga_dac[i * 3 + 2] & 63;
|
||||
pal[i] = 0xff000000u | (r << 2 | r >> 4) << 16 | (g << 2 | g >> 4) << 8 | (b << 2 | b >> 4);
|
||||
}
|
||||
if (SDL_LockTexture(tex, NULL, &pixels, &pitch) == 0) {
|
||||
const uint8_t *src = M + VGA_BASE;
|
||||
for (y = 0; y < 200; y++) {
|
||||
uint32_t *dst = (uint32_t *)((uint8_t *)pixels + y * pitch);
|
||||
for (x = 0; x < 320; x++) dst[x] = pal[src[y * 320 + x]];
|
||||
}
|
||||
SDL_UnlockTexture(tex);
|
||||
}
|
||||
SDL_SetRenderDrawColor(ren, 0, 0, 0, 255);
|
||||
SDL_RenderClear(ren);
|
||||
SDL_RenderCopy(ren, tex, NULL, NULL);
|
||||
SDL_RenderPresent(ren);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ événements */
|
||||
void host_pump(void) {
|
||||
SDL_Event e;
|
||||
while (SDL_PollEvent(&e)) {
|
||||
switch (e.type) {
|
||||
case SDL_QUIT: host_quit = 1; break;
|
||||
case SDL_MOUSEMOTION:
|
||||
mx = e.motion.x; my = e.motion.y * 200 / 240;
|
||||
break;
|
||||
case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: {
|
||||
int bit = e.button.button == SDL_BUTTON_LEFT ? 1 : e.button.button == SDL_BUTTON_RIGHT ? 2 : 4;
|
||||
mx = e.button.x; my = e.button.y * 200 / 240;
|
||||
if (e.type == SDL_MOUSEBUTTONDOWN) { mb |= bit; press_until[bit >> 1] = host_time_us() + 80000; }
|
||||
else mb &= ~bit;
|
||||
break;
|
||||
}
|
||||
case SDL_KEYDOWN: case SDL_KEYUP: {
|
||||
uint8_t sc;
|
||||
if (e.type == SDL_KEYDOWN && (e.key.keysym.scancode == SDL_SCANCODE_F11 ||
|
||||
(e.key.keysym.scancode == SDL_SCANCODE_RETURN && (e.key.keysym.mod & KMOD_ALT)))) {
|
||||
uint32_t fl = SDL_GetWindowFlags(win);
|
||||
SDL_SetWindowFullscreen(win, (fl & SDL_WINDOW_FULLSCREEN_DESKTOP) ? 0 : SDL_WINDOW_FULLSCREEN_DESKTOP);
|
||||
break;
|
||||
}
|
||||
sc = pc_scancode(e.key.keysym.scancode);
|
||||
if (sc)
|
||||
key_push(e.type == SDL_KEYDOWN ? sc : (uint8_t)(sc | 0x80));
|
||||
break;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
if (mx < 0) mx = 0; if (mx > 319) mx = 319;
|
||||
if (my < 0) my = 0; if (my > 199) my = 199;
|
||||
}
|
||||
|
||||
void host_idle(void) { SDL_Delay(1); }
|
||||
|
||||
void host_mouse(int *x, int *y, int *b) {
|
||||
uint64_t now = host_time_us();
|
||||
int i, held = mb;
|
||||
for (i = 0; i < 3; i++) if (now < press_until[i]) held |= 1 << i;
|
||||
*x = mx; *y = my; *b = held;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/* Charge TUCKER.EXE (format LE de DOS/4GW) dans la mémoire émulée et applique les relocations.
|
||||
* Même logique que tools/le.py ; le fichier d'origine n'est jamais modifié. */
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
static uint32_t u32(const uint8_t *d, uint32_t o) { return d[o] | d[o + 1] << 8 | d[o + 2] << 16 | (uint32_t)d[o + 3] << 24; }
|
||||
static uint16_t u16(const uint8_t *d, uint32_t o) { return (uint16_t)(d[o] | d[o + 1] << 8); }
|
||||
|
||||
int load_le_image(const char *path, uint32_t *entry, uint32_t *stack) {
|
||||
FILE *f = fopen(path, "rb");
|
||||
uint8_t *d;
|
||||
long n;
|
||||
uint32_t le, npages, eip_obj, eip, esp_obj, esp, page_size, last_page, obj_tab, nobj, opt, fpt, frt, data_pages;
|
||||
uint32_t base[8] = {0}, vsize[8], oflags[8] = {0}, pidx[8], pcnt[8], i, k;
|
||||
if (!f) return 0;
|
||||
fseek(f, 0, SEEK_END); n = ftell(f); fseek(f, 0, SEEK_SET);
|
||||
d = (uint8_t *)malloc((size_t)n);
|
||||
if (!d || fread(d, 1, (size_t)n, f) != (size_t)n) { fclose(f); return 0; }
|
||||
fclose(f);
|
||||
le = u32(d, 0x3c);
|
||||
if (d[le] != 'L' || d[le + 1] != 'E') { free(d); return 0; }
|
||||
npages = u32(d, le + 0x14); eip_obj = u32(d, le + 0x18); eip = u32(d, le + 0x1c);
|
||||
esp_obj = u32(d, le + 0x20); esp = u32(d, le + 0x24);
|
||||
page_size = u32(d, le + 0x28); last_page = u32(d, le + 0x2c);
|
||||
obj_tab = u32(d, le + 0x40); nobj = u32(d, le + 0x44); opt = u32(d, le + 0x48);
|
||||
fpt = u32(d, le + 0x68); frt = u32(d, le + 0x6c); data_pages = u32(d, le + 0x80);
|
||||
if (nobj > 8) nobj = 8;
|
||||
for (i = 0; i < nobj; i++) {
|
||||
uint32_t o = le + obj_tab + i * 24;
|
||||
vsize[i] = u32(d, o); base[i] = u32(d, o + 4); oflags[i] = u32(d, o + 8); pidx[i] = u32(d, o + 12); pcnt[i] = u32(d, o + 16);
|
||||
for (k = 0; k < pcnt[i]; k++) {
|
||||
uint32_t pn = pidx[i] + k, e = le + opt + (pn - 1) * 4;
|
||||
uint32_t num = (uint32_t)d[e] << 16 | (uint32_t)d[e + 1] << 8 | d[e + 2];
|
||||
uint32_t off = data_pages + (num - 1) * page_size;
|
||||
uint32_t ln = pn == npages ? last_page : page_size;
|
||||
memcpy(M + base[i] + k * page_size, d + off, ln);
|
||||
}
|
||||
}
|
||||
for (i = 0; i < nobj; i++) {
|
||||
for (k = 0; k < pcnt[i]; k++) {
|
||||
uint32_t pn = pidx[i] + k;
|
||||
uint32_t p = le + frt + u32(d, le + fpt + (pn - 1) * 4);
|
||||
uint32_t end = le + frt + u32(d, le + fpt + pn * 4);
|
||||
while (p < end) {
|
||||
uint8_t srct = d[p], flg = d[p + 1];
|
||||
uint32_t cnt = 1, tobj, toff = 0, j, offs_at;
|
||||
int single;
|
||||
p += 2;
|
||||
single = !(srct & 0x20);
|
||||
if (!single) { cnt = d[p]; p += 1; offs_at = 0; }
|
||||
else { offs_at = p; p += 2; }
|
||||
if (flg & 0x40) { tobj = u16(d, p); p += 2; } else { tobj = d[p]; p += 1; }
|
||||
if ((srct & 0x0f) != 2) {
|
||||
if (flg & 0x10) { toff = u32(d, p); p += 4; } else { toff = u16(d, p); p += 2; }
|
||||
}
|
||||
if (!single) { offs_at = p; p += 2 * cnt; }
|
||||
for (j = 0; j < cnt; j++) {
|
||||
int16_t so = (int16_t)u16(d, offs_at + 2 * j);
|
||||
int32_t a = (int32_t)(k * page_size) + so;
|
||||
uint32_t target = base[tobj - 1] + toff;
|
||||
if ((srct & 0x0f) == 7 && a >= 0) WR32(base[i] + (uint32_t)a, target);
|
||||
/* type 2 : sélecteur 16 bits de l'objet visé (modèle à plat) */
|
||||
if ((srct & 0x0f) == 2 && a >= 0) WR16(base[i] + (uint32_t)a, (oflags[tobj - 1] & 4) ? SEL_CODE : SEL_DATA);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*entry = base[eip_obj - 1] + eip;
|
||||
*stack = base[esp_obj - 1] + esp;
|
||||
free(d);
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/* Matériel : ports VGA, PIT, PIC, clavier ; interruptions matérielles (horloge, clavier). */
|
||||
#include <stdio.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
|
||||
uint8_t vga_dac[768];
|
||||
static uint32_t dac_w, dac_r;
|
||||
uint32_t pit_reload = 0; /* 0 = 65536 (18,2 Hz) */
|
||||
static int pit_lohi;
|
||||
uint8_t kbd_port60;
|
||||
static uint32_t retrace_toggle;
|
||||
|
||||
uint32_t rt_in(uint32_t port, int size) {
|
||||
(void)size;
|
||||
switch (port) {
|
||||
case 0x60: return kbd_port60;
|
||||
case 0x61: return 0;
|
||||
case 0x64: return 0x1c;
|
||||
case 0x3c9: { uint32_t v = vga_dac[dac_r % 768]; dac_r++; return v; }
|
||||
case 0x3da: retrace_toggle ^= 9; if (retrace_toggle & 8) rt_poll(); return retrace_toggle;
|
||||
case 0x21: case 0xa1: return 0;
|
||||
default:
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[port] in %03x\n", port);
|
||||
return 0xff;
|
||||
}
|
||||
}
|
||||
|
||||
void rt_out(uint32_t port, uint32_t v, int size) {
|
||||
(void)size;
|
||||
switch (port) {
|
||||
case 0x3c8: dac_w = (v & 0xff) * 3; break;
|
||||
case 0x3c7: dac_r = (v & 0xff) * 3; break;
|
||||
case 0x3c9: vga_dac[dac_w % 768] = (uint8_t)(v & 63); dac_w = (dac_w + 1) % 768; break;
|
||||
case 0x43: pit_lohi = 0; break;
|
||||
case 0x40:
|
||||
if (!pit_lohi) { pit_reload = (pit_reload & 0xff00u) | (v & 0xff); pit_lohi = 1; }
|
||||
else { pit_reload = (pit_reload & 0x00ffu) | ((v & 0xff) << 8); pit_lohi = 0;
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[pit] diviseur %u\n", pit_reload); }
|
||||
break;
|
||||
case 0x20: case 0xa0: case 0x21: case 0xa1: case 0x61: break;
|
||||
default:
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[port] out %03x <- %02x\n", port, v);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ interruptions matérielles */
|
||||
static int in_irq;
|
||||
|
||||
void rt_raise_irq(int irq) {
|
||||
int vec = irq < 8 ? 8 + irq : 0x70 + irq - 8;
|
||||
uint32_t off = pm_vec_off[vec];
|
||||
if (!off || in_irq) {
|
||||
if (irq == 0) WR32(0x46c, RD32(0x46c) + 1);
|
||||
return;
|
||||
}
|
||||
{
|
||||
uint32_t op = cpu.lf_op, sz = cpu.lf_sz, a = cpu.lf_a, b = cpu.lf_b, r = cpu.lf_r, c = cpu.lf_c, fl = cpu.lf_flags;
|
||||
uint32_t df = cpu.df;
|
||||
in_irq = 1;
|
||||
PUSH32(get_eflags());
|
||||
PUSH32(pm_vec_sel[vec]);
|
||||
PUSH32(0xfffffff0u); /* adresse de retour fictive : iretd la dépile */
|
||||
rt_call(off);
|
||||
in_irq = 0;
|
||||
cpu.lf_op = op; cpu.lf_sz = sz; cpu.lf_a = a; cpu.lf_b = b; cpu.lf_r = r; cpu.lf_c = c; cpu.lf_flags = fl;
|
||||
cpu.df = df;
|
||||
}
|
||||
}
|
||||
|
||||
void rt_callback(uint32_t addr) {
|
||||
Cpu save = cpu;
|
||||
in_irq = 1;
|
||||
PUSH32(0xfffffff0u);
|
||||
rt_call(addr);
|
||||
in_irq = 0;
|
||||
cpu = save;
|
||||
}
|
||||
|
||||
/* minuteur logiciel qui remplace AIL_register_timer */
|
||||
static uint32_t game_timer_fn, game_timer_hz;
|
||||
static uint64_t next_game_us;
|
||||
|
||||
void rt_game_timer(uint32_t callback, uint32_t hz) {
|
||||
game_timer_fn = callback; game_timer_hz = hz; next_game_us = 0;
|
||||
}
|
||||
|
||||
/* appelé régulièrement par le code traduit (POLL) */
|
||||
uint32_t poll_counter;
|
||||
static uint64_t next_tick_us, next_frame_us;
|
||||
static uint32_t polls_since_frame;
|
||||
|
||||
void rt_poll(void) {
|
||||
uint64_t now;
|
||||
int guard = 0;
|
||||
poll_counter = 0;
|
||||
if (in_irq) return;
|
||||
now = host_time_us();
|
||||
if (!next_tick_us) { next_tick_us = now; next_frame_us = now; }
|
||||
while (now >= next_tick_us && guard++ < 8) {
|
||||
uint32_t div = pit_reload ? pit_reload : 65536u;
|
||||
next_tick_us += (uint64_t)div * 1000000u / 1193182u;
|
||||
rt_raise_irq(0);
|
||||
}
|
||||
if (guard >= 8) next_tick_us = now;
|
||||
if (game_timer_fn) {
|
||||
if (!next_game_us) next_game_us = now;
|
||||
guard = 0;
|
||||
while (now >= next_game_us && guard++ < 8) {
|
||||
next_game_us += 1000000u / game_timer_hz;
|
||||
rt_callback(game_timer_fn);
|
||||
}
|
||||
if (guard >= 8) next_game_us = now;
|
||||
}
|
||||
/* Le jeu attend en boucle active (compteur de ticks, retour de balayage) : passé un certain
|
||||
* nombre de passages sans nouvelle image à produire, on dort un peu au lieu de brûler un cœur. */
|
||||
if (++polls_since_frame > 4096 && now + 2000 < next_frame_us) host_idle();
|
||||
if (now >= next_frame_us) {
|
||||
uint8_t sc;
|
||||
polls_since_frame = 0;
|
||||
next_frame_us = now + 14286; /* ~70 Hz */
|
||||
host_pump();
|
||||
if (host_quit) rt_exit(0);
|
||||
audio_update();
|
||||
host_frame();
|
||||
if (pm_vec_off[9]) /* gestionnaire clavier du jeu : IRQ1 ; sinon file BIOS (int 16h) */
|
||||
while (host_key_pop(&sc)) { kbd_port60 = sc; rt_raise_irq(1); }
|
||||
}
|
||||
}
|
||||
|
||||
/* état matériel d'un démarrage (avant de lancer un autre programme) */
|
||||
void machine_reset(void) {
|
||||
pit_reload = 0; pit_lohi = 0; kbd_port60 = 0; retrace_toggle = 0;
|
||||
in_irq = 0;
|
||||
game_timer_fn = 0; game_timer_hz = 0; next_game_us = 0;
|
||||
next_tick_us = 0; next_frame_us = 0; polls_since_frame = 0; poll_counter = 0;
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
/* Point d'entrée : prépare la mémoire, puis enchaîne les programmes recompilés comme BUD.BAT :
|
||||
* INTRO.EXE (logo, cinématiques), puis TUCKER.EXE (le jeu).
|
||||
* --sans-intro lance directement le jeu
|
||||
* --intro ne joue que l'intro
|
||||
* --cd D --hd D --root D --saves D dossiers des fichiers du jeu
|
||||
* -v journal détaillé */
|
||||
#include <setjmp.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
#include "recomp_tucker.h"
|
||||
#include "recomp_intro.h"
|
||||
|
||||
typedef struct {
|
||||
const char *name;
|
||||
const char *host_path; /* exécutable lu (en lecture seule) */
|
||||
const char *dos_name; /* nom vu par le programme dans son environnement */
|
||||
const FnEntry *table;
|
||||
unsigned count;
|
||||
void (*entry)(void);
|
||||
} Program;
|
||||
|
||||
static jmp_buf exit_jmp;
|
||||
static int exit_code;
|
||||
|
||||
void rt_fatal(const char *why) {
|
||||
fprintf(stderr, "arrêt : %s (esp=%08x ebp=%08x eax=%08x)\n", why, R(4), R(5), R(0));
|
||||
exit_code = 99;
|
||||
longjmp(exit_jmp, 1);
|
||||
}
|
||||
|
||||
void rt_exit(int code) {
|
||||
exit_code = code;
|
||||
longjmp(exit_jmp, 1);
|
||||
}
|
||||
|
||||
int host_init(int argc, char **argv);
|
||||
void host_shutdown(void);
|
||||
|
||||
static const char *arg(int argc, char **argv, const char *name, const char *def) {
|
||||
int i;
|
||||
for (i = 1; i + 1 < argc; i++) if (!strcmp(argv[i], name)) return argv[i + 1];
|
||||
return def;
|
||||
}
|
||||
|
||||
static int flag(int argc, char **argv, const char *name) {
|
||||
int i;
|
||||
for (i = 1; i < argc; i++) if (!strcmp(argv[i], name)) return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* charge et exécute un programme jusqu'à sa sortie ; renvoie son code de sortie */
|
||||
static int run_program(const Program *p) {
|
||||
uint32_t entry, stack;
|
||||
memset(M, 0, MEM_SIZE + 16);
|
||||
dos_reset();
|
||||
machine_reset();
|
||||
audio_reset();
|
||||
ail_reset();
|
||||
fpu_reset();
|
||||
if (!load_le_image(p->host_path, &entry, &stack)) {
|
||||
fprintf(stderr, "impossible de lire %s\n", p->host_path);
|
||||
return -1;
|
||||
}
|
||||
dos_init(p->dos_name);
|
||||
cur_fn_table = p->table;
|
||||
cur_fn_count = p->count;
|
||||
memset(&cpu, 0, sizeof cpu);
|
||||
set_seg(S_CS, SEL_CODE); set_seg(S_DS, SEL_DATA); set_seg(S_SS, SEL_DATA);
|
||||
set_seg(S_ES, SEL_PSP); set_seg(S_FS, 0); set_seg(S_GS, 0);
|
||||
R(4) = stack;
|
||||
set_eflags(0x202);
|
||||
PUSH32(0);
|
||||
exit_code = 0;
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[main] lance %s\n", p->name);
|
||||
if (!setjmp(exit_jmp)) {
|
||||
p->entry();
|
||||
fprintf(stderr, "%s est revenu de son point d'entrée\n", p->name);
|
||||
}
|
||||
if (rt_cfg.verbose) fprintf(stderr, "[main] %s terminé (code %d)\n", p->name, exit_code);
|
||||
return exit_code;
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
static char intro_path[600];
|
||||
Program progs[2];
|
||||
int i, first, last, code = 0;
|
||||
rt_cfg.cd_dir = arg(argc, argv, "--cd", "../extracted/iso/TUCKER");
|
||||
rt_cfg.hd_dir = arg(argc, argv, "--hd", "../Install/C/TUCKER");
|
||||
rt_cfg.root_dir = arg(argc, argv, "--root", "../Install/C");
|
||||
rt_cfg.save_dir = arg(argc, argv, "--saves", "saves");
|
||||
rt_cfg.exe_path = arg(argc, argv, "--exe", "../extracted/iso/TUCKER/TUCKER.EXE");
|
||||
snprintf(intro_path, sizeof intro_path, "%s/INTRO.EXE", rt_cfg.cd_dir);
|
||||
rt_cfg.mute = !flag(argc, argv, "--son");
|
||||
rt_cfg.verbose = flag(argc, argv, "-v");
|
||||
|
||||
progs[0].name = "intro"; progs[0].host_path = intro_path; progs[0].dos_name = "E:\\TUCKER\\INTRO.EXE";
|
||||
progs[0].table = intro_fn_table; progs[0].count = intro_fn_count; progs[0].entry = INTRO_ENTRY;
|
||||
progs[1].name = "jeu"; progs[1].host_path = rt_cfg.exe_path; progs[1].dos_name = "C:\\TUCKER\\TUCKER.EXE";
|
||||
progs[1].table = tucker_fn_table; progs[1].count = tucker_fn_count; progs[1].entry = TUCKER_ENTRY;
|
||||
first = flag(argc, argv, "--sans-intro") ? 1 : 0;
|
||||
last = flag(argc, argv, "--intro") ? 0 : 1;
|
||||
|
||||
M = (uint8_t *)calloc(MEM_SIZE + 16, 1);
|
||||
if (!M) { fprintf(stderr, "mémoire insuffisante\n"); return 1; }
|
||||
if (!host_init(argc, argv)) return 1;
|
||||
for (i = first; i <= last && !host_quit; i++) {
|
||||
code = run_program(&progs[i]);
|
||||
if (code < 0) break;
|
||||
}
|
||||
host_shutdown();
|
||||
fprintf(stderr, "fin (code %d)\n", code);
|
||||
return code < 0 ? 1 : code;
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
/* Fonctions de TUCKER.EXE réécrites à la main (liste : overrides.txt).
|
||||
* C'est aussi le point d'accroche des mods : une fonction du jeu remplacée ici peut appeler
|
||||
* l'originale (F_xxxxxxxx_orig) avant ou après son propre travail. */
|
||||
#include "cpu.h"
|
||||
#include "rt.h"
|
||||
#include "recomp_tucker.h"
|
||||
#include "recomp_intro.h"
|
||||
|
||||
/* int386x(eax = n° d'interruption, edx = REGS entrée, ebx = REGS sortie, ecx = SREGS) -> eax = sortie.eax
|
||||
* REGS : eax ebx ecx edx esi edi cflag (dwords) ; SREGS : es cs ss ds fs gs (mots).
|
||||
* L'original saute dans une table de stubs « int N ; ret » par push/ret (0x377CC). */
|
||||
static void int386x_impl(void) {
|
||||
uint32_t n = R(0), in = R(2), out = R(3), sregs = R(1);
|
||||
uint32_t keep_ebx = R(3), keep_ecx = R(1), keep_edx = R(2), keep_esi = R(6), keep_edi = R(7), keep_ebp = R(5);
|
||||
uint16_t keep_es = SEGR(S_ES), keep_ds = SEGR(S_DS);
|
||||
R(0) = RD32(in); R(3) = RD32(in + 4); R(1) = RD32(in + 8); R(2) = RD32(in + 12);
|
||||
R(6) = RD32(in + 16); R(7) = RD32(in + 20);
|
||||
if (sregs) { set_seg(S_ES, RD16(sregs)); set_seg(S_DS, RD16(sregs + 6)); }
|
||||
set_eflags(get_eflags() & ~1u);
|
||||
rt_int(n & 0xff);
|
||||
WR32(out, R(0)); WR32(out + 4, R(3)); WR32(out + 8, R(1)); WR32(out + 12, R(2));
|
||||
WR32(out + 16, R(6)); WR32(out + 20, R(7)); WR32(out + 24, get_eflags() & 1u);
|
||||
if (sregs) { WR16(sregs, SEGR(S_ES)); WR16(sregs + 6, SEGR(S_DS)); }
|
||||
set_seg(S_ES, keep_es); set_seg(S_DS, keep_ds);
|
||||
R(0) = RD32(out);
|
||||
R(3) = keep_ebx; R(1) = keep_ecx; R(2) = keep_edx; R(6) = keep_esi; R(7) = keep_edi; R(5) = keep_ebp;
|
||||
R(4) += 4; /* ret */
|
||||
}
|
||||
|
||||
void F_0002eea5(void) { int386x_impl(); } /* TUCKER.EXE */
|
||||
void I_000222a4(void) { int386x_impl(); } /* INTRO.EXE : même bibliothèque Watcom */
|
||||
|
||||
/* ------------------------------------------------------------------ son et minuteur
|
||||
* Le jeu passe par Miles AIL, qui charge un pilote .DIG 16 bits (SB16.DIG) : impossible à
|
||||
* recompiler. On remplace toutes les fonctions du module son du jeu (0x114d4-0x122f9) qui
|
||||
* appellent AIL ; elles jouent par notre mixeur (audio.c). Les chargements de WAV en mémoire
|
||||
* (0x11784 fx, 0x11ae8 musiques) restent ceux du jeu : ils ne travaillent que si [0x41f90] = 1. */
|
||||
#define SOUND_ON 0x41f90u
|
||||
#define SND_BASE 0x4661cu /* début de la zone où le jeu charge ses WAV (fx, musiques) */
|
||||
#define FX_LOOPS 0x46dd4u /* type de son par canal : 2, 5, 7 = en boucle */
|
||||
#define MUS_LOOPS 0x472a8u /* 2 = musique en boucle */
|
||||
#define FX_FLAGS 0x46644u /* « en cours » des canaux de bruitage 0..6 */
|
||||
#define MUS_FLAGS 0x4663cu /* « en cours » des musiques 0..1 */
|
||||
#define SPEECH_FLAG 0x46638u
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
void F_000114d4(void) { /* int son_init(void) -> 0 = succès */
|
||||
WR32(SOUND_ON, 1); /* les fonctions de chargement des WAV ne travaillent que si le son est actif */
|
||||
WR32(0x46674, 1); /* « pilote » AIL : seulement testé à zéro */
|
||||
WR32(0x46618, RD32(SND_BASE)); /* comme l'original */
|
||||
R(0) = 0;
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_00011598(void) { /* son_fin */
|
||||
int i;
|
||||
for (i = 0; i < AUDIO_FX_CH; i++) audio_stop(AUDIO_FX, i);
|
||||
for (i = 0; i < AUDIO_MUS_CH; i++) audio_stop(AUDIO_MUSIC, i);
|
||||
audio_stop(AUDIO_SPEECH, 0);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
static int fx_ch(uint32_t n) { return (int)(n % AUDIO_FX_CH); }
|
||||
static int mus_ch(uint32_t n) { return (int)(n % AUDIO_MUS_CH); }
|
||||
|
||||
/* bruitage_joue(eax = décalage du WAV dans la zone, edx = canal, ebx = volume 0..127) */
|
||||
void F_000118b0(void) {
|
||||
uint32_t off = R(0), n = R(2);
|
||||
int vol = (int)R(3), type = (int)RD32(FX_LOOPS + 4 * n);
|
||||
audio_play_mem(AUDIO_FX, fx_ch(n), RD32(SND_BASE) + off, vol, type == 2 || type == 5 || type == 7,
|
||||
n < 7 ? FX_FLAGS + 4 * n : 0);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_00011614(void) { /* bruitage_arrete(eax = canal) */
|
||||
uint32_t n = R(0);
|
||||
audio_stop(AUDIO_FX, fx_ch(n));
|
||||
if (n < 6) WR32(FX_FLAGS + 4 * n, 0);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_00011d78(void) { /* bruitage_volume(eax = canal, edx = volume) */
|
||||
int v = (int)R(2);
|
||||
audio_set_volume(AUDIO_FX, fx_ch(R(0)), v < 0 ? 0 : v);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
/* musique_joue(eax = décalage du WAV, edx = canal, ebx = volume) */
|
||||
void F_00011c14(void) {
|
||||
uint32_t off = R(0), n = R(2);
|
||||
audio_play_mem(AUDIO_MUSIC, mus_ch(n), RD32(SND_BASE) + off, (int)R(3), RD32(MUS_LOOPS + 4 * n) == 2,
|
||||
n < 2 ? MUS_FLAGS + 4 * n : 0);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_000115dc(void) { /* musique_arrete(eax = canal) */
|
||||
audio_stop(AUDIO_MUSIC, mus_ch(R(0)));
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_00011d2c(void) { /* musique_volume(eax = canal, edx = volume) */
|
||||
int v = (int)R(2);
|
||||
audio_set_volume(AUDIO_MUSIC, mus_ch(R(0)), v < 0 ? 0 : v);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
/* voix_joue(eax = numéro, edx = volume) : X:\tucker\speech\samNNNN.wav, X = [0x4671c] + 0x40 (lecteur CD) */
|
||||
void F_00011f64(void) {
|
||||
char name[64];
|
||||
uint32_t n = R(0) % 10000;
|
||||
snprintf(name, sizeof name, "%c:\\tucker\\speech\\sam%04u.wav", (char)(RD8(0x4671c) + 0x40), n);
|
||||
if (!audio_play_file(AUDIO_SPEECH, 0, name, (int)R(2), SPEECH_FLAG)) WR32(SPEECH_FLAG, 0);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_00011eb4(void) { /* voix_suite : l'original remplit le tampon de lecture en flux */
|
||||
audio_update();
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_00011f24(void) { /* voix_arrete */
|
||||
audio_stop(AUDIO_SPEECH, 0);
|
||||
WR32(SPEECH_FLAG, 0);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_00012274(void) { /* int minuteur_debut(void) -> poignée */
|
||||
rt_game_timer(0x12250, 46);
|
||||
R(0) = 0;
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
void F_000122c8(void) { /* minuteur_fin(poignée) */
|
||||
rt_game_timer(0, 0);
|
||||
R(4) += 4;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ INTRO.EXE : API AIL émulée (ail.c)
|
||||
* Canaux de l'intro : [0x35f80] musique, [0x35f70] flux audio\*.raw (narration), [0x35e14 + 4n] bruitages. */
|
||||
static int intro_group(uint32_t h) {
|
||||
if (h == RD32(0x35f80)) return AUDIO_MUSIC;
|
||||
if (h == RD32(0x35f70)) return AUDIO_SPEECH;
|
||||
return AUDIO_FX;
|
||||
}
|
||||
|
||||
void I_00014cf9(void) { ail_group_hint = intro_group; ail_startup(); }
|
||||
void I_00014e75(void) { ail_shutdown(); }
|
||||
void I_00014f08(void) { ail_set_preference(); }
|
||||
void I_00016032(void) { ail_install_DIG_INI(); }
|
||||
void I_0001626a(void) { ail_allocate_sample_handle(); }
|
||||
void I_00016448(void) { ail_release_sample_handle(); }
|
||||
void I_000164b5(void) { ail_init_sample(); }
|
||||
void I_00016522(void) { ail_set_sample_file(); }
|
||||
void I_000166aa(void) { ail_set_sample_type(); }
|
||||
void I_0001672c(void) { ail_start_sample(); }
|
||||
void I_00016799(void) { ail_stop_sample(); }
|
||||
void I_000168e0(void) { ail_set_sample_playback_rate(); }
|
||||
void I_00016956(void) { ail_set_sample_volume(); }
|
||||
void I_00016a42(void) { ail_set_sample_loop_count(); }
|
||||
void I_00016ab8(void) { ail_sample_status(); }
|
||||
void I_00017036(void) { ail_minimum_sample_buffer_size(); }
|
||||
void I_0001712f(void) { ail_sample_buffer_ready(); }
|
||||
void I_00017214(void) { ail_load_sample_buffer(); }
|
||||
@@ -0,0 +1,19 @@
|
||||
222a4 # int386x (bibliothèque Watcom), comme 2eea5 dans TUCKER.EXE
|
||||
14cf9 # AIL_startup -> ail.c
|
||||
14e75 # AIL_shutdown -> ail.c
|
||||
14f08 # AIL_set_preference -> ail.c
|
||||
16032 # AIL_install_DIG_INI -> ail.c
|
||||
1626a # AIL_allocate_sample_handle -> ail.c
|
||||
16448 # AIL_release_sample_handle -> ail.c
|
||||
164b5 # AIL_init_sample -> ail.c
|
||||
16522 # AIL_set_sample_file -> ail.c
|
||||
166aa # AIL_set_sample_type -> ail.c
|
||||
1672c # AIL_start_sample -> ail.c
|
||||
16799 # AIL_stop_sample -> ail.c
|
||||
168e0 # AIL_set_sample_playback_rate -> ail.c
|
||||
16956 # AIL_set_sample_volume -> ail.c
|
||||
16a42 # AIL_set_sample_loop_count -> ail.c
|
||||
16ab8 # AIL_sample_status -> ail.c
|
||||
17036 # AIL_minimum_sample_buffer_size -> ail.c
|
||||
1712f # AIL_sample_buffer_ready -> ail.c
|
||||
17214 # AIL_load_sample_buffer -> ail.c
|
||||
@@ -0,0 +1,16 @@
|
||||
# Fonctions de TUCKER.EXE remplacées par du C écrit à la main (runtime/overrides.c).
|
||||
# L'original reste disponible sous le nom F_xxxxxxxx_orig.
|
||||
2eea5 # int386x (Watcom) : saute dans une table de stubs « int N; ret » par push/ret
|
||||
114d4 # init du son (AIL_startup, pilote .DIG) : remplacé, son coupé pour l'instant
|
||||
11598 # arrêt du son
|
||||
12274 # démarre le minuteur du jeu (AIL_register_timer à 46 Hz, rappel 0x12250)
|
||||
122c8 # arrête ce minuteur
|
||||
118b0 # bruitage_joue -> mixeur
|
||||
11614 # bruitage_arrete
|
||||
11d78 # bruitage_volume
|
||||
11c14 # musique_joue
|
||||
115dc # musique_arrete
|
||||
11d2c # musique_volume
|
||||
11f64 # voix_joue (speech\samNNNN.wav)
|
||||
11eb4 # voix_suite (lecture en flux de l'original)
|
||||
11f24 # voix_arrete
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
/* Runtime : ce qui remplace DOS, DOS/4GW, le BIOS et le matériel du PC de 1996. */
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* ------------------------------------------------------------------ disposition mémoire */
|
||||
#define PSP_BASE 0x00008000u /* PSP DOS (256 octets) */
|
||||
#define ENV_BASE 0x00008200u /* environnement + nom du programme */
|
||||
#define LOWMEM_BASE 0x00009000u /* tampons « mémoire conventionnelle » (DPMI 0x100) */
|
||||
#define LOWMEM_END 0x0009f000u
|
||||
#define VGA_BASE 0x000a0000u
|
||||
#define HEAP_BASE 0x00100000u /* tas DPMI / DOS au-delà de 1 Mo */
|
||||
|
||||
/* sélecteurs (valeurs arbitraires, comme DOS/4GW en donnerait) */
|
||||
#define SEL_CODE 0x0170u
|
||||
#define SEL_DATA 0x0178u
|
||||
#define SEL_PSP 0x0024u
|
||||
#define SEL_ENV 0x002cu
|
||||
|
||||
void rt_fatal(const char *why);
|
||||
void rt_exit(int code);
|
||||
uint32_t sel_base(uint16_t sel);
|
||||
uint16_t sel_alloc(uint32_t base, uint32_t limit);
|
||||
|
||||
/* chemins : données du jeu en lecture seule, sauvegardes à part */
|
||||
typedef struct {
|
||||
const char *cd_dir; /* contenu du CD : ...\extracted\iso\TUCKER */
|
||||
const char *hd_dir; /* jeu installé : ...\Install\C\TUCKER (peut être NULL) */
|
||||
const char *root_dir; /* racine de C: (G.IN) : ...\Install\C (peut être NULL) */
|
||||
const char *save_dir; /* savegm.NN, nofiles.dta */
|
||||
const char *exe_path; /* TUCKER.EXE */
|
||||
int mute; /* G.IN virtuel sans pilote */
|
||||
int verbose;
|
||||
} RtConfig;
|
||||
extern RtConfig rt_cfg;
|
||||
|
||||
int load_le_image(const char *path, uint32_t *entry, uint32_t *stack);
|
||||
|
||||
/* DOS */
|
||||
void dos_int21(void);
|
||||
void dos_init(const char *exe_dos); /* nom DOS du programme, écrit dans l'environnement */
|
||||
void dos_reset(void);
|
||||
void machine_reset(void);
|
||||
void audio_reset(void);
|
||||
void fpu_reset(void);
|
||||
|
||||
/* DPMI / interruptions */
|
||||
void dpmi_int31(void);
|
||||
extern uint32_t pm_vec_off[256];
|
||||
extern uint16_t pm_vec_sel[256];
|
||||
void rt_raise_irq(int irq);
|
||||
void rt_game_timer(uint32_t callback, uint32_t hz); /* 0 = arrêt */
|
||||
void rt_callback(uint32_t addr); /* appel « en interruption » : état CPU préservé */
|
||||
|
||||
/* BIOS */
|
||||
void bios_int10(void);
|
||||
void bios_int16(void);
|
||||
void mouse_int33(void);
|
||||
|
||||
/* matériel */
|
||||
extern uint8_t vga_dac[768]; /* 6 bits par composante */
|
||||
extern int vga_mode;
|
||||
extern uint32_t pit_reload; /* compteur 0 du PIT (0 = 65536) */
|
||||
uint32_t ports_in(uint32_t port, int size);
|
||||
void ports_out(uint32_t port, uint32_t v, int size);
|
||||
|
||||
/* hôte (fenêtre, entrées, temps) : host_*.c */
|
||||
uint64_t host_time_us(void);
|
||||
void host_frame(void); /* appelé ~70 fois par seconde de temps du jeu */
|
||||
void host_pump(void);
|
||||
void host_idle(void);
|
||||
void host_audio_lock(void);
|
||||
void host_audio_unlock(void);
|
||||
|
||||
/* mixeur (audio.c) */
|
||||
#define AUDIO_RATE 44100
|
||||
enum { AUDIO_FX, AUDIO_MUSIC, AUDIO_SPEECH, AUDIO_GROUPS };
|
||||
#define AUDIO_FX_CH 32
|
||||
#define AUDIO_MUS_CH 4
|
||||
#define AUDIO_VOICES 64
|
||||
#define AUDIO_AIL_FIRST 40 /* voix 40..63 : canaux AIL émulés */
|
||||
void audio_v_init(int v, int group);
|
||||
int audio_v_load_wav(int v, const uint8_t *wav, uint32_t len);
|
||||
void audio_v_format(int v, int bits16, int stereo, int sign8);
|
||||
void audio_v_rate(int v, uint32_t rate);
|
||||
void audio_v_volume(int v, int vol);
|
||||
void audio_v_loops(int v, int loops); /* 0 = infini */
|
||||
void audio_v_group(int v, int group);
|
||||
void audio_v_start(int v);
|
||||
void audio_v_pause(int v, int paused);
|
||||
void audio_v_end(int v);
|
||||
void audio_v_free(int v);
|
||||
int audio_v_status(int v); /* 2 fini, 4 en cours, 8 en pause */
|
||||
int audio_v_ready(int v); /* double tampon : indice à remplir ou -1 */
|
||||
void audio_v_queue(int v, int slot, const uint8_t *data, uint32_t len); /* len 0 = fin du flux */
|
||||
/* émulation de l'API Miles AIL (ail.c) */
|
||||
void ail_reset(void);
|
||||
void ail_startup(void);
|
||||
void ail_shutdown(void);
|
||||
void ail_set_preference(void);
|
||||
void ail_install_DIG_INI(void);
|
||||
void ail_minimum_sample_buffer_size(void);
|
||||
void ail_allocate_sample_handle(void);
|
||||
void ail_release_sample_handle(void);
|
||||
void ail_init_sample(void);
|
||||
void ail_set_sample_file(void);
|
||||
void ail_set_sample_type(void);
|
||||
void ail_set_sample_playback_rate(void);
|
||||
void ail_set_sample_volume(void);
|
||||
void ail_set_sample_loop_count(void);
|
||||
void ail_start_sample(void);
|
||||
void ail_stop_sample(void);
|
||||
void ail_resume_sample(void);
|
||||
void ail_end_sample(void);
|
||||
void ail_sample_status(void);
|
||||
void ail_sample_buffer_ready(void);
|
||||
void ail_load_sample_buffer(void);
|
||||
extern int (*ail_group_hint)(uint32_t hsample); /* groupe de volume d'un canal, propre au programme */
|
||||
extern int audio_volume[AUDIO_GROUPS]; /* % par groupe */
|
||||
extern int audio_master; /* % général */
|
||||
void audio_mix(int16_t *out, int frames); /* stéréo entrelacé, AUDIO_RATE */
|
||||
void audio_update(void); /* fil principal, à chaque image */
|
||||
void audio_play_mem(int group, int ch, uint32_t addr, int vol, int loop, uint32_t flag);
|
||||
int audio_play_file(int group, int ch, const char *dos_name, int vol, uint32_t flag);
|
||||
void audio_stop(int group, int ch);
|
||||
void audio_set_volume(int group, int ch, int vol);
|
||||
int audio_playing(int group, int ch);
|
||||
int dos_map_path(const char *dos, char *out, size_t n, int for_write); /* le jeu tourne à vide : rendre la main au système (~1 ms) */
|
||||
int host_key_pop(uint8_t *scancode);
|
||||
int host_key_peek(uint8_t *scancode); /* scancodes PC jeu 1, relâchement = | 0x80 */
|
||||
void host_mouse(int *x, int *y, int *buttons);
|
||||
extern int host_quit;
|
||||
|
||||
/* clavier */
|
||||
extern uint8_t kbd_port60;
|
||||
+155
@@ -0,0 +1,155 @@
|
||||
"""Chargeur LE (DOS/4GW) pour le traducteur : objets en mémoire, relocations appliquées.
|
||||
|
||||
Lit le TUCKER.EXE d'origine (jamais modifié). Les objets gardent leur adresse de base LE
|
||||
(code 0x10000, données 0x40000), comme dans le jeu sous DOS/4GW.
|
||||
`fixups` liste les adresses où une adresse absolue 32 bits a été écrite, avec sa cible :
|
||||
c'est la meilleure source pour trouver les pointeurs de code (tables de saut, rappels).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import struct
|
||||
|
||||
SEL_CODE, SEL_DATA = 0x170, 0x178 # mêmes valeurs que runtime/rt.h
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass
|
||||
class LEObject:
|
||||
index: int
|
||||
base: int
|
||||
vsize: int
|
||||
flags: int
|
||||
data: bytearray
|
||||
|
||||
@property
|
||||
def is_code(self) -> bool:
|
||||
return bool(self.flags & 4)
|
||||
|
||||
@property
|
||||
def end(self) -> int:
|
||||
return self.base + max(self.vsize, len(self.data))
|
||||
|
||||
|
||||
@dataclass
|
||||
class LEImage:
|
||||
objects: list[LEObject]
|
||||
entry: int
|
||||
stack: int
|
||||
fixups: dict[int, int] = field(default_factory=dict) # adresse du champ -> cible
|
||||
|
||||
def obj_at(self, addr: int) -> LEObject | None:
|
||||
for o in self.objects:
|
||||
if o.base <= addr < o.end:
|
||||
return o
|
||||
return None
|
||||
|
||||
def read(self, addr: int, n: int) -> bytes:
|
||||
o = self.obj_at(addr)
|
||||
if o is None:
|
||||
raise KeyError(f"{addr:#x} hors image")
|
||||
i = addr - o.base
|
||||
return bytes(o.data[i:i + n]).ljust(n, b"\0")
|
||||
|
||||
def u32(self, addr: int) -> int:
|
||||
return struct.unpack("<I", self.read(addr, 4))[0]
|
||||
|
||||
@property
|
||||
def code(self) -> LEObject:
|
||||
return next(o for o in self.objects if o.is_code)
|
||||
|
||||
|
||||
def load_le(path: str) -> LEImage:
|
||||
data = open(path, "rb").read()
|
||||
u16 = lambda o: struct.unpack_from("<H", data, o)[0]
|
||||
s16 = lambda o: struct.unpack_from("<h", data, o)[0]
|
||||
u32 = lambda o: struct.unpack_from("<I", data, o)[0]
|
||||
le = u32(0x3C)
|
||||
if data[le:le + 2] != b"LE":
|
||||
raise ValueError("pas un exécutable LE")
|
||||
h = lambda off: u32(le + off)
|
||||
npages, eip_obj, eip, esp_obj, esp = h(0x14), h(0x18), h(0x1C), h(0x20), h(0x24)
|
||||
page_size, last_page = h(0x28), h(0x2C)
|
||||
obj_tab, nobj, opt = h(0x40), h(0x44), h(0x48)
|
||||
fpt, frt = h(0x68), h(0x6C)
|
||||
data_pages = h(0x80)
|
||||
|
||||
raw = []
|
||||
for i in range(nobj):
|
||||
vsize, base, flags, pidx, pcnt = struct.unpack_from("<IIIII", data, le + obj_tab + i * 24)
|
||||
raw.append((vsize, base, flags, pidx, pcnt))
|
||||
|
||||
def page_file_off(n: int) -> int:
|
||||
e = data[le + opt + (n - 1) * 4: le + opt + n * 4]
|
||||
num = (e[0] << 16) | (e[1] << 8) | e[2]
|
||||
return data_pages + (num - 1) * page_size
|
||||
|
||||
objects = []
|
||||
for i, (vsize, base, flags, pidx, pcnt) in enumerate(raw):
|
||||
buf = bytearray(max(vsize, pcnt * page_size))
|
||||
for k in range(pcnt):
|
||||
n = pidx + k
|
||||
ln = last_page if n == npages else page_size
|
||||
off = page_file_off(n)
|
||||
buf[k * page_size: k * page_size + ln] = data[off: off + ln]
|
||||
objects.append(LEObject(i + 1, base, vsize, flags, buf))
|
||||
|
||||
fixups: dict[int, int] = {}
|
||||
for ob, (vsize, base, flags, pidx, pcnt) in zip(objects, raw):
|
||||
for k in range(pcnt):
|
||||
n = pidx + k
|
||||
p = le + frt + u32(le + fpt + (n - 1) * 4)
|
||||
end = le + frt + u32(le + fpt + n * 4)
|
||||
while p < end:
|
||||
srct, flg = data[p], data[p + 1]
|
||||
p += 2
|
||||
stype = srct & 0x0F
|
||||
if srct & 0x20:
|
||||
cnt = data[p]
|
||||
p += 1
|
||||
offs = None
|
||||
else:
|
||||
offs = [s16(p)]
|
||||
p += 2
|
||||
if flg & 3:
|
||||
raise ValueError(f"relocation externe non gérée ({flg & 3})")
|
||||
if flg & 0x40:
|
||||
tobj = u16(p)
|
||||
p += 2
|
||||
else:
|
||||
tobj = data[p]
|
||||
p += 1
|
||||
toff = 0
|
||||
if stype != 2:
|
||||
if flg & 0x10:
|
||||
toff = u32(p)
|
||||
p += 4
|
||||
else:
|
||||
toff = u16(p)
|
||||
p += 2
|
||||
if offs is None:
|
||||
offs = [s16(p + 2 * j) for j in range(cnt)]
|
||||
p += 2 * cnt
|
||||
target = objects[tobj - 1].base + toff
|
||||
for so in offs:
|
||||
a = k * page_size + so
|
||||
if stype == 2: # sélecteur 16 bits : modèle à plat du runtime (rt.h)
|
||||
sel = SEL_CODE if objects[tobj - 1].is_code else SEL_DATA
|
||||
if 0 <= a <= len(ob.data) - 2:
|
||||
struct.pack_into("<H", ob.data, a, sel)
|
||||
continue
|
||||
if stype != 7:
|
||||
raise ValueError(f"relocation de type {stype} non gérée")
|
||||
if 0 <= a <= len(ob.data) - 4:
|
||||
struct.pack_into("<I", ob.data, a, target)
|
||||
fixups[ob.base + a] = target
|
||||
return LEImage(objects, objects[eip_obj - 1].base + eip, objects[esp_obj - 1].base + esp, fixups)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
img = load_le(sys.argv[1])
|
||||
for o in img.objects:
|
||||
print(f"objet {o.index}: {o.base:#x}..{o.end:#x} {'code' if o.is_code else 'données'}")
|
||||
print(f"entrée {img.entry:#x}, pile {img.stack:#x}, {len(img.fixups)} relocations")
|
||||
tgt_code = sum(1 for t in img.fixups.values() if img.code.base <= t < img.code.end)
|
||||
print(f"relocations vers le code : {tgt_code}")
|
||||
+669
@@ -0,0 +1,669 @@
|
||||
"""Traducteur statique x86 (32 bits, Watcom / DOS/4GW) -> C.
|
||||
|
||||
Usage : python -I tools/recomp.py CHEMIN\\TUCKER.EXE build/gen
|
||||
|
||||
Principe :
|
||||
- découverte du code par descente récursive, à partir du point d'entrée, des cibles d'appel et
|
||||
de toutes les adresses de code relogées (dans un LE, toute adresse absolue de code est une
|
||||
relocation : la couverture des pointeurs de fonction est donc complète) ;
|
||||
- une fonction C par point d'entrée ; ses blocs sont ceux qu'on atteint par sauts depuis
|
||||
l'entrée (un bloc partagé est simplement recopié) ; un saut vers l'entrée d'une autre fonction
|
||||
devient un appel terminal ;
|
||||
- l'état du processeur (registres, pile dans la mémoire émulée, indicateurs paresseux) est celui
|
||||
du runtime (runtime/cpu.h). `call` empile vraiment l'adresse de retour, `ret` la dépile.
|
||||
|
||||
Le C produit dérive du TUCKER.EXE de l'utilisateur : il reste dans build/ et n'est pas distribué.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
import capstone
|
||||
from capstone import x86 as X
|
||||
|
||||
sys.path.insert(0, os.path.dirname(__file__))
|
||||
from le import load_le # noqa: E402
|
||||
|
||||
FNS_PER_FILE = 60
|
||||
|
||||
_FPU_KNOWN: set[str] | None = None
|
||||
|
||||
|
||||
def fpu_known() -> set[str]:
|
||||
"""Instructions x87 implémentées par le runtime : les FPU_* déclarées dans runtime/cpu.h."""
|
||||
global _FPU_KNOWN
|
||||
if _FPU_KNOWN is None:
|
||||
import re
|
||||
h = open(os.path.join(os.path.dirname(__file__), "..", "runtime", "cpu.h"), encoding="utf-8").read()
|
||||
_FPU_KNOWN = set(re.findall(r"void FPU_([A-Z0-9]+)\(", h))
|
||||
return _FPU_KNOWN
|
||||
|
||||
REG32 = {"eax": 0, "ecx": 1, "edx": 2, "ebx": 3, "esp": 4, "ebp": 5, "esi": 6, "edi": 7}
|
||||
REG16 = {"ax": 0, "cx": 1, "dx": 2, "bx": 3, "sp": 4, "bp": 5, "si": 6, "di": 7}
|
||||
REG8L = {"al": 0, "cl": 1, "dl": 2, "bl": 3}
|
||||
REG8H = {"ah": 0, "ch": 1, "dh": 2, "bh": 3}
|
||||
SEGS = {"es": 0, "cs": 1, "ss": 2, "ds": 3, "fs": 4, "gs": 5}
|
||||
SEG_IDS = {X.X86_REG_ES: 0, X.X86_REG_CS: 1, X.X86_REG_SS: 2, X.X86_REG_DS: 3, X.X86_REG_FS: 4, X.X86_REG_GS: 5}
|
||||
|
||||
JCC = {
|
||||
"jo": "OF", "jno": "!OF", "jb": "CF", "jae": "!CF", "je": "ZF", "jne": "!ZF",
|
||||
"jbe": "(CF||ZF)", "ja": "!(CF||ZF)", "js": "SF", "jns": "!SF", "jp": "PF", "jnp": "!PF",
|
||||
"jl": "(SF!=OF)", "jge": "(SF==OF)", "jle": "(ZF||(SF!=OF))", "jg": "(!ZF&&(SF==OF))",
|
||||
}
|
||||
SETCC = {"set" + k[1:]: v for k, v in JCC.items()}
|
||||
COND_FN = {"OF": "cOF()", "CF": "cCF()", "ZF": "cZF()", "SF": "cSF()", "PF": "cPF()"}
|
||||
|
||||
|
||||
def cond_lazy(expr: str) -> str:
|
||||
for k, v in COND_FN.items():
|
||||
expr = expr.replace(k, v)
|
||||
return expr
|
||||
|
||||
|
||||
def fused_cmp(cc: str, sz: int) -> str:
|
||||
"""Condition directe après `cmp a, b` (temporaires a, b)."""
|
||||
s = {8: "int8_t", 16: "int16_t", 32: "int32_t"}[sz]
|
||||
u = {8: "uint8_t", 16: "uint16_t", 32: "uint32_t"}[sz]
|
||||
return {
|
||||
"e": f"(({u})a==({u})b)", "ne": f"(({u})a!=({u})b)",
|
||||
"b": f"(({u})a<({u})b)", "ae": f"(({u})a>=({u})b)",
|
||||
"be": f"(({u})a<=({u})b)", "a": f"(({u})a>({u})b)",
|
||||
"l": f"(({s})a<({s})b)", "ge": f"(({s})a>=({s})b)",
|
||||
"le": f"(({s})a<=({s})b)", "g": f"(({s})a>({s})b)",
|
||||
"s": f"(({s})(a-b)<0)", "ns": f"(({s})(a-b)>=0)",
|
||||
}.get(cc)
|
||||
|
||||
|
||||
def fused_test(cc: str, sz: int) -> str:
|
||||
s = {8: "int8_t", 16: "int16_t", 32: "int32_t"}[sz]
|
||||
u = {8: "uint8_t", 16: "uint16_t", 32: "uint32_t"}[sz]
|
||||
return {
|
||||
"e": f"(({u})r==0)", "ne": f"(({u})r!=0)", "s": f"(({s})r<0)", "ns": f"(({s})r>=0)",
|
||||
"l": f"(({s})r<0)", "ge": f"(({s})r>=0)", "le": f"(({s})r<=0)", "g": f"(({s})r>0)",
|
||||
"be": f"(({u})r==0)", "a": f"(({u})r!=0)", "b": "0", "ae": "1",
|
||||
}.get(cc)
|
||||
|
||||
|
||||
class Recompiler:
|
||||
def __init__(self, exe: str):
|
||||
self.img = load_le(exe)
|
||||
self.code = self.img.code
|
||||
self.md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_32)
|
||||
self.md.detail = True
|
||||
self._cache: dict[int, object] = {}
|
||||
self.tables: dict[int, list[int]] = {} # adresse du jmp indirect -> cibles
|
||||
self.table_sites: set[int] = set()
|
||||
self.entries: set[int] = set()
|
||||
self.unresolved: dict[int, str] = {}
|
||||
self.traps: dict[int, str] = {}
|
||||
self._labels: set[int] = set()
|
||||
self._cur = 0
|
||||
self.overrides: set[int] = set()
|
||||
self._fused = -1
|
||||
|
||||
# ------------------------------------------------------------------ décodage
|
||||
def in_code(self, a: int) -> bool:
|
||||
return self.code.base <= a < self.code.base + self.code.vsize
|
||||
|
||||
def ins(self, a: int):
|
||||
if a in self._cache:
|
||||
return self._cache[a]
|
||||
r = None
|
||||
if self.in_code(a):
|
||||
for i in self.md.disasm(self.img.read(a, 16), a, count=1):
|
||||
r = i
|
||||
self._cache[a] = r
|
||||
return r
|
||||
|
||||
def jump_table(self, i) -> list[int] | None:
|
||||
"""jmp dword ptr [idx*4 + table] : entrées = relocations consécutives vers le code."""
|
||||
op = i.operands[0]
|
||||
if op.type != X.X86_OP_MEM:
|
||||
return None
|
||||
scaled = op.mem.base == 0 and op.mem.scale == 4 and op.mem.index != 0
|
||||
prescaled = op.mem.index == 0 and op.mem.base != 0 and op.mem.disp > 0
|
||||
if not (scaled or prescaled):
|
||||
return None
|
||||
t = op.mem.disp & 0xFFFFFFFF
|
||||
out = []
|
||||
while t in self.img.fixups and self.in_code(self.img.fixups[t]):
|
||||
out.append(self.img.fixups[t])
|
||||
self.table_sites.add(t)
|
||||
t += 4
|
||||
return out or None
|
||||
|
||||
def successors(self, i) -> tuple[list[int], list[int], bool]:
|
||||
"""(sauts dans la fonction, appels, l'instruction continue-t-elle à la suivante ?)"""
|
||||
m, nxt = i.mnemonic, i.address + i.size
|
||||
op0 = i.operands[0] if i.operands else None
|
||||
if m == "jmp":
|
||||
if op0.type == X.X86_OP_IMM:
|
||||
return [op0.imm & 0xFFFFFFFF], [], False
|
||||
tab = self.jump_table(i)
|
||||
if tab:
|
||||
self.tables[i.address] = tab
|
||||
return tab, [], False
|
||||
self.unresolved[i.address] = f"{m} {i.op_str}"
|
||||
return [], [], False
|
||||
if m in JCC or m in ("loop", "loope", "loopne", "jecxz", "jcxz"):
|
||||
return [op0.imm & 0xFFFFFFFF, nxt], [], False
|
||||
if m == "call":
|
||||
if op0.type == X.X86_OP_IMM:
|
||||
return [], [op0.imm & 0xFFFFFFFF], True
|
||||
return [], [], True
|
||||
if m in ("ret", "retf", "iretd", "iret", "hlt"):
|
||||
return [], [], False
|
||||
return [], [], True
|
||||
|
||||
# ------------------------------------------------------------------ découverte
|
||||
def closure(self, entry: int, stop_at_entries: bool) -> tuple[dict[int, object], set[int], set[int]]:
|
||||
insns: dict[int, object] = {}
|
||||
labels: set[int] = {entry}
|
||||
calls: set[int] = set()
|
||||
work = [entry]
|
||||
while work:
|
||||
a = work.pop()
|
||||
while a not in insns:
|
||||
i = self.ins(a)
|
||||
if i is None:
|
||||
self.traps[a] = "instruction illisible"
|
||||
insns[a] = None
|
||||
break
|
||||
insns[a] = i
|
||||
jumps, cs, falls = self.successors(i)
|
||||
calls.update(cs)
|
||||
for t in jumps:
|
||||
if stop_at_entries and t in self.entries and t != entry:
|
||||
continue
|
||||
labels.add(t)
|
||||
work.append(t)
|
||||
if not falls:
|
||||
break
|
||||
a = i.address + i.size
|
||||
return insns, labels, calls
|
||||
|
||||
def discover(self, extra: list[int]):
|
||||
seeds = {self.img.entry, *extra}
|
||||
while True:
|
||||
code_ptrs = {t for s, t in self.img.fixups.items()
|
||||
if self.in_code(t) and s not in self.table_sites}
|
||||
entries = seeds | code_ptrs
|
||||
done: set[int] = set()
|
||||
work = list(entries)
|
||||
while work:
|
||||
e = work.pop()
|
||||
if e in done:
|
||||
continue
|
||||
done.add(e)
|
||||
_, _, calls = self.closure(e, stop_at_entries=False)
|
||||
for c in calls:
|
||||
if c not in entries and self.in_code(c):
|
||||
entries.add(c)
|
||||
work.append(c)
|
||||
code_ptrs2 = {t for s, t in self.img.fixups.items()
|
||||
if self.in_code(t) and s not in self.table_sites}
|
||||
if code_ptrs2 == code_ptrs:
|
||||
self.entries = {e for e in entries if self.in_code(e)}
|
||||
break
|
||||
|
||||
# ------------------------------------------------------------------ opérandes
|
||||
def reg(self, i, r: int) -> str:
|
||||
n = i.reg_name(r)
|
||||
if n in REG32:
|
||||
return f"R({REG32[n]})"
|
||||
if n in REG16:
|
||||
return f"W({REG16[n]})"
|
||||
if n in REG8L:
|
||||
return f"BL_({REG8L[n]})"
|
||||
if n in REG8H:
|
||||
return f"BH_({REG8H[n]})"
|
||||
if n in SEGS:
|
||||
return f"SEGR({SEGS[n]})"
|
||||
raise NotImplementedError(f"registre {n}")
|
||||
|
||||
def ea(self, i, op) -> str:
|
||||
m = op.mem
|
||||
parts = []
|
||||
if m.base:
|
||||
parts.append(self.reg(i, m.base))
|
||||
if m.index:
|
||||
idx = self.reg(i, m.index)
|
||||
parts.append(idx if m.scale == 1 else f"{idx}*{m.scale}u")
|
||||
if m.disp or not parts:
|
||||
parts.append(f"0x{m.disp & 0xFFFFFFFF:x}u")
|
||||
if m.segment in SEG_IDS:
|
||||
seg = SEG_IDS[m.segment]
|
||||
elif m.base in (X.X86_REG_ESP, X.X86_REG_EBP):
|
||||
seg = 2
|
||||
else:
|
||||
seg = 3
|
||||
return "(uint32_t)(" + "+".join([f"SB({seg})"] + parts) + ")"
|
||||
|
||||
def ea_noseg(self, i, op) -> str:
|
||||
"""lea : l'adresse effective seule, sans base de segment."""
|
||||
m = op.mem
|
||||
parts = []
|
||||
if m.base:
|
||||
parts.append(self.reg(i, m.base))
|
||||
if m.index:
|
||||
idx = self.reg(i, m.index)
|
||||
parts.append(idx if m.scale == 1 else f"{idx}*{m.scale}u")
|
||||
if m.disp or not parts:
|
||||
parts.append(f"0x{m.disp & 0xFFFFFFFF:x}u")
|
||||
return "(uint32_t)(" + "+".join(parts) + ")"
|
||||
|
||||
def rd(self, i, op, sz: int | None = None) -> str:
|
||||
sz = sz or op.size * 8
|
||||
if op.type == X.X86_OP_REG:
|
||||
return self.reg(i, op.reg)
|
||||
if op.type == X.X86_OP_IMM:
|
||||
return f"0x{op.imm & ((1 << sz) - 1):x}u"
|
||||
return f"RD{sz}({self.ea(i, op)})"
|
||||
|
||||
def wr(self, i, op, val: str) -> str:
|
||||
sz = op.size * 8
|
||||
if op.type == X.X86_OP_REG:
|
||||
r = self.reg(i, op.reg)
|
||||
if r.startswith("SEGR("):
|
||||
return f"set_seg({r[5:-1]}, (uint16_t)({val}));"
|
||||
return f"{r} = ({ {8: 'uint8_t', 16: 'uint16_t', 32: 'uint32_t'}[sz]})({val});"
|
||||
return f"WR{sz}({self.ea(i, op)}, {val});"
|
||||
|
||||
# ------------------------------------------------------------------ traduction
|
||||
def emit_fn(self, entry: int) -> list[str]:
|
||||
insns, labels, _ = self.closure(entry, stop_at_entries=True)
|
||||
order = sorted(insns)
|
||||
self._fused = -1
|
||||
name = f"{self.prefix}_{entry:08x}" + ("_orig" if entry in self.overrides else "")
|
||||
out = [f"void {name}(void) {{", " int fz = 0; (void)fz;", " POLL();", f" goto L_{entry:08x};"]
|
||||
# étiquettes : cibles de saut + suites de blocs non contigus
|
||||
fall_targets = set()
|
||||
for k, a in enumerate(order):
|
||||
i = insns[a]
|
||||
if i is None:
|
||||
continue
|
||||
nxt = a + i.size
|
||||
_, _, falls = self.successors(i)
|
||||
if (falls or i.mnemonic in JCC or i.mnemonic.startswith("loop") or i.mnemonic == "jecxz") \
|
||||
and (k + 1 >= len(order) or order[k + 1] != nxt):
|
||||
fall_targets.add(nxt)
|
||||
labels |= fall_targets
|
||||
for k, a in enumerate(order):
|
||||
i = insns[a]
|
||||
if a in labels:
|
||||
out.append(f"L_{a:08x}:")
|
||||
if i is None:
|
||||
out.append(f" TRAP(0x{a:x}u); return;")
|
||||
continue
|
||||
prev = insns.get(order[k - 1]) if k else None
|
||||
if prev is not None and prev.address + prev.size != a:
|
||||
prev = None
|
||||
try:
|
||||
self._labels = labels
|
||||
self._cur = a
|
||||
body = self.translate(i, entry, prev)
|
||||
except NotImplementedError as e:
|
||||
self.traps[a] = f"{i.mnemonic} {i.op_str} ({e})"
|
||||
body = [f"TRAP(0x{a:x}u); return; /* {i.mnemonic} {i.op_str} */"]
|
||||
out.append(f" /* {a:08x} {i.mnemonic} {i.op_str} */")
|
||||
out.extend(" " + b for b in body)
|
||||
nxt = a + i.size
|
||||
if nxt in fall_targets and (k + 1 >= len(order) or order[k + 1] != nxt):
|
||||
_, _, falls = self.successors(i)
|
||||
if falls or i.mnemonic in JCC or i.mnemonic.startswith("loop") or i.mnemonic == "jecxz":
|
||||
out.append(f" {self.goto(nxt, entry)}")
|
||||
out.append("}")
|
||||
return out
|
||||
|
||||
def goto(self, t: int, entry: int) -> str:
|
||||
if t in self.entries and t != entry:
|
||||
return f"{{ {self.prefix}_{t:08x}(); return; }}"
|
||||
if t <= self._cur:
|
||||
return f"{{ POLL(); goto L_{t:08x}; }}"
|
||||
return f"goto L_{t:08x};"
|
||||
|
||||
def translate(self, i, entry: int, prev) -> list[str]:
|
||||
m = i.mnemonic
|
||||
ops = i.operands
|
||||
nxt = i.address + i.size
|
||||
sz = ops[0].size * 8 if ops else 32
|
||||
mask = {8: "0xffu", 16: "0xffffu", 32: "0xffffffffu"}.get(sz, "0xffffffffu")
|
||||
|
||||
# préfixes rep : capstone écrit « rep movsd », « repne scasb »…
|
||||
if m.startswith("rep ") or m.startswith("repne ") or m.startswith("repe "):
|
||||
pre, base = m.split(" ", 1)
|
||||
return self.string_op(i, base, pre)
|
||||
if m in ("movsb", "movsw", "movsd", "stosb", "stosw", "stosd", "lodsb", "lodsw", "lodsd",
|
||||
"cmpsb", "cmpsw", "cmpsd", "scasb", "scasw", "scasd") and not (m == "movsd" and len(ops) == 2 and ops[0].type == X.X86_OP_REG):
|
||||
# capstone ne montre pas F2 devant movs/stos/lods (Watcom écrit « repne movsd ») :
|
||||
# on lit les préfixes dans les octets ; F2/F3 y valent tous deux « rep »
|
||||
pre = ""
|
||||
for byte in i.bytes:
|
||||
if byte in (0xF2, 0xF3):
|
||||
pre = "repne" if byte == 0xF2 else "repe"
|
||||
elif byte not in (0x66, 0x67, 0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0xF0):
|
||||
break
|
||||
if pre and m[:4] in ("movs", "stos", "lods"):
|
||||
pre = "rep"
|
||||
return self.string_op(i, m, pre)
|
||||
|
||||
if m == "nop" or m == "wait" or m in ("cli", "sti", "fwait"):
|
||||
return [";"]
|
||||
if m == "mov":
|
||||
if ops[0].type == X.X86_OP_REG and self.reg(i, ops[0].reg).startswith("SEGR("):
|
||||
return [self.wr(i, ops[0], self.rd(i, ops[1]))]
|
||||
src = self.rd(i, ops[1], sz)
|
||||
if ops[1].type == X.X86_OP_REG and self.reg(i, ops[1].reg).startswith("SEGR("):
|
||||
src = self.reg(i, ops[1].reg)
|
||||
return [self.wr(i, ops[0], src)]
|
||||
if m in ("movsx", "movzx"):
|
||||
ssz = ops[1].size * 8
|
||||
st = {8: "int8_t", 16: "int16_t"}[ssz] if m == "movsx" else {8: "uint8_t", 16: "uint16_t"}[ssz]
|
||||
dst = {16: "int16_t", 32: "int32_t"}[sz] if m == "movsx" else "uint32_t"
|
||||
return [self.wr(i, ops[0], f"({dst})({st})({self.rd(i, ops[1])})")]
|
||||
if m == "lea":
|
||||
return [self.wr(i, ops[0], self.ea_noseg(i, ops[1]))]
|
||||
if m == "xchg":
|
||||
if ops[0].type == X.X86_OP_REG and ops[1].type == X.X86_OP_REG and ops[0].reg == ops[1].reg:
|
||||
return [";"]
|
||||
return ["{", f" uint32_t t = {self.rd(i, ops[0])};",
|
||||
" " + self.wr(i, ops[0], self.rd(i, ops[1])),
|
||||
" " + self.wr(i, ops[1], "t"), "}"]
|
||||
if m == "push":
|
||||
if ops[0].type == X.X86_OP_IMM:
|
||||
return [f"PUSH32(0x{ops[0].imm & 0xFFFFFFFF:x}u);"]
|
||||
if ops[0].type == X.X86_OP_REG and self.reg(i, ops[0].reg).startswith("SEGR("):
|
||||
return [f"PUSH32({self.reg(i, ops[0].reg)});"]
|
||||
if ops[0].size == 2:
|
||||
return [f"PUSH16({self.rd(i, ops[0])});"]
|
||||
return [f"PUSH32({self.rd(i, ops[0])});"]
|
||||
if m == "pop":
|
||||
if ops[0].type == X.X86_OP_REG and self.reg(i, ops[0].reg).startswith("SEGR("):
|
||||
return ["{ uint32_t t = POP32(); " + self.wr(i, ops[0], "t") + " }"]
|
||||
if ops[0].size == 2:
|
||||
return ["{ uint16_t t = POP16(); " + self.wr(i, ops[0], "t") + " }"]
|
||||
if ops[0].type == X.X86_OP_MEM:
|
||||
return ["{ uint32_t t = POP32(); " + self.wr(i, ops[0], "t") + " }"]
|
||||
return [self.wr(i, ops[0], "POP32()")]
|
||||
if m == "pushal":
|
||||
return ["PUSHAD();"]
|
||||
if m == "popal":
|
||||
return ["POPAD();"]
|
||||
if m in ("pushfd", "pushf"):
|
||||
return ["PUSH32(get_eflags());"]
|
||||
if m in ("popfd", "popf"):
|
||||
return ["set_eflags(POP32());"]
|
||||
if m == "lahf":
|
||||
return ["BH_(0) = (uint8_t)get_eflags();"]
|
||||
if m == "sahf":
|
||||
return ["set_eflags((get_eflags() & ~0xffu) | BH_(0));"]
|
||||
if m == "cld":
|
||||
return ["cpu.df = 0;"]
|
||||
if m == "std":
|
||||
return ["cpu.df = 1;"]
|
||||
if m == "clc":
|
||||
return ["set_eflags(get_eflags() & ~1u);"]
|
||||
if m == "stc":
|
||||
return ["set_eflags(get_eflags() | 1u);"]
|
||||
if m == "cmc":
|
||||
return ["set_eflags(get_eflags() ^ 1u);"]
|
||||
if m == "cwde":
|
||||
return ["R(0) = (uint32_t)(int32_t)(int16_t)W(0);"]
|
||||
if m == "cbw":
|
||||
return ["W(0) = (uint16_t)(int16_t)(int8_t)BL_(0);"]
|
||||
if m == "cwd":
|
||||
return ["W(2) = ((int16_t)W(0) < 0) ? 0xffffu : 0;"]
|
||||
if m == "cdq":
|
||||
return ["R(2) = ((int32_t)R(0) < 0) ? 0xffffffffu : 0;"]
|
||||
if m == "leave":
|
||||
return ["R(4) = R(5); R(5) = POP32();"]
|
||||
if m in ("les", "lds", "lfs", "lgs", "lss"):
|
||||
seg = {"les": 0, "lds": 3, "lfs": 4, "lgs": 5, "lss": 2}[m]
|
||||
a = self.ea(i, ops[1])
|
||||
return ["{", f" uint32_t ea = {a};", " " + self.wr(i, ops[0], "RD32(ea)"),
|
||||
f" set_seg({seg}, RD16(ea + 4));", "}"]
|
||||
if m == "lsl":
|
||||
return [self.wr(i, ops[0], "0xffffffffu") + " LF_ZF(1);"]
|
||||
if m == "lar":
|
||||
return [self.wr(i, ops[0], "0x00cff300u") + " LF_ZF(1);"]
|
||||
if m == "verr" or m == "verw":
|
||||
return ["LF_ZF(1);"]
|
||||
if m == "enter":
|
||||
if ops[1].imm != 0:
|
||||
raise NotImplementedError("enter imbriqué")
|
||||
return [f"PUSH32(R(5)); R(5) = R(4); R(4) -= 0x{ops[0].imm:x}u;"]
|
||||
|
||||
# ---------------------------------------------------------- arithmétique
|
||||
if m in ("add", "sub", "and", "or", "xor", "cmp", "test", "adc", "sbb"):
|
||||
a = self.rd(i, ops[0], sz)
|
||||
b = self.rd(i, ops[1], sz)
|
||||
if ops[1].type == X.X86_OP_IMM:
|
||||
b = f"0x{ops[1].imm & ((1 << sz) - 1):x}u"
|
||||
lines = ["{", f" uint32_t a = {a}, b = {b};"]
|
||||
if m in ("add", "adc"):
|
||||
cin = " + c" if m == "adc" else ""
|
||||
if m == "adc":
|
||||
lines.append(" uint32_t c = cCF();")
|
||||
lines.append(f" uint32_t r = (a + b{cin}) & {mask};")
|
||||
lines.append(f" LF({'LF_ADC' if m == 'adc' else 'LF_ADD'}, {sz}, a, b, r{', c' if m == 'adc' else ', 0'});")
|
||||
elif m in ("sub", "cmp", "sbb"):
|
||||
cin = " - c" if m == "sbb" else ""
|
||||
if m == "sbb":
|
||||
lines.append(" uint32_t c = cCF();")
|
||||
lines.append(f" uint32_t r = (a - b{cin}) & {mask};")
|
||||
lines.append(f" LF({'LF_SBB' if m == 'sbb' else 'LF_SUB'}, {sz}, a, b, r{', c' if m == 'sbb' else ', 0'});")
|
||||
else:
|
||||
op = {"and": "&", "test": "&", "or": "|", "xor": "^"}[m]
|
||||
if m == "xor" and ops[0].type == X.X86_OP_REG and ops[1].type == X.X86_OP_REG and ops[0].reg == ops[1].reg:
|
||||
lines = ["{", " uint32_t r = 0;"]
|
||||
else:
|
||||
lines.append(f" uint32_t r = (a {op} b) & {mask};")
|
||||
lines.append(f" LF(LF_LOGIC, {sz}, 0, 0, r, 0);")
|
||||
if m not in ("cmp", "test"):
|
||||
lines.append(" " + self.wr(i, ops[0], "r"))
|
||||
nx = self.ins(nxt)
|
||||
# fusion cmp/test + jcc/setcc
|
||||
if m in ("cmp", "test") and nx is not None and (nx.mnemonic in JCC or nx.mnemonic in SETCC) and nxt not in self._labels:
|
||||
cc = nx.mnemonic[1:] if nx.mnemonic in JCC else nx.mnemonic[3:]
|
||||
cexpr = fused_cmp(cc, sz) if m == "cmp" else fused_test(cc, sz)
|
||||
if cexpr:
|
||||
lines.append(f" fz = {cexpr};")
|
||||
self._fused = nxt
|
||||
lines.append("}")
|
||||
return lines
|
||||
if m in ("inc", "dec", "neg", "not"):
|
||||
a = self.rd(i, ops[0])
|
||||
if m == "not":
|
||||
return [self.wr(i, ops[0], f"~{a}")]
|
||||
expr = {"inc": f"(a + 1) & {mask}", "dec": f"(a - 1) & {mask}", "neg": f"(0u - a) & {mask}"}[m]
|
||||
lf = {"inc": "LF_INC", "dec": "LF_DEC", "neg": "LF_NEG"}[m]
|
||||
cf = "cCF()" if m != "neg" else "0"
|
||||
return ["{", f" uint32_t a = {a}; uint32_t c = {cf};", f" uint32_t r = {expr};",
|
||||
f" LF({lf}, {sz}, a, 0, r, c);", " " + self.wr(i, ops[0], "r"), "}"]
|
||||
if m in ("shl", "sal", "shr", "sar", "rol", "ror", "rcl", "rcr"):
|
||||
a = self.rd(i, ops[0])
|
||||
cnt = "1u" if len(ops) == 1 else self.rd(i, ops[1], 8)
|
||||
fn = {"shl": "SHL", "sal": "SHL", "shr": "SHR", "sar": "SAR", "rol": "ROL", "ror": "ROR",
|
||||
"rcl": "RCL", "rcr": "RCR"}[m]
|
||||
return ["{", f" uint32_t n = ({cnt}) & 31u;", f" uint32_t r = {fn}{sz}({a}, n);",
|
||||
" " + self.wr(i, ops[0], "r"), "}"]
|
||||
if m in ("shld", "shrd"):
|
||||
raise NotImplementedError("shld/shrd")
|
||||
if m == "imul":
|
||||
if len(ops) == 1:
|
||||
if sz == 32:
|
||||
return ["{ int64_t p = (int64_t)(int32_t)R(0) * (int32_t)" + self.rd(i, ops[0]) + ";",
|
||||
" R(0) = (uint32_t)p; R(2) = (uint32_t)(p >> 32); LF_MULFLAGS(p != (int64_t)(int32_t)p); }"]
|
||||
if sz == 16:
|
||||
return ["{ int32_t p = (int32_t)(int16_t)W(0) * (int16_t)" + self.rd(i, ops[0]) + ";",
|
||||
" W(0) = (uint16_t)p; W(2) = (uint16_t)(p >> 16); LF_MULFLAGS(p != (int32_t)(int16_t)p); }"]
|
||||
return ["{ int16_t p = (int16_t)(int8_t)BL_(0) * (int8_t)" + self.rd(i, ops[0]) + ";",
|
||||
" W(0) = (uint16_t)p; LF_MULFLAGS(p != (int16_t)(int8_t)p); }"]
|
||||
src1 = self.rd(i, ops[1]) if len(ops) == 3 else self.rd(i, ops[0])
|
||||
src2 = (f"0x{ops[2].imm & 0xFFFFFFFF:x}u" if len(ops) == 3 else self.rd(i, ops[1]))
|
||||
st = {16: "int16_t", 32: "int32_t"}[sz]
|
||||
wide = {16: "int32_t", 32: "int64_t"}[sz]
|
||||
return ["{", f" {wide} p = ({wide})({st})({src1}) * ({wide})({st})({src2});",
|
||||
" " + self.wr(i, ops[0], "p"), f" LF_MULFLAGS(p != ({wide})({st})p);", "}"]
|
||||
if m == "mul":
|
||||
if sz == 32:
|
||||
return ["{ uint64_t p = (uint64_t)R(0) * " + self.rd(i, ops[0]) + ";",
|
||||
" R(0) = (uint32_t)p; R(2) = (uint32_t)(p >> 32); LF_MULFLAGS(R(2) != 0); }"]
|
||||
if sz == 16:
|
||||
return ["{ uint32_t p = (uint32_t)W(0) * " + self.rd(i, ops[0]) + ";",
|
||||
" W(0) = (uint16_t)p; W(2) = (uint16_t)(p >> 16); LF_MULFLAGS(W(2) != 0); }"]
|
||||
return ["{ uint16_t p = (uint16_t)BL_(0) * " + self.rd(i, ops[0]) + ";",
|
||||
" W(0) = p; LF_MULFLAGS(BH_(0) != 0); }"]
|
||||
if m in ("div", "idiv"):
|
||||
return [f"{m.upper()}{sz}({self.rd(i, ops[0])}, 0x{i.address:x}u);"]
|
||||
if m in SETCC:
|
||||
return [self.wr(i, ops[0], self.cond(m[3:], i.address))]
|
||||
|
||||
# ---------------------------------------------------------- flot
|
||||
if m == "jmp":
|
||||
if ops[0].type == X.X86_OP_IMM:
|
||||
return [self.goto(ops[0].imm & 0xFFFFFFFF, entry)]
|
||||
if i.address in self.tables:
|
||||
op = ops[0]
|
||||
idx = self.reg(i, op.mem.index) if op.mem.index else f"({self.reg(i, op.mem.base)} >> 2)"
|
||||
tab = self.tables[i.address]
|
||||
lines = [f"switch ({idx}) {{"]
|
||||
for k, t in enumerate(tab):
|
||||
lines.append(f" case {k}: {self.goto(t, entry)}")
|
||||
lines.append(f" default: JUMP_INDIRECT(RD32({self.ea(i, op)})); return;")
|
||||
lines.append("}")
|
||||
return lines
|
||||
if ops[0].type == X.X86_OP_MEM and ops[0].size == 6: # jmp far [m16:32]
|
||||
return [f"JUMP_FAR({self.ea(i, ops[0])}); return;"]
|
||||
return [f"JUMP_INDIRECT({self.rd(i, ops[0])}); return;"]
|
||||
if m in JCC:
|
||||
return [f"if ({self.cond(m[1:], i.address)}) {self.goto(ops[0].imm & 0xFFFFFFFF, entry)}"]
|
||||
if m == "jecxz":
|
||||
return [f"if (R(1) == 0) {self.goto(ops[0].imm & 0xFFFFFFFF, entry)}"]
|
||||
if m == "loop":
|
||||
return [f"if (--R(1) != 0) {self.goto(ops[0].imm & 0xFFFFFFFF, entry)}"]
|
||||
if m in ("loope", "loopne"):
|
||||
c = "cZF()" if m == "loope" else "!cZF()"
|
||||
return [f"if (--R(1) != 0 && {c}) {self.goto(ops[0].imm & 0xFFFFFFFF, entry)}"]
|
||||
if m == "call":
|
||||
if ops[0].type == X.X86_OP_IMM:
|
||||
t = ops[0].imm & 0xFFFFFFFF
|
||||
if t == nxt: # call $+5 : lit eip
|
||||
return [f"PUSH32(0x{nxt:x}u);"]
|
||||
if t not in self.entries: # données décodées comme du code
|
||||
return [f"TRAP(0x{i.address:x}u); return;"]
|
||||
return [f"PUSH32(0x{nxt:x}u); {self.prefix}_{t:08x}();"]
|
||||
if ops[0].type == X.X86_OP_MEM and ops[0].size == 6: # call far [m16:32]
|
||||
return [f"CALL_FAR({self.ea(i, ops[0])}, 0x{nxt:x}u);"]
|
||||
return ["{", f" uint32_t t = {self.rd(i, ops[0])};", f" PUSH32(0x{nxt:x}u); CALL_INDIRECT(t);", "}"]
|
||||
if m == "ret":
|
||||
n = ops[0].imm if ops else 0
|
||||
return [f"R(4) += {4 + n}u; return;"]
|
||||
if m == "iretd":
|
||||
return ["R(4) += 12u; return;"]
|
||||
if m == "int":
|
||||
return [f"rt_int(0x{ops[0].imm & 0xff:x}u);"]
|
||||
if m == "int3":
|
||||
return ["rt_int(3u);"]
|
||||
if m == "in":
|
||||
p = self.rd(i, ops[1], 16) if ops[1].type == X.X86_OP_REG else f"0x{ops[1].imm & 0xffff:x}u"
|
||||
return [self.wr(i, ops[0], f"rt_in({p}, {sz})")]
|
||||
if m == "out":
|
||||
p = self.rd(i, ops[0], 16) if ops[0].type == X.X86_OP_REG else f"0x{ops[0].imm & 0xffff:x}u"
|
||||
return [f"rt_out({p}, {self.rd(i, ops[1])}, {ops[1].size * 8});"]
|
||||
if m == "hlt":
|
||||
return [f"TRAP(0x{i.address:x}u); return;"]
|
||||
if m.startswith("f"):
|
||||
return self.fpu(i)
|
||||
raise NotImplementedError("instruction non gérée")
|
||||
|
||||
def cond(self, cc: str, addr: int) -> str:
|
||||
"""Condition : valeur calculée par le cmp/test juste avant (fz), sinon indicateurs paresseux."""
|
||||
if self._fused == addr:
|
||||
return "fz"
|
||||
return cond_lazy(JCC["j" + cc])
|
||||
|
||||
def string_op(self, i, base: str, pre: str) -> list[str]:
|
||||
k = base[:4]
|
||||
sz = {"b": 8, "w": 16, "d": 32}[base[-1]]
|
||||
fn = {"movs": "MOVS", "stos": "STOS", "lods": "LODS", "cmps": "CMPS", "scas": "SCAS"}[k]
|
||||
if pre and k in ("cmps", "scas"):
|
||||
return [f"REP{'NE' if pre == 'repne' else 'E'}_{fn}{sz}();"]
|
||||
if pre:
|
||||
return [f"REP_{fn}{sz}();"]
|
||||
return [f"{fn}{sz}();"]
|
||||
|
||||
def fpu(self, i) -> list[str]:
|
||||
m = i.mnemonic
|
||||
ops = i.operands
|
||||
args = []
|
||||
for op in ops:
|
||||
if op.type == X.X86_OP_REG:
|
||||
n = i.reg_name(op.reg)
|
||||
if n.startswith("st"):
|
||||
args.append(f"ST_REG({n[3:-1] if '(' in n else '0'})")
|
||||
else:
|
||||
args.append(f"REG_{n}")
|
||||
elif op.type == X.X86_OP_MEM:
|
||||
args.append(f"MEM{op.size * 8}({self.ea(i, op)})")
|
||||
else:
|
||||
args.append(f"0x{op.imm:x}u")
|
||||
name = m.upper()
|
||||
if len(args) == 2 and m in ("fadd", "fsub", "fsubr", "fmul", "fdiv", "fdivr"):
|
||||
if args[0] == "ST_REG(0)":
|
||||
args = args[1:] # st(0) op= src : forme à un opérande
|
||||
else:
|
||||
name += "2" # st(i) op= st(0)
|
||||
elif len(args) == 2 and m in ("faddp", "fsubp", "fsubrp", "fmulp", "fdivp", "fdivrp"):
|
||||
args = args[:1] # st(i) = st(i) op st(0) ; pop
|
||||
if name not in fpu_known(): # non implémentée (souvent des données lues comme du code)
|
||||
self.traps[i.address] = f"{m} {i.op_str}"
|
||||
return [f"TRAP(0x{i.address:x}u); return;"]
|
||||
return [f"FPU_{name}({', '.join(args)});"]
|
||||
|
||||
# ------------------------------------------------------------------ sortie
|
||||
def run(self, outdir: str, mod: str = "tucker", prefix: str = "F"):
|
||||
self.prefix = prefix
|
||||
ov = os.path.join(os.path.dirname(__file__), "..", "runtime", f"overrides_{mod}.txt")
|
||||
if os.path.exists(ov):
|
||||
for line in open(ov, encoding="utf-8"):
|
||||
line = line.split("#")[0].strip()
|
||||
if line:
|
||||
self.overrides.add(int(line, 16))
|
||||
self.discover([])
|
||||
os.makedirs(outdir, exist_ok=True)
|
||||
fns = sorted(self.entries)
|
||||
bodies = {e: self.emit_fn(e) for e in fns}
|
||||
hdr = f"recomp_{mod}.h"
|
||||
with open(os.path.join(outdir, hdr), "w", encoding="utf-8") as f:
|
||||
f.write("/* Généré par tools/recomp.py : ne pas modifier, ne pas distribuer. */\n#pragma once\n")
|
||||
for e in fns:
|
||||
f.write(f"void {prefix}_{e:08x}(void);\n")
|
||||
f.write(f"#define {mod.upper()}_ENTRY {prefix}_{self.img.entry:08x}\n")
|
||||
f.write(f"#define {mod.upper()}_STACK 0x{self.img.stack:x}u\n")
|
||||
f.write(f"extern const FnEntry {mod}_fn_table[];\nextern const unsigned {mod}_fn_count;\n")
|
||||
for n in range(0, len(fns), FNS_PER_FILE):
|
||||
with open(os.path.join(outdir, f"{mod}_{n // FNS_PER_FILE:03d}.c"), "w", encoding="utf-8") as f:
|
||||
f.write(f'#include "cpu.h"\n#include "{hdr}"\n\n')
|
||||
for e in fns[n:n + FNS_PER_FILE]:
|
||||
f.write("\n".join(bodies[e]) + "\n\n")
|
||||
with open(os.path.join(outdir, f"{mod}_fntable.c"), "w", encoding="utf-8") as f:
|
||||
f.write(f'#include "cpu.h"\n#include "{hdr}"\n\nconst FnEntry {mod}_fn_table[] = {{\n')
|
||||
for e in fns:
|
||||
f.write(f" {{0x{e:x}u, {prefix}_{e:08x}}},\n")
|
||||
f.write(f"}};\nconst unsigned {mod}_fn_count = {len(fns)};\n")
|
||||
report = [f"fonctions : {len(fns)}", f"tables de saut : {len(self.tables)}",
|
||||
f"sauts indirects non résolus : {len(self.unresolved)}"]
|
||||
report += [f" {a:#x} {s}" for a, s in sorted(self.unresolved.items())]
|
||||
report.append(f"instructions non traduites : {len(self.traps)}")
|
||||
report += [f" {a:#x} {s}" for a, s in sorted(self.traps.items())]
|
||||
with open(os.path.join(outdir, "rapport.txt"), "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(report) + "\n")
|
||||
print("\n".join(report[:3]), f"\ninstructions non traduites : {len(self.traps)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# recomp.py EXE DOSSIER [module] [préfixe] ex. : recomp.py INTRO.EXE build/gen_intro intro I
|
||||
Recompiler(sys.argv[1]).run(sys.argv[2], *(sys.argv[3:5]))
|
||||
Reference in new issue
Block a user