summaryrefslogtreecommitdiff
path: root/src/pal/src/misc/environ.cpp
blob: fed7b69f382e3fc27ca2709f1a5d55cb279d1374 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/*++



Module Name:

    environ.cpp

Abstract:

    Implementation of functions manipulating environment variables.

Revision History:



--*/

#include "pal/palinternal.h"
#include "pal/critsect.h"
#include "pal/dbgmsg.h"
#include "pal/environ.h"
#include "pal/malloc.hpp"

#if HAVE_CRT_EXTERNS_H
#include <crt_externs.h>
#endif

#include <stdlib.h>

using namespace CorUnix;

SET_DEFAULT_DEBUG_CHANNEL(MISC);

char **palEnvironment = nullptr;
int palEnvironmentCount = 0;
int palEnvironmentCapacity = 0;

CRITICAL_SECTION gcsEnvironment;

/*++
Function:
  GetEnvironmentVariableA

The GetEnvironmentVariable function retrieves the value of the
specified variable from the environment block of the calling
process. The value is in the form of a null-terminated string of
characters.

Parameters

lpName 
       [in] Pointer to a null-terminated string that specifies the environment variable.
lpBuffer 
       [out] Pointer to a buffer to receive the value of the specified environment variable.
nSize 
       [in] Specifies the size, in TCHARs, of the buffer pointed to by the lpBuffer parameter.

Return Values

If the function succeeds, the return value is the number of TCHARs
stored into the buffer pointed to by lpBuffer, not including the
terminating null character.

If the specified environment variable name was not found in the
environment block for the current process, the return value is zero.

If the buffer pointed to by lpBuffer is not large enough, the return
value is the buffer size, in TCHARs, required to hold the value string
and its terminating null character.

--*/
DWORD
PALAPI
GetEnvironmentVariableA(
            IN LPCSTR lpName,
            OUT LPSTR lpBuffer,
            IN DWORD nSize)
{
    char  *value;
    DWORD dwRet = 0;

    PERF_ENTRY(GetEnvironmentVariableA);
    ENTRY("GetEnvironmentVariableA(lpName=%p (%s), lpBuffer=%p, nSize=%u)\n",
        lpName ? lpName : "NULL",
        lpName ? lpName : "NULL", lpBuffer, nSize);

    CPalThread * pthrCurrent = InternalGetCurrentThread();

    if (lpName == nullptr)
    {
        ERROR("lpName is null\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    if (lpName[0] == 0)
    {
        TRACE("lpName is an empty string\n", lpName);
        SetLastError(ERROR_ENVVAR_NOT_FOUND);
        goto done;
    }

    if (strchr(lpName, '=') != nullptr)
    {
        // GetEnvironmentVariable doesn't permit '=' in variable names.
        value = nullptr;
    }
    else
    {
        // Enter the environment critical section so that we can safely get
        // the environment variable value without EnvironGetenv making an
        // intermediate copy. We will just copy the string to the output 
        // buffer anyway, so just stay in the critical section until then.
        InternalEnterCriticalSection(pthrCurrent, &gcsEnvironment);

        value = EnvironGetenv(lpName, /* copyValue */ FALSE);

        if (value != nullptr)
        {
            DWORD valueLength = strlen(value);
            if (valueLength < nSize)
            {
                strcpy_s(lpBuffer, nSize, value);
                dwRet = valueLength;
            }
            else 
            {
                dwRet = valueLength + 1;
            }

            SetLastError(ERROR_SUCCESS);
        }

        InternalLeaveCriticalSection(pthrCurrent, &gcsEnvironment);
    }

    if (value == nullptr)
    {
        TRACE("%s is not found\n", lpName);
        SetLastError(ERROR_ENVVAR_NOT_FOUND);
    }

done:

    LOGEXIT("GetEnvironmentVariableA returns DWORD 0x%x\n", dwRet);
    PERF_EXIT(GetEnvironmentVariableA);
    return dwRet;
}

/*++
Function:
  GetEnvironmentVariableW

See MSDN doc.
--*/
DWORD
PALAPI
GetEnvironmentVariableW(
            IN LPCWSTR lpName,
            OUT LPWSTR lpBuffer,
            IN DWORD nSize)
{
    CHAR *inBuff = nullptr;
    CHAR *outBuff = nullptr;
    INT inBuffSize;
    DWORD size = 0;

    PERF_ENTRY(GetEnvironmentVariableW);
    ENTRY("GetEnvironmentVariableW(lpName=%p (%S), lpBuffer=%p, nSize=%u)\n",
          lpName ? lpName : W16_NULLSTRING,
          lpName ? lpName : W16_NULLSTRING, lpBuffer, nSize);

    inBuffSize = WideCharToMultiByte(CP_ACP, 0, lpName, -1,
                                     inBuff, 0, nullptr, nullptr);
    if (0 == inBuffSize)
    {
        ERROR("lpName has to be a valid parameter\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    inBuff = (CHAR *)PAL_malloc(inBuffSize);
    if (inBuff == nullptr)
    {
        ERROR("malloc failed\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto done;
    }

    if (nSize)
    {
        outBuff = (CHAR *)PAL_malloc(nSize*2);
        if (outBuff == nullptr)
        {
            ERROR("malloc failed\n");
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            goto done;
        }
    }

    if (0 == WideCharToMultiByte(CP_ACP, 0, lpName, -1, inBuff,
                                   inBuffSize, nullptr, nullptr))
    {
        ASSERT("WideCharToMultiByte failed!\n");
        SetLastError(ERROR_INTERNAL_ERROR);
        goto done;
    }

    size = GetEnvironmentVariableA(inBuff, outBuff, nSize);
    if (size > nSize)
    {
        TRACE("Insufficient buffer\n");
    }
    else if (size == 0)
    {
        // handle error in GetEnvironmentVariableA
    }
    else
    {
        size = MultiByteToWideChar(CP_ACP, 0, outBuff, -1, lpBuffer, nSize);
        if (0 != size)
        {
            // -1 for the null.
            size--;
        }
        else
        {
            ASSERT("MultiByteToWideChar failed!\n");
            SetLastError(ERROR_INTERNAL_ERROR);
            size = 0;
            *lpBuffer = '\0';
        }
    }

done:
    PAL_free(outBuff);
    PAL_free(inBuff);

    LOGEXIT("GetEnvironmentVariableW returns DWORD 0x%x\n", size);
    PERF_EXIT(GetEnvironmentVariableW);

    return size;
}

/*++
Function:
  SetEnvironmentVariableW

The SetEnvironmentVariable function sets the value of an environment
variable for the current process.

Parameters

lpName 
       [in] Pointer to a null-terminated string that specifies the
       environment variable whose value is being set. The operating
       system creates the environment variable if it does not exist
       and lpValue is not null.
lpValue
       [in] Pointer to a null-terminated string containing the new
       value of the specified environment variable. If this parameter
       is null, the variable is deleted from the current process's
       environment.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error
information, call GetLastError.

Remarks

This function has no effect on the system environment variables or the
environment variables of other processes.

--*/
BOOL
PALAPI
SetEnvironmentVariableW(
            IN LPCWSTR lpName,
            IN LPCWSTR lpValue)
{
    PCHAR name = nullptr;
    PCHAR value = nullptr;
    INT nameSize = 0;
    INT valueSize = 0;
    BOOL bRet = FALSE;

    PERF_ENTRY(SetEnvironmentVariableW);
    ENTRY("SetEnvironmentVariableW(lpName=%p (%S), lpValue=%p (%S))\n",
        lpName?lpName:W16_NULLSTRING,
        lpName?lpName:W16_NULLSTRING, lpValue?lpValue:W16_NULLSTRING, lpValue?lpValue:W16_NULLSTRING);

    if ((nameSize = WideCharToMultiByte(CP_ACP, 0, lpName, -1, name, 0, 
                                        nullptr, nullptr)) == 0)
    {
        ERROR("WideCharToMultiByte failed\n");
        SetLastError(ERROR_INVALID_PARAMETER);
        goto done;
    }

    name = (PCHAR)PAL_malloc(sizeof(CHAR)* nameSize);
    if (name == nullptr)
    {
        ERROR("malloc failed\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto done;
    }
    
    if (0 == WideCharToMultiByte(CP_ACP, 0, lpName,  -1, 
                                 name,  nameSize, nullptr, nullptr))
    {
        ASSERT("WideCharToMultiByte returned 0\n");
        SetLastError(ERROR_INTERNAL_ERROR);
        goto done;
    }

    if (lpValue != nullptr)
    {
        if ((valueSize = WideCharToMultiByte(CP_ACP, 0, lpValue, -1, value, 
                                             0, nullptr, nullptr)) == 0)
        {
            ERROR("WideCharToMultiByte failed\n");
            SetLastError(ERROR_INVALID_PARAMETER);
            goto done;
        }

        value = (PCHAR)PAL_malloc(sizeof(CHAR)*valueSize);

        if (value == nullptr)
        {
            ERROR("malloc failed\n");
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            goto done;
        }

        if (0 == WideCharToMultiByte(CP_ACP, 0, lpValue, -1,
                                     value, valueSize, nullptr, nullptr))
        {
            ASSERT("WideCharToMultiByte failed\n");
            SetLastError( ERROR_INTERNAL_ERROR );
            goto done;
        }
    }

    bRet = SetEnvironmentVariableA(name, value);
done:
    PAL_free(value);
    PAL_free(name);

    LOGEXIT("SetEnvironmentVariableW returning BOOL %d\n", bRet);
    PERF_EXIT(SetEnvironmentVariableW);
    return bRet;
}

/*++
Function:
  GetEnvironmentStringsW

The GetEnvironmentStrings function retrieves the environment block for
the current process.

Parameters

This function has no parameters.

Return Values

The return value is a pointer to an environment block for the current process.

Remarks

The GetEnvironmentStrings function returns a pointer to the
environment block of the calling process. This should be treated as a
read-only block; do not modify it directly.  Instead, use the
GetEnvironmentVariable and SetEnvironmentVariable functions to
retrieve or change the environment variables within this block. When
the block is no longer needed, it should be freed by calling
FreeEnvironmentStrings.

--*/
LPWSTR
PALAPI
GetEnvironmentStringsW(
               VOID)
{
    WCHAR *wenviron = nullptr, *tempEnviron;
    int i, len, envNum;

    PERF_ENTRY(GetEnvironmentStringsW);
    ENTRY("GetEnvironmentStringsW()\n");

    CPalThread * pthrCurrent = InternalGetCurrentThread();
    InternalEnterCriticalSection(pthrCurrent, &gcsEnvironment);

    envNum = 0;
    len    = 0;

    /* get total length of the bytes that we need to allocate */
    for (i = 0; palEnvironment[i] != 0; i++)
    {
        len = MultiByteToWideChar(CP_ACP, 0, palEnvironment[i], -1, wenviron, 0);
        envNum += len;
    }

    wenviron = (WCHAR *)PAL_malloc(sizeof(WCHAR)* (envNum + 1));
    if (wenviron == nullptr) 
    {
        ERROR("malloc failed\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto EXIT;
    }

    len = 0;
    tempEnviron = wenviron;
    for (i = 0; palEnvironment[i] != 0; i++)
    {
        len = MultiByteToWideChar(CP_ACP, 0, palEnvironment[i], -1, tempEnviron, envNum);
        tempEnviron += len;
        envNum      -= len;
    }

    *tempEnviron = 0; /* Put an extra null at the end */

 EXIT:
    InternalLeaveCriticalSection(pthrCurrent, &gcsEnvironment);

    LOGEXIT("GetEnvironmentStringsW returning %p\n", wenviron);
    PERF_EXIT(GetEnvironmentStringsW);
    return wenviron;
}

/*++
Function:
  GetEnvironmentStringsA

See GetEnvironmentStringsW.

--*/
LPSTR
PALAPI
GetEnvironmentStringsA(
               VOID)
{
    char *environ = nullptr, *tempEnviron;
    int i, len, envNum;

    PERF_ENTRY(GetEnvironmentStringsA);
    ENTRY("GetEnvironmentStringsA()\n");

    CPalThread * pthrCurrent = InternalGetCurrentThread();
    InternalEnterCriticalSection(pthrCurrent, &gcsEnvironment);

    envNum = 0;
    len    = 0;

    /* get total length of the bytes that we need to allocate */
    for (i = 0; palEnvironment[i] != 0; i++)
    {
        len = strlen(palEnvironment[i]) + 1;
        envNum += len;
    }

    environ = (char *)PAL_malloc(envNum + 1);
    if (environ == nullptr)
    {
        ERROR("malloc failed\n");
        SetLastError(ERROR_NOT_ENOUGH_MEMORY);
        goto EXIT;
    }

    len = 0;
    tempEnviron = environ;
    for (i = 0; palEnvironment[i] != 0; i++)
    {
        len = strlen(palEnvironment[i]) + 1;
        memcpy(tempEnviron, palEnvironment[i], len);
        tempEnviron += len;
        envNum      -= len;
    }

    *tempEnviron = 0; /* Put an extra null at the end */

 EXIT:
    InternalLeaveCriticalSection(pthrCurrent, &gcsEnvironment);

    LOGEXIT("GetEnvironmentStringsA returning %p\n", environ);
    PERF_EXIT(GetEnvironmentStringsA);
    return environ;
}

/*++
Function:
  FreeEnvironmentStringsW

The FreeEnvironmentStrings function frees a block of environment strings.

Parameters

lpszEnvironmentBlock   [in] Pointer to a block of environment strings. The pointer to
                            the block must be obtained by calling the
                            GetEnvironmentStrings function. 

Return Values

If the function succeeds, the return value is nonzero.  If the
function fails, the return value is zero. To get extended error
information, call GetLastError.

Remarks

When GetEnvironmentStrings is called, it allocates memory for a block
of environment strings. When the block is no longer needed, it should
be freed by calling FreeEnvironmentStrings.

--*/
BOOL
PALAPI
FreeEnvironmentStringsW(
            IN LPWSTR lpValue)
{
    PERF_ENTRY(FreeEnvironmentStringsW);
    ENTRY("FreeEnvironmentStringsW(lpValue=%p (%S))\n", lpValue ? lpValue : W16_NULLSTRING, lpValue ? lpValue : W16_NULLSTRING);

    if (lpValue != nullptr)
    {
        PAL_free(lpValue);
    }

    LOGEXIT("FreeEnvironmentStringW returning BOOL TRUE\n");
    PERF_EXIT(FreeEnvironmentStringsW);
    return TRUE;
}

/*++
Function:
  FreeEnvironmentStringsA

See FreeEnvironmentStringsW.

--*/
BOOL
PALAPI
FreeEnvironmentStringsA(
            IN LPSTR lpValue)
{
    PERF_ENTRY(FreeEnvironmentStringsA);
    ENTRY("FreeEnvironmentStringsA(lpValue=%p (%s))\n", lpValue ? lpValue : "NULL", lpValue ? lpValue : "NULL");

    if (lpValue != nullptr)
    {
        PAL_free(lpValue);
    }

    LOGEXIT("FreeEnvironmentStringA returning BOOL TRUE\n");
    PERF_EXIT(FreeEnvironmentStringsA);
    return TRUE;
}

/*++
Function:
  SetEnvironmentVariableA

The SetEnvironmentVariable function sets the value of an environment
variable for the current process.

Parameters

lpName
       [in] Pointer to a null-terminated string that specifies the
       environment variable whose value is being set. The operating
       system creates the environment variable if it does not exist
       and lpValue is not null.
lpValue
       [in] Pointer to a null-terminated string containing the new
       value of the specified environment variable. If this parameter
       is null, the variable is deleted from the current process's
       environment.

Return Values

If the function succeeds, the return value is nonzero.

If the function fails, the return value is zero. To get extended error
information, call GetLastError.

Remarks

This function has no effect on the system environment variables or the
environment variables of other processes.

--*/
BOOL
PALAPI
SetEnvironmentVariableA(
            IN LPCSTR lpName,
            IN LPCSTR lpValue)
{

    BOOL bRet = FALSE;
    int nResult =0;
    PERF_ENTRY(SetEnvironmentVariableA);
    ENTRY("SetEnvironmentVariableA(lpName=%p (%s), lpValue=%p (%s))\n",
        lpName ? lpName : "NULL", lpName ? lpName : "NULL",
        lpValue ? lpValue : "NULL", lpValue ? lpValue : "NULL");

    // exit if the input variable name is null
    if ((lpName == nullptr) || (lpName[0] == 0))
    {
        ERROR("lpName is null\n");
        goto done;
    }

    /* check if the input value is null and if so
     * check if the input name is valid and delete
     * the variable name from process environment */
    if (lpValue == nullptr)
    {
        // We tell EnvironGetenv not to bother with making a copy of the
        // value since we're not going to use it for anything interesting
        // apart from checking whether it's null.
        if ((lpValue = EnvironGetenv(lpName, /* copyValue */ FALSE)) == nullptr)
        {
            ERROR("Couldn't find environment variable (%s)\n", lpName);
            SetLastError(ERROR_ENVVAR_NOT_FOUND);
            goto done;
        }

        EnvironUnsetenv(lpName);
    }
    else
    {
        // All the conditions are met. Set the variable.
        int iLen = strlen(lpName) + strlen(lpValue) + 2;
        LPSTR string = (LPSTR) PAL_malloc(iLen);
        if (string == nullptr)
        {
            bRet = FALSE;
            ERROR("Unable to allocate memory\n");
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            goto done;
        }

        sprintf_s(string, iLen, "%s=%s", lpName, lpValue);
        nResult = EnvironPutenv(string, FALSE) ? 0 : -1;

        PAL_free(string);
        string = nullptr;

        // If EnvironPutenv returns FALSE, it almost certainly failed to allocate memory.
        if (nResult == -1)
        {
            bRet = FALSE;
            ERROR("Unable to allocate memory\n");
            SetLastError(ERROR_NOT_ENOUGH_MEMORY);
            goto done;
        }
    }

    bRet = TRUE;

done:
    LOGEXIT("SetEnvironmentVariableA returning BOOL %d\n", bRet);
    PERF_EXIT(SetEnvironmentVariableA);
    return bRet;
}

/*++
Function:
  ResizeEnvironment

Resizes the PAL environment buffer.

Parameters

    newSize 
           [in] New size of palEnvironment

Return Values

    TRUE on success, FALSE otherwise

--*/
BOOL ResizeEnvironment(int newSize)
{
    CPalThread * pthrCurrent = InternalGetCurrentThread();
    InternalEnterCriticalSection(pthrCurrent, &gcsEnvironment);

    BOOL ret = FALSE;
    if (newSize >= palEnvironmentCount)
    {
        // If palEnvironment is null, realloc acts like malloc.
        char **newEnvironment = (char**)realloc(palEnvironment, newSize * sizeof(char *));
        if (newEnvironment != nullptr)
        {
            // realloc succeeded, so set palEnvironment to what it returned.
            palEnvironment = newEnvironment;
            palEnvironmentCapacity = newSize;
            ret = TRUE;
        }
    }
    else
    {
        ASSERT("ResizeEnvironment: newSize < current palEnvironmentCount!\n");
    }

    InternalLeaveCriticalSection(pthrCurrent, &gcsEnvironment);
    return ret;
}

/*++
Function:
  EnvironUnsetenv

Remove the environment variable with the given name from the PAL version
of the environment if it exists.

Parameters

    name 
           [in] Name of variable to unset.

--*/
void EnvironUnsetenv(const char *name)
{
    int nameLength = strlen(name);

    CPalThread * pthrCurrent = InternalGetCurrentThread();
    InternalEnterCriticalSection(pthrCurrent, &gcsEnvironment);

    for (int i = 0; palEnvironment[i] != nullptr; ++i)
    {
        const char *equalsSignPosition = strchr(palEnvironment[i], '=');
        if (equalsSignPosition == nullptr)
        {
            equalsSignPosition = palEnvironment[i] + strlen(palEnvironment[i]);
        }

        // Check whether the name of this variable has the same length as the one
        // we're looking for before proceeding to compare them.
        if (equalsSignPosition - palEnvironment[i] == nameLength)
        {
            if (memcmp(name, palEnvironment[i], nameLength) == 0)
            {
                // Free the string we're removing.
                free(palEnvironment[i]);

                // Move the last environment variable pointer here.
                palEnvironment[i] = palEnvironment[palEnvironmentCount - 1];
                palEnvironment[palEnvironmentCount - 1] = nullptr;

                palEnvironmentCount--;
            }
        }
    }

    InternalLeaveCriticalSection(pthrCurrent, &gcsEnvironment);
}

/*++
Function:
  EnvironPutenv

Add the environment variable string provided to the PAL version
of the environment.

Parameters

    entry
            [in] The variable string to add. Should be in the format
                 "name=value", where value might be empty (see below).
    deleteIfEmpty
            [in] If this is TRUE, "name=" will unset the 'name' variable.

Return Values

    TRUE on success, FALSE otherwise

--*/
BOOL EnvironPutenv(const char* entry, BOOL deleteIfEmpty)
{
    BOOL result = FALSE;

    bool fOwningCS = false;

    CPalThread * pthrCurrent = InternalGetCurrentThread();

    const char *equalsSignPosition = strchr(entry, '=');
    if (equalsSignPosition == entry || equalsSignPosition == nullptr)
    {
        // "=foo" and "foo" have no meaning
        return FALSE;
    }

    char* copy = strdup(entry);
    if (copy == nullptr)
    {
        return FALSE;
    }

    int nameLength = equalsSignPosition - entry;

    if (equalsSignPosition[1] == '\0' && deleteIfEmpty)
    {
        // "foo=" removes foo from the environment in _putenv() on Windows.
        // The same string can result from a call to SetEnvironmentVariable()
        // with the empty string as the value, but in that case we want to
        // set the variable's value to "". deleteIfEmpty will be FALSE in
        // that case.

        // Change '=' to '\0'
        copy[nameLength] = '\0';

        EnvironUnsetenv(copy);
        free(copy);

        result = TRUE;
    }
    else
    {
        // See if we are replacing an item or adding one.

        InternalEnterCriticalSection(pthrCurrent, &gcsEnvironment);
        fOwningCS = true;

        int i;
        for (i = 0; palEnvironment[i] != nullptr; i++)
        {
            const char *existingEquals = strchr(palEnvironment[i], '=');
            if (existingEquals == nullptr)
            {
                // The PAL screens out malformed strings, but the strings which
                // came from the system during initialization might not have the
                // equals sign. We treat the entire string as a name in that case.
                existingEquals = palEnvironment[i] + strlen(palEnvironment[i]);
            }

            if (existingEquals - palEnvironment[i] == nameLength)
            {
                if (memcmp(entry, palEnvironment[i], nameLength) == 0)
                {
                    free(palEnvironment[i]);
                    palEnvironment[i] = copy;

                    result = TRUE;
                    break;
                }
            }
        }

        if (palEnvironment[i] == nullptr)
        {
            _ASSERTE(i < palEnvironmentCapacity);
            if (i == (palEnvironmentCapacity - 1))
            {
                // We found the first null, but it's the last element in our environment
                // block. We need more space in our environment, so let's double its size.
                int resizeRet = ResizeEnvironment(palEnvironmentCapacity * 2);
                if (resizeRet != TRUE)
                {
                    free(copy);
                    goto done;
                }
            }

            _ASSERTE(copy != nullptr);
            palEnvironment[i] = copy;
            palEnvironment[i + 1] = nullptr;
            palEnvironmentCount++;

            result = TRUE;
        }
    }
done:

    if (fOwningCS)
    {
        InternalLeaveCriticalSection(pthrCurrent, &gcsEnvironment);
    }

    return result;
}

/*++
Function:
  EnvironGetenv

Get the value of environment variable with the given name.

Parameters

    name
            [in] The name of the environment variable to get.
    copyValue
            [in] If this is TRUE, the function will make a copy of the
                 value and return a pointer to that. Otherwise, it will
                 return a pointer to the value in the PAL environment
                 directly. Calling this function with copyValue set to
                 FALSE is therefore unsafe without taking special pre-
                 cautions since the pointer may point to garbage later.

Return Value

    A pointer to the value of the environment variable if it exists,
    or nullptr otherwise.

--*/
char* EnvironGetenv(const char* name, BOOL copyValue)
{
    char *retValue = nullptr;

    CPalThread * pthrCurrent = InternalGetCurrentThread();
    InternalEnterCriticalSection(pthrCurrent, &gcsEnvironment);

    int nameLength = strlen(name);
    for (int i = 0; palEnvironment[i] != nullptr; ++i)
    {
        if (strlen(palEnvironment[i]) < nameLength)
        {
            continue;
        }

        if (memcmp(palEnvironment[i], name, nameLength) == 0)
        {
            char *equalsSignPosition = palEnvironment[i] + nameLength;

            // If this is one of the variables which has no equals sign, we
            // treat the whole thing as name, so the value is an empty string.
            if (*equalsSignPosition == '\0')
            {
                retValue = (char *)"";
                break;
            }
            else if (*equalsSignPosition == '=')
            {
                retValue = equalsSignPosition + 1;
                break;
            }
        }
    }

    if ((retValue != nullptr) && copyValue)
    {
        retValue = strdup(retValue);
    }

    InternalLeaveCriticalSection(pthrCurrent, &gcsEnvironment);
    return retValue;
}

/*++
Function:
  EnvironGetSystemEnvironment

Get a pointer to the array of pointers representing the process's
environment.

See 'man environ' for details.

Return Value

    A pointer to the environment.

--*/
char** EnvironGetSystemEnvironment()
{
    char** sysEnviron;

#if HAVE__NSGETENVIRON
    sysEnviron = *(_NSGetEnviron());
#else   // HAVE__NSGETENVIRON
    extern char **environ;
    sysEnviron = environ;
#endif  // HAVE__NSGETENVIRON

    return sysEnviron;
}

/*++
Function:
  EnvironInitialize

Initialization function called from PAL_Initialize.

Note: This is called before debug channels are initialized, so it
      cannot use debug tracing calls.
--*/
BOOL
EnvironInitialize(void)
{
    BOOL ret = FALSE;

    InternalInitializeCriticalSection(&gcsEnvironment);

    CPalThread * pthrCurrent = InternalGetCurrentThread();
    InternalEnterCriticalSection(pthrCurrent, &gcsEnvironment);

    char** sourceEnviron = EnvironGetSystemEnvironment();

    int variableCount = 0;
    while (sourceEnviron[variableCount] != nullptr)
        variableCount++;

    palEnvironmentCount = 0;

    // We need to decide how much space to allocate. Since we need enough
    // space for all of the 'n' current environment variables, but we don't
    // know how many more there will be, we will initially make room for
    // '2n' variables. If even more are added, we will resize again.
    // If there are no variables, we will still make room for 1 entry to 
    // store a nullptr there.
    int initialSize = (variableCount == 0) ? 1 : variableCount * 2;

    ret = ResizeEnvironment(initialSize);
    if (ret == TRUE)
    {
        _ASSERTE(palEnvironment != nullptr);
        for (int i = 0; i < variableCount; ++i)
        {
            palEnvironment[i] = strdup(sourceEnviron[i]);
            palEnvironmentCount++;
        }

        // Set the entry after the last variable to null to indicate the end.
        palEnvironment[variableCount] = nullptr;
    }

    InternalLeaveCriticalSection(pthrCurrent, &gcsEnvironment);
    return ret;
}

/*++

Function : _putenv.
    
See MSDN for more details.

Note:   The BSD implementation can cause
        memory leaks. See man pages for more details.
--*/
int
__cdecl 
_putenv( const char * envstring )
{
    int ret = -1;

    PERF_ENTRY(_putenv);
    ENTRY( "_putenv( %p (%s) )\n", envstring ? envstring : "NULL", envstring ? envstring : "NULL") ;

    if (envstring != nullptr)
    {
        ret = EnvironPutenv(envstring, TRUE) ? 0 : -1;
    }
    else
    {
        ERROR( "_putenv() called with NULL envstring!\n");
    }

    LOGEXIT( "_putenv returning %d\n", ret);
    PERF_EXIT(_putenv);
    return ret;
}

/*++

Function : PAL_getenv
    
See MSDN for more details.
--*/
char * __cdecl PAL_getenv(const char *varname)
{
    char *retval;

    PERF_ENTRY(getenv);
    ENTRY("getenv (%p (%s))\n", varname ? varname : "NULL", varname ? varname : "NULL");

    if (strcmp(varname, "") == 0)
    {
        ERROR("getenv called with a empty variable name\n");
        LOGEXIT("getenv returning NULL\n");
        PERF_EXIT(getenv);
        return(NULL);
    }

    retval = EnvironGetenv(varname);

    LOGEXIT("getenv returning %p\n", retval);
    PERF_EXIT(getenv);
    return(retval);
}