win_setenv.nim 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #[
  2. Copyright (c) Facebook, Inc. and its affiliates.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. Adapted `setenv` from https://github.com/facebook/folly/blob/master/folly/portability/Stdlib.cpp
  13. translated from C to nim.
  14. ]#
  15. #[
  16. Introduced in https://github.com/facebook/folly/commit/5d8ca09a3f96afefb44e35808f03651a096ab9c7
  17. TODO:
  18. check errno_t vs cint
  19. ]#
  20. when not defined(windows): discard
  21. else:
  22. when defined(nimPreviewSlimSystem):
  23. import std/widestrs
  24. type wchar_t {.importc: "wchar_t".} = int16
  25. proc setEnvironmentVariableW*(lpName, lpValue: WideCString): int32 {.
  26. stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW", sideEffect.}
  27. # same as winlean.setEnvironmentVariableA
  28. proc c_getenv(varname: cstring): cstring {.importc: "getenv", header: "<stdlib.h>".}
  29. proc c_wputenv(envstring: ptr wchar_t): cint {.importc: "_wputenv", header: "<stdlib.h>".}
  30. proc c_wgetenv(varname: ptr wchar_t): ptr wchar_t {.importc: "_wgetenv", header: "<stdlib.h>".}
  31. var errno {.importc, header: "<errno.h>".}: cint
  32. var genviron {.importc: "_environ".}: ptr ptr char
  33. # xxx `ptr UncheckedArray[WideCString]` did not work
  34. proc wcstombs(wcstr: ptr char, mbstr: ptr wchar_t, count: csize_t): csize_t {.importc, header: "<stdlib.h>".}
  35. # xxx cint vs errno_t?
  36. proc setEnvImpl*(name: string, value: string, overwrite: cint): cint =
  37. const EINVAL = cint(22)
  38. let wideName: WideCString = newWideCString(name)
  39. if overwrite == 0 and c_wgetenv(cast[ptr wchar_t](wideName)) != nil:
  40. return 0
  41. if value != "":
  42. let envstring: WideCString = newWideCString(name & "=" & value)
  43. let e = c_wputenv(cast[ptr wchar_t](envstring))
  44. if e != 0:
  45. errno = EINVAL
  46. return -1
  47. return 0
  48. #[
  49. We are trying to set the value to an empty string, but `_putenv` deletes
  50. entries if the value is an empty string, and just calling
  51. SetEnvironmentVariableA doesn't update `_environ`,
  52. so we have to do these terrible things.
  53. ]#
  54. let envstring: WideCString = newWideCString(name & "= ")
  55. if c_wputenv(cast[ptr wchar_t](envstring)) != 0:
  56. errno = EINVAL
  57. return -1
  58. # Here lies the documentation we blatently ignore to make this work.
  59. var s = cast[WideCString](c_wgetenv(cast[ptr wchar_t](wideName)))
  60. s[0] = Utf16Char('\0')
  61. #[
  62. This would result in a double null termination, which normally signifies the
  63. end of the environment variable list, so we stick a completely empty
  64. environment variable into the list instead.
  65. ]#
  66. s = cast[WideCString](c_wgetenv(cast[ptr wchar_t](wideName)))
  67. s[1] = Utf16Char('=')
  68. #[
  69. If genviron is null, the MBCS environment has not been initialized
  70. yet, and we don't need to try to update it. We have to do this otherwise
  71. we'd be forcing the initialization and maintenance of the MBCS environment
  72. even though it's never actually used in most programs.
  73. ]#
  74. if genviron != nil:
  75. # wcstombs returns `high(csize_t)` if any characters cannot be represented
  76. # in the current codepage. Skip updating MBCS environment in this case.
  77. # For some reason, second `wcstombs` can find non-convertible characters
  78. # that the first `wcstombs` cannot.
  79. let requiredSizeS = wcstombs(nil, cast[ptr wchar_t](wideName), 0)
  80. if requiredSizeS != high(csize_t):
  81. let requiredSize = requiredSizeS.int
  82. var buf = newSeq[char](requiredSize + 1)
  83. let buf2 = buf[0].addr
  84. if wcstombs(buf2, cast[ptr wchar_t](wideName), csize_t(requiredSize + 1)) != high(csize_t):
  85. var ptrToEnv = c_getenv(cast[cstring](buf2))
  86. ptrToEnv[0] = '\0'
  87. ptrToEnv = c_getenv(cast[cstring](buf2))
  88. ptrToEnv[1] = '='
  89. # And now, we have to update the outer environment to have a proper empty value.
  90. if setEnvironmentVariableW(wideName, value.newWideCString) == 0:
  91. errno = EINVAL
  92. return -1
  93. return 0