go-setenv.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /* go-setenv.c -- set the C environment from Go.
  2. Copyright 2011 The Go Authors. All rights reserved.
  3. Use of this source code is governed by a BSD-style
  4. license that can be found in the LICENSE file. */
  5. #include "config.h"
  6. #include <stddef.h>
  7. #include <stdlib.h>
  8. #include "runtime.h"
  9. /* Set the C environment from Go. This is called by syscall.Setenv. */
  10. void setenv_c (String, String) __asm__ (GOSYM_PREFIX "syscall.setenv__c");
  11. void
  12. setenv_c (String k, String v)
  13. {
  14. const byte *ks;
  15. unsigned char *kn;
  16. const byte *vs;
  17. unsigned char *vn;
  18. ks = k.str;
  19. if (ks == NULL)
  20. ks = (const byte *) "";
  21. kn = NULL;
  22. vs = v.str;
  23. if (vs == NULL)
  24. vs = (const byte *) "";
  25. vn = NULL;
  26. #ifdef HAVE_SETENV
  27. if (ks[k.len] != 0)
  28. {
  29. kn = malloc (k.len + 1);
  30. if (kn == NULL)
  31. runtime_throw ("out of malloc memory");
  32. __builtin_memcpy (kn, ks, k.len);
  33. kn[k.len] = '\0';
  34. ks = kn;
  35. }
  36. if (vs[v.len] != 0)
  37. {
  38. vn = malloc (v.len + 1);
  39. if (vn == NULL)
  40. runtime_throw ("out of malloc memory");
  41. __builtin_memcpy (vn, vs, v.len);
  42. vn[v.len] = '\0';
  43. vs = vn;
  44. }
  45. setenv ((const char *) ks, (const char *) vs, 1);
  46. #else /* !defined(HAVE_SETENV) */
  47. len = k.len + v.len + 2;
  48. kn = malloc (len);
  49. if (kn == NULL)
  50. runtime_throw ("out of malloc memory");
  51. __builtin_memcpy (kn, ks, k.len);
  52. kn[k.len] = '=';
  53. __builtin_memcpy (kn + k.len + 1, vs, v.len);
  54. kn[k.len + v.len + 1] = '\0';
  55. putenv ((char *) kn);
  56. kn = NULL; /* putenv takes ownership of the string. */
  57. #endif /* !defined(HAVE_SETENV) */
  58. if (kn != NULL)
  59. free (kn);
  60. if (vn != NULL)
  61. free (vn);
  62. }