@@ -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