putenv.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* Copyright (C) 1991-2019 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with the GNU C Library; if not, see
  13. <http://www.gnu.org/licenses/>. */
  14. #if defined _AIX && !defined __GNUC__
  15. #pragma alloca
  16. #endif
  17. #if HAVE_CONFIG_H
  18. # include <config.h>
  19. #endif
  20. #if _LIBC || HAVE_STDLIB_H
  21. # include <stdlib.h>
  22. #endif
  23. #if _LIBC || HAVE_STRING_H
  24. # include <string.h>
  25. #endif
  26. #if !__GNU_LIBRARY__ && !HAVE_STRCHR
  27. # define strchr index
  28. #endif
  29. #ifndef _LIBC
  30. # ifdef HAVE_ALLOCA_H
  31. # include <alloca.h>
  32. # else
  33. # ifdef __GNUC__
  34. # define alloca __builtin_alloca
  35. # else
  36. extern char *alloca ();
  37. # endif /* __GNUC__ */
  38. # endif /* HAVE_ALLOCA_H */
  39. #endif /* _LIBC */
  40. /* Put STRING, which is of the form "NAME=VALUE", in the environment. */
  41. int
  42. putenv (char *string)
  43. {
  44. const char *const name_end = strchr (string, '=');
  45. if (name_end != NULL)
  46. {
  47. char *name;
  48. #ifdef _LIBC
  49. int use_malloc = !__libc_use_alloca (name_end - string + 1);
  50. if (__builtin_expect (use_malloc, 0))
  51. {
  52. name = __strndup (string, name_end - string);
  53. if (name == NULL)
  54. return -1;
  55. }
  56. else
  57. name = strndupa (string, name_end - string);
  58. #else
  59. # define use_malloc 1
  60. name = malloc (name_end - string + 1);
  61. if (name == NULL)
  62. return -1;
  63. memcpy (name, string, name_end - string);
  64. name[name_end - string] = '\0';
  65. #endif
  66. int result = __add_to_environ (name, NULL, string, 1);
  67. if (__glibc_unlikely (use_malloc))
  68. free (name);
  69. return result;
  70. }
  71. __unsetenv (string);
  72. return 0;
  73. }