[PR #16190] env: properly handle nulls in REG_SZ strings #30859

Open
opened 2026-01-31 09:43:25 +00:00 by claunia · 0 comments
Owner

Original Pull Request: https://github.com/microsoft/terminal/pull/16190

State: closed
Merged: Yes


eb871bf fails to properly handle REG_SZ strings, which are documented as
being null-terminated and length restricted.
wcsnlen is the perfect fit for handling this situation as it returns
the position of the first \0, or the given length parameter.

As a drive by improvement, this also drops some redundant code:

  • to_environment_strings_w which is the same as to_string
  • Retrieving USERNAME/USERDOMAIN via LookupAccountSidW and
    COMPUTERNAME via GetComputerNameW is not necessary as the
    variables are "volatile" and I believe there's generally no
    expectation that they change unless you log in again.

Closes #16051

Validation Steps Performed

  • Run this in PowerShell to insert a env value with \0:
    $hklm = [Microsoft.Win32.RegistryKey]::OpenBaseKey(
      [Microsoft.Win32.RegistryHive]::LocalMachine,
      0
    )
    $key = $hklm.OpenSubKey(
      'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
      $true
    )
    $key.SetValue('test', "foo`0bar")
    
  • All EnvTests still pass ✅
  • (Don't forget to remove the above value again!)
**Original Pull Request:** https://github.com/microsoft/terminal/pull/16190 **State:** closed **Merged:** Yes --- eb871bf fails to properly handle REG_SZ strings, which are documented as being null-terminated _and_ length restricted. `wcsnlen` is the perfect fit for handling this situation as it returns the position of the first \0, or the given length parameter. As a drive by improvement, this also drops some redundant code: * `to_environment_strings_w` which is the same as `to_string` * Retrieving `USERNAME`/`USERDOMAIN` via `LookupAccountSidW` and `COMPUTERNAME` via `GetComputerNameW` is not necessary as the variables are "volatile" and I believe there's generally no expectation that they change unless you log in again. Closes #16051 ## Validation Steps Performed * Run this in PowerShell to insert a env value with \0: ```pwsh $hklm = [Microsoft.Win32.RegistryKey]::OpenBaseKey( [Microsoft.Win32.RegistryHive]::LocalMachine, 0 ) $key = $hklm.OpenSubKey( 'SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true ) $key.SetValue('test', "foo`0bar") ``` * All `EnvTests` still pass ✅ * (Don't forget to remove the above value again!)
claunia added the pull-request label 2026-01-31 09:43:25 +00:00
Sign in to join this conversation.
No Label pull-request
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: starred/terminal#30859