Skip to the content.

Architecture & Technical Implementation

🏠 Overview  •  📦 Installation  •  📖 Usage  •  🏗️ Architecture  •  🏢 Enterprise  •  🔒 Locking  •  🌐 Networking  •  🐚 Shells  •  🎯 Threat Matrix  •  ❓ FAQ  •  ⚖️ SDKMAN! Comparison  •  📜 Changelog  •  🛡️ Security  •  🤝 Contributing  •  💬 Support


This project is a zero-dependency, lightweight, native Windows implementation designed to bypass the traditional complexities of virtualized bash scripts (like SDKMAN!) on Windows operating systems.

🔍 Quick Jump


The Core Mechanism: Directory Junctions

Instead of constantly appending and pruning your Windows PATH variable to point to different JDK folders (which quickly leads to the 1024-character PATH limit and environment variable bloat), the manager maintains a single Directory Junction (mklink /J) at:

%LOCALAPPDATA%\DiamTek\JVM\current

Your system PATH only ever needs to contain %LOCALAPPDATA%\DiamTek\JVM\current\bin. When you switch Java versions, the manager simply tears down the old junction and repoints it to the target JDK directory. This provides O(1) symlink resolution for the OS.

JDK Discovery Engine & Scanned Locations

During startup, inventory listing (jvm list), and quick-switching, the discovery engine scans all recognized local storage locations for valid bin\java.exe targets. It dynamically queries 12 fixed filesystem locations plus user-space package manager directories (13 total entries in the discovery inventory):

Discovered Location Target Distribution / Managing Tool Discovery Mode
C:\Program Files\Java\* Standard Oracle, Adoptium, Microsoft, Corretto, Liberica, Semeru, SapMachine, Mandrel, Dragonwell, Kona installs Automatic Scan
C:\Program Files (x86)\Java\* Legacy 32-bit JDKs and JREs Automatic Scan
C:\Program Files\Eclipse Adoptium\* Official Eclipse Adoptium / Temurin installer root Automatic Scan
C:\Program Files\Amazon Corretto\* Official Amazon Corretto installer root Automatic Scan
C:\Program Files\Zulu\* Official Azul Zulu OpenJDK installer root Automatic Scan
C:\Program Files\BellSoft\* Official BellSoft Liberica OpenJDK installer root Automatic Scan
C:\Program Files\Semeru\* Official IBM Semeru Runtime (OpenJ9) installer root Automatic Scan
C:\Program Files\Microsoft\* Official Microsoft Build of OpenJDK installer root Automatic Scan
C:\Java\* Enterprise standard root installations Automatic Scan
%USERPROFILE%\.jdks\* IntelliJ IDEA / JetBrains Toolbox managed JDKs Automatic Scan
%USERPROFILE%\.gradle\jdks\* Gradle automated toolchain downloads Automatic Scan
%USERPROFILE%\scoop\apps\* Scoop package manager Java installations (apps\*\current\bin\java.exe) Dynamic Scan
%LOCALAPPDATA%\JavaVersionManager\links\* Bring Your Own JDK (jvm link) custom junctions Link Store Scan

The discovery engine extracts release metadata (vendor, version, release type) from release files or parses binary headers, cataloging each JDK into memory without writing temporary files.

graph TD
    Shell["Developer Terminal, Shell & IDE Environments<br/>PowerShell • CMD • Windows Terminal • VS Code"]
    Path["Persistent User PATH Environment Entry<br/>%LOCALAPPDATA%\DiamTek\JVM\current\bin"]
    Junction["NTFS Directory Junction Repointing Target<br/>%LOCALAPPDATA%\DiamTek\JVM\current"]
    
    JDK21["Adoptium OpenJDK 21 (Long-Term Support)<br/>C:\Program Files\Java\jdk-21"]
    JDK17["Oracle JDK 17 (Long-Term Support)<br/>C:\Program Files\Java\jdk-17"]
    JDKCustom["Custom Enterprise or GraalVM JDK<br/>C:\Development\graalvm-21"]

    Shell --> Path
    Path --> Junction
    Junction -.->|"Active Switch (O(1))"| JDK21
    Junction -.->|"Alternative Target"| JDK17
    Junction -.->|"BYO-JDK Link"| JDKCustom

Directory Junction Lifecycle & Safe Unbinding (Remove-DirectorySafely)

Directory junctions in Windows are NTFS reparse points (IO_REPARSE_TAG_MOUNT_POINT) that redirect directory path resolution at the kernel filesystem driver level. Managing junctions safely requires handling reparse point unbinding, recursive deletion hazards, and dangling junction deadlocks.

flowchart TD
    TargetDir["Target Folder Path<br/>e.g. %LOCALAPPDATA%\\DiamTek\\JVM"] --> InspectAttrs{"Is ReparsePoint?<br/>Attributes -band ReparsePoint"}
    
    InspectAttrs -->|Yes - Reparse Point| UnbindJunction["Unbind Junction Pointer<br/>[System.IO.Directory]::Delete(Path, $false)<br/>or cmd.exe /c rmdir /q Path"]
    UnbindJunction --> CompleteClean["Junction Pointer Removed<br/>Target JDK Directory Untouched (100% Preserved)"]
    
    InspectAttrs -->|No - Physical Directory| EnumerateChildren["Enumerate All Child Items Recursively"]
    EnumerateChildren --> FilterReparse{"Child is ReparsePoint?"}
    
    FilterReparse -->|Yes| BottomUpUnbind["Bottom-Up Child Unbinding<br/>Unlinks nested junctions in candidate stores"]
    FilterReparse -->|No| KeepPhysical["Retain physical files for tree delete"]
    
    BottomUpUnbind --> TreeRemoval["Execute cmd.exe /c rmdir /s /q Path<br/>(Junction-safe tree deletion in PS 5.1)"]
    KeepPhysical --> TreeRemoval
    TreeRemoval --> PurgeComplete["Sanitized Directory Tree"]

