This patch fixes an issue where getenv_s returns seemingly random results when 
reading a variable with empty value. Here's a small test case:

#include <windows.h>
#include <stdlib.h>
#include <assert.h>

static void
check (void)
{
  char buffer[100];
  size_t len;
  errno_t ret;

  ret = getenv_s (&len, buffer, sizeof (buffer), "EMPTY");
  assert (ret == 0 && len == 1);
}

int
main (void)
{
  SetEnvironmentVariableA ("EMPTY", "");

  check ();
  SetEvent (NULL);
  check (); /* fails */

  return EXIT_SUCCESS;
}

To ease testing, one might copy the implementation of getenv_s from 
mingw-w64-libraries/winstorecompat/src/getenv_s.c into the test code. Best if 
the function is renamed to something else, e.g. "my_getenv_s".

Best Regards,
Luca
From 1328184b8e120f38f2379f4865eed47390e2f409 Mon Sep 17 00:00:00 2001
From: Luca Bacci <[email protected]>
Date: Wed, 14 Jan 2026 09:44:59 +0100
Subject: [PATCH] winstorecompat,getenv_s: Call SetLastError(0) before
 GetEnvironmentVariable

GetEnvironmentVariable returns 0 in two cases:

 1. Failure
 2. Success when environment variable has empty value

We call GetLastError to differentiate between the two outcomes. However
GetEnvironmentVariable updates the thread error code only on case 1.
Before this commit, on case 2 we read the error code set by previous
functions.

Signed-off-by: Luca Bacci <[email protected]>
---
 mingw-w64-libraries/winstorecompat/src/getenv_s.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/mingw-w64-libraries/winstorecompat/src/getenv_s.c 
b/mingw-w64-libraries/winstorecompat/src/getenv_s.c
index fc45f522..f25dad3f 100644
--- a/mingw-w64-libraries/winstorecompat/src/getenv_s.c
+++ b/mingw-w64-libraries/winstorecompat/src/getenv_s.c
@@ -37,6 +37,7 @@ errno_t __cdecl getenv_s(size_t *pReturnValue, char *dstBuf, 
rsize_t dstSize, co
      * Function GetEnvironmentVariableA() is documented on:
      * 
https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-getenvironmentvariablea
      */
+    SetLastError(ERROR_SUCCESS);
     ret = GetEnvironmentVariableA(varName, dstBuf, dstSize);
     if (ret == 0) {
         /* If the function fails, the return value is zero (e.g. specified
-- 
2.49.0.windows.1

_______________________________________________
Mingw-w64-public mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/mingw-w64-public

Reply via email to