Skip to content

Commit 4fa72bc

Browse files
kbleespatthoyts
authored andcommitted
Win32: factor out environment block creation
Signed-off-by: Karsten Blees <[email protected]>
1 parent 63e444f commit 4fa72bc

File tree

1 file changed

+32
-23
lines changed

1 file changed

+32
-23
lines changed

compat/mingw.c

Lines changed: 32 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -995,6 +995,36 @@ static char *path_lookup(const char *cmd, char **path, int exe_only)
995995
return prog;
996996
}
997997

998+
/*
999+
* Create environment block suitable for CreateProcess.
1000+
*/
1001+
static wchar_t *make_environment_block(char **env)
1002+
{
1003+
wchar_t *wenvblk = NULL;
1004+
int count = 0;
1005+
char **e, **tmpenv;
1006+
int size = 0, wenvsz = 0, wenvpos = 0;
1007+
1008+
for (e = env; *e; e++)
1009+
count++;
1010+
1011+
/* environment must be sorted */
1012+
tmpenv = xmalloc(sizeof(*tmpenv) * (count + 1));
1013+
memcpy(tmpenv, env, sizeof(*tmpenv) * (count + 1));
1014+
qsort(tmpenv, count, sizeof(*tmpenv), compareenv);
1015+
1016+
/* create environment block from temporary environment */
1017+
for (e = tmpenv; *e; e++) {
1018+
size = 2 * strlen(*e) + 2; /* +2 for final \0 */
1019+
ALLOC_GROW(wenvblk, (wenvpos + size) * sizeof(wchar_t), wenvsz);
1020+
wenvpos += xutftowcs(&wenvblk[wenvpos], *e, size) + 1;
1021+
}
1022+
/* add final \0 terminator */
1023+
wenvblk[wenvpos] = 0;
1024+
free(tmpenv);
1025+
return wenvblk;
1026+
}
1027+
9981028
struct pinfo_t {
9991029
struct pinfo_t *next;
10001030
pid_t pid;
@@ -1071,29 +1101,8 @@ static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **env,
10711101
xutftowcs(wargs, args.buf, 2 * args.len + 1);
10721102
strbuf_release(&args);
10731103

1074-
if (env) {
1075-
int count = 0;
1076-
char **e, **sorted_env;
1077-
int size = 0, wenvsz = 0, wenvpos = 0;
1078-
1079-
for (e = env; *e; e++)
1080-
count++;
1081-
1082-
/* environment must be sorted */
1083-
sorted_env = xmalloc(sizeof(*sorted_env) * (count + 1));
1084-
memcpy(sorted_env, env, sizeof(*sorted_env) * (count + 1));
1085-
qsort(sorted_env, count, sizeof(*sorted_env), compareenv);
1086-
1087-
/* create environment block from temporary environment */
1088-
for (e = sorted_env; *e; e++) {
1089-
size = 2 * strlen(*e) + 2; /* +2 for final \0 */
1090-
ALLOC_GROW(wenvblk, (wenvpos + size) * sizeof(wchar_t), wenvsz);
1091-
wenvpos += xutftowcs(&wenvblk[wenvpos], *e, size) + 1;
1092-
}
1093-
/* add final \0 terminator */
1094-
wenvblk[wenvpos] = 0;
1095-
free(sorted_env);
1096-
}
1104+
if (env)
1105+
wenvblk = make_environment_block(env);
10971106

10981107
memset(&pi, 0, sizeof(pi));
10991108
ret = CreateProcessW(wcmd, wargs, NULL, NULL, TRUE, flags,

0 commit comments

Comments
 (0)