Skip to content
This repository has been archived by the owner on Jan 23, 2023. It is now read-only.

Commit

Permalink
Replace malloc/memcpy with strdup in EnvironPutenv.
Browse files Browse the repository at this point in the history
  • Loading branch information
adityamandaleeka committed Feb 16, 2016
1 parent 2a754f9 commit 4125345
Showing 1 changed file with 19 additions and 21 deletions.
40 changes: 19 additions & 21 deletions src/pal/src/misc/environ.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -782,36 +782,37 @@ Return Values
--*/
BOOL EnvironPutenv(const char* entry, BOOL deleteIfEmpty)
{
bool fOwningCS = false;
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
goto done;
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.
int length = strlen(entry);
char* copy = (char *) InternalMalloc(length);
if (copy == nullptr)
{
goto done;
}

memcpy(copy, entry, length - 1);

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

EnvironUnsetenv(copy);
InternalFree(copy);
Expand All @@ -822,15 +823,6 @@ BOOL EnvironPutenv(const char* entry, BOOL deleteIfEmpty)
{
// See if we are replacing an item or adding one.

// Make our copy up front, since we'll use it either way.
char* copy = strdup(entry);
if (copy == nullptr)
{
goto done;
}

int nameLength = equalsSignPosition - entry;

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

Expand Down Expand Up @@ -1010,14 +1002,20 @@ EnvironInitialize(void)
// 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.
ResizeEnvironment(variableCount * 2);
// 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;
ResizeEnvironment(initialSize);

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 TRUE;
Expand Down

0 comments on commit 4125345

Please sign in to comment.