# Applier Tool Guide Complete guide to using the CyberPatchMaker applier tool for applying delta patches to installations. ## Overview The applier tool safely applies binary patches to existing installations. It verifies the current version, creates selective backups of files being changed, applies modifications, and validates the result. ## Basic Usage ### Apply Patch with Full Verification **The recommended method** - apply patch with complete safety checks: ```bash patch-apply --patch ./patches/1.0.0-to-1.0.3.patch --current-dir ./myapp --verify ``` This will: 1. Load and display patch information 2. Verify current version is 1.0.0 (pre-verification) 3. Create selective backup of files being modified/deleted 4. Apply all patch operations 5. Verify result matches version 1.0.3 (post-verification) 6. Preserve backup for manual rollback (or restore on failure) **Example Output:** ``` Loading patch: patches/1.0.0-to-1.0.3.patch === Patch Information === From Version: 1.0.0 To Version: 1.0.3 Key File: program.exe Created: 2025-10-04 10:30:00 Patch Size: 2.1 MB Compression: zstd Operations: 5 files to add 12 files to modify 3 files to delete 2 directories to add Applying patch from 1.0.0 to 1.0.3... Verifying current version... Pre-patch verification successful Creating selective backup... Backing up: program.exe Backing up: data\config.json Backing up: libs\oldfeature.dll Backup created in: C:\MyApp\backup.cyberpatcher Applying 20 operations... Modified: program.exe Modified: data/config.json Added: libs/newfeature.dll Deleted: libs/oldfeature.dll ... (16 more operations) Post-patch verification successful === Patch Applied Successfully === Version updated from 1.0.0 to 1.0.3 Backup preserved in: C:\MyApp\backup.cyberpatcher Time elapsed: 12.3 seconds ``` --- ### Dry-Run Mode (Preview Changes) **Preview what would happen** without making any changes: ```bash patch-apply --patch ./patches/1.0.0-to-1.0.3.patch --current-dir ./myapp --dry-run ``` This will: 1. Load patch information 2. Display what operations would be performed 3. **NOT** create backup 4. **NOT** apply any changes 5. **NOT** modify any files **Example Output:** ``` Loading patch: patches/1.0.0-to-1.0.3.patch === Patch Information === From Version: 1.0.0 To Version: 1.0.3 Key File: program.exe === DRY RUN MODE - NO CHANGES WILL BE MADE === Would perform the following operations: ADD: libs/newfeature.dll (2.1 MB) MODIFY: program.exe (52.4 MB) MODIFY: data/config.json (1.2 KB) DELETE: libs/oldfeature.dll ... (16 more operations) Total size of changes: 54.7 MB Dry-run completed successfully No changes were made to your installation ``` --- ## Command-Line Options ### Required Options **`--patch `** - Path to the patch file - Must be a .patch file generated by the generator tool - Example: `./patches/1.0.0-to-1.0.3.patch` **`--current-dir `** - Directory containing the current installation - Must contain the expected source version - Example: `C:\MyApp\` ### Optional Options **`--key-file `** - Specify custom key file path if renamed or moved - Can be absolute path or relative to current-dir - Example: `--key-file app.exe` or `--key-file C:\MyApp\renamed.exe` - Use case: When the key file (typically the main executable) has been renamed - Default: Uses key file path stored in patch **`--verify`** (Enabled by Default) - Check files before and after patching - Verifies current version before patching - Verifies result after patching - Default: `true` (enabled) - Disable with `--verify=false` (not recommended) **`--backup`** (Enabled by Default) - Create backup of changed files before patching - Selective backup (only files being modified/deleted) - Backup saved to `\backup.cyberpatcher\` - Default: `true` (enabled) - Disable with `--backup=false` (not recommended) - Manual rollback: Delete patched files, restore from backup **`--dry-run`** - Preview mode - show what would happen - No backup created - No changes made - Useful for testing and planning **`--silent`** - Silent mode for automation and scripting - Automatically applies patch without user prompts - Works with self-contained executables only - Applies patch with default settings (verify=true, backup=true) - Returns exit code 0 on success, 1 on failure - Example: `1.2.4-to-1.2.5.exe --silent` - Useful for automated deployments and CI/CD pipelines **`--ignore1gb`** - Bypass the 1GB patch size limit for embedded patches - Use with caution - large patches may consume significant memory - Only relevant for self-contained executables with embedded patches - Example: `1.0.0-to-1.0.1.exe --ignore1gb` **`--version`** - Display version information for the applier tool - Prints version string and exits - Example: `patch-apply --version` **`--help`** - Display usage information - Shows all available options --- ## Automation Mode (Silent Flag) ### Overview The `--silent` flag enables fully automated patching for **self-contained executables** (`.exe` files created with `--create-exe`). This mode is designed for: - **Automated deployments** via scripts or task schedulers - **CI/CD pipelines** that need to update installations - **Mass deployments** across multiple machines - **Unattended updates** without user interaction ### Key Features - **No user prompts**: Applies patch immediately without asking - **Default settings**: Uses verify=true and backup=true automatically - **Exit codes**: Returns 0 for success, 1 for failure (scriptable) - **Minimal output**: Only shows essential status messages - **Error handling**: Proper error codes for automation tools - **Automatic logging**: Creates log file `log_.txt` with complete patch execution details ### Basic Usage ```bash # Basic silent mode (uses current directory) 1.2.4-to-1.2.5.exe --silent # Silent mode with explicit target directory 1.2.4-to-1.2.5.exe --silent --current-dir C:\MyApp # Silent mode with custom key file 1.2.4-to-1.2.5.exe --silent --current-dir C:\MyApp --key-file renamed.exe ``` ### Exit Codes **Exit Code 0: Success** - Patch applied successfully - All verifications passed - Backup created and preserved **Exit Code 1: Failure** - Target directory not found - Pre-verification failed (wrong version/corrupted files) - Patch application failed - Post-verification failed - Any other error during patching ### Log Files Silent mode automatically creates a timestamped log file to track patch execution: **Log File Name Format:** ``` log_.txt ``` Example: `log_1728372045.txt` (Unix epoch timestamp) **Log File Contents:** - Patch execution start time and end time - Complete patch information (versions, key file, compression) - Target directory and settings - All operations performed - Success or failure status - Error messages (if any) **Example Log File:** ``` ======================================== CyberPatchMaker Silent Mode Log Started: 2025-10-08 14:30:45 ======================================== Patch Information: From Version: 1.0.0 To Version: 1.0.1 Key File: program.exe Target Dir: C:\MyApp Compression: zstd Applying patch... [Applier output here...] Patch applied successfully: 1.0.0 → 1.0.1 ======================================== Status: SUCCESS Completed: 2025-10-08 14:31:12 ======================================== Log saved to: log_1728372045.txt ``` ### Example Output **Success:** ``` ======================================== CyberPatchMaker Silent Mode Log Started: 2025-10-08 14:30:45 ======================================== Patch Information: From Version: 1.0.0 To Version: 1.0.1 Key File: program.exe Target Dir: C:\MyApp Compression: zstd Applying patch... Patch applied successfully: 1.0.0 → 1.0.1 ======================================== Status: SUCCESS Completed: 2025-10-08 14:31:12 ======================================== Log saved to: log_1728372045.txt ``` **Failure:** ``` ======================================== CyberPatchMaker Silent Mode Log Started: 2025-10-08 14:30:45 ======================================== Patch Information: From Version: 1.0.0 To Version: 1.0.1 Key File: program.exe Target Dir: C:\NonExistent Compression: zstd Applying patch... Error: Target directory not found: C:\NonExistent ======================================== Status: FAILED Completed: 2025-10-08 14:30:46 ======================================== Log saved to: log_1728372045.txt ``` ### Automation Examples **PowerShell Script:** ```powershell # Deploy patch to multiple servers $servers = @("Server1", "Server2", "Server3") $patchExe = "\\share\patches\1.2.4-to-1.2.5.exe" foreach ($server in $servers) { Write-Host "Updating $server..." $targetDir = "\\$server\C$\MyApp" # Run patch in silent mode & $patchExe --silent --current-dir $targetDir if ($LASTEXITCODE -eq 0) { Write-Host "✓ $server updated successfully" -ForegroundColor Green # Archive log file $logFile = Get-ChildItem -Path . -Filter "log_*.txt" | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($logFile) { Move-Item $logFile.FullName "\\share\logs\$server`_$($logFile.Name)" } } else { Write-Host "✗ $server update failed" -ForegroundColor Red # Archive failure log for investigation $logFile = Get-ChildItem -Path . -Filter "log_*.txt" | Sort-Object LastWriteTime -Descending | Select-Object -First 1 if ($logFile) { Move-Item $logFile.FullName "\\share\logs\FAILED_$server`_$($logFile.Name)" } } } ``` **Batch Script:** ```batch @echo off REM Automated patch deployment echo Applying patch silently... 1.2.4-to-1.2.5.exe --silent --current-dir C:\MyApp if %ERRORLEVEL% EQU 0 ( echo Success: Patch applied exit /b 0 ) else ( echo Error: Patch failed exit /b 1 ) ``` **Task Scheduler:** ```powershell # Create scheduled task for automated patching $action = New-ScheduledTaskAction -Execute "C:\Patches\1.2.4-to-1.2.5.exe" ` -Argument "--silent --current-dir C:\MyApp" $trigger = New-ScheduledTaskTrigger -At 2:00AM -Daily Register-ScheduledTask -TaskName "MyApp Update" ` -Action $action ` -Trigger $trigger ` -User "SYSTEM" ` -RunLevel Highest ``` **CI/CD Pipeline (GitHub Actions):** ```yaml name: Deploy Patch on: workflow_dispatch: jobs: deploy: runs-on: windows-latest steps: - name: Download patch uses: actions/download-artifact@v3 with: name: patch-executable - name: Apply patch silently run: | .\1.2.4-to-1.2.5.exe --silent --current-dir C:\DeployedApp - name: Check result run: | if ($LASTEXITCODE -ne 0) { throw "Patch application failed" } ``` ### Best Practices for Automation 1. **Always test first**: Run in interactive mode once to verify 2. **Monitor exit codes**: Check `$LASTEXITCODE` / `%ERRORLEVEL%` / `$?` 3. **Review log files**: Check `log_.txt` files for detailed execution history 4. **Archive logs**: Save log files for troubleshooting and audit trails 5. **Check disk space**: Ensure space for backup before running 6. **Close application**: Ensure target application is stopped 7. **Handle failures**: Implement retry logic or alerting 8. **Verify result**: Check application version after patching ### Limitations - **Self-contained executables only**: The `--silent` flag only works with `.exe` files created using `--create-exe` - **Standard patch files**: Regular `.patch` files require explicit `--patch` and `--current-dir` flags - **No confirmation**: Cannot undo once started (backup preserved for manual rollback) - **Default settings only**: Cannot customize verify/backup settings in silent mode (always enabled) ### Error Handling Silent mode still performs all safety checks: - Pre-verification (version and file integrity) - Backup creation (automatic and selective) - Post-verification (result validation) - Automatic restoration on failure If any check fails: 1. Operation stops immediately 2. Backup is restored (if created) 3. Exit code 1 is returned 4. Error message is written to stderr --- ## Simple Mode for End Users (Fully Automated) ### Overview **Available since v1.0.9**: The `SimpleMode` field in the `Patch` struct and `runSimpleMode()` function exist in the codebase. When set to `true`, Simple Mode provides a fully automated patching experience — dry-run validation followed by automatic patch application with no user interaction. **Current status:** No generator code path currently sets `SimpleMode = true`. The field and function are reserved for future use. Silent Mode (`--silent` flag) is the currently available automation path for self-contained executables. ### How It Works (When Enabled) The applier's `runSimpleMode()` function: 1. Reads patch metadata from the embedded self-contained executable 2. Uses current directory as target 3. Runs automatic dry-run validation (key file + required files) 4. If validation passes, applies the patch with verification and backup 5. Logs all output to `__log.txt` 6. Exits with code 0 on success, 1 on failure ### No Menu or Prompts Simple Mode does **not** show a menu or prompt for user decisions. Unlike the interactive mode (which presents options 1-6), Simple Mode runs automatically from start to finish. All safety features (verification, backup) are enabled by default. --- ## Safety Features ### Pre-Verification Before any changes are made, the applier verifies: 1. **Key File Verification** - Checks that the key file (e.g., program.exe) exists - Calculates SHA-256 hash of the key file - Compares against required hash from patch - **Fails if hash doesn't match** → Wrong version or corrupted 2. **Required Files Verification** - Checks that all required files exist - Calculates SHA-256 hash of each required file - Compares against required hashes from patch - **Fails if any hash doesn't match** → Modified or corrupted installation **If Pre-Verification Fails:** - **NO BACKUP is created** (why backup corrupted state?) - **NO CHANGES are made** (patch rejected immediately) - Error message explains what's wrong - Installation remains in current state (unmodified) --- ### Backup Creation **When:** After pre-verification passes, before any operations **Location:** **INSIDE** target directory at `\backup.cyberpatcher\` - Example: If current-dir is `C:\MyApp\`, backup is `C:\MyApp\backup.cyberpatcher\` **Contents:** **Selective** mirror-structure backup of only files being changed - **Modified files** (OpModify operations): Backed up before changes - **Deleted files** (OpDelete operations): Backed up before deletion - **NOT backed up**: New files being added (OpAdd) - they don't exist yet - **Directory structure**: Mirrored exactly to preserve original paths - **File permissions**: Preserved where supported **Cleanup:** - **On success**: Backup is **PRESERVED** (kept for manual rollback if needed) - **On failure**: **AUTOMATIC ROLLBACK** from backup, then backup preserved for investigation - **User action**: Delete `backup.cyberpatcher` folder when no longer needed --- ### Post-Verification After all operations are applied, the applier verifies: 1. **Modified Files Verification** - Calculates SHA-256 hash of every modified/added file - Compares against expected hashes from patch - **Fails if any hash doesn't match** → Operation failed or corrupted 2. **Target Key File Verification** - Verifies key file now has target version hash - Ensures version was successfully updated **If Post-Verification Fails:** - **Backup is restored** (return to clean state) - Error message explains what went wrong - Installation returns to original state - User can investigate and retry --- ## Understanding Errors ### Pre-Verification Errors **"Key file checksum mismatch"** ``` Error: patch application failed: key file verification failed: key file checksum mismatch: expected 63573ff071ea5fa2, got 8f3c9d2e1a4b7c5e ``` **Meaning:** Your key file (program.exe) doesn't match expected version **Causes:** - Applying wrong patch (e.g., 1.0.0→1.0.3 patch to version 1.0.1) - Key file was modified or corrupted - Different application entirely **Solution:** - Verify you have the correct version installed - Use patch matching your current version - Re-install clean version if corrupted --- **"Required file missing or modified"** ``` Error: patch application failed: required files verification failed: found 1 mismatches: [data/config.json: checksum mismatch (expected a1b2c3d4e5f67890, got z9y8x7w6v5u43210)] ``` **Meaning:** A file in your installation was modified or corrupted **Causes:** - User edited files manually - File corruption - Incomplete installation - Previous patch failed **Solution:** - Re-install clean source version - Don't manually edit application files - Check disk for errors --- ### Operation Errors **"Permission denied"** ``` Error: failed to write file: permission denied Restoring from backup... ``` **Meaning:** Cannot write to files (insufficient permissions) **Causes:** - Files are in use (application running) - Insufficient user permissions - Read-only files - Antivirus blocking **Solution:** - Close the application before patching - Run applier as administrator - Check file permissions - Temporarily disable antivirus --- **"Disk full"** ``` Error: failed to write file: no space left on device Restoring from backup... ``` **Meaning:** Not enough disk space **Causes:** - Disk is full - Backup requires additional space - Large patch operations **Solution:** - Free up disk space (backup needs ~installation size) - Move to larger disk - Clean temporary files --- ### Post-Verification Errors **"Modified file checksum mismatch"** ``` Error: post-patch verification failed: file "program.exe" checksum mismatch after patching Restoring from backup... ``` **Meaning:** Patch application produced wrong result **Causes:** - Corrupted patch file - Disk error during write - Binary diff application failed - Memory corruption **Solution:** - Re-download patch file - Check disk for errors - Retry patching - Report bug if persistent --- **"Key file not found"** ``` Error: patch application failed: key file verification failed: key file not found: program.exe ``` **Meaning:** The key file specified in the patch cannot be found **Causes:** - Key file was renamed (e.g., program.exe → app.exe) - Key file was moved to different location - Key file was deleted **Solution:** - Use `--key-file` option to specify the renamed/moved key file - Example: `patch-apply --patch 1.0.0-to-1.0.1.patch --current-dir ./myapp --key-file app.exe` - Restore the key file to its original name/location --- ## Custom Key File Usage ### When to Use Custom Key File The `--key-file` option is useful when: 1. **Main executable was renamed** for branding or clarity - `program.exe` → `MyApp.exe` - `server.exe` → `MyCompanyServer.exe` 2. **Executable location changed** in directory structure - Moved from root to `bin/` subdirectory - Restructured folder hierarchy 3. **Testing with renamed files** in development/staging environments ### How It Works The key file is the primary executable that uniquely identifies your application version. When you specify a custom key file: 1. The applier uses your specified file for version verification 2. Hash is checked against expected version hash from patch 3. All other patch operations proceed normally 4. Custom key file path only affects verification, not patching operations ### Examples **Simple rename (relative path):** ```bash # Key file renamed from program.exe to MyApp.exe patch-apply --patch ./patches/1.0.0-to-1.0.1.patch \ --current-dir ./myapp \ --key-file MyApp.exe ``` **Moved to subdirectory:** ```bash # Key file moved to bin/ subdirectory patch-apply --patch ./patches/1.0.0-to-1.0.1.patch \ --current-dir ./myapp \ --key-file bin/program.exe ``` **Absolute path:** ```bash # Using absolute path to key file patch-apply --patch ./patches/1.0.0-to-1.0.1.patch \ --current-dir C:\MyApp \ --key-file C:\MyApp\renamed_program.exe ``` **With dry-run (test before applying):** ```bash # Test with custom key file first patch-apply --patch ./patches/1.0.0-to-1.0.1.patch \ --current-dir ./myapp \ --key-file MyApp.exe \ --dry-run ``` ### Self-Contained Executable Support Self-contained `.exe` patches provide an interactive console menu: 1. Run the self-contained executable 2. Accept or change the default target directory (current working directory) The interactive menu provides the following options: **Option 1: Dry Run** - Simulate the patch without making changes **Option 2: Apply Patch** - Apply the patch with verification and backup **Option 3: Toggle 1GB Bypass Mode** - Enable or disable the 1GB size limit bypass for large embedded patches (default: Disabled). Shows warning about memory usage when enabled. **Option 4: Change Target Directory** - Change the target installation directory. Validates that the new directory exists. **Option 5: Specify Custom Key File** - Enter a custom key file path if the original key file was renamed or moved. Shows current key file (default from patch or previously set custom path). Can be reset to default by pressing Enter without input. **Option 6: Exit** - Quit the application without patching --- ## Examples ### Example 1: Safe Production Update Update production installation with full safety: ```bash # Always use --verify for production! patch-apply --patch ./patches/1.0.2-to-1.0.3.patch --current-dir C:\Production\MyApp --verify ``` **What Happens:** 1. Verifies you're running 1.0.2 2. Creates backup at `C:\Production\MyApp\backup.cyberpatcher\` 3. Applies changes 4. Verifies result is 1.0.3 5. Preserves backup for manual rollback --- ### Example 2: Preview Before Applying Preview changes before committing: ```bash # First: Dry-run to see what would change patch-apply --patch ./patches/1.0.0-to-1.0.3.patch --current-dir ./myapp --dry-run # If everything looks good, apply for real: patch-apply --patch ./patches/1.0.0-to-1.0.3.patch --current-dir ./myapp --verify ``` --- ### Example 3: Testing Environment (Less Safe) For testing environments where speed matters more than safety: ```bash # Skip verification and backup (FASTER but RISKY!) patch-apply --patch ./patches/1.0.0-to-1.0.3.patch --current-dir ./test-app --verify=false --backup=false ``` **WARNING:** Only use this for disposable test environments! --- ### Example 4: Network Drive Installation Applying patch to network-installed application: ```bash patch-apply --patch ./patches/1.0.1-to-1.0.2.patch --current-dir \\server\share\MyApp --verify ``` **Note:** Backup will be at `\\server\share\MyApp\backup.cyberpatcher\` --- ## Performance Expectations ### Small Patches (<10MB) - **Pre-verification**: 2-5 seconds - **Backup creation**: 10-30 seconds - **Apply operations**: 3-10 seconds - **Post-verification**: 2-5 seconds - **Total time**: ~30-60 seconds ### Medium Patches (10-100MB) - **Pre-verification**: 5-10 seconds - **Backup creation**: 30-60 seconds - **Apply operations**: 10-30 seconds - **Post-verification**: 5-10 seconds - **Total time**: ~1-2 minutes ### Large Patches (100MB+) - **Pre-verification**: 10-20 seconds - **Backup creation**: 1-3 minutes - **Apply operations**: 30-90 seconds - **Post-verification**: 10-20 seconds - **Total time**: ~2-5 minutes **Factors:** - Installation size (backup time) - Number of files (verification time) - Disk speed (SSD vs HDD) - Patch size (operation time) --- ## Best Practices ### Before Patching 1. **Close the Application**: Ensure application is not running 2. **Check Disk Space**: Ensure space for backup (~installation size) 3. **Backup Separately**: Create your own backup for critical systems 4. **Test First**: Use --dry-run to preview changes 5. **Right Patch**: Verify you have the correct patch for your version ### During Patching 1. **Use --verify**: Always use --verify flag for production 2. **Don't Interrupt**: Let the process complete 3. **Watch Output**: Monitor for errors or warnings 4. **Stable Connection**: Ensure stable disk/network access ### After Patching 1. **Test Application**: Verify application works correctly 2. **Check Version**: Confirm version was updated 3. **Remove Backup**: If successful, remove `backup.cyberpatcher` folder 4. **Keep Patch**: Keep patch file for future re-installations --- ## Troubleshooting ### Patch Fails with "Version Mismatch" **Problem:** Current version doesn't match patch requirements **Solution:** 1. Check current version: `./myapp/program.exe --version` 2. Find correct patch for your version 3. If no patch exists, reinstall target version --- ### Backup Restoration Fails **Problem:** Cannot restore from backup after failure **Solution:** 1. Check disk space 2. Manually copy files from `backup.cyberpatcher` to installation 3. Check permissions 4. Contact support if manual restoration fails --- ### Slow Performance **Problem:** Patching takes very long **Solution:** 1. Check disk speed (HDD vs SSD) 2. Close unnecessary applications 3. Ensure antivirus isn't scanning 4. Check if disk is fragmented (HDD) --- ### Application Won't Start After Patching **Problem:** Application fails to run after successful patch **Solution:** 1. Check post-verification passed (all hashes correct) 2. Re-apply patch 3. Restore from `backup.cyberpatcher` if it still exists 4. Re-install clean version and try again 5. Report bug with error logs --- ## Related Documentation - [Generator Tool Guide](generator-guide.md) - Creating patches - [Backup System](backup-system.md) - Backup, lifecycle, and rollback - [Hash Verification](hash-verification.md) - How verification works - [Troubleshooting](troubleshooting.md) - Common issues