Skip to content

Commit

Permalink
CreateUniqueDirectory
Browse files Browse the repository at this point in the history
  • Loading branch information
shinokaro committed Feb 21, 2024
1 parent 0d7f3de commit 88146c6
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions src/stub.c
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,71 @@ void MarkInstDirForDeletion(void)
LocalFree(marker);
}

#define UID_LENGTH 12

char *GenerateUniqueName(const char *prefix)
{
size_t prefix_len = 0;
if (prefix) { prefix_len = strlen(prefix); }
char *name = (char *)LocalAlloc(LPTR, prefix_len + UID_LENGTH + 1);
if (name == NULL) {
LAST_ERROR("Failed to allocate memory for unique name");
return NULL;
}

LARGE_INTEGER time;
// This function always succeeds on Windows XP and later
QueryPerformanceCounter(&time);
unsigned long long timestamp = time.QuadPart;
char hex[] = "0123456789ABCDEF";
char t[UID_LENGTH + 1];
for (int i = 0; i < UID_LENGTH; i++) {
t[i] = hex[(timestamp >> (4 * (UID_LENGTH - 1 - i))) & 0xF];
}
t[UID_LENGTH] = '\0';

strcpy(name, prefix);
strcat(name, t);
return name;
}

char* CreateUniqueDirectory(const char* base_path)
{
if (base_path == NULL) {
FATAL("Base path is null");
return NULL;
}

unsigned int retry_limit = 1000;
for (unsigned int retry = 0; retry < retry_limit; retry++) {
char *temp_name = GenerateUniqueName("ocran");
if (temp_name == NULL) {
FATAL("Failed to generate a unique name");
return NULL;
}

char *full_path = ConcatStr(base_path, "\\", temp_name, NULL);
free(temp_name);
if (full_path == NULL) {
LAST_ERROR("Failed to allocate memory for full_path");
return NULL;
}

if (CreateDirectory(full_path, NULL)) {
return full_path;
}
free(full_path);
if (GetLastError() != ERROR_ALREADY_EXISTS) {
LAST_ERROR("Failed to create unique directory");
return NULL;
}
Sleep(10);
}

FATAL("Failed to create a unique directory after %u retries", retry_limit);
return NULL;
}

BOOL CreateInstDirectory(BOOL debug_extract)
{
/* Create an installation directory that will hold the extracted files */
Expand Down

0 comments on commit 88146c6

Please sign in to comment.