diff --git a/lib/pure/includes/osenv.nim b/lib/pure/includes/osenv.nim index d0c92d56611d6..db291c5fd3773 100644 --- a/lib/pure/includes/osenv.nim +++ b/lib/pure/includes/osenv.nim @@ -45,8 +45,10 @@ else: proc c_getenv(env: cstring): cstring {. importc: "getenv", header: "".} - proc c_putenv(env: cstring): cint {. - importc: "putenv", header: "".} + when defined(vcc): + proc c_putenv_s(envname: cstring, envval: cstring): cint {.importc: "_putenv_s", header: "".} + else: + proc c_setenv(envname: cstring, envval: cstring, overwrite: cint): cint {.importc: "setenv", header: "".} proc c_unsetenv(env: cstring): cint {. importc: "unsetenv", header: "".} @@ -220,8 +222,11 @@ else: if setEnvironmentVariableW(k, v) == 0'i32: raiseOSError(osLastError()) else: if setEnvironmentVariableA(key, val) == 0'i32: raiseOSError(osLastError()) + elif defined(vcc): + if c_putenv_s(key, val) != 0'i32: + raiseOSError(osLastError()) else: - if c_putenv(environment[indx]) != 0'i32: + if c_setenv(key, val, 1'i32) != 0'i32: raiseOSError(osLastError()) proc delEnv*(key: string) {.tags: [WriteEnvEffect].} = diff --git a/tests/stdlib/tos.nim b/tests/stdlib/tos.nim index 9125584612725..8a12b9b9066e2 100644 --- a/tests/stdlib/tos.nim +++ b/tests/stdlib/tos.nim @@ -614,6 +614,9 @@ block osenv: doAssert existsEnv(dummyEnvVar) == false delEnv(dummyEnvVar) # deleting an already deleted env var doAssert existsEnv(dummyEnvVar) == false + block: # putEnv, bug #18502 + doAssertRaises(OSError): putEnv("DUMMY_ENV_VAR_PUT=DUMMY_VALUE", "NEW_DUMMY_VALUE") + doAssertRaises(OSError): putEnv("", "NEW_DUMMY_VALUE") block: doAssert getEnv("DUMMY_ENV_VAR_NONEXISTENT", "") == "" doAssert getEnv("DUMMY_ENV_VAR_NONEXISTENT", " ") == " "