Commit c1a65d72 authored by Aaron Dierking's avatar Aaron Dierking

Provide a default progname on Windows

parent 9e0d0950
Pipeline #2007 passed with stage
in 1 minute and 27 seconds
/*
* Copyright © 2006 Robert Millan
* Copyright © 2010-2012 Guillem Jover <guillem@hadrons.org>
* Copyright © 2018 Facebook, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
......@@ -33,8 +34,12 @@
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <sys/param.h>
#ifdef _WIN32
#include <Windows.h>
#endif
#if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
#ifdef _WIN32
#define LIBBSD_IS_PATHNAME_SEPARATOR(c) ((c) == '/' || (c) == '\\')
#else
#define LIBBSD_IS_PATHNAME_SEPARATOR(c) ((c) == '/')
......@@ -56,6 +61,67 @@ getprogname(void)
/* getexecname(3) returns an absolute pathname, normalize it. */
if (__progname == NULL)
setprogname(getexecname());
#elif defined(_WIN32)
if (__progname == NULL) {
WCHAR *wpath = NULL;
WCHAR *wname = NULL;
DWORD wpathsiz = MAX_PATH;
DWORD len, i;
char *mbname = NULL;
int mbnamesiz;
wpath = reallocarray(NULL, wpathsiz, sizeof(*wpath));
if (wpath == NULL)
goto done;
/*
* Use the Unicode version of this function to support long paths.
* MAX_PATH isn't actually the maximum length of a path in this case.
*/
while ((len = GetModuleFileNameW(NULL, wpath, wpathsiz)) == wpathsiz) {
WCHAR *wpathnew;
if (wpathsiz == UNICODE_STRING_MAX_CHARS)
goto done;
wpathsiz *= 2;
wpathsiz = MIN(wpathsiz, UNICODE_STRING_MAX_CHARS);
wpathnew = reallocarray(wpath, wpathsiz, sizeof(*wpath));
if (wpathnew == NULL)
goto done;
wpath = wpathnew;
}
if (len == 0)
goto done;
/*
* GetModuleFileNameW() retrieves an absolute path. Locate the filename
* now to only convert necessary characters and save memory.
*/
wname = wpath;
for (i = len; i > 0; i--) {
if (LIBBSD_IS_PATHNAME_SEPARATOR(wpath[i - 1])) {
wname = wpath + i;
break;
}
}
mbnamesiz = WideCharToMultiByte(CP_UTF8, 0, wname, -1, NULL, 0, NULL,
NULL);
if (mbnamesiz == 0)
goto done;
mbname = malloc(mbnamesiz);
if (mbname == NULL)
goto done;
mbnamesiz = WideCharToMultiByte(CP_UTF8, 0, wname, -1, mbname,
mbnamesiz, NULL, NULL);
if (mbnamesiz == 0)
goto done;
__progname = mbname;
mbname = NULL;
done:
free(wpath);
free(mbname);
}
#endif
return __progname;
......
......@@ -36,7 +36,11 @@ main(int argc, char **argv)
progname = getprogname();
if (strncmp(progname, "lt-", 3) == 0)
progname += 3;
#ifdef _WIN32
assert(strcmp(progname, "progname.exe") == 0);
#else
assert(strcmp(progname, "progname") == 0);
#endif
setprogname("program-name");
assert(strcmp(getprogname(), "program-name") == 0);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment