20 #include <winpr/config.h>
22 #include <winpr/crt.h>
23 #include <winpr/handle.h>
25 #include <winpr/thread.h>
27 #ifdef WINPR_HAVE_UNISTD_H
32 #define TAG WINPR_TAG("thread")
89 LPSTR* CommandLineToArgvA(LPCSTR lpCmdLine,
int* pNumArgs)
93 const char* pBeg = NULL;
94 const char* pEnd = NULL;
99 size_t maxNumArgs = 0;
100 size_t maxBufferSize = 0;
101 size_t cmdLineLength = 0;
102 BOOL* lpEscapedChars = NULL;
103 LPSTR lpEscapedCmdLine = NULL;
112 lpEscapedCmdLine = NULL;
113 cmdLineLength = strlen(lpCmdLine);
114 lpEscapedChars = (BOOL*)calloc(cmdLineLength + 1,
sizeof(BOOL));
119 if (strstr(lpCmdLine,
"\\\""))
122 const char* pLastEnd = NULL;
123 lpEscapedCmdLine = (
char*)calloc(cmdLineLength + 1,
sizeof(
char));
125 if (!lpEscapedCmdLine)
127 free(lpEscapedChars);
131 p = (
const char*)lpCmdLine;
132 pLastEnd = (
const char*)lpCmdLine;
133 pOutput = (
char*)lpEscapedCmdLine;
135 while (p < &lpCmdLine[cmdLineLength])
137 pBeg = strstr(p,
"\\\"");
142 CopyMemory(pOutput, p, length);
149 while (pBeg >= lpCmdLine)
160 n = ((pEnd - pBeg) - 1);
161 length = (pBeg - pLastEnd);
162 CopyMemory(pOutput, p, length);
166 for (
size_t i = 0; i < (n / 2); i++)
172 lpEscapedChars[pOutput - lpEscapedCmdLine] = TRUE;
179 lpCmdLine = (LPCSTR)lpEscapedCmdLine;
180 cmdLineLength = strlen(lpCmdLine);
184 p = (
const char*)lpCmdLine;
186 while (p < lpCmdLine + cmdLineLength)
188 p += strcspn(p,
" \t");
189 p += strspn(p,
" \t");
193 maxBufferSize = (maxNumArgs * (
sizeof(
char*))) + (cmdLineLength + 1);
194 buffer = calloc(maxBufferSize,
sizeof(
char));
198 free(lpEscapedCmdLine);
199 free(lpEscapedChars);
203 pArgs = (LPSTR*)buffer;
204 pOutput = &buffer[maxNumArgs * (
sizeof(
char*))];
205 p = (
const char*)lpCmdLine;
207 while (p < lpCmdLine + cmdLineLength)
213 p += strcspn(p,
" \t\"\0");
215 if ((*p !=
'"') || !lpEscapedChars[p - lpCmdLine])
225 CopyMemory(pOutput, pBeg, length);
226 pOutput[length] =
'\0';
227 pArgs[numArgs++] = pOutput;
228 pOutput += (length + 1);
236 p += strcspn(p,
"\"\0");
238 if ((*p !=
'"') || !lpEscapedChars[p - lpCmdLine])
245 WLog_ERR(TAG,
"parsing error: uneven number of unescaped double quotes!");
248 p += strcspn(p,
" \t\0");
250 pArgs[numArgs++] = pOutput;
263 p += strspn(p,
" \t");
266 free(lpEscapedCmdLine);
267 free(lpEscapedChars);
274 LPWSTR* CommandLineToArgvW(LPCWSTR lpCmdLine,
int* pNumArgs)