1. Non-Destructive Reparse Point Unbinding (Remove-DirectorySafely)

In Windows automation, executing naive recursive deletions (such as PowerShell’s Remove-Item -Recurse in Windows PowerShell 5.1 or batch rmdir /s /q across poorly managed junction trees) can inadvertently traverse into the target directory, deleting the user’s real JDK installation (e.g. wiping C:\Program Files\Java\jdk-21 when attempting to delete the symlink folder %LOCALAPPDATA%\DiamTek\JVM\current).

Remove-DirectorySafely (implemented in uninstall.ps1 and packages\msi\build-msi.ps1) enforces deterministic, non-destructive junction unbinding:

  1. Root Reparse Point Audit: Queries filesystem metadata using the Win32 file attribute flag:
    $rootItem.Attributes -band [System.IO.FileAttributes]::ReparsePoint
    
  2. Atomic Unbind Without Target Mutation: If the path is a reparse point container, it unlinks the junction via .NET [System.IO.Directory]::Delete($rootItem.FullName, $false) with the recursive parameter explicitly set to $false (falling back to cmd.exe /c "rmdir /q \"$path\"" without /s). This destroys the reparse tag and link record in NTFS master file table (MFT) without recursing into the target folder.
  3. Bottom-Up Child Reparse Point Unlinking: If the target path is a physical directory containing nested candidate junctions (e.g., %LOCALAPPDATA%\DiamTek\JVM\candidates\), the routine traverses children bottom-up, isolating each reparse point and unbinding it before attempting to remove physical parent folders.
  4. Junction-Safe Tree Teardown: Uses cmd.exe /c "rmdir /s /q \"$Path\"" to perform tree deletion, eliminating recursion bugs present in older PowerShell versions.

2. Broken Junction Recovery Without if exist Deadlocks

Windows cmd.exe contains a well-known architectural quirk: the if exist <path> condition evaluates the existence of the target of a directory junction rather than the junction entry itself.

The engine provides two distinct switching engines that users can toggle via the Settings menu or CLI flags:

  1. Symlink Mode (Default, UAC-Free):
    • Mechanism: Updates the NTFS Directory Junction pointer (%LOCALAPPDATA%\DiamTek\JVM\current) in user-space.
    • Privileges: Standard user space (UAC-free, zero admin popups).
    • Compatibility: Native for modern tools and standard classloaders (Maven, Gradle, IntelliJ IDEA, VS Code, Eclipse).
  2. Registry Mode (Legacy, UAC Required):
    • Mechanism: Directly writes the absolute JDK path to the Machine-level Windows Registry (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) and updates the system-wide Machine PATH. Invoked on the CLI via --legacy or --registry.
    • Privileges: Requires Administrator (UAC) Elevation on every switch, spawning an elevated background PowerShell worker via Start-Process -Verb RunAs.
    • Compatibility: Dependable fallback for legacy enterprise applications, obscure Windows service runners, or custom classloaders that perform strict canonical path checks and cannot resolve NTFS Directory Junctions.

[!NOTE] Internal Mode Sentinel: The user’s active mode preference is persisted in %LOCALAPPDATA%\DiamTek\JVM\mode.txt. Internally, mode.txt stores either SYMLINK (Symlink Mode) or DIRECT (Registry Mode, activated via --legacy or --registry).

flowchart TD
    Command["jvm switch / quick-switch command"] --> ModeCheck{"Active Mode?"}
    
    ModeCheck -->|Symlink Mode| TearDown
    ModeCheck -->|Registry Mode| CheckAdmin

    subgraph SymlinkMode["Symlink Mode (Default - UAC-Free)"]
        TearDown["Remove-Item / rmdir current"] --> CreateJunction["New-Item -ItemType Junction<br/>targeting selected JDK"]
        CreateJunction --> UpdateProfile["Invoke PowerShell Set-JvmVar Session Hook<br/>Updates active shell process memory"]
        UpdateProfile --> InstantSuccess["Instant Switch Across All Open Shells (0 UAC)"]
    end
    
    subgraph RegistryMode["Registry Mode (Legacy - UAC Required)"]
        CheckAdmin{"Running as Admin?"}
        CheckAdmin -->|Yes| WriteHKLM["[Environment]::SetEnvironmentVariable<br/>('JAVA_HOME', target, 'Machine')"]
        CheckAdmin -->|No| Elevate["Spawn Start-Process -Verb RunAs<br/>(Triggers Windows UAC Prompt)"]
        Elevate --> WriteHKLM
        WriteHKLM --> Broadcast["Broadcast Win32 SendMessageTimeout API<br/>WM_SETTINGCHANGE: Environment"]
    end

Dual Update Channel Engine & Trust Model Architecture

DiamTek JVM embeds an autonomous, dual-track self-update and verification engine designed to reconcile enterprise stability with rapid developer iteration. The engine decouples channel selection, remote manifest resolution, cryptographic integrity verification, ahead-of-remote downgrade blocking, and external atomic process replacement.

