Skip to content

Commit ac19e43

Browse files
committed
check_env_var_len
1 parent 8d1f2e5 commit ac19e43

File tree

3 files changed

+22
-1
lines changed

3 files changed

+22
-1
lines changed

Lib/test/test_os.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1152,7 +1152,6 @@ def test_putenv_unsetenv(self):
11521152
self.assertEqual(proc.stdout.rstrip(), repr(None))
11531153

11541154
# On OS X < 10.6, unsetenv() doesn't return a value (bpo-13415).
1155-
@unittest.expectedFailureIfWindows('TODO: RUSTPYTHON; (AssertionError: ValueError not raised by putenv)')
11561155
@support.requires_mac_ver(10, 6)
11571156
def test_putenv_unsetenv_error(self):
11581157
# Empty variable name is invalid.

crates/common/src/windows.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ use std::{
33
os::windows::ffi::{OsStrExt, OsStringExt},
44
};
55

6+
/// _MAX_ENV from Windows CRT stdlib.h - maximum environment variable size
7+
pub const _MAX_ENV: usize = 32767;
8+
69
pub trait ToWideString {
710
fn to_wide(&self) -> Vec<u16>;
811
fn to_wide_with_nul(&self) -> Vec<u16>;

crates/vm/src/stdlib/os.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,20 @@ pub(super) mod _os {
428428
}
429429
}
430430

431+
/// Check if environment variable length exceeds Windows limit.
432+
/// size should be key.len() + value.len() + 2 (for '=' and null terminator)
433+
#[cfg(windows)]
434+
fn check_env_var_len(size: usize, vm: &VirtualMachine) -> PyResult<()> {
435+
use crate::common::windows::_MAX_ENV;
436+
if size > _MAX_ENV {
437+
return Err(vm.new_value_error(format!(
438+
"the environment variable is longer than {} characters",
439+
_MAX_ENV
440+
)));
441+
}
442+
Ok(())
443+
}
444+
431445
#[pyfunction]
432446
fn putenv(
433447
key: Either<PyStrRef, PyBytesRef>,
@@ -442,6 +456,8 @@ pub(super) mod _os {
442456
if key.is_empty() || key.contains(&b'=') {
443457
return Err(vm.new_value_error("illegal environment variable name"));
444458
}
459+
#[cfg(windows)]
460+
check_env_var_len(key.len() + value.len() + 2, vm)?;
445461
let key = super::bytes_as_os_str(key, vm)?;
446462
let value = super::bytes_as_os_str(value, vm)?;
447463
// SAFETY: requirements forwarded from the caller
@@ -464,6 +480,9 @@ pub(super) mod _os {
464480
),
465481
));
466482
}
483+
// For unsetenv, size is key + '=' (no value, just clearing)
484+
#[cfg(windows)]
485+
check_env_var_len(key.len() + 1, vm)?;
467486
let key = super::bytes_as_os_str(key, vm)?;
468487
// SAFETY: requirements forwarded from the caller
469488
unsafe { env::remove_var(key) };

0 commit comments

Comments
 (0)