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