flowchart TD
    Trigger["jvm self-update / Settings Option 5"] --> ReadChannel["Read %LOCALAPPDATA%\\DiamTek\\JVM\\channel.txt<br/>(Defaults to STABLE if missing)"]
    
    ReadChannel --> ChannelCheck{"Target Channel?"}
    
    subgraph StableChannel["🟢 Stable Channel Pipeline (Official Releases)"]
        ChannelCheck -->|Stable| QueryRel["Query GitHub Releases API<br/>/repos/.../releases/latest"]
        QueryRel -->|HTTP 403 / 429 Rate Limited| FallbackRedirect["HTTP 302 Location Header Sniffer<br/>HttpWebRequest to releases/latest (Zero API Quota)"]
        FallbackRedirect --> ParseTag["Extract Latest SemVer Tag & Assets"]
        QueryRel -->|HTTP 200 OK| ParseTag
        ParseTag --> CompareStableBuild{"Local Build >= Remote Build?"}
        CompareStableBuild -->|Local Build Newer| BlockDowngradeStable["[SKIP] Local Build is Newer<br/>Prevents Dev Downgrade"]
        CompareStableBuild -->|New Release Available| FetchSums["Fetch Official SHA256SUMS.txt<br/>from GitHub Release Assets"]
        FetchSums --> DownloadPayloads["Download Target Assets to %TEMP%<br/>install.ps1 / jvm.bat"]
        DownloadPayloads --> VerifySHA["Verify ComputeHash(SHA256) == Manifest<br/>System.Security.Cryptography.SHA256"]
        VerifySHA -->|Hash Mismatch| AbortSecurity["[FATAL] Cryptographic Hash Mismatch<br/>Halt Execution & Clean Temp"]
        VerifySHA -->|Integrity Verified| SpawnRunner["Handoff to Decoupled Update Runner"]
    end

    subgraph NightlyChannel["🟣 Nightly Channel Pipeline (Cutting-Edge Main Branch)"]
        ChannelCheck -->|Nightly| QueryCommits["Query GitHub Commits API<br/>/repos/.../commits/main"]
        QueryCommits -->|HTTP 403 / 429 Rate Limited| FastlyCDN["Stream tip from raw.githubusercontent.com<br/>(Fastly Anycast Global CDN)"]
        QueryCommits -->|HTTP 200 OK| ExtractCommit["Extract Short Commit SHA & Date"]
        FastlyCDN --> DownloadNightly["Download latest jvm.bat to %TEMP%"]
        ExtractCommit --> DownloadNightly
        DownloadNightly --> ParseNightlyBuild["Parse JVM_BUILD from Streamed jvm.bat"]
        ParseNightlyBuild --> CompareNightlyBuild{"Local Build >= Nightly Build?"}
        CompareNightlyBuild -->|Local Build Newer| BlockDowngradeNightly["[SKIP] Local Build is Newer<br/>(Build X > Nightly Build Y)"]
        CompareNightlyBuild -->|Equal Build| UpToDate["[OK] Already Up to Date"]
        CompareNightlyBuild -->|Nightly Build Newer| AuditSHA["Verify Git Blob SHA-1 vs GitHub Contents API & Compute SHA-256"]
        AuditSHA -->|Blob SHA Mismatch| AbortSecurity
        AuditSHA -->|Blob SHA Verified| SpawnRunner
    end

    subgraph AtomicHandoff["Decoupled Process Handoff & Atomic Swap"]
        SpawnRunner --> WriteRunner["Write update_runner.bat to %LOCALAPPDATA%\\DiamTek\\JVM\\"]
        WriteRunner --> ExecDetached["Execute detached: start cmd.exe /c update_runner.bat<br/>Parent jvm.bat exits immediately (releasing file locks)"]
        ExecDetached --> WaitUnlock["Runner waits for file handle release<br/>(ping -n 2 127.0.0.1 >nul)"]
        WaitUnlock --> AtomicMove["Move /Y %TEMP%\\jvm.bat to %LOCALAPPDATA%\\DiamTek\\JVM\\bin\\jvm.bat"]
        AtomicMove --> SyncMetadata["Refresh Taskbar & Start Menu Shortcuts<br/>Update channel.txt Sentinel"]
        SyncMetadata --> PurgeSelf["Self-Delete update_runner.bat & Temp Files"]
    end

1. Channel Persistence & Runtime Selection

2. Upstream Resolution & Zero-Quota Rate Limit Resilience

To prevent GitHub’s 60-request-per-hour unauthenticated REST API quota from breaking update checks:

3. Cryptographic Integrity & Downgrade Prevention

4. Decoupled Runner Handoff & Atomic Swap

Because Windows enforces strict kernel file locking (ERROR_SHARING_VIOLATION / 0x00000020) on active running executables, a running batch file cannot overwrite itself in place. JVM resolves this through a detached handoff mechanism:

  1. The active jvm.bat process stages the verified replacement file in %TEMP%\jvm_update.bat.
  2. It generates an ephemeral runner script (%LOCALAPPDATA%\DiamTek\JVM\update_runner.bat).
  3. It executes the runner in a detached, asynchronous subshell (start "" cmd.exe /c "%RUNNER%") and immediately calls exit /b 0 to release all file locks on %LOCALAPPDATA%\DiamTek\JVM\bin\jvm.bat.
  4. The runner polls for lock release, atomically moves the replacement file into the binary directory, synchronizes pinned shortcuts and Windows Terminal profiles, and self-deletes upon completion.

Deep OS Environment Management

To ensure deep OS integration without requiring users to download external binaries (like setx augmentations), the tool relies on inline PowerShell execution invoked seamlessly via cmd.exe.

Global/Machine State (HKLM)

Session State Isolation

UAC Elevation Boundary & Process Isolation

When modifying Machine-level environment variables (HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) or executing system-wide JDK cleanups, unprivileged users must elevate across the Windows User Account Control (UAC) security boundary. Traditional automation approaches often introduce Local Privilege Escalation (LPE), Time-of-Check to Time-of-Use (TOCTOU) race windows, or command-line quoting injection vulnerabilities.

