Skip to content

Instantly share code, notes, and snippets.

@oguz-ismail
Last active September 16, 2024 10:24
Show Gist options
  • Save oguz-ismail/707c875d48f0324bd265ba6cff244214 to your computer and use it in GitHub Desktop.
Save oguz-ismail/707c875d48f0324bd265ba6cff244214 to your computer and use it in GitHub Desktop.
#include <windows.h>
#define DELIM(c) ((c) == ' ' || (c) == '\t')
static int
maybe_unescape(const TCHAR **src, TCHAR **dst, int quot) {
const TCHAR *p;
int i, n;
switch (*(p = *src)) {
case '\\':
while (*++p == '\\');
if (*p != '"')
return 0;
n = p-*src;
for (i = 0; i < n/2; i++)
*(*dst)++ = '\\';
if (n%2 != 0)
*(*dst)++ = '"';
else
p--;
break;
case '"':
if (!quot)
return 0;
for (; p[1] == '"'; p++);
if (p == *src)
return 0;
n = p-*src + 2;
for (i = 0; i < n/3; i++)
*(*dst)++ = '"';
if (n%3 != 1)
p--;
break;
default:
return 0;
}
*src = p;
return 1;
}
int
mainCRTStartup(void) {
static TCHAR buf[32767];
static TCHAR *argv[ARRAYSIZE(buf)/2];
int argc;
const TCHAR *p;
TCHAR *q;
int quot;
p = GetCommandLine();
argv[0] = q = buf;
quot = 0;
for (; DELIM(*p); p++);
for (; *p; p++)
if (!quot && DELIM(*p))
break;
else if (*p == '"')
quot = !quot;
else
*q++ = *p;
*q++ = 0;
for (argc = 1; ; argc++) {
for (; DELIM(*p); p++);
if (!*p)
break;
argv[argc] = q;
quot = 0;
for (; *p; p++)
if (!quot && DELIM(*p))
break;
else if (maybe_unescape(&p, &q, quot))
continue;
else if (*p == '"')
quot = !quot;
else
*q++ = *p;
*q++ = 0;
}
argv[argc] = 0;
ExitProcess(
#ifdef UNICODE
wmain
#else
main
#endif
(argc, argv));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment