Skip to content

Commit

Permalink
GetImagePath
Browse files Browse the repository at this point in the history
  • Loading branch information
shinokaro committed Feb 21, 2024
1 parent 88146c6 commit 5356c23
Showing 1 changed file with 48 additions and 2 deletions.
50 changes: 48 additions & 2 deletions src/stub.c
Original file line number Diff line number Diff line change
Expand Up @@ -484,13 +484,59 @@ BOOL CreateInstDirectory(BOOL debug_extract)
}
}

char *GetImagePath(void) {
/**
* Note: This implementation supports long path names up to the maximum total path length
* of 32,767 characters, as permitted by Windows when the longPathAware setting is enabled.
* For more information, see the documentation on maximum file path limitations:
* https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation
*/
DWORD buffer_size = 32767;
wchar_t *image_path_w = (wchar_t *)LocalAlloc(LPTR, buffer_size * sizeof(wchar_t));
if (image_path_w == NULL) {
LAST_ERROR("Failed to allocate buffer for image path");
return NULL;
}

DWORD copied = GetModuleFileNameW(NULL, image_path_w, buffer_size);
if (copied == 0 || GetLastError() == ERROR_INSUFFICIENT_BUFFER) {
LocalFree(image_path_w);
LAST_ERROR("Failed to get image path");
return NULL;
}

int utf8_size = WideCharToMultiByte(CP_UTF8, 0, image_path_w, -1, NULL, 0, NULL, NULL);
if (utf8_size == 0) {
LocalFree(image_path_w);
LAST_ERROR("Failed to calculate buffer size for UTF-8 conversion");
return NULL;
}

char *image_path_utf8 = (char *)LocalAlloc(LPTR, utf8_size);
if (image_path_utf8 == NULL) {
LocalFree(image_path_w);
LAST_ERROR("Failed to allocate buffer for UTF-8 image path");
return NULL;
}

if (WideCharToMultiByte(CP_UTF8, 0, image_path_w, -1, image_path_utf8, utf8_size, NULL, NULL) == 0) {
LocalFree(image_path_w);
LocalFree(image_path_utf8);
LAST_ERROR("Failed to convert image path to UTF-8");
return NULL;
}

LocalFree(image_path_w);
return image_path_utf8;
}

int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
DWORD exit_code = 0;
char image_path[MAX_PATH];

/* Find name of image */
if (!GetModuleFileName(NULL, image_path, MAX_PATH)) {
char *image_path = GetImagePath();
if (image_path == NULL) {
return LAST_ERROR("Failed to get executable name");
}

Expand Down

0 comments on commit 5356c23

Please sign in to comment.