flowchart TD
    UnprivilegedUser["Unprivileged Process<br/>(jvm.bat / install.ps1 / uninstall.ps1)"] --> BuildScript["Construct Memory Script Block<br/>$script = '...'"]
    
    subgraph Sanitization["Isolation & Encoding Pipeline"]
        BuildScript --> EncodeParams["Base64 Encode Dynamic Parameters<br/>[Convert]::ToBase64String(UTF-16LE)"]
        EncodeParams --> EmbedScript["Interpolate Encoded Tokens into Script"]
        EmbedScript --> EncodePayload["Base64 Encode Full Script to UTF-16LE<br/>$enc = [Convert]::ToBase64String(...)"]
    end
    
    subgraph Execution["Hardened Process Invocation"]
        EncodePayload --> PinWorkingDir["Explicit System32 Working Directory<br/>-WorkingDirectory $s (SpecialFolder::System)"]
        PinWorkingDir --> PinBinaryPath["Absolute Binary Path Pinning<br/>$ps = Join-Path $s 'WindowsPowerShell\\v1.0\\powershell.exe'"]
        PinBinaryPath --> SpawnElevated["Start-Process -FilePath $ps -Verb RunAs<br/>-ArgumentList @('-NoProfile', '-EncodedCommand', $enc)<br/>-WorkingDirectory $s -WindowStyle Hidden -Wait"]
    end
    
    SpawnElevated --> UACPrompt{"Windows UAC Prompt<br/>Consent / Credential"}
    UACPrompt -->|Granted| ElevatedWorker["Isolated Elevated Worker<br/>Executes purely in-memory in System32 context"]
    ElevatedWorker --> Complete["Registry / System Updated & Exits Cleanly"]

1. In-Memory Base64 UTF-16LE -EncodedCommand Protocol

Passing dynamic parameters (such as directory paths with spaces, single quotes, double quotes, ampersands, or parenthesis) across the Start-Process -Verb RunAs boundary via standard string concatenation (-ArgumentList "-Command ..."):

JVM completely neutralizes this by encoding both individual dynamic parameters and the overall payload into UTF-16LE Base64 strings:

