diff --git a/.gitignore b/.gitignore index a527ad50..8844bae2 100644 --- a/.gitignore +++ b/.gitignore @@ -35,6 +35,7 @@ __pycache__/ *.xci *.xcz *.nsp +*.nup *.nsz *.nca dump/ diff --git a/Makefile b/Makefile index db3683de..8f5f981a 100644 --- a/Makefile +++ b/Makefile @@ -439,6 +439,7 @@ deps-windows: dist: @[ -f build/deps-win/lib/libavcodec.dll.a ] || { echo "make deps-windows first (LGPL FFmpeg)"; exit 1; } @[ -d build/helper/swgen ] || { echo "make gen-helper first (the game code generator)"; exit 1; } + @[ -x build/helper/nxpatch/nxpatch.exe ] || { echo "make package-helper first (the NSP reader)"; exit 1; } @! find tools -maxdepth 1 -name '*.py' -newer build/helper/swgen/swgen.exe | grep -q . || \ { echo "make gen-helper first: tools/*.py changed since build/helper/swgen was frozen"; exit 1; } @[ -x build/zig/zig.exe ] || { echo "tools/fetch_zig.sh first (the compiler)"; exit 1; } @@ -451,6 +452,7 @@ dist: tools/zig_slim.sh $(strip $(filter-out -Iruntime,$(GENFLAGS))) \ $(if $(GENFLAGS_COMPAT),-- $(strip $(filter-out -Iruntime,$(GENFLAGS_COMPAT)))) # (zig, its runtime built ahead of time) cp -R build/helper/swgen "$(DIST)/" + cp -R build/helper/nxpatch "$(DIST)/" cp -R build/zig-slim "$(DIST)/zig" cp runtime/cpu.h runtime/simd.h runtime/simd_fp.h runtime/simd_softfma.h runtime/gamelib.h tools/gamelib_entry.c \ runtime/hle/hle_symbols.txt "$(DIST)/gamelib-src/" @@ -503,11 +505,15 @@ gen-helper: build/gen-venv/.ok $(if $(filter windows,$(PLATFORM)),$(GEN_VPY) tools/pe_no_cfg.py build/helper/swgen/swgen.exe) @du -sh build/helper/swgen -build/gen-venv/.ok: +build/gen-venv/.ok: Makefile $(GEN_PY) -m venv build/gen-venv - $(GEN_VPY) -m pip install -q capstone==5.0.9 unicorn==2.1.4 lz4==4.4.5 pyinstaller==6.22.3 + $(GEN_VPY) -m pip install -q capstone==5.0.9 unicorn==2.1.4 lz4==4.4.5 pyinstaller==6.22.3 zstandard==0.25.0 touch $@ +.PHONY: package-helper +package-helper: + bash tools/build_package_helper.sh $(if $(filter windows,$(PLATFORM)),win-x64,linux-$(if $(filter aarch64,$(ARCH)),arm64,x64)) build/helper/nxpatch + # Linux: build/dist/Savage_Wind--.AppImage, built in Ubuntu 22.04 containers (podman) with SDL3, LGPL # FFmpeg, shaderc and the game code generator helper inside; the Vulkan loader and GPU drivers are the system's. # `make appimage` (ARCH: this machine's, or aarch64 cross-compiled), `make appimages` both. See docs/linux.md. diff --git a/README.md b/README.md index e9b33413..47e5b438 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,8 @@ about 20 GB of free disk space. - **Linux and Steam Deck:** the file ending in `x86_64.AppImage`. Make it executable and run it ([docs/linux.md](docs/linux.md)). - **Linux on ARM:** the file ending in `aarch64.AppImage`. It is highly experimental. -2. Start it and choose the folder with your extracted game (`exefs/` and `romfs/`). Then choose **Set up game files**. +2. Start it and choose the folder with your extracted game (`exefs/` and `romfs/`), or choose **Import game packages** + to extract local NUP or NSP files into a new folder. Then choose **Set up game files**. It checks the version, copies the files and recompiles the game code once, about 15 minutes on a 12-thread CPU. Your own files aren't changed. 3. Play. Settings and languages are in the game's Options. **Savage Wind Configuration** has your game files and the diff --git a/docs/BUILD-windows.md b/docs/BUILD-windows.md index faca83f4..f98eef78 100644 --- a/docs/BUILD-windows.md +++ b/docs/BUILD-windows.md @@ -33,6 +33,7 @@ Run from a shell that has `C:\msys64\ucrt64\bin` on PATH (SDL3, FFmpeg, Vulkan, ## Package make deps-windows # once: FFmpeg built as LGPL only (build/deps-win; downloads its source, needs nasm) make gen-helper # the game code generator without Python (build/helper/swgen) + make package-helper # the NSP reader (requires the .NET 10 SDK on the build machine) tools/fetch_zig.sh # the compiler the start screen builds the game code with (build/zig) make dist # -> build/dist/SavageWind--windows.zip (no game code inside) diff --git a/docs/game-files.md b/docs/game-files.md index 9da67a1e..3b918cfb 100644 --- a/docs/game-files.md +++ b/docs/game-files.md @@ -27,6 +27,18 @@ extracted/ The `main` module's build id tells the exact version; `python tools/sw_probe.py` (it reads `extracted/exefs`) prints it and what the recompiler will find there. +## Importing packages + +On Windows and Linux, choose **Import game packages** on the game files page. Select a combined NUP or select +the base, update and DLC packages together. Review the identified content, source files and release versions, +then choose **Extract packages**. A game NUP must contain the **1.9.0** RomFS. For a game imported from NSP, +select the base and matching update together. The importer checks the merged RomFS version before extraction. +If you select several updates, it checks the newest one. DLC-only imports can be extracted separately. +Encrypted NSPs need your local keys file. + +The launcher extracts into a new `extracted-import-*/files/` folder in the data directory and selects that +folder for you. Choose **Set up game files** to check the game version and install the extracted files. + ## The DLC Each DLC's RomFS goes in a folder of its own, named `aoc1/` and `aoc2/` as above, with its folders right inside it diff --git a/docs/linux.md b/docs/linux.md index 052b32ee..00e1bcc1 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -150,7 +150,7 @@ stb_image_write in `third_party/stb`.) Then from the repo root: - python3 -m venv tools/venv && tools/venv/bin/pip install lz4 capstone unicorn + python3 -m venv tools/venv && tools/venv/bin/pip install lz4 capstone unicorn zstandard make -j # the start screen only (no game code yet): set up the game files there, or put extracted/ here make gen # once: recompile the game from your own game files make -j # -> build/savagewind and the game code library build/swgame.so diff --git a/runtime/ui/i18n/de.inc b/runtime/ui/i18n/de.inc index 98b8c277..1d90ed89 100644 --- a/runtime/ui/i18n/de.inc +++ b/runtime/ui/i18n/de.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps bis zum nächsten F5") T("Frame rate as set again", "Bildrate wieder wie eingestellt") T("30 fps for a physics puzzle, until pressed again: F5", "30 fps für ein Physikrätsel, bis zum erneuten Drücken: F5") +T("Import game packages", "Spielpakete importieren") +T("Extract NUP or NSP files into a folder for setup.", "NUP- oder NSP-Dateien zur Einrichtung in einen Ordner entpacken.") +T("Choose the keys file for NSP packages", "Schlüsseldatei für NSP-Pakete auswählen") +T("Extracting game packages...", "Spielpakete werden entpackt...") +T("Esc or B cancels the import.", "Esc oder B bricht den Import ab.") +T("Package import cancelled.", "Paketimport abgebrochen.") +T("Packages extracted. Select Set up game files.", "Pakete entpackt. Wähle Spieldateien einrichten.") +T("Could not open the package picker", "Paketauswahl konnte nicht geöffnet werden") +T("Could not extract game packages", "Spielpakete konnten nicht entpackt werden") +T("Package reader is missing", "Paketleser fehlt") +T("Add the matching base game NSP", "Passendes NSP des Basisspiels hinzufügen") +T("No Breath of the Wild content was found", "Keine Inhalte von Breath of the Wild gefunden") +T("Choose one copy of each game package", "Wähle nur eine Kopie jedes Spielpakets") +T("Base game", "Basisspiel") +T("Game update", "Spielupdate") +T("Extract packages", "Pakete entpacken") +T("Inspecting game packages...", "Spielpakete werden geprüft...") +T("Add the version %s update NSP", "NSP für das Spielupdate auf Version %s hinzufügen") diff --git a/runtime/ui/i18n/es.inc b/runtime/ui/i18n/es.inc index 60b05004..d102b220 100644 --- a/runtime/ui/i18n/es.inc +++ b/runtime/ui/i18n/es.inc @@ -1555,3 +1555,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps hasta volver a pulsar F5") T("Frame rate as set again", "Frecuencia de cuadros como estaba") T("30 fps for a physics puzzle, until pressed again: F5", "30 fps para un puzle de física, hasta volver a pulsarla: F5") +T("Import game packages", "Importar paquetes del juego") +T("Extract NUP or NSP files into a folder for setup.", "Extrae archivos NUP o NSP en una carpeta para la configuración.") +T("Choose the keys file for NSP packages", "Elegir el archivo de claves para paquetes NSP") +T("Extracting game packages...", "Extrayendo paquetes del juego...") +T("Esc or B cancels the import.", "Esc o B cancela la importación.") +T("Package import cancelled.", "Importación de paquetes cancelada.") +T("Packages extracted. Select Set up game files.", "Paquetes extraídos. Selecciona Configurar archivos del juego.") +T("Could not open the package picker", "No se pudo abrir el selector de paquetes") +T("Could not extract game packages", "No se pudieron extraer los paquetes del juego") +T("Package reader is missing", "Falta el lector de paquetes") +T("Add the matching base game NSP", "Añade el NSP del juego base correspondiente") +T("No Breath of the Wild content was found", "No se encontró contenido de Breath of the Wild") +T("Choose one copy of each game package", "Elige una sola copia de cada paquete del juego") +T("Base game", "Juego base") +T("Game update", "Actualización del juego") +T("Extract packages", "Extraer paquetes") +T("Inspecting game packages...", "Inspeccionando paquetes del juego...") +T("Add the version %s update NSP", "Añade el NSP de la actualización a la versión %s") diff --git a/runtime/ui/i18n/fr.inc b/runtime/ui/i18n/fr.inc index 692350e4..3f39cc96 100644 --- a/runtime/ui/i18n/fr.inc +++ b/runtime/ui/i18n/fr.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps jusqu'au prochain F5") T("Frame rate as set again", "Fréquence d'images comme réglée") T("30 fps for a physics puzzle, until pressed again: F5", "30 fps pour une énigme physique, jusqu'au prochain appui : F5") +T("Import game packages", "Importer des paquets de jeu") +T("Extract NUP or NSP files into a folder for setup.", "Extraire les fichiers NUP ou NSP dans un dossier pour la configuration.") +T("Choose the keys file for NSP packages", "Choisir le fichier de clés pour les paquets NSP") +T("Extracting game packages...", "Extraction des paquets de jeu...") +T("Esc or B cancels the import.", "Échap ou B annule l’importation.") +T("Package import cancelled.", "Importation des paquets annulée.") +T("Packages extracted. Select Set up game files.", "Paquets extraits. Sélectionnez Configurer les fichiers du jeu.") +T("Could not open the package picker", "Impossible d’ouvrir le sélecteur de paquets") +T("Could not extract game packages", "Impossible d’extraire les paquets de jeu") +T("Package reader is missing", "Le lecteur de paquets est manquant") +T("Add the matching base game NSP", "Ajoutez le NSP du jeu de base correspondant") +T("No Breath of the Wild content was found", "Aucun contenu de Breath of the Wild trouvé") +T("Choose one copy of each game package", "Choisissez une seule copie de chaque paquet de jeu") +T("Base game", "Jeu de base") +T("Game update", "Mise à jour du jeu") +T("Extract packages", "Extraire les paquets") +T("Inspecting game packages...", "Inspection des paquets de jeu...") +T("Add the version %s update NSP", "Ajoutez le NSP de mise à jour vers la version %s") diff --git a/runtime/ui/i18n/he.inc b/runtime/ui/i18n/he.inc index 9939b5ca..3cc1dde6 100644 --- a/runtime/ui/i18n/he.inc +++ b/runtime/ui/i18n/he.inc @@ -1555,3 +1555,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps עד לחיצה נוספת על F5") T("Frame rate as set again", "קצב הפריימים שוב כפי שהוגדר") T("30 fps for a physics puzzle, until pressed again: F5", "30 fps לחידת פיזיקה, עד לחיצה נוספת: F5") +T("Import game packages", "ייבוא חבילות משחק") +T("Extract NUP or NSP files into a folder for setup.", "חלצו קובצי NUP או NSP לתיקייה לצורך הגדרה.") +T("Choose the keys file for NSP packages", "בחירת קובץ המפתחות לחבילות NSP") +T("Extracting game packages...", "מחלץ חבילות משחק...") +T("Esc or B cancels the import.", "Esc או B מבטלים את הייבוא.") +T("Package import cancelled.", "ייבוא החבילות בוטל.") +T("Packages extracted. Select Set up game files.", "החבילות חולצו. בחרו בהגדרת קובצי המשחק.") +T("Could not open the package picker", "לא ניתן לפתוח את בורר החבילות") +T("Could not extract game packages", "לא ניתן לחלץ את חבילות המשחק") +T("Package reader is missing", "קורא החבילות חסר") +T("Add the matching base game NSP", "הוסיפו את קובץ ה-NSP של משחק הבסיס המתאים") +T("No Breath of the Wild content was found", "לא נמצא תוכן של Breath of the Wild") +T("Choose one copy of each game package", "בחרו עותק אחד מכל חבילת משחק") +T("Base game", "משחק בסיס") +T("Game update", "עדכון משחק") +T("Extract packages", "חילוץ חבילות") +T("Inspecting game packages...", "בודק חבילות משחק...") +T("Add the version %s update NSP", "הוסיפו את קובץ ה-NSP של העדכון לגרסה %s") diff --git a/runtime/ui/i18n/it.inc b/runtime/ui/i18n/it.inc index 38b4bfab..9711a895 100644 --- a/runtime/ui/i18n/it.inc +++ b/runtime/ui/i18n/it.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps fino al prossimo F5") T("Frame rate as set again", "Frequenza dei fotogrammi come impostata") T("30 fps for a physics puzzle, until pressed again: F5", "30 fps per un enigma di fisica, finché non la premi di nuovo: F5") +T("Import game packages", "Importa pacchetti di gioco") +T("Extract NUP or NSP files into a folder for setup.", "Estrai i file NUP o NSP in una cartella per la configurazione.") +T("Choose the keys file for NSP packages", "Scegli il file delle chiavi per i pacchetti NSP") +T("Extracting game packages...", "Estrazione dei pacchetti di gioco...") +T("Esc or B cancels the import.", "Esc o B annulla l’importazione.") +T("Package import cancelled.", "Importazione dei pacchetti annullata.") +T("Packages extracted. Select Set up game files.", "Pacchetti estratti. Seleziona Configura i file di gioco.") +T("Could not open the package picker", "Impossibile aprire il selettore dei pacchetti") +T("Could not extract game packages", "Impossibile estrarre i pacchetti di gioco") +T("Package reader is missing", "Manca il lettore dei pacchetti") +T("Add the matching base game NSP", "Aggiungi il file NSP del gioco base corrispondente") +T("No Breath of the Wild content was found", "Nessun contenuto di Breath of the Wild trovato") +T("Choose one copy of each game package", "Scegli una sola copia di ogni pacchetto di gioco") +T("Base game", "Gioco base") +T("Game update", "Aggiornamento del gioco") +T("Extract packages", "Estrai pacchetti") +T("Inspecting game packages...", "Analisi dei pacchetti di gioco...") +T("Add the version %s update NSP", "Aggiungi il file NSP dell’aggiornamento alla versione %s") diff --git a/runtime/ui/i18n/ja.inc b/runtime/ui/i18n/ja.inc index 4175a940..70b86979 100644 --- a/runtime/ui/i18n/ja.inc +++ b/runtime/ui/i18n/ja.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "もう一度F5を押すまで30fps") T("Frame rate as set again", "フレームレートを設定どおりに戻しました") T("30 fps for a physics puzzle, until pressed again: F5", "物理パズル用に30fps(もう一度押すまで): F5") +T("Import game packages", "ゲームパッケージをインポート") +T("Extract NUP or NSP files into a folder for setup.", "セットアップ用に NUP または NSP ファイルをフォルダーに展開します。") +T("Choose the keys file for NSP packages", "NSP パッケージのキーファイルを選択") +T("Extracting game packages...", "ゲームパッケージを展開中...") +T("Esc or B cancels the import.", "Esc または B でインポートをキャンセルします。") +T("Package import cancelled.", "パッケージのインポートをキャンセルしました。") +T("Packages extracted. Select Set up game files.", "展開が完了しました。ゲームファイルのセットアップを選択してください。") +T("Could not open the package picker", "パッケージ選択画面を開けませんでした") +T("Could not extract game packages", "ゲームパッケージを展開できませんでした") +T("Package reader is missing", "パッケージリーダーが見つかりません") +T("Add the matching base game NSP", "対応するベースゲームの NSP を追加してください") +T("No Breath of the Wild content was found", "Breath of the Wild のコンテンツが見つかりませんでした") +T("Choose one copy of each game package", "各ゲームパッケージを1つずつ選択してください") +T("Base game", "ベースゲーム") +T("Game update", "ゲームのアップデート") +T("Extract packages", "パッケージを展開") +T("Inspecting game packages...", "ゲームパッケージを確認中...") +T("Add the version %s update NSP", "バージョン %s のアップデート NSP を追加してください") diff --git a/runtime/ui/i18n/ko.inc b/runtime/ui/i18n/ko.inc index 83e7fdac..34ed73b0 100644 --- a/runtime/ui/i18n/ko.inc +++ b/runtime/ui/i18n/ko.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "F5를 다시 누를 때까지 30fps") T("Frame rate as set again", "프레임 속도를 설정대로 되돌렸습니다") T("30 fps for a physics puzzle, until pressed again: F5", "물리 퍼즐용 30fps, 다시 누를 때까지: F5") +T("Import game packages", "게임 패키지 가져오기") +T("Extract NUP or NSP files into a folder for setup.", "설정에 사용할 NUP 또는 NSP 파일을 폴더에 풉니다.") +T("Choose the keys file for NSP packages", "NSP 패키지의 키 파일 선택") +T("Extracting game packages...", "게임 패키지를 푸는 중...") +T("Esc or B cancels the import.", "Esc 또는 B를 누르면 가져오기가 취소됩니다.") +T("Package import cancelled.", "패키지 가져오기가 취소되었습니다.") +T("Packages extracted. Select Set up game files.", "패키지 풀기가 완료되었습니다. 게임 파일 설정을 선택하세요.") +T("Could not open the package picker", "패키지 선택 창을 열 수 없습니다") +T("Could not extract game packages", "게임 패키지를 풀 수 없습니다") +T("Package reader is missing", "패키지 읽기 도구가 없습니다") +T("Add the matching base game NSP", "일치하는 본편 게임 NSP를 추가하세요") +T("No Breath of the Wild content was found", "Breath of the Wild 콘텐츠를 찾을 수 없습니다") +T("Choose one copy of each game package", "게임 패키지마다 하나의 사본을 선택하세요") +T("Base game", "본편 게임") +T("Game update", "게임 업데이트") +T("Extract packages", "패키지 풀기") +T("Inspecting game packages...", "게임 패키지를 확인하는 중...") +T("Add the version %s update NSP", "버전 %s 업데이트 NSP를 추가하세요") diff --git a/runtime/ui/i18n/nl.inc b/runtime/ui/i18n/nl.inc index dc0c934d..3937e9c4 100644 --- a/runtime/ui/i18n/nl.inc +++ b/runtime/ui/i18n/nl.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps tot je weer op F5 drukt") T("Frame rate as set again", "Framerate weer zoals ingesteld") T("30 fps for a physics puzzle, until pressed again: F5", "30 fps voor een natuurkundepuzzel, tot je opnieuw drukt: F5") +T("Import game packages", "Spelpakketten importeren") +T("Extract NUP or NSP files into a folder for setup.", "Pak NUP- of NSP-bestanden uit naar een map voor de installatie.") +T("Choose the keys file for NSP packages", "Sleutelbestand voor NSP-pakketten kiezen") +T("Extracting game packages...", "Spelpakketten uitpakken...") +T("Esc or B cancels the import.", "Esc of B annuleert het importeren.") +T("Package import cancelled.", "Importeren van pakketten geannuleerd.") +T("Packages extracted. Select Set up game files.", "Pakketten uitgepakt. Kies Spelbestanden instellen.") +T("Could not open the package picker", "Pakketkiezer kon niet worden geopend") +T("Could not extract game packages", "Spelpakketten konden niet worden uitgepakt") +T("Package reader is missing", "Pakketlezer ontbreekt") +T("Add the matching base game NSP", "Voeg het bijbehorende NSP-bestand van het basisspel toe") +T("No Breath of the Wild content was found", "Geen Breath of the Wild-inhoud gevonden") +T("Choose one copy of each game package", "Kies één exemplaar van elk spelpakket") +T("Base game", "Basisspel") +T("Game update", "Spelupdate") +T("Extract packages", "Pakketten uitpakken") +T("Inspecting game packages...", "Spelpakketten controleren...") +T("Add the version %s update NSP", "Voeg de NSP-update naar versie %s toe") diff --git a/runtime/ui/i18n/pt.inc b/runtime/ui/i18n/pt.inc index 0b7dc092..8c8336a8 100644 --- a/runtime/ui/i18n/pt.inc +++ b/runtime/ui/i18n/pt.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps até apertar F5 de novo") T("Frame rate as set again", "Taxa de quadros como configurada") T("30 fps for a physics puzzle, until pressed again: F5", "30 fps para um quebra-cabeça de física, até apertar de novo: F5") +T("Import game packages", "Importar pacotes do jogo") +T("Extract NUP or NSP files into a folder for setup.", "Extraia os arquivos NUP ou NSP em uma pasta para a configuração.") +T("Choose the keys file for NSP packages", "Escolher o arquivo de chaves para pacotes NSP") +T("Extracting game packages...", "Extraindo pacotes do jogo...") +T("Esc or B cancels the import.", "Esc ou B cancela a importação.") +T("Package import cancelled.", "Importação de pacotes cancelada.") +T("Packages extracted. Select Set up game files.", "Pacotes extraídos. Selecione Configurar arquivos do jogo.") +T("Could not open the package picker", "Não foi possível abrir o seletor de pacotes") +T("Could not extract game packages", "Não foi possível extrair os pacotes do jogo") +T("Package reader is missing", "O leitor de pacotes está ausente") +T("Add the matching base game NSP", "Adicione o NSP do jogo base correspondente") +T("No Breath of the Wild content was found", "Nenhum conteúdo de Breath of the Wild foi encontrado") +T("Choose one copy of each game package", "Escolha uma cópia de cada pacote do jogo") +T("Base game", "Jogo base") +T("Game update", "Atualização do jogo") +T("Extract packages", "Extrair pacotes") +T("Inspecting game packages...", "Inspecionando pacotes do jogo...") +T("Add the version %s update NSP", "Adicione o NSP da atualização para a versão %s") diff --git a/runtime/ui/i18n/ru.inc b/runtime/ui/i18n/ru.inc index da69aecb..5cec72a9 100644 --- a/runtime/ui/i18n/ru.inc +++ b/runtime/ui/i18n/ru.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 кадров/с до следующего нажатия F5") T("Frame rate as set again", "Частота кадров снова как в настройках") T("30 fps for a physics puzzle, until pressed again: F5", "30 кадров/с для физической головоломки, до повторного нажатия: F5") +T("Import game packages", "Импортировать пакеты игры") +T("Extract NUP or NSP files into a folder for setup.", "Распакуйте файлы NUP или NSP в папку для настройки.") +T("Choose the keys file for NSP packages", "Выбрать файл ключей для пакетов NSP") +T("Extracting game packages...", "Распаковка пакетов игры...") +T("Esc or B cancels the import.", "Esc или B отменяет импорт.") +T("Package import cancelled.", "Импорт пакетов отменён.") +T("Packages extracted. Select Set up game files.", "Пакеты распакованы. Выберите «Настроить файлы игры».") +T("Could not open the package picker", "Не удалось открыть окно выбора пакетов") +T("Could not extract game packages", "Не удалось распаковать пакеты игры") +T("Package reader is missing", "Отсутствует программа чтения пакетов") +T("Add the matching base game NSP", "Добавьте соответствующий NSP базовой игры") +T("No Breath of the Wild content was found", "Данные Breath of the Wild не найдены") +T("Choose one copy of each game package", "Выберите по одной копии каждого пакета игры") +T("Base game", "Базовая игра") +T("Game update", "Обновление игры") +T("Extract packages", "Распаковать пакеты") +T("Inspecting game packages...", "Проверка пакетов игры...") +T("Add the version %s update NSP", "Добавьте NSP обновления до версии %s") diff --git a/runtime/ui/i18n/th.inc b/runtime/ui/i18n/th.inc index 3f5faf9d..294a40fb 100644 --- a/runtime/ui/i18n/th.inc +++ b/runtime/ui/i18n/th.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps จนกว่าจะกด F5 อีกครั้ง") T("Frame rate as set again", "อัตราเฟรมกลับเป็นตามที่ตั้งไว้") T("30 fps for a physics puzzle, until pressed again: F5", "30 fps สำหรับปริศนาฟิสิกส์ จนกว่าจะกดอีกครั้ง: F5") +T("Import game packages", "นำเข้าแพ็กเกจเกม") +T("Extract NUP or NSP files into a folder for setup.", "แตกไฟล์ NUP หรือ NSP ลงในโฟลเดอร์เพื่อใช้ตั้งค่า") +T("Choose the keys file for NSP packages", "เลือกไฟล์คีย์สำหรับแพ็กเกจ NSP") +T("Extracting game packages...", "กำลังแตกแพ็กเกจเกม...") +T("Esc or B cancels the import.", "กด Esc หรือ B เพื่อยกเลิกการนำเข้า") +T("Package import cancelled.", "ยกเลิกการนำเข้าแพ็กเกจแล้ว") +T("Packages extracted. Select Set up game files.", "แตกแพ็กเกจแล้ว เลือกตั้งค่าไฟล์เกม") +T("Could not open the package picker", "เปิดหน้าต่างเลือกแพ็กเกจไม่ได้") +T("Could not extract game packages", "แตกแพ็กเกจเกมไม่ได้") +T("Package reader is missing", "ไม่พบโปรแกรมอ่านแพ็กเกจ") +T("Add the matching base game NSP", "เพิ่มไฟล์ NSP ของเกมหลักที่ตรงกัน") +T("No Breath of the Wild content was found", "ไม่พบเนื้อหาของ Breath of the Wild") +T("Choose one copy of each game package", "เลือกแพ็กเกจเกมอย่างละหนึ่งชุด") +T("Base game", "เกมหลัก") +T("Game update", "อัปเดตเกม") +T("Extract packages", "แตกแพ็กเกจ") +T("Inspecting game packages...", "กำลังตรวจสอบแพ็กเกจเกม...") +T("Add the version %s update NSP", "เพิ่มไฟล์ NSP ของอัปเดตเวอร์ชัน %s") diff --git a/runtime/ui/i18n/zh-Hans.inc b/runtime/ui/i18n/zh-Hans.inc index 01fa0d68..2d03b2e5 100644 --- a/runtime/ui/i18n/zh-Hans.inc +++ b/runtime/ui/i18n/zh-Hans.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps,直到再次按 F5") T("Frame rate as set again", "帧率恢复为设置值") T("30 fps for a physics puzzle, until pressed again: F5", "物理谜题时 30 fps,再按一次恢复: F5") +T("Import game packages", "导入游戏包") +T("Extract NUP or NSP files into a folder for setup.", "将 NUP 或 NSP 文件解压到文件夹以便设置。") +T("Choose the keys file for NSP packages", "选择 NSP 包的密钥文件") +T("Extracting game packages...", "正在解压游戏包…") +T("Esc or B cancels the import.", "按 Esc 或 B 取消导入。") +T("Package import cancelled.", "已取消游戏包导入。") +T("Packages extracted. Select Set up game files.", "游戏包已解压。请选择设置游戏文件。") +T("Could not open the package picker", "无法打开游戏包选择器") +T("Could not extract game packages", "无法解压游戏包") +T("Package reader is missing", "缺少游戏包读取工具") +T("Add the matching base game NSP", "请添加匹配的游戏本体 NSP") +T("No Breath of the Wild content was found", "未找到《旷野之息》的内容") +T("Choose one copy of each game package", "每个游戏包只选择一份") +T("Base game", "游戏本体") +T("Game update", "游戏更新") +T("Extract packages", "解压游戏包") +T("Inspecting game packages...", "正在检查游戏包…") +T("Add the version %s update NSP", "请添加 %s 版本的更新 NSP") diff --git a/runtime/ui/i18n/zh-Hant.inc b/runtime/ui/i18n/zh-Hant.inc index cd6907c6..d409fe3e 100644 --- a/runtime/ui/i18n/zh-Hant.inc +++ b/runtime/ui/i18n/zh-Hant.inc @@ -1556,3 +1556,21 @@ T("Press the sprint button once while moving and Link keeps sprinting until he s T("30 fps until F5 again", "30 fps,直到再次按 F5") T("Frame rate as set again", "影格率恢復為設定值") T("30 fps for a physics puzzle, until pressed again: F5", "物理謎題時 30 fps,再按一次恢復: F5") +T("Import game packages", "匯入遊戲套件") +T("Extract NUP or NSP files into a folder for setup.", "將 NUP 或 NSP 檔案解壓縮到資料夾以便設定。") +T("Choose the keys file for NSP packages", "選擇 NSP 套件的金鑰檔案") +T("Extracting game packages...", "正在解壓縮遊戲套件…") +T("Esc or B cancels the import.", "按 Esc 或 B 取消匯入。") +T("Package import cancelled.", "已取消遊戲套件匯入。") +T("Packages extracted. Select Set up game files.", "遊戲套件已解壓縮。請選擇設定遊戲檔案。") +T("Could not open the package picker", "無法開啟遊戲套件選擇器") +T("Could not extract game packages", "無法解壓縮遊戲套件") +T("Package reader is missing", "缺少遊戲套件讀取工具") +T("Add the matching base game NSP", "請加入相符的遊戲本體 NSP") +T("No Breath of the Wild content was found", "找不到《曠野之息》的內容") +T("Choose one copy of each game package", "每個遊戲套件只選擇一份") +T("Base game", "遊戲本體") +T("Game update", "遊戲更新") +T("Extract packages", "解壓縮套件") +T("Inspecting game packages...", "正在檢查遊戲套件…") +T("Add the version %s update NSP", "請加入 %s 版本的更新 NSP") diff --git a/runtime/ui/launcher.mm b/runtime/ui/launcher.mm index cb3ae1ed..0606be2d 100644 --- a/runtime/ui/launcher.mm +++ b/runtime/ui/launcher.mm @@ -443,7 +443,7 @@ static void find_game(const std::string &dir, int depth, std::string &exefs, std if (n[0] == '.') continue; std::string ext = n.size() > 4 ? n.substr(n.size() - 4) : ""; for (auto &ch : ext) ch = (char)tolower((unsigned char)ch); - if (ext == ".xci" || ext == ".nsp" || ext == ".nca" || ext == ".nsz" || ext == ".xcz") unusable = true; + if (ext == ".nup" || ext == ".xci" || ext == ".nsp" || ext == ".nca" || ext == ".nsz" || ext == ".xcz") unusable = true; if (is_dir(dir + "/" + n)) sub.push_back(dir + "/" + n); } closedir(d); @@ -1206,6 +1206,223 @@ static void SDLCALL picked(void *, const char *const *files, int) { select_game_folder(files[0]); } +#ifndef __APPLE__ +static std::atomic g_importing{false}, g_import_cancel{false}; +static std::atomic g_import_approved{false}; +struct PackagePreview { std::string kind, version, filename; }; +static std::vector g_import_preview; // guarded by g_lock +static bool g_import_finished; // guarded by g_lock +static bool g_packages_selected; // guarded by g_lock +static std::string g_package_keys; // a path selected for this session only; guarded by g_lock +static const SDL_DialogFileFilter package_filter[] = {{"NUP / NSP", "nup;nsp"}}; // i18n-skip +static const SDL_DialogFileFilter key_filter[] = {{"*.keys", "keys"}}; // i18n-skip + +static void SDLCALL picked_package_keys(void *, const char *const *files, int) { + if (!files || !files[0]) return; + pthread_mutex_lock(&g_lock); + if (!g_busy) g_package_keys = files[0]; + pthread_mutex_unlock(&g_lock); +} + +static bool draw_package_review(ImVec2 size) { + pthread_mutex_lock(&g_lock); + std::vector items = g_import_preview; + pthread_mutex_unlock(&g_lock); + if (items.empty() || g_import_cancel || g_import_approved) return false; + const char *popup = "##package-review"; + if (!ImGui::IsPopupOpen(popup)) ImGui::OpenPopup(popup); + ImGui::SetNextWindowPos(ImVec2(size.x * 0.5f, size.y * 0.5f), ImGuiCond_Always, ImVec2(0.5f, 0.5f)); + if (ImGui::BeginPopupModal(popup, NULL, ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar)) { + ImGui::TextUnformatted(tr("Import game packages")); + ImGui::Separator(); + ImGui::PushTextWrapPos(ImGui::GetCursorPosX() + size.x * 0.5f); + for (const auto &item : items) { + const bool base = item.kind == "base", update = item.kind == "update"; + const char *addon = item.kind == "aoc1" ? "1" : "2"; + if (base) ImGui::TextUnformatted(tr("Base game")); + else if (update) ImGui::TextUnformatted(tr("Game update")); + else ImGui::Text("%s %s", tr("Downloadable content"), addon); + if (!item.version.empty()) ImGui::TextDisabled(tr("Version %s"), item.version.c_str()); + ImGui::TextUnformatted(item.filename.c_str()); + ImGui::Spacing(); + } + ImGui::PopTextWrapPos(); + if (ImGui::Button(tr("Extract packages"))) { + g_import_approved = true; + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button(tr("Cancel")) || ImGui::IsKeyPressed(ImGuiKey_Escape, false) || + ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) { + g_import_cancel = true; + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + return true; +} + +static std::string import_packages(const std::vector &packages, const std::string &keys) { + namespace fs = std::filesystem; + char helper[1100], script[1100] = "", nxpatch[1100]; + if (!rt_resource("swgen/swgen" PLAT_EXE_SUFFIX, NULL, helper, sizeof helper) && + !(rt_resource(NULL, "tools/" PLAT_VENV_PYTHON, helper, sizeof helper) && + rt_resource(NULL, "tools/gen.py", script, sizeof script))) { + set_job("Package reader is missing", true); + return {}; + } + bool have_nxpatch = rt_resource("nxpatch/nxpatch" PLAT_EXE_SUFFIX, + "build/helper/nxpatch/nxpatch" PLAT_EXE_SUFFIX, nxpatch, sizeof nxpatch); + std::error_code ec; + // A fresh directory beside extracted/, with no user-owned files inside it. + std::string stage = std::string(rt_data_root()) + "/extracted-import-" + std::to_string(SDL_GetTicksNS()); + if (!fs::create_directory(fs::u8path(stage), ec)) { + set_job("Could not extract game packages", true); + return {}; + } + std::string folder = stage + "/files", log = stage + "/progress", cancel = stage + "/cancel"; + std::string confirm = stage + "/confirm"; + if (!fs::create_directory(fs::u8path(folder), ec)) { + fs::remove(fs::u8path(stage), ec); + set_job("Could not extract game packages", true); + return {}; + } + std::vector args = {helper}; + if (*script) args.push_back(script); + args.insert(args.end(), {"--import-packages", "--out", folder, "--cancel", cancel, "--confirm", confirm}); + if (have_nxpatch) args.insert(args.end(), {"--nxpatch", nxpatch}); + args.insert(args.end(), {"--keys", keys.empty() ? std::string(rt_data_root()) + "/prod.keys" : keys}); + for (const auto &version : VERSIONS) + if (version.supported) args.insert(args.end(), {"--game-version", version.name}); + args.push_back("--"); + args.insert(args.end(), packages.begin(), packages.end()); + std::vector argv; + for (const auto &a : args) argv.push_back(a.c_str()); + argv.push_back(NULL); + + PlatProc process = plat_spawn(argv.data(), log.c_str(), false); + std::string error, pending; + std::vector items; + long log_offset = 0; + int result = process ? -1 : 1; + bool sent_cancel = false, sent_confirm = false; + while (process) { + result = plat_proc_wait(process, false); + // Reopen the growing log on each poll, as gamebuild does. On Windows the helper + // keeps its write handle open for the entire review. + if (FILE *stream = fopen(log.c_str(), "rb")) { + char buf[1024]; + if (fseek(stream, log_offset, SEEK_SET) == 0) { + while (size_t n = fread(buf, 1, sizeof buf, stream)) { + pending.append(buf, n); + log_offset += (long)n; + } + } + fclose(stream); + size_t start = 0; + for (size_t end; (end = pending.find('\n', start)) != std::string::npos; start = end + 1) { + std::string line = pending.substr(start, end - start); + if (!line.empty() && line.back() == '\r') line.pop_back(); + unsigned long long value; + if (sscanf(line.c_str(), "total\t%llu", &value) == 1) g_total = value, g_done = 0; // i18n-skip + else if (sscanf(line.c_str(), "progress\t%llu", &value) == 1) g_done = value; // i18n-skip + else if (line.compare(0, 8, "failure\t") == 0) error = line.substr(8); // i18n-skip + else if (line.compare(0, 5, "item\t") == 0) { // i18n-skip + size_t version = line.find('\t', 5); + if (version == std::string::npos) continue; + size_t filename = line.find('\t', version + 1); + if (filename != std::string::npos) + items.push_back({line.substr(5, version - 5), line.substr(version + 1, filename - version - 1), + line.substr(filename + 1)}); + } else if (line == "review") { + pthread_mutex_lock(&g_lock); + g_import_preview = items; + pthread_mutex_unlock(&g_lock); + } + } + pending.erase(0, start); + } + if (result != -1) break; + if (g_import_cancel && !sent_cancel) { + if (SDL_IOStream *file = SDL_IOFromFile(cancel.c_str(), "wb")) { // i18n-skip + SDL_CloseIO(file); + sent_cancel = true; + } + } + if (g_import_approved && !g_import_cancel && !sent_confirm) { + if (SDL_IOStream *file = SDL_IOFromFile(confirm.c_str(), "wb")) { // i18n-skip + SDL_CloseIO(file); + sent_confirm = true; + set_job("Extracting game packages..."); + } + } + SDL_Delay(50); + } + if (!result && !g_import_cancel) { + fs::remove(fs::u8path(log), ec); + fs::remove(fs::u8path(confirm), ec); + return folder; + } + fs::remove_all(fs::u8path(stage), ec); + if (error == "cancelled" || g_import_cancel) set_job("Package import cancelled."); + else if (error == "keys") set_job("Choose the keys file for NSP packages", true); + else if (error == "helper" || !process) set_job("Package reader is missing", true); + else if (error == "base") set_job("Add the matching base game NSP", true); + else if (error == "update") set_job("Add the version %s update NSP", true); + else if (error == "version") set_job(NOT_SUPPORTED, true); + else if (error == "title") set_job("No Breath of the Wild content was found", true); + else if (error == "space") set_job("Not enough free disk space", true); + else if (error == "conflict") set_job("Choose one copy of each game package", true); + else if (result) set_job("Could not extract game packages", true); + return {}; +} + +static void *import_thread(void *data) { + auto *packages = static_cast *>(data); + pthread_mutex_lock(&g_lock); + std::string keys = g_package_keys; + pthread_mutex_unlock(&g_lock); + set_job("Inspecting game packages..."); + std::string folder = import_packages(*packages, keys); + delete packages; + if (!folder.empty()) set_job("Packages extracted. Select Set up game files."); + pthread_mutex_lock(&g_lock); + if (!folder.empty()) g_src = folder; + g_import_finished = true; + g_import_preview.clear(); + g_importing = false; + g_busy = false; + pthread_mutex_unlock(&g_lock); + return NULL; +} + +static void SDLCALL picked_packages(void *, const char *const *files, int) { + if (!files) { set_job("Could not open the package picker", true); return; } + if (!files[0]) return; + pthread_mutex_lock(&g_lock); + if (g_busy) { pthread_mutex_unlock(&g_lock); return; } + g_packages_selected = true; + g_busy = g_importing = true; + g_import_cancel = false; + g_import_approved = false; + g_done = 0, g_total = 0, g_build_frac = -1, g_copy_skipped = false; + pthread_mutex_unlock(&g_lock); + auto *packages = new std::vector; + for (; *files; ++files) packages->push_back(*files); + pthread_t worker; + if (!pthread_create(&worker, NULL, import_thread, packages)) { + pthread_detach(worker); + return; + } + delete packages; + set_job("Could not extract game packages", true); + pthread_mutex_lock(&g_lock); + g_importing = false; + g_busy = false; + pthread_mutex_unlock(&g_lock); +} +#endif + // ------------------------------------------------------------------ the user's own Nintendo fonts (not shipped) // runtime/hle/pl.c loads fonts/ first, else a close substitute (Hiragino Sans). Import copies recognized files only. static const char *FONT_STD[] = {"nintendo_udsg-r_std_003.bfttf", "nintendo_udsg-r_std_003.ttf", @@ -2470,7 +2687,15 @@ static void left_shade(ImDrawList *bg, ImVec2 ds) { while (SDL_PollEvent(&e)) { if (page == SETTINGS && bind_capture_event(&e)) continue; // (waiting for a new binding: controls_ui.mm) if (!launcher_pad_event(e)) ImGui_ImplSDL3_ProcessEvent(&e); - if (e.type == SDL_EVENT_QUIT) exit(0); + if (e.type == SDL_EVENT_QUIT) { +#ifndef __APPLE__ + if (g_importing) { + g_import_cancel = true; + while (g_importing) SDL_Delay(50); + } +#endif + exit(0); + } if (e.type == SDL_EVENT_WINDOW_FOCUS_GAINED) { pthread_mutex_lock(&g_lock); bool b = g_busy; @@ -2481,10 +2706,16 @@ static void left_shade(ImDrawList *bg, ImVec2 ds) { // extraction finished: re-check pthread_mutex_lock(&g_lock); bool busy = g_busy; +#ifndef __APPLE__ + bool imported = g_import_finished; + g_import_finished = false; +#else + bool imported = false; +#endif RtDlcCheck dlc_st = g_dlc; pthread_mutex_unlock(&g_lock); g_file_size.set_suspended(busy); - if (was_busy && !busy) { + if (was_busy && !busy && !imported) { status = check_game_files(g_root); if (status.empty() && g_setup_only) { // set up: on into the game (after the first-start note) if (g_settings.menu_tip_seen) play = true; @@ -2843,6 +3074,9 @@ static void left_shade(ImDrawList *bg, ImVec2 ds) { pthread_mutex_lock(&g_lock); std::string src = g_src, job = g_job, job_hint = g_job_hint; bool failed = g_job_failed; +#ifndef __APPLE__ + bool packages_selected = g_packages_selected, keys_selected = !g_package_keys.empty(); +#endif pthread_mutex_unlock(&g_lock); bool ready = status.empty() && !busy; // (set up: the window offers to delete them, or set them up again) bool shipped_release = post_update_shipped(); @@ -3008,6 +3242,19 @@ static void left_shade(ImDrawList *bg, ImVec2 ds) { if (opt_action("Game files folder", src_v.c_str(), src_d.c_str(), true)) SDL_ShowOpenFolderDialog(picked, NULL, win, NULL, false); if (!src.empty()) check_left_of_value(src_v); +#ifndef __APPLE__ + std::string packages_value = tr(packages_selected ? "Selected" : "Choose..."); + if (busy) opt_disable_next(); + if (opt_action("Import game packages", packages_value.c_str(), + "Extract NUP or NSP files into a folder for setup.", true)) + SDL_ShowOpenFileDialog(picked_packages, NULL, win, package_filter, 1, NULL, true); + if (packages_selected) check_left_of_value(packages_value); + std::string keys_value = tr(keys_selected ? "Selected" : "Choose..."); + if (busy) opt_disable_next(); + if (opt_action("Choose the keys file for NSP packages", keys_value.c_str(), "", true)) + SDL_ShowOpenFileDialog(picked_package_keys, NULL, win, key_filter, 1, NULL, false); + if (keys_selected) check_left_of_value(keys_value); +#endif if (busy) opt_disable_next(); { static char path_buf[1024]; @@ -3182,7 +3429,11 @@ static void left_shade(ImDrawList *bg, ImVec2 ds) { g_confirm_delete = g_confirm_setup = false, back = true; // (B / Esc: back out of the question first) content_focus = ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows); static bool test_busy = getenv("SAVAGEWIND_LAUNCHER_SHOT") && strstr(getenv("SAVAGEWIND_LAUNCHER_SHOT"), ":extracting"); - if (busy || test_busy) { // working: everything dimmed, a card with a progress bar in front (input waits) + bool review = false; +#ifndef __APPLE__ + if (busy && g_importing) review = draw_package_review(ds); +#endif + if ((busy || test_busy) && !review) { // working: everything dimmed, a card with a progress bar in front ImDrawList *fg = ImGui::GetForegroundDrawList(); ImVec2 o = ImGui::GetMainViewport()->Pos; fg->AddRectFilled(o, ImVec2(o.x + ds.x, o.y + ds.y), IM_COL32(0, 0, 0, 150)); @@ -3191,9 +3442,18 @@ static void left_shade(ImDrawList *bg, ImVec2 ds) { bool recompiling = g_build_frac >= 0, dlc_check = g_dlc_checking; const char *title = tr(dlc_check ? "Downloadable content" : recompiling ? "Recompiling the game" : "Setting up the game files"); - const char *const notes[] = {tr("This only needs to be done once and may take a while."), - tr("Esc or B stops it: what is done is kept.")}; + const char *notes[] = {tr("This only needs to be done once and may take a while."), + tr("Esc or B stops it: what is done is kept.")}; int nnotes = dlc_check ? 0 : recompiling ? 1 : 0; +#ifndef __APPLE__ + if (g_importing) { + title = tr("Import game packages"); + notes[0] = tr("Esc or B cancels the import."); + nnotes = 1; + if (ImGui::IsKeyPressed(ImGuiKey_Escape, false) || ImGui::IsKeyPressed(ImGuiKey_GamepadFaceRight, false)) + g_import_cancel = true; + } +#endif if (update_apply_progress() >= 0) { f = update_apply_progress(); title = tr("Updating Savage Wind"); diff --git a/tools/build_package_helper.sh b/tools/build_package_helper.sh new file mode 100644 index 00000000..877d8428 --- /dev/null +++ b/tools/build_package_helper.sh @@ -0,0 +1,15 @@ +#!/bin/bash +# Publish the NSP reader with its runtime so release users need no .NET installation. +set -euo pipefail +cd "$(dirname "$0")/.." +rid=${1:?target .NET runtime identifier} +out=${2:?output directory} +dotnet publish tools/nxpatch/nxpatch.csproj -c Release -r "$rid" --self-contained true \ + -p:PublishSingleFile=true -p:EnableCompressionInSingleFile=true \ + -p:IncludeNativeLibrariesForSelfExtract=true -p:DebugType=none \ + --artifacts-path build/nxpatch-artifacts -o "$out" +runtime="$(dotnet --list-runtimes | tr -d '\r' | sed -n 's/^Microsoft\.NETCore\.App 10\..* \[\(.*\)\]$/\1/p' | tail -1)" +: "${runtime:?.NET 10 runtime location unavailable}" +if command -v cygpath >/dev/null; then runtime="$(cygpath -u "$runtime")"; fi +cp "$runtime/../../LICENSE.txt" "$out/dotnet-LICENSE.txt" +cp "$runtime/../../ThirdPartyNotices.txt" "$out/dotnet-ThirdPartyNotices.txt" diff --git a/tools/gen.py b/tools/gen.py index 02b439e8..fa7aa9d3 100644 --- a/tools/gen.py +++ b/tools/gen.py @@ -32,6 +32,10 @@ import time from collections import Counter +if __name__ == '__main__' and sys.argv[1:2] == ['--import-packages']: + from package_import import main as import_packages + sys.exit(import_packages(sys.argv[2:])) + import capstone import unicorn as uc from unicorn import arm64_const as A diff --git a/tools/linux/Containerfile b/tools/linux/Containerfile index bafb4494..70973c08 100644 --- a/tools/linux/Containerfile +++ b/tools/linux/Containerfile @@ -20,3 +20,13 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && apt-get install -y --no-install-recommends python3.12 python3.12-venv python3.12-dev clang-21 lld-21 llvm-21 \ && rm -rf /var/lib/apt/lists/* \ && for t in clang clang++ ld.lld llvm-ar llvm-nm llvm-ranlib llvm-strip; do ln -sf $t-21 /usr/bin/$t; done + +# The amd64 container publishes the self-contained NSP helper for both AppImage targets. +ARG DOTNET_SDK=10.0.401 +RUN if [ "$(uname -m)" = x86_64 ]; then \ + mkdir -p /opt/dotnet \ + && curl -fsSL "https://dotnetcli.blob.core.windows.net/dotnet/Sdk/$DOTNET_SDK/dotnet-sdk-$DOTNET_SDK-linux-x64.tar.gz" -o /tmp/dotnet.tar.gz \ + && tar -xzf /tmp/dotnet.tar.gz -C /opt/dotnet \ + && rm /tmp/dotnet.tar.gz \ + && ln -s /opt/dotnet/dotnet /usr/local/bin/dotnet; \ + fi diff --git a/tools/linux/gen_helper.sh b/tools/linux/gen_helper.sh index e7a4901a..9629eb17 100755 --- a/tools/linux/gen_helper.sh +++ b/tools/linux/gen_helper.sh @@ -6,10 +6,10 @@ set -euo pipefail cd "$(dirname "$0")/../.." L=$PWD/build/linux/$1 V=$L/gen-venv -if [ ! -f "$V/.ok" ]; then +if [ ! -f "$V/.ok" ] || [ tools/linux/gen_helper.sh -nt "$V/.ok" ]; then rm -rf "$V" && python3.12 -m venv "$V" "$V/bin/python" -m pip install -q --upgrade pip - "$V/bin/python" -m pip install -q capstone==5.0.9 unicorn==2.1.4 lz4==4.4.5 pyinstaller==6.22.3 + "$V/bin/python" -m pip install -q capstone==5.0.9 unicorn==2.1.4 lz4==4.4.5 pyinstaller==6.22.3 zstandard==0.25.0 touch "$V/.ok" fi "$V/bin/python" -m PyInstaller --noconfirm --clean --log-level WARN --distpath "$L/helper" --workpath "$L/pyinstaller" \ diff --git a/tools/linux/package.sh b/tools/linux/package.sh index 34976b79..395ba973 100755 --- a/tools/linux/package.sh +++ b/tools/linux/package.sh @@ -53,7 +53,12 @@ mkdir "$APPDIR/usr/bin/colour-luts" && cp third_party/luts/*.cube third_party/lu cp README.md LICENSE "$APPDIR/usr/bin/" # (licenses and source links of the bundled components: README "License") cp recomplauncher.json "$APPDIR/" # (RecompLauncher reads /recomplauncher.json from inside the AppImage) [ -d "$L/helper/swgen" ] || { echo "no game code generator helper: tools/linux/gen_helper.sh $ARCH first"; exit 1; } -cp -R "$L/helper/swgen" build/zig "$APPDIR/usr/bin/" +case "$ARCH" in + x86_64) RID=linux-x64 ;; + aarch64) RID=linux-arm64 ;; +esac +bash tools/build_package_helper.sh "$RID" "$L/helper/nxpatch" +cp -R "$L/helper/swgen" "$L/helper/nxpatch" build/zig "$APPDIR/usr/bin/" mkdir "$APPDIR/usr/bin/gamelib-src" cp runtime/cpu.h runtime/simd.h runtime/simd_fp.h runtime/simd_softfma.h runtime/gamelib.h tools/gamelib_entry.c \ runtime/hle/hle_symbols.txt "$APPDIR/usr/bin/gamelib-src/" diff --git a/tools/nxpatch/LICENSE b/tools/nxpatch/LICENSE new file mode 100644 index 00000000..1d8ab8f6 --- /dev/null +++ b/tools/nxpatch/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 HereOrCode + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/nxpatch/LibHac-LICENSE.txt b/tools/nxpatch/LibHac-LICENSE.txt new file mode 100644 index 00000000..2a5c9c96 --- /dev/null +++ b/tools/nxpatch/LibHac-LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright © 2018-2022 Alex Barney + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/nxpatch/Program.cs b/tools/nxpatch/Program.cs new file mode 100644 index 00000000..d1c6857d --- /dev/null +++ b/tools/nxpatch/Program.cs @@ -0,0 +1,421 @@ +// nxpatch — reads Nintendo Switch NSP files for NSPtoNUP (built on LibHac). +// NCAs are read directly from the NSP; nothing is unpacked to disk first. +// +// Savage Wind invokes this helper from tools/package_import.py. See README.md for attribution. +// +// Title keys: common tickets (.tik) inside the NSP come first (personalized tickets cannot be used), +// then title.keys. Key values are never printed. +// +// The protocol reports stable error codes. File names and key material are kept out of status output. + +using System.Buffers.Binary; +using LibHac; +using LibHac.Common; +using LibHac.Common.Keys; +using LibHac.Fs; +using LibHac.Fs.Fsa; +using LibHac.FsSystem; +using LibHac.Spl; +using LibHac.Tools.Fs; +using LibHac.Tools.FsSystem; +using LibHac.Tools.FsSystem.NcaUtils; + +const string Usage = """ + Usage: + nxpatch identify -k ... + nxpatch extract -k [--titlekeys ] [--base ] [--update --version ] [--dlc ]... --out + """; + +if (args.Length == 0) { Console.Error.WriteLine(Usage); return 2; } +string command = args[0]; +var single = new Dictionary(); +var multi = new Dictionary>(); +var positional = new List(); +for (int i = 1; i < args.Length; i++) +{ + string arg = args[i]; + if (!arg.StartsWith("-")) { positional.Add(arg); continue; } + if (i + 1 >= args.Length) { Console.Error.WriteLine($"Missing value for {arg}\n{Usage}"); return 2; } + string value = args[++i]; + single[arg] = value; + if (!multi.TryGetValue(arg, out var list)) multi[arg] = list = new List(); + list.Add(value); +} +string? Option(string name) => single.TryGetValue(name, out var value) ? value : null; +List Options(string name) => multi.TryGetValue(name, out var values) ? values : new List(); + +string? keysPath = Option("-k"); +if (keysPath is null) { Console.Error.WriteLine(Usage); return 2; } + +try +{ + switch (command) + { + case "identify": + { + if (positional.Count == 0) { Console.Error.WriteLine(Usage); return 2; } + var keySet = Keys.Load(keysPath, Option("--titlekeys")); + foreach (string path in positional) + { + try + { + using var package = new Package(path, keySet); + foreach (var meta in package.ReadMetas()) + Console.WriteLine($"content\t{meta.Kind}\t{meta.TitleId:X16}\t{meta.Version}"); + } + catch (Exception error) + { + var failure = Failure.From(error); + Console.WriteLine($"error\t{failure.Code}"); + } + } + return 0; + } + + case "extract": + { + string? baseNsp = Option("--base"), output = Option("--out"); + if (output is null) { Console.Error.WriteLine(Usage); return 2; } + var keySet = Keys.Load(keysPath, Option("--titlekeys")); + uint? version = Option("--version") is string value ? uint.Parse(value) : null; + long? free = Option("--free") is string bytes ? long.Parse(bytes) : null; + return Extractor.Run(keySet, baseNsp, Option("--update"), version, Options("--dlc"), output, free, + Option("--versions") == "1", Option("--require-version")); + } + + default: + Console.Error.WriteLine(Usage); + return 2; + } +} +catch (Exception error) +{ + var failure = Failure.From(error); + Console.Error.WriteLine($"nxpatch-error\t{failure.Code}"); + return 1; +} + +/// An error with a stable code (for callers to localize), an optional detail and an English message. +sealed class Failure(string code, string detail, string message) : Exception(message) +{ + public string Code { get; } = code; + public string Detail { get; } = detail; + + /// Maps any exception to a failure; only the reason is reported, never a stack trace or key value. + public static Failure From(Exception error) => error switch + { + Failure failure => failure, + MissingKeyException missing when missing.Type == LibHac.Common.Keys.KeyType.Title => new Failure( + "missing_title_key", missing.Name ?? "", + $"No title key: the NSP has no usable common ticket and title.keys has no entry (rights ID {missing.Name})"), + MissingKeyException missing => new Failure( + "missing_key", missing.Name ?? "", + $"prod.keys is missing {missing.Name}; use prod.keys that match the game's firmware version"), + _ => new Failure("unknown", "", OneLine(error.Message)), + }; + + private static string OneLine(string text) => text.Replace('\t', ' ').Replace('\n', ' ').Replace('\r', ' '); +} + +static class Keys +{ + private static string? titleKeysFile; + private static readonly HashSet loadedTitleKeys = new(); + + /// Reads prod.keys only. title.keys is loaded after the NSP's tickets are imported, + /// so a rights ID that already has a key from a ticket is not overwritten (tickets take priority). + public static KeySet Load(string prodKeys, string? titleKeys) + { + var keySet = KeySet.CreateDefaultKeySet(); + ExternalKeyReader.ReadKeyFile(keySet, prodKeys, null, null, logger: null); + titleKeysFile = titleKeys; + return keySet; + } + + public static void LoadTitleKeysOnce(KeySet keySet) + { + if (titleKeysFile is null || !loadedTitleKeys.Add(keySet)) return; + ExternalKeyReader.ReadKeyFile(keySet, null, titleKeysFile, null, logger: null); + } + + /// Common ticket (title key type 0): rights ID at body+0x160, encrypted title key at body+0x40. + public static void ImportTicket(KeySet keySet, byte[] ticket) + { + if (ticket.Length < 4) return; + int body = BinaryPrimitives.ReadUInt32LittleEndian(ticket) switch + { + 0x10000 or 0x10003 => 0x240, + 0x10001 or 0x10004 => 0x140, + 0x10002 or 0x10005 => 0x80, + _ => -1, + }; + if (body < 0 || ticket.Length < body + 0x170 || ticket[body + 0x141] != 0) return; + var rightsId = new RightsId(ticket.AsSpan(body + 0x160, 0x10)); + var key = new AccessKey(ticket.AsSpan(body + 0x40, 0x10)); + keySet.ExternalKeySet.Add(rightsId, key); + } +} + +/// One NSP: the NCAs and tickets inside its PFS0. +sealed class Package : IDisposable +{ + public readonly string Path; + private readonly KeySet keySet; + private readonly LocalStorage storage; + private readonly PartitionFileSystem pfs = new(); + private readonly List names; + + public Package(string path, KeySet keySet) + { + Path = path; + this.keySet = keySet; + storage = new LocalStorage(path, FileAccess.Read); + if (pfs.Initialize(storage).IsFailure()) throw new Failure("invalid_nsp", "", "Not a valid NSP file"); + names = pfs.EnumerateEntries("/", "*").Where(e => e.Type == DirectoryEntryType.File).Select(e => e.Name).ToList(); + if (names.Any(n => n.EndsWith(".ncz"))) + throw new Failure("nsz_unsupported", "", "This is an NSZ package; decompress it to NSP first"); + foreach (string name in names.Where(n => n.EndsWith(".tik"))) Keys.ImportTicket(keySet, ReadAll(name)); + Keys.LoadTitleKeysOnce(keySet); + } + + private IStorage OpenStorage(string name) + { + using var file = new UniqueRef(); + pfs.OpenFile(ref file.Ref, ("/" + name).ToU8Span(), OpenMode.Read).ThrowIfFailure(); + return new FileStorage(file.Release()); + } + + private byte[] ReadAll(string name) + { + using var file = OpenStorage(name); + file.GetSize(out long size).ThrowIfFailure(); + if (size > 64 * 1024) throw new Failure("bad_ticket", "", "Ticket is too large"); + var data = new byte[size]; + file.Read(0, data).ThrowIfFailure(); + return data; + } + + public Nca OpenNca(string name) => new(keySet, OpenStorage(name)); + + /// Finds an NCA by content type (skipping the Meta NCA); returns the largest when there are several. + public Nca? FindNca(Meta meta, params NcaContentType[] types) + { + Nca? best = null; + long bestSize = -1; + foreach (string name in names.Where(meta.ContentNames.Contains)) + { + var nca = OpenNca(name); + if (!types.Contains(nca.Header.ContentType)) continue; + nca.BaseStorage.GetSize(out long size).ThrowIfFailure(); + if (size > bestSize) { best = nca; bestSize = size; } + } + return best; + } + + public record Meta(string Kind, ulong TitleId, uint Version, HashSet ContentNames); + + /// cnmt header: TitleId u64 @0x0, Version u32 @0x8, Type u8 @0xC (0x80 base, 0x81 update, 0x82 DLC). + public IEnumerable ReadMetas() + { + foreach (string metaName in names.Where(n => n.EndsWith(".cnmt.nca", StringComparison.OrdinalIgnoreCase))) + { + var meta = ReadMeta(metaName); + if (meta is not null) yield return meta; + } + } + + private Meta? ReadMeta(string metaName) + { + var nca = OpenNca(metaName); + using var fs = nca.OpenFileSystem(0, IntegrityCheckLevel.None); + var entry = fs.EnumerateEntries("/", "*.cnmt").FirstOrDefault() + ?? throw new Failure("bad_cnmt", "", "The content metadata is damaged"); + using var file = new UniqueRef(); + fs.OpenFile(ref file.Ref, entry.FullPath.ToU8Span(), OpenMode.Read).ThrowIfFailure(); + var header = new byte[0x20]; + file.Get.Read(out long read, 0, header).ThrowIfFailure(); + if (read != header.Length) throw new Failure("bad_cnmt", "", "The content metadata is damaged"); + string kind = header[0x0C] switch + { + 0x80 => "base", + 0x81 => "update", + 0x82 => "dlc", + _ => "", + }; + if (kind.Length == 0) return null; + int offset = 0x20 + BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(0xE)); + int count = BinaryPrimitives.ReadUInt16LittleEndian(header.AsSpan(0x10)); + var contentNames = new HashSet(StringComparer.OrdinalIgnoreCase); + var content = new byte[0x38]; + for (int i = 0; i < count; i++) + { + file.Get.Read(out read, offset + i * content.Length, content).ThrowIfFailure(); + if (read != content.Length) throw new Failure("bad_cnmt", "", "Content entry is truncated"); + contentNames.Add(Convert.ToHexString(content.AsSpan(0x20, 16)) + ".nca"); + } + return new Meta(kind, BinaryPrimitives.ReadUInt64LittleEndian(header), + BinaryPrimitives.ReadUInt32LittleEndian(header.AsSpan(8)), contentNames); + } + + public void Dispose() => storage.Dispose(); +} + +/// Copies a file system to a local directory and reports progress in bytes. +sealed class Copier : IProgressReport +{ + private readonly Action? onProgress; + private long done; + + private Copier(Action? onProgress) { this.onProgress = onProgress; } + + public static long TotalSize(IFileSystem fs) + { + var paths = new HashSet(StringComparer.OrdinalIgnoreCase); + long total = 0; + foreach (var entry in fs.EnumerateEntries("/", "*", SearchOptions.RecurseSubdirectories)) + { + string name = entry.Name; + string stem = name.Split('.', 2)[0].TrimEnd(' ').ToUpperInvariant(); + if (name.Length == 0 || name.EndsWith('.') || name.EndsWith(' ') || + name.Any(c => c < ' ' || "<>:\"/\\|?*".Contains(c)) || + stem is "CON" or "PRN" or "AUX" or "NUL" or "CONIN$" or "CONOUT$" || + (stem.Length == 4 && (stem.StartsWith("COM") || stem.StartsWith("LPT")) && + "123456789¹²³".Contains(stem[3])) || !paths.Add(entry.FullPath)) + throw new Failure("unsafe_path", "", "Invalid or colliding file name"); + if (entry.Type == DirectoryEntryType.File) total = checked(total + entry.Size); + } + return total; + } + + public static void Copy(IFileSystem source, string directory, Action? onProgress) + { + Directory.CreateDirectory(directory); + using var target = new LocalFileSystem(directory); + source.CopyDirectory(target, "/", "/", new Copier(onProgress)).ThrowIfFailure(); + } + + public void Report(long value) { } + public void ReportAdd(long value) { done += value; onProgress?.Invoke(done); } + public void SetTotal(long value) { } + public void LogMessage(string message) { } +} + +static class Extractor +{ + private static string ReadVersion(IFileSystem fs, string path, long offset, int length) + { + using var file = new UniqueRef(); + if (fs.OpenFile(ref file.Ref, path.ToU8Span(), OpenMode.Read).IsFailure()) return ""; + if (file.Get.GetSize(out long size).IsFailure() || size <= offset) return ""; + var buffer = new byte[(int)Math.Min(length, size - offset)]; + if (file.Get.Read(out long read, offset, buffer).IsFailure()) return ""; + string version = System.Text.Encoding.UTF8.GetString(buffer, 0, (int)read) + .Split('\0', 2)[0].TrimStart('\uFEFF').Trim(); + return Version.TryParse(version, out _) ? version : ""; + } + + private static string ControlVersion(Package package, Package.Meta meta) + { + var control = package.FindNca(meta, NcaContentType.Control); + if (control is null || !control.CanOpenSection(NcaSectionType.Data)) return ""; + using var fs = control.OpenFileSystem(NcaSectionType.Data, IntegrityCheckLevel.None); + return ReadVersion(fs, "/control.nacp", 0x3060, 0x10); // NACP DisplayVersion + } + + public static int Run(KeySet keySet, string? basePath, string? updatePath, uint? version, List dlcPaths, + string output, long? free, bool versions, string? requiredVersion) + { + using var basePackage = basePath is null ? null : new Package(basePath, keySet); + var baseMeta = basePackage?.ReadMetas().Single(meta => meta.Kind == "base" && meta.TitleId == 0x01007EF00011E000UL); + var baseNca = baseMeta is null ? null : basePackage!.FindNca(baseMeta, NcaContentType.Program) + ?? throw new Failure("nca_not_found", "program", "No Program NCA found in the base"); + + var jobs = new List<(IFileSystem Fs, string Dir)>(); + var packages = new List(); + void Add(Nca nca, Nca? patch, NcaSectionType type, string dir, string kind = "", Func? fallback = null) + { + if (versions && type == NcaSectionType.Code) return; + bool available = nca.CanOpenSection(type) || (patch?.CanOpenSection(type) ?? false); + if (!available) throw new Failure("missing_section", "", "Content section is missing"); + var fs = patch is null ? nca.OpenFileSystem(type, IntegrityCheckLevel.None) + : nca.OpenFileSystemWithPatch(patch, type, IntegrityCheckLevel.None); + if (kind == "update" && requiredVersion is not null && + ReadVersion(fs, "/System/Version.txt", 0, 64) != requiredVersion) + { + fs.Dispose(); + throw new Failure("bad_game_version", "", "The merged RomFS version changed"); + } + if (!versions) { jobs.Add((fs, dir)); return; } + using (fs) + { + string path = kind.StartsWith("aoc") ? "/System/AocVersion.txt" : "/System/Version.txt"; + string display = ReadVersion(fs, path, 0, 64); + if (display.Length == 0 && fallback is not null) display = fallback(); + if (display.Length != 0) Console.WriteLine($"version\t{kind}\t{display}"); + } + } + + if (updatePath is not null) + { + var package = new Package(updatePath, keySet); + packages.Add(package); + var meta = package.ReadMetas().Single(m => m.Kind == "update" && m.Version == version && + m.TitleId == 0x01007EF00011E800UL); + if (baseNca is null) + throw new Failure("update_mismatch", System.IO.Path.GetFileName(updatePath), + $"{System.IO.Path.GetFileName(updatePath)} is not an update for this game"); + var patch = package.FindNca(meta, NcaContentType.Program) + ?? throw new Failure("nca_not_found", "program", "No Program NCA found in the update"); + if (versions) + Add(baseNca, null, NcaSectionType.Data, output, "base", + () => ControlVersion(basePackage!, baseMeta!)); + Add(baseNca, patch, NcaSectionType.Code, System.IO.Path.Combine(output, "exefs")); + Add(baseNca, patch, NcaSectionType.Data, System.IO.Path.Combine(output, "romfs"), "update"); + } + else if (baseNca is not null) + { + Add(baseNca, null, NcaSectionType.Code, System.IO.Path.Combine(output, "exefs")); + Add(baseNca, null, NcaSectionType.Data, System.IO.Path.Combine(output, "romfs"), "base", + () => ControlVersion(basePackage!, baseMeta!)); + } + + foreach (string dlcPath in dlcPaths) + { + var parts = dlcPath.Split('|', 3); + ulong title = Convert.ToUInt64(parts[0], 16); + uint dlcVersion = uint.Parse(parts[1]); + var package = new Package(parts[2], keySet); + packages.Add(package); + var meta = package.ReadMetas().Single(m => m.Kind == "dlc" && m.TitleId == title && m.Version == dlcVersion + && (title == 0x01007EF00011F001UL || title == 0x01007EF00011F002UL)); + var data = package.FindNca(meta, NcaContentType.PublicData, NcaContentType.Data) + ?? throw new Failure("nca_not_found", "data", $"No data NCA found in DLC {meta.TitleId:X16}"); + string kind = title == 0x01007EF00011F001UL ? "aoc1" : "aoc2"; + Add(data, null, NcaSectionType.Data, System.IO.Path.Combine(output, kind), kind); + } + + if (versions) return 0; + long total = jobs.Sum(job => Copier.TotalSize(job.Fs)); + if (free < total) + throw new Failure("disk_space", "", "Not enough free disk space"); + Console.WriteLine($"total\t{total}"); + long finished = 0, reported = 0; + var clock = System.Diagnostics.Stopwatch.StartNew(); + foreach (var job in jobs) + { + long start = finished; + Copier.Copy(job.Fs, job.Dir, done => + { + finished = start + done; + // At most one progress line every 0.25 seconds + if (clock.ElapsedMilliseconds - reported < 250) return; + reported = clock.ElapsedMilliseconds; + Console.WriteLine($"progress\t{finished}"); + }); + job.Fs.Dispose(); + } + Console.WriteLine($"progress\t{total}"); + packages.ForEach(package => package.Dispose()); + return 0; + } +} diff --git a/tools/nxpatch/README.md b/tools/nxpatch/README.md new file mode 100644 index 00000000..ec441cfa --- /dev/null +++ b/tools/nxpatch/README.md @@ -0,0 +1,11 @@ +# NSP reader + +Adapted from HereOrCode's MIT-licensed `tools/nxpatch` at commit +`7ef602fe8e7c46e357febb897ad8b06c2892260c`. Savage Wind uses it as a +subprocess to inventory NSPs and extract selected base, update and DLC content. +It matches each NCA to its CNMT entry and supports several content records in +one NSP. An NSP patch requires the original base NSP. DLC can be read by itself. + +`make package-helper` publishes the helper with the .NET 10 runtime. +The helper also uses LibHac 0.19.0. The corresponding license notices are +included with release builds. diff --git a/tools/nxpatch/nxpatch.csproj b/tools/nxpatch/nxpatch.csproj new file mode 100644 index 00000000..e3388407 --- /dev/null +++ b/tools/nxpatch/nxpatch.csproj @@ -0,0 +1,13 @@ + + + Exe + net10.0 + enable + enable + true + + + + + + diff --git a/tools/package_import.py b/tools/package_import.py new file mode 100644 index 00000000..b5a6fb9d --- /dev/null +++ b/tools/package_import.py @@ -0,0 +1,366 @@ +"""Extract selected BOTW packages into an empty launcher-owned directory.""" + +import argparse +from contextlib import ExitStack +from dataclasses import dataclass +import hashlib +import io +from pathlib import Path, PureWindowsPath +from queue import Empty, SimpleQueue +import re +import shutil +import struct +import subprocess +import sys +from threading import Thread +import time + +from package_nup import format as nup +from package_nup.read import NupReader, PackageInfo + + +BASE = 0x01007EF00011E000 +UPDATE = BASE + 0x800 +DLC = {BASE + 0x1001: "aoc1", BASE + 0x1002: "aoc2"} +BLOCK = 1024 * 1024 + + +class PackageError(Exception): + pass + + +@dataclass(frozen=True) +class Content: + path: Path + kind: str + title: int + version: int + reader: NupReader | None = None + package: PackageInfo | None = None + + +class Extent(io.RawIOBase): + def __init__(self, archive, start, length): + self.archive = archive + self.offset = start + self.end = start + length + + def readable(self): + return True + + def readinto(self, target): + count = min(len(target), self.end - self.offset) + target[:count] = self.archive[self.offset:self.offset + count] + self.offset += count + return count + + +def blocks(reader, index): + _, size, digest, offset, stored, codec = reader.file_info(index) + if codec == nup.CODEC_RAW and stored != size: + raise PackageError("invalid") + if not size and (offset or stored or codec != nup.CODEC_RAW): + raise PackageError("invalid") + + source = io.BufferedReader(Extent(reader._mm, offset, stored), BLOCK) + with ExitStack() as stack: + stack.enter_context(source) + if codec == nup.CODEC_ZSTD: + import zstandard + frame = zstandard.get_frame_parameters(source.peek(18)) + if frame.content_size != size or frame.window_size > 128 * BLOCK: + raise PackageError("invalid") + source = stack.enter_context( + zstandard.ZstdDecompressor() + .stream_reader(source, read_across_frames=True)) + hashed = hashlib.sha256() + remaining = size + while data := source.read(min(BLOCK, remaining + 1)): + remaining -= len(data) + if remaining < 0: + raise PackageError("invalid") + hashed.update(data) + yield data + if remaining or hashed.digest() != digest: + raise PackageError("invalid") + + +def members(reader, root, folder): + pending = [(root, folder)] + visited = set() + while pending: + directory, target = pending.pop() + if directory in visited: + raise PackageError("invalid") + visited.add(directory) + _, first, count = reader.dirs[directory] + names = set() + for node in reader.children[first:first + count]: + is_dir = node < reader.dir_count + index = node if is_dir else node - reader.dir_count + if not is_dir and index >= reader.file_count: + raise PackageError("invalid") + name = (reader.dirs if is_dir else reader.files)[index][0].decode("utf-8") + if (not name or name.endswith((".", " ")) or PureWindowsPath(name).is_reserved() + or any(ch in '<>:"/\\|?*' or ord(ch) < 32 for ch in name) + or name.casefold() in names): + raise PackageError("invalid") + names.add(name.casefold()) + if is_dir: + pending.append((index, target / name)) + else: + yield target / name, index + + +def run_nxpatch(args, command, options): + argv = [str(args.nxpatch), command, "-k", str(args.keys)] + if command == "extract": + argv += ["--free", str(shutil.disk_usage(args.out).free)] + titlekeys = args.keys.with_name("title.keys") + if titlekeys.is_file(): + argv += ["--titlekeys", str(titlekeys)] + # Capture the protocol only. Helper diagnostics can contain player paths. + errors = set() + records = [] + with subprocess.Popen(argv + options, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, + encoding="utf-8", errors="replace") as child: + lines = SimpleQueue() + + def read_lines(): + try: + for line in child.stdout: + lines.put(line) + finally: + lines.put(None) + + reader = Thread(target=read_lines, daemon=True) + reader.start() + while True: + if args.cancel.exists(): + child.kill() + reader.join() + raise PackageError("cancelled") + try: + line = lines.get(timeout=0.1) + except Empty: + continue + if line is None: + break + fields = line.rstrip("\r\n").split("\t") + if fields[0] == "content" and len(fields) == 4: + records.append(fields[1:]) + elif fields[0] == "version" and len(fields) == 3: + records.append(fields[1:]) + elif fields[0] == "nxpatch-error" and len(fields) >= 2: + errors.add(fields[1]) + elif fields[0] == "error": + errors.add(fields[1] if len(fields) >= 2 else "invalid") + elif fields[0] in ("total", "progress") and len(fields) == 2 and fields[1].isdigit(): + if command == "extract": + print(line.rstrip(), flush=True) + if child.wait() or errors: + if errors & {"missing_key", "missing_title_key"}: + raise PackageError("keys") + if "bad_game_version" in errors: + raise PackageError("version") + raise PackageError("space" if "disk_space" in errors else "invalid") + return records + + +def inventory(args, stack): + for path in dict.fromkeys(path.resolve(strict=True) for path in args.packages): + if args.cancel.exists(): + raise PackageError("cancelled") + if path.suffix.lower() == ".nup": + reader = stack.enter_context(NupReader(path)) + for p in reader.packages: + yield Content(path, {"addon": "dlc"}.get(p.kind_name, p.kind_name), + p.title_id, p.version, reader, p) + elif path.suffix.lower() == ".nsp": + if args.nxpatch is None or not args.nxpatch.is_file(): + raise PackageError("helper") + if args.keys is None or not args.keys.is_file(): + raise PackageError("keys") + for kind, title, version in run_nxpatch(args, "identify", [str(path)]): + yield Content(path, kind, int(title, 16), int(version)) + else: + raise PackageError("invalid") + + +def newest(entries): + ordered = sorted(entries, key=lambda e: -e.version) + if len(ordered) > 1 and ordered[0].version == ordered[1].version: + raise PackageError("conflict") + return ordered[0] if ordered else None + + +def display_version(value): + value = value.split("\0", 1)[0].strip() + return value if re.fullmatch(r"[0-9]+(?:\.[0-9]+){1,3}", value) else "" + + +def nup_version(entry, *, allow_metadata=True): + reader, package = entry.reader, entry.package + + def child(directory, name, is_dir): + if directory == nup.NO_DIR: + return nup.NO_DIR + _, start, count = reader.dirs[directory] + for node in reader.children[start:start + count]: + if node < reader.dir_count: + if is_dir and reader.dirs[node][0] == name: + return node + elif not is_dir: + index = node - reader.dir_count + if index < reader.file_count and reader.file_info(index)[0] == name: + return index + return nup.NO_DIR + + system = child(package.romfs_dir, b"System", True) + index = child(system, b"AocVersion.txt" if entry.kind == "dlc" else b"Version.txt", False) + if index != nup.NO_DIR and reader.file_info(index)[1] <= 64: + version = display_version(b"".join(blocks(reader, index)).decode("utf-8-sig", errors="replace")) + if version: + return version + if not allow_metadata or entry.kind == "base": + # Some writers put the bundle's updated display version on the base record. + return "" + # The published spec and older reference writers use different TLV numbers. + start, end = package.meta_offset, package.meta_offset + package.meta_size + while start + nup._tlv_s.size <= end: + kind, _, size = nup._tlv_s.unpack_from(reader._mm, start) + start += nup._tlv_s.size + if start + size > end: + break + if kind in (4, nup.TLV_DISPLAY_VERSION) and size <= 64: + version = display_version(reader._mm[start:start + size].decode("utf-8", errors="replace")) + if version: + return version + start += size + return "" + + +def review(args, selected, nsp_versions): + if args.confirm is None: + return + for entry in selected: + kind = DLC[entry.title] if entry.kind == "dlc" else entry.kind + name = "".join(ch if ord(ch) >= 32 else " " for ch in entry.path.name) + version = nup_version(entry) if entry.reader else display_version(nsp_versions.get(kind, "")) + print(f"item\t{kind}\t{version}\t{name}", flush=True) + print("review", flush=True) + while not args.confirm.exists(): + if args.cancel.exists(): + raise PackageError("cancelled") + time.sleep(0.1) + if args.cancel.exists(): + raise PackageError("cancelled") + + +def extract(args, entries): + base = [e for e in entries if e.kind == "base" and e.title == BASE] + # Some NUP producers record the application ID on the update instead of the patch ID. + updates = [e for e in entries if e.kind == "update" and + (e.title == UPDATE or (e.reader and e.title == BASE))] + addons = [e for e in entries if e.kind == "dlc" and e.title in DLC] + if not base and not updates and not addons: + raise PackageError("title") + + game = newest(updates) or newest(base) + selected = [game] if game else [] + nsp_options = [] + if game and not game.reader: + if game.kind != "update": + raise PackageError("update") + nsp_base = newest(e for e in base if e.reader is None) + if not nsp_base: + raise PackageError("base") + nsp_options = ["--base", str(nsp_base.path), "--update", str(game.path), + "--version", str(game.version)] + selected.insert(0, nsp_base) + elif game: + if nup_version(game, allow_metadata=False) not in args.game_version: + raise PackageError("version") + if game.kind == "update" and len(base) == 1: + selected.insert(0, base[0]) + + tasks = [] + if game and game.reader: + tasks.extend((game.reader, section, args.out / name) for name, section in + (("exefs", game.package.exefs_dir), ("romfs", game.package.romfs_dir)) + if section != nup.NO_DIR) + for title, name in DLC.items(): + entry = newest(e for e in addons if e.title == title) + if not entry: + continue + selected.append(entry) + if entry.reader: + if entry.package.romfs_dir == nup.NO_DIR: + raise PackageError("invalid") + tasks.append((entry.reader, entry.package.romfs_dir, args.out / name)) + else: + nsp_options += ["--dlc", f"{title:X}|{entry.version}|{entry.path}"] + + files = [(reader, path, index) for reader, root, target in tasks + for path, index in members(reader, root, target)] + total = sum(reader.file_info(index)[1] for reader, _, index in files) + if shutil.disk_usage(args.out).free < total: + raise PackageError("space") + if not files and not nsp_options: + raise PackageError("invalid") + nsp_versions = {} + if nsp_options and (args.confirm is not None or (game and not game.reader)): + nsp_versions = dict(run_nxpatch(args, "extract", nsp_options + + ["--out", str(args.out), "--versions", "1"])) + if game and not game.reader: + merged_version = nsp_versions.get("update") + if merged_version not in args.game_version: + raise PackageError("version") + nsp_options += ["--require-version", merged_version] + review(args, selected, nsp_versions) + if files: + print(f"total\t{total}", flush=True) + done = 0 + for reader, path, index in files: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("xb") as output: + for chunk in blocks(reader, index): + if args.cancel.exists(): + raise PackageError("cancelled") + output.write(chunk) + done += len(chunk) + if done // (64 * BLOCK) != (done - reader.file_info(index)[1]) // (64 * BLOCK): + print(f"progress\t{done}", flush=True) + if files: + print(f"progress\t{done}", flush=True) + if nsp_options: + run_nxpatch(args, "extract", nsp_options + ["--out", str(args.out)]) + + +def main(argv=None): + parser = argparse.ArgumentParser() + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--cancel", type=Path, required=True) + parser.add_argument("--confirm", type=Path) + parser.add_argument("--keys", type=Path) + parser.add_argument("--nxpatch", type=Path) + parser.add_argument("--game-version", action="append", required=True) + parser.add_argument("packages", type=Path, nargs="+") + args = parser.parse_args(argv) + if isinstance(sys.stdout, io.TextIOWrapper): + sys.stdout.reconfigure(encoding="utf-8", errors="replace") + try: + if not args.out.is_dir() or any(args.out.iterdir()): + raise PackageError("invalid") + with ExitStack() as stack: + extract(args, list(inventory(args, stack))) + return 0 + except PackageError as error: + print(f"failure\t{error}", flush=True) + except (OSError, ValueError, struct.error, nup.NupError): + print("failure\tinvalid", flush=True) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/package_nup/LICENSE b/tools/package_nup/LICENSE new file mode 100644 index 00000000..0182ee70 --- /dev/null +++ b/tools/package_nup/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 a55uka + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/package_nup/README.md b/tools/package_nup/README.md new file mode 100644 index 00000000..693f6aa9 --- /dev/null +++ b/tools/package_nup/README.md @@ -0,0 +1,7 @@ +# NUP reference reader + +`format.py` and `read.py` come from the MIT-licensed a55uka/nup reference +implementation at commit `a4840f06c94ddeb414eea5b33c9704ffe995f11c`, with small +changes for bounds validation and Python 3.10 compatibility. +`tools/package_import.py` selects content, validates output names and verifies the +contents of each extracted file. diff --git a/tools/package_nup/__init__.py b/tools/package_nup/__init__.py new file mode 100644 index 00000000..df11d8fd --- /dev/null +++ b/tools/package_nup/__init__.py @@ -0,0 +1 @@ +"""Vendored NUP v1 reader.""" diff --git a/tools/package_nup/format.py b/tools/package_nup/format.py new file mode 100644 index 00000000..e22e0e2e --- /dev/null +++ b/tools/package_nup/format.py @@ -0,0 +1,214 @@ +"""NUP (NX Package) format constants and binary layout. + +Implements SPEC.md v1 exactly. All integers little-endian. All reserved +fields must be zero on write and are validated on read. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from enum import IntEnum, auto +import struct +from typing import Final, TypedDict + +MAGIC: Final = b"NUP\x01" # 'N','U','P', format major version 1 +TOC_MAGIC: Final = b"TOC\x01" +HEADER_SIZE: Final = 0x80 +PKG_SIZE: Final = 0x40 +DIR_SIZE: Final = 0x18 +FILE_SIZE: Final = 0x50 +EXTENT_ALIGN: Final = 16 +NO_DIR: Final = 0xFFFFFFFF + +class Codec(IntEnum): + RAW = 0 + ZSTD = auto() + +CODEC_RAW: Final = Codec.RAW +CODEC_ZSTD: Final = Codec.ZSTD +assert len(Codec) == 2 + +class Kind(IntEnum): + BASE = 0 + UPDATE = auto() + ADDON = auto() + ADDON_UPDATE = auto() + SYSTEM = auto() + +KIND_BASE: Final = Kind.BASE +KIND_UPDATE: Final = Kind.UPDATE +KIND_ADDON: Final = Kind.ADDON +KIND_ADDON_UPDATE: Final = Kind.ADDON_UPDATE +KIND_SYSTEM: Final = Kind.SYSTEM +assert len(Kind) == 5 + +KIND_NAMES: Final = { + KIND_BASE: "base", + KIND_UPDATE: "update", + KIND_ADDON: "addon", + KIND_ADDON_UPDATE: "addon_update", + KIND_SYSTEM: "system", +} + +# Meta TLV types (SPEC §5) +class TVL(IntEnum): + NPDM = 0 + NACP = auto() + ICON = auto() + DISPLAY_VERSION = auto() + TITLE_NAME = auto() + PUBLISHER = auto() + BUILD_ID = auto() + SOURCE_DUMP = auto() + LOCALIZED_TITLES = auto() + LOCALIZED_ICONS = auto() + +TLV_NPDM: Final = TVL.NPDM +TLV_NACP: Final = TVL.NACP +TLV_ICON: Final = TVL.ICON +TLV_DISPLAY_VERSION: Final = TVL.DISPLAY_VERSION +TLV_TITLE_NAME: Final = TVL.TITLE_NAME +TLV_PUBLISHER: Final = TVL.PUBLISHER +TLV_BUILD_ID: Final = TVL.BUILD_ID +TLV_SOURCE_DUMP: Final = TVL.SOURCE_DUMP +TLV_LOCALIZED_TITLES: Final = TVL.LOCALIZED_TITLES +TLV_LOCALIZED_ICONS: Final = TVL.LOCALIZED_ICONS +assert len(TVL) == 10 + +PKG_FLAG_STANDALONE_UPDATE: Final = 0x01 + +_super_s: Final = struct.Struct("<4sHHQQ32sQQII16s32s") # 128 +_pkg_s: Final = struct.Struct(" bytes: + assert len(toc_sha256) == 32 and len(uuid) == 16 + return _super_s.pack(magic, header_size, header_version, toc_offset, toc_size, + toc_sha256, blob_offset, file_size, package_count, flags, uuid, + b"\0" * 32) + + +def pack_pkg(p: Package) -> bytes: + return _pkg_s.pack(p.title_id, p.root_dir, p.exefs_dir, p.romfs_dir, p.version, + p.kind, p.flags, 0, 0, p.meta_offset, p.meta_size) + + +def pack_dir(d: DirNode) -> bytes: + return _dir_s.pack(0, 0, d.first_child, d.child_count, 0) # name off/len patched at write + + +def pack_file(f: FileNode) -> bytes: + return _file_s.pack(0, 0, f.size, f.extent_offset, f.extent_size, f.sha256, + f.codec, f.codec_flags, 0) + + +def parse_super(buf: bytes) -> Super: + if len(buf) < HEADER_SIZE: + raise NupError(f"superblock truncated: {len(buf)} < {HEADER_SIZE}") + (magic, header_size, header_version, toc_offset, toc_size, toc_sha256, + blob_offset, file_size, package_count, flags, uuid, reserved) = _super_s.unpack_from(buf, 0) + if magic[0:3] != MAGIC[0:3]: + raise NupError(f"bad magic {magic!r}, expected {MAGIC[0:3]!r}") + if magic[3] != 1: + raise NupError(f"unsupported format major version {magic[3]}") + if header_size < HEADER_SIZE: + raise NupError(f"header_size {header_size:#x} < {HEADER_SIZE:#x}") + if reserved != b"\0" * 32: + raise NupError("superblock reserved bytes not zero") + if flags != 0: + raise NupError(f"unknown superblock flags {flags:#x}") + return Super(header_size=header_size, header_version=header_version, + toc_offset=toc_offset, toc_size=toc_size, toc_sha256=toc_sha256, + blob_offset=blob_offset, file_size=file_size, + package_count=package_count, flags=flags, uuid=uuid) + + +def parse_pkg(buf: bytes, off: int) -> Package: + (title_id, root, exefs, romfs, version, kind, flags, _r, _r2, + meta_offset, meta_size) = _pkg_s.unpack_from(buf, off) + if kind >= len(KIND_NAMES): + raise NupError(f"unknown package kind {kind}") + if _r != 0 or _r2 != 0: + raise NupError("package reserved bytes not zero") + return Package(title_id=title_id, root_dir=root, exefs_dir=exefs, romfs_dir=romfs, + version=version, kind=kind, flags=flags, + meta_offset=meta_offset, meta_size=meta_size) + + +def parse_file(toc: bytes, pos: int) -> tuple[tuple[int, int], int, bytes, int, int, Codec]: + (off, ln, size, eoff, esz, sha, codec, cflags, _r4) = \ + _file_s.unpack_from(toc, pos) + pos += FILE_SIZE + try: + codec = Codec(codec) + except ValueError as error: + raise NupError(f"unknown extent codec {codec}") from error + if cflags != 0: + raise NupError(f"unknown codec_flags {cflags}") + if size == 0 and (eoff != 0 or esz != 0 or codec != CODEC_RAW): + raise NupError("zero-size file with nonempty extent") + if size != 0 and esz == 0: + raise NupError(f"file with nonzero size but empty extent") + return ((off, ln), size, sha, eoff, esz, codec) diff --git a/tools/package_nup/read.py b/tools/package_nup/read.py new file mode 100644 index 00000000..31fe9831 --- /dev/null +++ b/tools/package_nup/read.py @@ -0,0 +1,231 @@ +"""NUP reader: validated parsing and integrity checking. + +Reader conformance (SPEC §6.1): validate superblock, verify TOC SHA-256 +before trusting TOC-derived values, bounds-check every offset/size, treat +title_id/version/NPDM/NACP as opaque, reject unknown codecs and flags. +Tree traversal, metadata access, and extraction live in .access. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import mmap +import os +import struct +from typing import TYPE_CHECKING + +from . import format as F + +if TYPE_CHECKING: + from types import TracebackType + + +@dataclass(frozen=True, slots=True) +class PackageInfo: + index: int + title_id: int + kind: F.Kind + version: int + flags: int + root_dir: int + exefs_dir: int + romfs_dir: int + meta_offset: int + meta_size: int + + @property + def kind_name(self) -> str: + return F.KIND_NAMES.get(self.kind, f"kind{self.kind}") + + @property + def version_str(self) -> str: + return f"{self.version >> 16}.{(self.version >> 8) & 0xFF}.{self.version & 0xFF}" + + +@dataclass(frozen=True, slots=True) +class NodeRef: + """A child reference: is_dir + index into the respective array.""" + is_dir: bool + index: int + name: bytes + + +class NupReader: + __slots__ = ("path", "_fh", "_mm", "super", "dir_count", "file_count", "pool", "packages", "files", "dirs", "children") + def __init__(self, path: str) -> None: + self.path = path + self._fh = open(path, "rb") + self._mm: mmap.mmap | bytes = b"" + try: + try: + self._mm = mmap.mmap(self._fh.fileno(), 0, access=mmap.ACCESS_READ) + except ValueError: # empty file + self._mm = b"" + self.super = F.parse_super(self._mm[:F.HEADER_SIZE]) + real_size = os.fstat(self._fh.fileno()).st_size + if self.super["file_size"] != real_size: + raise F.NupError( + f"file_size {self.super['file_size']} != actual {real_size}") + if self.super["toc_offset"] != self.super["header_size"]: + raise F.NupError("TOC does not follow the header") + if not self.super["package_count"] or self.super["blob_offset"] > real_size: + raise F.NupError("missing packages or blob region out of bounds") + if self.super["blob_offset"] < self.super["toc_offset"] + self.super["toc_size"]: + raise F.NupError("blob region overlaps TOC") + if self.super["blob_offset"] % F.EXTENT_ALIGN: + raise F.NupError("blob_offset not 16-byte aligned") + + toc_start = self.super["toc_offset"] + raw_toc = self._mm[toc_start:toc_start + self.super["toc_size"]] + if hashlib.sha256(raw_toc).digest() != self.super["toc_sha256"]: + raise F.NupError("TOC SHA-256 mismatch - file corrupt or tampered") + self._parse_toc(raw_toc) + self._check_bounds() + except BaseException: + # Never leak an open handle/mmap: on Windows it locks the file + # against rename/delete until GC. + self.close() + raise + + def close(self) -> None: + mm = self._mm + if isinstance(mm, mmap.mmap): + mm.close() + self._mm = b"" + self._fh.close() + + def __enter__(self) -> "NupReader": + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.close() + + # ---- TOC parsing ---- + + def _parse_toc(self, toc: bytes) -> None: + magic, pkg_count, dir_count, file_count, pool_off, pool_size, _r = \ + F._toc_head_s.unpack_from(toc, 0) + if magic != F.TOC_MAGIC: + raise F.NupError(f"bad TOC magic {magic!r}") + if pkg_count != self.super["package_count"]: + raise F.NupError("package_count mismatch between superblock and TOC") + need = (F._toc_head_s.size + pkg_count * F.PKG_SIZE + + dir_count * F.DIR_SIZE + file_count * F.FILE_SIZE) + if len(toc) < need: + raise F.NupError("TOC truncated") + if pool_off + pool_size > len(toc) or pool_off < need: + raise F.NupError("string pool out of TOC bounds") + + self.dir_count = dir_count + self.file_count = file_count + self.pool = toc[pool_off:pool_off + pool_size] + + pos = F._toc_head_s.size + self.packages: list[PackageInfo] = [] + for i in range(pkg_count): + p = F.parse_pkg(toc, pos) + pos += F.PKG_SIZE + self.packages.append(PackageInfo( + index=i, title_id=p.title_id, kind=F.Kind(p.kind), version=p.version, + flags=p.flags, root_dir=p.root_dir, exefs_dir=p.exefs_dir, + romfs_dir=p.romfs_dir, meta_offset=p.meta_offset, + meta_size=p.meta_size)) + + self.dirs: list[tuple[bytes, int, int]] = [] # (name, first_child, child_count) + for _ in range(dir_count): + off, ln, first, count, _r2 = F._dir_s.unpack_from(toc, pos) + pos += F.DIR_SIZE + self.dirs.append((self._pool_str(off, ln), first, count)) + + # (name, size, sha256, ext_off, ext_size, codec) + self.files: list[tuple[bytes, int, bytes, int, int, F.Codec]] = [] + for _ in range(file_count): + (off, ln), size, sha, eoff, esz, codec = F.parse_file(toc, pos) + pos += F.FILE_SIZE + self.files.append((self._pool_str(off, ln), size, sha, eoff, esz, codec)) + + slot_end = pool_off + if (slot_end - pos) % 4: + raise F.NupError("children array not 4-byte aligned") + self.children = list(struct.unpack_from(f"<{(slot_end - pos) // 4}I", toc, pos)) + + def _pool_str(self, off: int, ln: int) -> bytes: + if off + ln > len(self.pool): + raise F.NupError("string reference out of pool bounds") + return self.pool[off:off + ln] + + def _check_bounds(self) -> None: + file_size = self.super["file_size"] + blob_start = self.super["blob_offset"] + for name, size, sha, eoff, esz, codec in self.files: + if size == 0: + continue + if eoff < blob_start or eoff + esz > file_size: + raise F.NupError(f"extent out of bounds for file {name!r}") + if eoff % F.EXTENT_ALIGN: + raise F.NupError(f"extent not {F.EXTENT_ALIGN}-aligned for {name!r}") + slot_total = len(self.children) + used = 0 + for name, first, count in self.dirs: + if first + count > slot_total: + raise F.NupError(f"child range out of bounds for dir {name!r}") + used += count + if used != slot_total: + raise F.NupError(f"child slots used {used} != total {slot_total}") + for p in self.packages: + if p.root_dir >= self.dir_count: + raise F.NupError(f"package {p.index}: root_dir out of bounds") + for d in (p.exefs_dir, p.romfs_dir): + if d != F.NO_DIR and d >= self.dir_count: + raise F.NupError(f"package {p.index}: exefs/romfs dir out of bounds") + if p.meta_size and (p.meta_offset + p.meta_size > file_size): + raise F.NupError(f"package {p.index}: meta block out of bounds") + if p.flags & ~F.PKG_FLAG_STANDALONE_UPDATE: + raise F.NupError(f"package {p.index}: unknown package flags {p.flags:#x}") + # SPEC §3.1.2: update packages need a base in the same container, or + # the standalone_update flag (record flags, offset 0x19, bit 0). + has_base = any(p.kind == F.KIND_BASE for p in self.packages) + for p in self.packages: + if (p.kind == F.KIND_UPDATE and not has_base + and not (p.flags & F.PKG_FLAG_STANDALONE_UPDATE)): + raise F.NupError( + f"package {p.index}: update without base in container and " + f"standalone_update flag not set") + + # ---- member access ---- + + def node_name(self, ref: NodeRef) -> bytes: + if ref.is_dir: + return self.dirs[ref.index][0] + return self.files[ref.index][0] + + def file_info(self, file_index: int) -> tuple[bytes, int, bytes, int, int, F.Codec]: + return self.files[file_index] + + def read_file(self, file_index: int) -> bytes: + name, size, sha, eoff, esz, codec = self.files[file_index] + if size == 0: + data = b"" + elif codec == F.CODEC_RAW: + data = self._mm[eoff:eoff + esz] + if len(data) != esz: + raise F.NupError(f"short read for {name!r}") + elif codec == F.CODEC_ZSTD: + import zstandard + comp = self._mm[eoff:eoff + esz] + if len(comp) != esz: + raise F.NupError(f"short read for {name!r}") + dctx = zstandard.ZstdDecompressor() + data = dctx.decompress(comp, max_output_size=size) + else: + raise F.NupError(f"unknown codec {codec}") + assert len(F.Codec) == 2 + if len(data) != size: + raise F.NupError(f"size mismatch for {name!r}: {len(data)} != {size}") + return data diff --git a/tools/setup_windows.ps1 b/tools/setup_windows.ps1 index 0f7caa11..2adb2522 100644 --- a/tools/setup_windows.ps1 +++ b/tools/setup_windows.ps1 @@ -26,7 +26,7 @@ if (-not (Test-Path $py)) { winget install --id Python.Python.3.12 -e --scope user --accept-source-agreements --accept-package-agreements --silent } if (-not (Test-Path "$root\tools\venv\Scripts\python.exe")) { & $py -m venv "$root\tools\venv" } -& "$root\tools\venv\Scripts\python.exe" -m pip install -q lz4 capstone unicorn +& "$root\tools\venv\Scripts\python.exe" -m pip install -q lz4 capstone unicorn zstandard # LF line endings in this clone (the bash tools break with CRLF; Git for Windows defaults to autocrlf=true) git -C $root config core.autocrlf false diff --git a/tools/swgen.spec b/tools/swgen.spec index 5ab57f2c..3e414a3d 100644 --- a/tools/swgen.spec +++ b/tools/swgen.spec @@ -23,7 +23,7 @@ a = Analysis( pathex=[TOOLS], binaries=collect_dynamic_libs('capstone') + collect_dynamic_libs('unicorn') + [(p, 'unicorn/lib') for p in _uc_versioned], - datas=[], + datas=[(os.path.join(TOOLS, 'package_nup', 'LICENSE'), 'package_nup')], hiddenimports=collect_submodules('unicorn'), # (it imports its arch modules by name at run time) excludes=['tkinter', 'pydoc', 'doctest', 'unittest', 'pdb', 'IPython', 'numpy', 'setuptools', '_distutils_hack', 'pkg_resources', 'ssl', '_ssl', '_hashlib', '_multibytecodec', '_codecs_cn', '_codecs_hk', diff --git a/tools/test_package_import.py b/tools/test_package_import.py new file mode 100644 index 00000000..cbcbc864 --- /dev/null +++ b/tools/test_package_import.py @@ -0,0 +1,212 @@ +"""Synthetic NUP and NSP orchestration checks. No game data is used.""" + +from contextlib import redirect_stdout +import hashlib +import io +from pathlib import Path +import struct +import tempfile +import unittest +from unittest.mock import patch + +import package_import as importer +from package_nup import format as nup + + +def fixture(path, packages, *, compressed=False, bad_hash=False): + """Write a NUP with one section and one file per package.""" + strings, nodes, children, files, records = bytearray(), [], [], [], [] + + def name(value): + offset = len(strings) + encoded = value.encode() + strings.extend(encoded) + return offset, len(encoded) + + dir_count = sum(2 + ("/" in entry[3]) for entry in packages) + for i, (title, kind, version, filename, content) in enumerate(packages): + root, section = len(nodes), len(nodes) + 1 + child = len(children) + flags = (nup.PKG_FLAG_STANDALONE_UPDATE if kind == nup.KIND_UPDATE and + not any(p[1] == nup.KIND_BASE for p in packages) else 0) + records.append(nup.pack_pkg(nup.Package(title, root, nup.NO_DIR, section, version, kind, flags))) + nodes.extend([nup._dir_s.pack(*name(""), child, 1, 0), + nup._dir_s.pack(*name("romfs"), child + 1, 1, 0)]) + children.append(section) + if "/" in filename: + directory, filename = filename.split("/", 1) + nodes.append(nup._dir_s.pack(*name(directory), child + 2, 1, 0)) + children.append(section + 1) + children.append(dir_count + i) + files.append((name(filename), content)) + + child_data = struct.pack(f"<{len(children)}I", *children) + pool_offset = (nup._toc_head_s.size + len(records) * nup.PKG_SIZE + len(nodes) * nup.DIR_SIZE + + len(files) * nup.FILE_SIZE + len(child_data)) + toc_size = pool_offset + len(strings) + blob_at = (nup.HEADER_SIZE + toc_size + 15) & ~15 + blobs, file_data = bytearray(), [] + for (offset, length), content in files: + codec = nup.CODEC_RAW + stored = content + if compressed: + import zstandard + stored = zstandard.ZstdCompressor().compress(content) + codec = nup.CODEC_ZSTD + blobs.extend(b"\0" * (-len(blobs) % 16)) + digest = hashlib.sha256(b"bad" if bad_hash else content).digest() + file_data.append(nup._file_s.pack(offset, length, len(content), blob_at + len(blobs), + len(stored), digest, codec, 0, 0)) + blobs.extend(stored) + toc = (nup._toc_head_s.pack(nup.TOC_MAGIC, len(records), len(nodes), len(files), + pool_offset, len(strings), 0) + + b"".join(records + nodes + file_data) + child_data + bytes(strings)) + header = nup._super_s.pack(nup.MAGIC, nup.HEADER_SIZE, 1, nup.HEADER_SIZE, len(toc), + hashlib.sha256(toc).digest(), blob_at, blob_at + len(blobs), + len(records), 0, b"\0" * 16, b"\0" * 32) + path.write_bytes((header + toc).ljust(blob_at, b"\0") + blobs) + + +class PackageImportTest(unittest.TestCase): + def setUp(self): + directory = tempfile.TemporaryDirectory() + self.addCleanup(directory.cleanup) + self.root = Path(directory.name) + self.out = self.root / "out" + self.out.mkdir() + self.cancel = self.root / "cancel" + self.archive = self.root / "game.nup" + + def run_import(self, *args): + log = io.StringIO() + with redirect_stdout(log): + result = importer.main(["--out", str(self.out), "--cancel", str(self.cancel), + "--game-version", "1.9.0", *args]) + return result, log.getvalue() + + def test_bundle_uses_newest_update_and_keeps_dlc_separate(self): + fixture(self.archive, [ + (importer.BASE, nup.KIND_BASE, 0, "game", b"base"), + (importer.UPDATE, nup.KIND_UPDATE, 2, "System/Version.txt", b"1.9.0"), + (importer.UPDATE, nup.KIND_UPDATE, 1, "System/Version.txt", b"1.8.0"), + (importer.BASE + 0x1002, nup.KIND_ADDON, 0, "addon", b"dlc"), + ], compressed=True) + self.assertEqual(self.run_import(str(self.archive))[0], 0) + self.assertEqual((self.out / "romfs/System/Version.txt").read_bytes(), b"1.9.0") + self.assertEqual((self.out / "aoc2/addon").read_bytes(), b"dlc") + + def test_rejects_unsafe_names(self): + fixture(self.archive, [(importer.BASE + 0x1001, nup.KIND_ADDON, 0, "../outside", b"data")]) + self.assertEqual(self.run_import(str(self.archive)), (1, "failure\tinvalid\n")) + self.assertFalse((self.out / "outside").exists()) + + def test_standalone_nup_update(self): + fixture(self.archive, [(importer.UPDATE, nup.KIND_UPDATE, 2, "System/Version.txt", b"1.9.0")]) + self.assertEqual(self.run_import(str(self.archive))[0], 0) + self.assertEqual((self.out / "romfs/System/Version.txt").read_bytes(), b"1.9.0") + + def test_unsupported_nup_is_rejected_before_review(self): + fixture(self.archive, [(importer.UPDATE, nup.KIND_UPDATE, 1114112, "System/Version.txt", b"2.4.7")]) + self.assertEqual(self.run_import("--confirm", str(self.root / "confirm"), str(self.archive)), + (1, "failure\tversion\n")) + self.assertEqual(list(self.out.iterdir()), []) + + def test_dlc_only_nup(self): + fixture(self.archive, [(importer.BASE + 0x1002, nup.KIND_ADDON, 2, "addon", b"dlc")]) + self.assertEqual(self.run_import(str(self.archive))[0], 0) + self.assertEqual((self.out / "aoc2/addon").read_bytes(), b"dlc") + self.assertFalse((self.out / "romfs").exists()) + + def test_verifies_payload_hashes(self): + fixture(self.archive, [(importer.BASE + 0x1001, nup.KIND_ADDON, 0, "data", b"data")], bad_hash=True) + self.assertEqual(self.run_import(str(self.archive))[0], 1) + + def test_cancellation(self): + fixture(self.archive, [(importer.BASE, nup.KIND_BASE, 0, "data", b"data")]) + self.cancel.touch() + self.assertEqual(self.run_import(str(self.archive))[0], 1) + + def test_preview_reports_metadata_before_writing_payload(self): + fixture(self.archive, [ + (importer.BASE, nup.KIND_BASE, 0, "game", b"base"), + (importer.UPDATE, nup.KIND_UPDATE, 1114112, "System/Version.txt", b"\xef\xbb\xbf1.9.0\r\n"), + (importer.BASE + 0x1001, nup.KIND_ADDON, 0, "System/AocVersion.txt", b"3.5\n"), + (importer.BASE + 0x1002, nup.KIND_ADDON, 0, "System/AocVersion.txt", b"6.1\n"), + ], compressed=True) + confirm = self.root / "confirm" + + def approve(_): + self.assertEqual(list(self.out.iterdir()), []) + confirm.touch() + + with patch.object(importer.time, "sleep", side_effect=approve) as wait: + result, log = self.run_import("--confirm", str(confirm), str(self.archive)) + wait.assert_called_once() + self.assertEqual(result, 0) + self.assertTrue(log.startswith("item\tbase\t\tgame.nup\nitem\tupdate\t1.9.0\tgame.nup\n" + "item\taoc1\t3.5\tgame.nup\nitem\taoc2\t6.1\tgame.nup\nreview\n")) + self.assertEqual((self.out / "romfs/System/Version.txt").read_bytes(), b"\xef\xbb\xbf1.9.0\r\n") + + def test_cancel_from_preview_leaves_destination_empty(self): + fixture(self.archive, [(importer.UPDATE, nup.KIND_UPDATE, 0, "System/Version.txt", b"1.9.0")]) + with patch.object(importer.time, "sleep", side_effect=lambda _: self.cancel.touch()): + result, log = self.run_import("--confirm", str(self.root / "confirm"), str(self.archive)) + self.assertEqual(result, 1) + self.assertTrue(log.endswith("review\nfailure\tcancelled\n")) + self.assertEqual(list(self.out.iterdir()), []) + + def test_standalone_nsp_patch_requires_base(self): + with patch.object(importer, "inventory", return_value=[ + importer.Content(self.root / "update.nsp", "update", importer.UPDATE, 10), + ]): + self.assertEqual(self.run_import(str(self.archive)), (1, "failure\tbase\n")) + + def test_nsp_base_requires_matching_update(self): + with patch.object(importer, "inventory", return_value=[ + importer.Content(self.root / "base.nsp", "base", importer.BASE, 0), + importer.Content(self.root / "other-update.nsp", "update", importer.UPDATE + 0x2000, 10), + ]): + self.assertEqual(self.run_import(str(self.archive)), (1, "failure\tupdate\n")) + self.assertEqual(list(self.out.iterdir()), []) + + def test_nsp_merge_must_report_supported_romfs_version(self): + with patch.object(importer, "inventory", return_value=[ + importer.Content(self.root / "base.nsp", "base", importer.BASE, 0), + importer.Content(self.root / "update.nsp", "update", importer.UPDATE, 1114112), + ]), patch.object(importer, "run_nxpatch", return_value=[("update", "2.4.7")]) as helper: + self.assertEqual(self.run_import(str(self.archive)), (1, "failure\tversion\n")) + helper.assert_called_once() + self.assertEqual(helper.call_args.args[-1][-2:], ["--versions", "1"]) + self.assertEqual(list(self.out.iterdir()), []) + + def test_combined_nsp_protocol(self): + nsp = self.root / "combined.nsp" + records = [ + importer.Content(nsp, "dlc", importer.BASE + 0x1001, 2), + importer.Content(nsp, "update", importer.UPDATE, 10), + importer.Content(nsp, "base", importer.BASE, 0), + ] + confirm = self.root / "confirm" + versions = [("base", "1.0.0"), ("update", "1.9.0"), ("aoc1", "3.5")] + with patch.object(importer, "inventory", return_value=records), patch.object( + importer, "run_nxpatch", side_effect=[versions, []]) as helper: + def approve(_): + helper.assert_called_once() + self.assertEqual(helper.call_args.args[-1][-2:], ["--versions", "1"]) + self.assertEqual(list(self.out.iterdir()), []) + confirm.touch() + + with patch.object(importer.time, "sleep", side_effect=approve): + result, log = self.run_import("--confirm", str(confirm), str(nsp)) + self.assertEqual(result, 0) + self.assertIn("item\tupdate\t1.9.0\tcombined.nsp\n", log) + self.assertIn("item\taoc1\t3.5\tcombined.nsp\n", log) + self.assertEqual(helper.call_args.args[1:], ("extract", [ + "--base", str(nsp), "--update", str(nsp), "--version", "10", + "--dlc", f"{importer.BASE + 0x1001:X}|2|{nsp}", "--require-version", "1.9.0", + "--out", str(self.out), + ])) + + +if __name__ == "__main__": + unittest.main()