From dce8e98be28db78f7d2b1ff4034199c5dd7918f5 Mon Sep 17 00:00:00 2001 From: GustavoLCR Date: Fri, 21 Jun 2019 11:23:32 -0300 Subject: [PATCH] Fix spp_var_get on Windows --- p/spp.h | 4 ++-- r_api.c | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++---- r_api.h | 1 + 3 files changed, 59 insertions(+), 6 deletions(-) diff --git a/p/spp.h b/p/spp.h index 265dd84..12c63ff 100644 --- a/p/spp.h +++ b/p/spp.h @@ -5,11 +5,11 @@ #endif static char *spp_var_get(char *var) { - return getenv(var); + return r_sys_getenv (var); } static int spp_var_set(const char *var, const char *val) { - return r_sys_setenv(var, val); + return r_sys_setenv (var, val); } #if HAVE_SYSTEM diff --git a/r_api.c b/r_api.c index efb45ba..c1f7bfe 100644 --- a/r_api.c +++ b/r_api.c @@ -87,20 +87,72 @@ void r_strbuf_fini(SStrBuf *sb) { /* --------- */ int r_sys_setenv(const char *key, const char *value) { -#if __UNIX__ || __CYGWIN__ && !defined(MINGW32) if (!key) { return 0; } +#if __UNIX__ if (!value) { unsetenv (key); return 0; } return setenv (key, value, 1); #elif __WINDOWS__ - SetEnvironmentVariable (key, (LPSTR)value); - return 0; // TODO. get ret + LPTSTR key_ = r_sys_conv_utf8_to_win (key); + LPTSTR value_ = r_sys_conv_utf8_to_win (value); + int ret = SetEnvironmentVariable (key_, value_); + if (!ret) { + r_sys_perror ("r_sys_setenv/SetEnvironmentVariable"); + } + free (key_); + free (value_); + return ret ? 0 : -1; #else -#warning s_sys_setenv : unimplemented for this platform +#warning r_sys_setenv : unimplemented for this platform return 0; #endif } + +char *r_sys_getenv(const char *key) { +#if __WINDOWS__ + DWORD dwRet; + LPTSTR envbuf = NULL, key_ = NULL, tmp_ptr; + char *val = NULL; + + if (!key) { + return NULL; + } + envbuf = (LPTSTR)malloc (sizeof (TCHAR) * TMP_BUFSIZE); + if (!envbuf) { + goto err_r_sys_get_env; + } + key_ = r_sys_conv_utf8_to_win (key); + dwRet = GetEnvironmentVariable (key_, envbuf, TMP_BUFSIZE); + if (dwRet == 0) { + if (GetLastError () == ERROR_ENVVAR_NOT_FOUND) { + goto err_r_sys_get_env; + } + } else if (TMP_BUFSIZE < dwRet) { + tmp_ptr = (LPTSTR)realloc (envbuf, dwRet * sizeof (TCHAR)); + if (!tmp_ptr) { + goto err_r_sys_get_env; + } + envbuf = tmp_ptr; + dwRet = GetEnvironmentVariable (key_, envbuf, dwRet); + if (!dwRet) { + goto err_r_sys_get_env; + } + } + val = r_sys_conv_win_to_utf8_l (envbuf, (int)dwRet); +err_r_sys_get_env: + free (key_); + free (envbuf); + return val; +#else + char *b; + if (!key) { + return NULL; + } + b = getenv (key); + return b? strdup (b): NULL; +#endif +} diff --git a/r_api.h b/r_api.h index 522d421..2d8db1a 100644 --- a/r_api.h +++ b/r_api.h @@ -21,6 +21,7 @@ void r_strbuf_free(SStrBuf *sb); void r_strbuf_fini(SStrBuf *sb); void r_strbuf_init(SStrBuf *sb); int r_sys_setenv(const char *key, const char *value); +char *r_sys_getenv(const char *key); #endif #endif