$target = $env:CURRENT_JDK_PATH;
$b64 = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($target));
$script = '$target = [System.Text.Encoding]::Unicode.GetString([Convert]::FromBase64String(''' + $b64 + ''')); ' +
          '[Environment]::SetEnvironmentVariable(''JAVA_HOME'', $target, ''Machine''); ...';
$enc = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($script));
$s = [Environment]::GetFolderPath([Environment+SpecialFolder]::System);
$ps = Join-Path $s 'WindowsPowerShell\v1.0\powershell.exe';
Start-Process -FilePath $ps -Verb RunAs `
    -WorkingDirectory $s `
    -WindowStyle Hidden -Wait `
    -ArgumentList @('-NoProfile', '-EncodedCommand', $enc)

Because -EncodedCommand consumes a Base64 Unicode string directly, the Windows process loader performs zero command-line tokenization or quote unescaping, preventing command injection and shell syntax errors.

2. Process & Working Directory Isolation with Environment Saturation Immunity

When an elevated process is spawned via Start-Process -Verb RunAs, by default it inherits the caller process’s current working directory and process environment.

Environment Broadcast & Registry ValueKind Preservation

Modifying environment variables in the Windows Registry (HKCU\Environment or HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment) does not automatically update already running desktop processes (such as Windows Explorer, taskbar runners, or existing command prompts). The operating system requires an explicit environment change notification broadcast.

1. Non-Blocking P/Invoke SendMessageTimeout Architecture

Windows applications listen for WM_SETTINGCHANGE (0x001A) messages sent to HWND_BROADCAST (0xFFFF) with lParam set to "Environment".

2. Registry ValueKind Preservation (REG_EXPAND_SZ vs REG_SZ)

The Windows PATH environment variable frequently relies on variable expansion tags (e.g., %SystemRoot%\system32, %USERPROFILE%\AppData\Local\Microsoft\WindowsApps).

Ecosystem Routing (Universal Candidate Engine)

Like SDKMAN!, this tool intercepts commands for popular Java and JVM ecosystem tools (Maven, Gradle, Kotlin, Scala, Groovy, Ant, sbt, JBang, Quarkus, Spring Boot CLI, Micronaut). The CLI acts as a universal router:

  1. It intercepts the jvm install <candidate> <version> command.
  2. It executes a PowerShell Invoke-RestMethod to the respective API (Adoptium, GitHub Releases, Azul, BellSoft, IBM, SAP, Alibaba, Tencent, Apache, etc.) to securely resolve the download URL and SHA-256 / SHA-512 / SHA-1 / MD5 checksums.
  3. The payloads are extracted via Expand-Archive and isolated in %LOCALAPPDATA%\DiamTek\JVM\candidates\<candidate>.
  4. Specific <CANDIDATE>_HOME variables (JAVA_HOME, MAVEN_HOME, GRADLE_HOME, KOTLIN_HOME, SCALA_HOME, GROOVY_HOME, ANT_HOME, SBT_HOME, JBANG_HOME, QUARKUS_HOME, SPRING_HOME, MICRONAUT_HOME) are injected into the registry, mapping the ecosystem completely identically to native Java.

LTS Target Resolution Architecture

The lts semantic target operates under two complementary models depending on the operation:

Multi-Tier Hash Resolution & Downloader Pipeline (:ExecuteSharedDownloader)

Downloading and installing remote developer toolchains introduces significant supply chain and integrity risks (CWE-494). The universal downloader pipeline (:ExecuteSharedDownloader) implements a resilient 5-tier cryptographic resolution and verification protocol:

flowchart TD
    Start["Initiate Candidate Download (:ExecuteSharedDownloader)"] --> ChecksumProvided{"Explicit Checksum URL Supplied by Vendor?"}
    
    ChecksumProvided -->|Yes| FetchSumFile["Tier 1: Fetch Remote Checksum File (.sha256 / .sha512 / .sha1 / .md5)"]
    FetchSumFile --> ParseSumFile{"Checksum File Found? (HTTP 200 vs 404)"}
    
    ParseSumFile -->|HTTP 200 OK| ExtractHex["Extract Raw Hex Hash (Normalize BSD / GNU Format)"]
    
    ChecksumProvided -->|No / Missing| GitHubCheck
    ParseSumFile -->|HTTP 404 Not Found| GitHubCheck{"Asset on GitHub Releases? (github.com/.../releases/download/...)"}
    
    GitHubCheck -->|Yes| QueryGHAPI["Tier 2: Query GitHub Releases API (/repos/:owner/:repo/releases/tags/:tag)"]
    QueryGHAPI --> SniffDigest{"API Asset Digest Available? (digest: sha256:hex)"}
    SniffDigest -->|Found| BindDigest["Extract SHA-256 Digest (Authenticated Infrastructure Hash)"]
    
    GitHubCheck -->|No / Mirror Available| MirrorFallback["Tier 3: Multi-Mirror Redirection (e.g. Apache archive.apache.org Fallback)"]
    SniffDigest -->|Not Found / Blocked| InteractiveCheck
    MirrorFallback --> InteractiveCheck{"Interactive TUI Mode? (!CLI_COMMAND! == '')"}
    
    InteractiveCheck -->|Yes - Interactive| PromptUser["Tier 4: Interactive Confirmation Prompt (Continue without checksum? y/N)"]
    PromptUser --> UserChoice{"User Consent? (y/N)"}
    UserChoice -->|Y / Yes| UnverifiedWarning["[WARNING] Proceeding unverified (Explicit user consent recorded)"]
    UserChoice -->|N / No / Enter| FailClosedAbort["[ERROR] Aborting due to security policy (Preserve diagnostics & Pause)"]
    
    InteractiveCheck -->|No - Headless CLI| FlagCheck{"--skip-checksum or --no-verify? (Explicit CLI Flag)"}
    FlagCheck -->|Yes| UnverifiedWarning
    FlagCheck -->|No - Fail-Closed| FailClosedAbort
    
    ExtractHex --> StreamPayload["Download Payload via WebClient/Stream (Validate SSRF: Test-TrustedJvmUri)"]
    BindDigest --> StreamPayload
    UnverifiedWarning --> StreamPayload
    
    StreamPayload --> ComputeHash{"Compute Archive Hash (SHA256 / SHA512)"}
    ComputeHash --> CheckMatch{"Hash Matches Manifest? (Byte-for-byte equality)"}
    CheckMatch -->|Match OK| Unpack["Atomic Archive Unpack & Staging (Validate ZipSlip & Reparse Points)"]
    CheckMatch -->|Mismatch| PurgeAbort["[FATAL] Cryptographic Hash Mismatch (Delete corrupt payload & halt)"]
    Unpack --> PromptActivate{"Candidate Installed (Prompt or Auto-Activate)"}

1. Tier 1: Vendor Checksum File Resolution (.sha256, .sha512, .sha1, .md5)

The downloader attempts to resolve standalone vendor checksum manifests over HTTPS. It normalizes both single-line raw hex digests and GNU/BSD manifest formats (<hash> <filename> or SHA256 (<filename>) = <hash>).

2. Tier 2: Upstream GitHub Releases REST API Asset Digest Auto-Discovery (CWE-494)

When vendors publish archives on GitHub Releases without accompanying .sha256 files (e.g., Micronaut CLI), attempting to download a .sha256 URL returns HTTP 404.

3. Tier 3: Multi-Mirror Redirection & Archive Fallback (e.g., Apache Maven)

For vendors that transition active releases from production mirrors (downloads.apache.org or repo.maven.apache.org) to long-term archives (archive.apache.org), the downloader chains fallback URLs automatically before failing.

4. Tier 4: Interactive TUI Confirmation Fallback

If upstream vendor mirrors provide neither a checksum file nor an API asset digest:

5. Tier 5: Headless CLI Bypassing & Fail-Closed Enforcement (--skip-checksum / --no-verify)

In non-interactive CI/CD scripting:

6. Candidate Version Activation & Batch Parser Escaping Rails

Real-Time PowerShell Session Propagation (Set-JvmVar)

Because Windows process environments cannot ordinarily be modified by a child batch process, install.ps1 injects a native PowerShell function hook into $PROFILE. When jvm switches an active tool or JDK:

  1. jvm.bat writes target environment pairs (KEY=VALUE) to $env:TEMP\.jvm_session_target.
  2. The PowerShell wrapper intercepts the return code and invokes Set-JvmVar.
  3. Set-JvmVar surgically strips the old \bin directory from $env:Path and prepends the new \bin directory directly into the current PowerShell process memory.
  4. It updates $env:JAVA_HOME (or corresponding tool variables) live, providing instantaneous switching without reopening terminal tabs.

Decoupled Profile Hook Management (jvm hook)

The PowerShell profile wrapper is decoupled from global User PATH installation. Developers can manage the hook independently via jvm hook [install|remove|status] or via Option 2 in the interactive Settings menu. The hook automatically discovers and synchronizes both Windows PowerShell 5.1 and modern PowerShell 7+ profiles across standard or redirected Documents directories ([Environment]::GetFolderPath('MyDocuments')).

Automated Health Diagnostics & Shadow Detection (jvm doctor)

The jvm doctor diagnostic engine runs a deterministic 7-point system health audit across:

  1. Storage Root Accessibility: Verifies %LOCALAPPDATA%\DiamTek\JVM exists and has NTFS write permissions.
  2. Directory Junction Target Validity: Validates that %LOCALAPPDATA%\DiamTek\JVM\current points to an active JDK containing bin\java.exe.
  3. Registry Synchronization: Cross-references User (HKCU) and Machine (HKLM) JAVA_HOME variables.
  4. PATH Precedence & Rogue Shadowing: Scans where.exe java to detect legacy Oracle javapath or System32\java.exe shims overriding JVM in your system PATH.
  5. PowerShell $PROFILE Hook: Audits wrapper function presence across detected PowerShell profiles.
  6. CPU Architecture: Confirms native architecture matches (x64 / ARM64).
  7. Discovered JDK Distribution Inventory: Audits recognized runtimes on disk.

Ephemeral Execution Architecture (jvm exec / jvm run)

Unlike persistent switching which mutates directory junctions or registries, jvm exec / jvm run resolves the requested JDK build, spawns an isolated child subshell with local JAVA_HOME and prepended bin\ in PATH, invokes the user command, and propagates the child process’s exact exit code back to the host shell prompt, leaving global OS state 100% untouched.

Bulletproof Batch Heredoc Escaping

Windows cmd.exe does not natively support Bash-style heredocs (cat <<EOF). Embedding multi-line PowerShell scripts inside a batch ( ... ) > script.ps1 redirection block requires careful escaping:

Deep Uninstaller & Windows Integration Architecture

The uninstaller subsystem (uninstall.ps1) is designed for 100% total system sanitization:

  1. UAC Escalation: Uses .NET security principals to check for elevated tokens; if missing, automatically spawns an elevated PowerShell host via Start-Process -Verb RunAs.
  2. Registry Integration: Registers under HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall\DiamTek.JVM with native Windows “Installed apps” metadata, dynamic EstimatedSize computation (with a 1,024 KB floor for Windows 11 compatibility), and creates a Start Menu uninstaller shortcut in Start Menu\Programs\DiamTek.
  3. Dual-Scope Cleanup: Cleans both User and Machine environment variables and PATH registries, surgically strips the $PROFILE hook, deletes the AppData Ecosystem cache, purges Windows Terminal profiles, removes pinned taskbar shortcuts, cleans session files, and prompts to clean C:\Program Files\Java.

Windows Terminal & Shell Integration Architecture

To provide a first-class modern Windows developer experience while strictly maintaining 100% pure Batch & PowerShell code:

  1. Dynamic Profile Injection: install.ps1 scans for Windows Terminal configurations across Release, Preview, and Unpackaged locations (LocalState\settings.json). It injects a dedicated profile with GUID {b20650a4-4212-4d64-9edf-744e9285e2be}, pointing to high-resolution assets/icon.png.
  2. Tab Lifecycle Management: Configured with cmd.exe /c and closeOnExit: always. When a developer exits the interactive JVM menu (exit /B 0), the hosting cmd.exe process terminates, signaling Windows Terminal to immediately close the tab.
  3. Shortcut Synchronization: Creates Start Menu application shortcuts targeting wt.exe -p "Java Version Manager" (falling back to cmd.exe /c on systems without Windows Terminal). During installation and self-updates, the script automatically searches %APPDATA%\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar\ to detect and update existing pinned taskbar shortcuts in place.
  4. AppUserModelID & Taskbar Mechanics: Windows Terminal is a packaged WinUI app that hardcodes its own process-level AppUserModelID (Microsoft.WindowsTerminal...) on all hosting windows. By registering a dedicated profile with native icon and dropdown integration rather than forcing brittle binary wrappers, the utility respects the OS container model while maintaining a zero-binary, 100% script-based repository.

Windows Terminal Settings JSONC Parser Engine

Windows Terminal stores user profiles and preferences in settings.json located within package application local data or unpackaged user profiles across Release, Preview, and Unpackaged installations:

The JSONC Parsing Challenge

Microsoft Windows Terminal formats settings.json as JSON with Comments (JSONC):

Standard PowerShell ConvertFrom-Json (particularly in Windows PowerShell 5.1, the default engine pre-installed on all Windows 10 and 11 workstations) is a strict RFC 8259 JSON parser and throws a terminating syntax error when encountering comments or trailing commas.

Regex Preprocessor Engine

To achieve zero-dependency JSONC parsing across all PowerShell versions without requiring external libraries or third-party modules, install.ps1, uninstall.ps1, and packages\msi\build-msi.ps1 execute a high-performance regex preprocessing pipeline:

$wtContent = Get-Content $wtSettings -Raw -ErrorAction Stop

# 1. Strip block comments (/* ... */) in single-line mode (?s)
# 2. Strip single-line comments (// ...) in multi-line mode (?m)
# 3. Strip trailing commas preceding closing braces or brackets
$cleanJson = $wtContent `
    -replace '(?s)/\*.*?\*/', '' `
    -replace '(?m)//.*$', '' `
    -replace ',\s*([\}\]])', '$1'

$wtJson = $cleanJson | ConvertFrom-Json

Idempotent Profile Synchronization

Once sanitized and parsed into a PowerShell object graph:

  1. Deduplication Check: Queries $wtJson.profiles.list for matching profile GUID {b20650a4-4212-4d64-9edf-744e9285e2be} or name 'Java Version Manager'.
  2. Profile Creation: If missing, constructs a [PSCustomObject] with:
    • commandline: 'cmd.exe /c "%LOCALAPPDATA%\DiamTek\JVM\bin\jvm.bat"'
    • guid: '{b20650a4-4212-4d64-9edf-744e9285e2be}'
    • icon: '%LOCALAPPDATA%\DiamTek\JVM\assets\icon.png'
    • closeOnExit: 'always'
    • startingDirectory: '%USERPROFILE%'
  3. In-Place Update: If the profile already exists, surgically updates commandline, icon, and closeOnExit without mutating custom font, color scheme, or keybinding customizations set by the user.
  4. Atomic UTF-8 Serialization: Serializes the object graph back via ConvertTo-Json -Depth 32 and writes the file via Set-Content $wtSettings $newWtContent -Encoding utf8.
  5. Clean Uninstallation: During uninstall.ps1, the parser removes the JVM profile, checks if defaultProfile was assigned to JVM, redirects defaultProfile to the first available profile if necessary, and rewrites settings.json cleanly.

Multi-Channel Packaging Pipelines

graph LR
    Source["Repository Source Code<br/>(jvm.bat & assets)"] --> WixBuild["WiX Toolset v4 Engine<br/>(build-msi.ps1)"]
    WixBuild --> OutputMSI["Standalone Dual-Architecture MSI<br/>x64 & arm64 (Embedded CAB)"]
    OutputMSI --> TestSuite["21-Point Test Suite<br/>(test-msi.ps1)"]
    TestSuite --> Provenance["GitHub Actions SLSA Attestation<br/>Sigstore In-Toto Provenance"]
    Provenance --> Release["Official GitHub Production Release<br/>MSIs, Zips & Checksums"]
    Release --> PM["Windows Package Manager Ecosystem<br/>Winget • Scoop • Chocolatey"]

Reproducible Lockfile Architecture (.jvm.lock & jvm install –locked)

To guarantee zero runtime drift across distributed engineering teams, CI/CD runners, and reproducible deployment pipelines (CWE-354 / CWE-494), DiamTek JVM provides native lockfile generation and validation:

1. Specification & JSON Schema Contract (Schema v2)

The .jvm.lock manifest records the exact tool candidate, runtime version, vendor, host architecture, official vendor download URL, and cryptographic digest:

{
  "schema": 2,
  "$schema": "https://raw.githubusercontent.com/DiamTek/Java-Version-Manager-Windows/main/schemas/jvm.lock.json",
  "lockfile_version": 1,
  "platform": "windows-x64",
  "generated_at": "2026-10-01T07:00:00Z",
  "tools": {
    "java": {
      "version": "21",
      "vendor": "adoptium",
      "arch": "x64",
      "url": "https://github.com/adoptium/temurin21-binaries/releases/download/...",
      "checksum": "a1b2c3d4e5...",
      "checksum_type": "sha256"
    },
    "maven": {
      "version": "3.9.9",
      "vendor": null,
      "arch": "all",
      "url": "https://archive.apache.org/dist/maven/maven-3/3.9.9/binaries/...",
      "checksum": "f6e5d4...",
      "checksum_type": "sha512"
    }
  }
}

2. Multi-Tool Composition & Atomic Staged Commit (CWE-362)

3. Hierarchical Traversal & Reparse Boundary Defense (CWE-59 / CWE-22)

4. Cryptographic Fail-Closed Enforcement (CWE-494 / CWE-354)

During --locked execution:

  1. Every download URL is strictly validated against Test-TrustedJvmUri domain allowlists (CWE-918).
  2. The payload is downloaded to an ACL-protected staging directory (%LOCALAPPDATA%\DiamTek\JVM\temp).
  3. Native .NET Cryptography APIs compute the SHA-256 (or SHA-512) digest of the downloaded archive.
  4. If the computed hash fails to match the lockfile checksum, the payload is immediately purged, the operation aborts fail-closed, and a security violation is emitted.

5. Lockfile Auditing & Lifecycle Management


Cryptographic Provenance Verification (jvm verify)

DiamTek JVM implements a dedicated, multi-tier cryptographic and provenance verification engine accessible via jvm verify <version|all>. This engine actively audits the local integrity and chain of trust for any installed runtime or ecosystem tool against a strict 6-tier checklist:

  1. Artifact exists: Confirms the physical binary or JAR exists on the local filesystem.
  2. HTTPS verified: Validates the payload originated from a secure https:// transport layer.
  3. Host trusted: Asserts the download host is explicitly permitted in the Test-TrustedJvmUri domain allowlist (CWE-918 / CWE-601).
  4. SHA-256 verified: Computes the payload’s hash and ensures byte-for-byte equality with the official manifest.
  5. Signature verified: Checks the binary for a valid, unbroken Authenticode or embedded digital signature.
  6. Provenance chain intact: Conclusively asserts the end-to-end cryptographic and origin integrity of the artifact.

Failure Recovery, Atomic State Rollback & Resource Hygiene

In enterprise developer environments, operations may abort unexpectedly due to canceled UAC prompts, network timeouts, power interruptions, or malformed archives. DiamTek JVM enforces a comprehensive, zero-dangling-state architecture across all execution paths.

flowchart TD
    Operation["Initiate Mutation<br/>(Switch, Install, Update, Elevation)"] --> Snapshot["Capture State Snapshot<br/>PREV_JUNCTION_TARGET • .bak • Manifests"]
    Snapshot --> TryStage["Execute Staged Mutation<br/>(Temporary .tmp files, in-memory wrappers)"]
    TryStage --> VerifyOutcome{"Operation Successful?<br/>ExitCode == 0 & Hash/Integrity OK"}
    VerifyOutcome -->|"Yes (Success)"| CommitState["Atomic Commit<br/>Swap pointers, purge backups, release handles"]
    VerifyOutcome -->|"No (Failure / Abort)"| RollbackState["Atomic Rollback<br/>Restore PREV_JUNCTION_TARGET / .bak / registry"]
    RollbackState --> CleanupStaging["Deterministic Finally Cleanup<br/>Purge *.stage.*.tmp, Close Win32/COM/Stream handles"]
    CleanupStaging --> PropagateCode["Propagate Exit Code (exit /b 1)<br/>Sanitized diagnostic warning (CWE-209)"]

1. Atomic State Rollback Operations (CWE-460)

2. Deterministic Resource & Handle Lifecycle (CWE-459)

3. Zero Silent Catches & Sanitized Diagnostics (CWE-209 / CWE-390)

4. Transactional Installations & Crash-Safe State Machine (jvm transaction)

Every download, extraction, and activation is coordinated through an atomic JSON transaction journal (%LOCALAPPDATA%\DiamTek\JVM\transactions):


Unified Configuration Engine & config.json

DiamTek JVM provides an atomic configuration engine backed by %LOCALAPPDATA%\DiamTek\JVM\config.json.

Project Toolchain Parser (.jvm.toml / .jvmrc)

Projects can specify toolchains across Java and ecosystem candidates using standard TOML structure:

CMD & PowerShell Transparent Directory Switching Hooks


Content-Addressed Storage & Resilient Transport Engine


Environment Resolution, Toolchain & Diagnostic Subsystems

1. 7-Tier Precedence Resolution Graph Engine (jvm why)

To provide deterministic visibility into runtime selection across nested project structures and shell sessions, the engine evaluates environment precedence across 7 strictly ordered tiers:

  1. Tier 1 (CLI / Ephemeral Session): Temporary session overrides stored in %LOCALAPPDATA%\DiamTek\JVM\temp\.jvm_session_target_*.
  2. Tier 2 (Directory .java-version): Nearest directory-level .java-version pin discovered by upward directory traversal.
  3. Tier 3 (Directory .sdkmanrc): Standard SDKMAN! configuration translated into native candidate/version mappings.
  4. Tier 4 (Project .jvm.toml / .jvmrc): Project toolchain configuration defining required runtimes.
  5. Tier 5 (Reproducible .jvm.lock): Cryptographic manifest pinning candidate, vendor, URL, and SHA-256 hash.
  6. Tier 6 (User Configuration / Junction Link): Default runtime defined in config.json or target of active junction link (%LOCALAPPDATA%\DiamTek\JVM\current).
  7. Tier 7 (System PATH Fallback): Machine-level or inherited Windows PATH fallback.

2. 7-Layer Deep Candidate Analysis (jvm explain <candidate>)

Audits any installed candidate across 7 technical layers:

3. Smart Contextual Execution & Toolchain Conflict Matrix (jvm run)

Inspects active directory build descriptors and transparently delegates tasks:

4. CAS Telemetry & Deduplication Engine (jvm cache stats & jvm cache dedupe)

Monitors Content-Addressed Storage layout across sha256/, jdk/, maven/, gradle/, and kotlin/ categories, calculating item counts and megabyte footprint. Deduplication performs SHA-256 hashing across cached blobs and candidate trees to identify redundant payloads and calculate reclaimable disk space.

5. Sanitized Diagnostic Reporting & Support Bundler (jvm report, jvm doctor --report, jvm support)

Generates comprehensive troubleshooting artifacts while enforcing strict secret redaction (CWE-209 / CWE-532):

6. Self-Update History & Integrity-Verified Rollback (jvm self-update --history & --rollback)

Maintains an immutable archive of previous jvm.bat releases in %LOCALAPPDATA%\DiamTek\JVM\backups\. Before applying rollback, verifies target backup files for end-of-file validation markers (rem END OF SCRIPT), preventing partial or corrupt rollbacks (CWE-494).

Queries upstream metadata catalogs (Adoptium, Azul Zulu, SAP SapMachine, Gradle, Maven) without requiring browser access. Supports candidate tool routing, shorthand version queries (jvm search 21), and structured JSON output (--json) for automation.

8. Semantic Release Comparison Engine (jvm compare)

Evaluates platform differences between JDK releases. Features automated multi-LTS milestone JEP chaining (8 -> 11 -> 17 -> 21 -> 25) to detail cumulative language features, VM enhancements, and deprecations across LTS generations, alongside Java classfile format bytecode baseline matrices.

9. Next-Gen Portability & Toolchain Bundles Subsystem (profiles, snapshots, bundles, distro)

Architected for enterprise environment portability and strict air-gapped deployments:


Automated Adversarial Test Architecture (327 Tests, 41 CWEs)

The security, integrity, and operational resilience of DiamTek JVM are verified on every commit via tests/Test-JvmSecurity.ps1. The test harness executes 327 automated test cases across 16 defensive suites, covering 41 MITRE CWE classes (including CWE-798) with a verified 10.0 / 10.0 scorecard:

Suite Category Focus Status
Suite 1 Adversarial & Fuzzing Defense (Poison characters, ADS, Traversal, SSRF, TOML Metacharacters, Diagnostic Telemetry) PASS
Suite 2 Registry & Env Boundaries (ValueKind preservation, UAC elevation, Config Engine, Env Diff) PASS
Suite 3 Symlink & Junction Lifecycle (Reparse unbinding, auto-recovery, Doctor Self-Healing) PASS
Suite 4 Package Manifest Integrity & Lockfiles (WiX v4, Choco, Winget, .jvm.lock, CAS Layout, Cache CLI, Ownership) PASS
Suite 5 Concurrency & Reparse Resilience (Rapid switching, ACL verification, PID timestamping) PASS
Suite 6 Corrupt Registry Recovery & PATH Resilience (De-bloat, length limits) PASS
Suite 7 Uninstallation Safety & Markers (Root markers, deferred cleanup) PASS
Suite 8 Windows Terminal JSONC Parsing (Comment stripping, profile injection) PASS
Suite 9 Advanced Cache & Content-Addressed Storage (CAS Layout, Deduplication, Cache Bundling) PASS
Suite 10 Multi-Candidate Ecosystem Toolchains (Ecosystem candidates, SDKMAN translations, Version resolution) PASS
Suite 11 Transactional Recovery & Journal Logging (Crash-safe journals, Pre-state restoration, Rollback) PASS
Suite 12 Enterprise Networking & Machine Policy Enforcement (policy.toml, Corporate Proxy, Windows Cert Store) PASS
Suite 13 Advanced Lockfile Lifecycle, Freezing & Signatures (.jvm.lock v2, authentic archive checksums in freeze, 3-state signature verification, freeze, thaw, HMAC .jvm.lock.sig, managed secret enforcement & CWE-798 elimination) PASS
Suite 14 Unified Status, Ergonomics & Multi-Shell Cross-Compatibility (jvm status, Dynamic Completions, CMD Aliases) PASS
Suite 15 Adversarial Robustness, Fuzzing & Mutation Resilience (ADS streams, Fault injection, AST zero empty catch, Help cards, Timings, Universal JSON schema) PASS
Suite 16 Next-Gen Portability, Profiles, Snapshots & Toolchain Distros (Profiles lifecycle, Snapshots, transactional restore rollback, .jvmbundle ZipSlip/magic byte defense, Air-gapped distros, install.ps1 -Offline) PASS
Total Comprehensive Full-System Security Suite (327 / 327) 10.0 / 10.0

← Back to Documentation Overview