]> git.ipfire.org Git - thirdparty/git.git/blame - compat/mingw.c
msvc: support building Git using MS Visual C++
[thirdparty/git.git] / compat / mingw.c
CommitLineData
f4626df5 1#include "../git-compat-util.h"
444dc903 2#include "win32.h"
28a559c0 3#include <conio.h>
85faec9d 4#include <wchar.h>
7e5d7768 5#include "../strbuf.h"
c9b78400 6#include "../run-command.h"
7eb2619c 7#include "../cache.h"
564be791 8#include "win32/lazyload.h"
bdfbb0ea 9#include "../config.h"
9e9da23c 10#include "dir.h"
f4626df5 11
7c00bc39
JS
12#define HCAST(type, handle) ((type)(intptr_t)handle)
13
19e12549
HV
14static const int delay[] = { 0, 1, 10, 20, 40 };
15
44626dc7 16int err_win_to_posix(DWORD winerr)
b3debd2b
PK
17{
18 int error = ENOSYS;
19 switch(winerr) {
20 case ERROR_ACCESS_DENIED: error = EACCES; break;
21 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
22 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
23 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
24 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
25 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
26 case ERROR_BAD_COMMAND: error = EIO; break;
27 case ERROR_BAD_DEVICE: error = ENODEV; break;
28 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
29 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
30 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
31 case ERROR_BAD_LENGTH: error = EINVAL; break;
32 case ERROR_BAD_PATHNAME: error = ENOENT; break;
33 case ERROR_BAD_PIPE: error = EPIPE; break;
34 case ERROR_BAD_UNIT: error = ENODEV; break;
35 case ERROR_BAD_USERNAME: error = EINVAL; break;
36 case ERROR_BROKEN_PIPE: error = EPIPE; break;
37 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
38 case ERROR_BUSY: error = EBUSY; break;
39 case ERROR_BUSY_DRIVE: error = EBUSY; break;
40 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
41 case ERROR_CANNOT_MAKE: error = EACCES; break;
42 case ERROR_CANTOPEN: error = EIO; break;
43 case ERROR_CANTREAD: error = EIO; break;
44 case ERROR_CANTWRITE: error = EIO; break;
45 case ERROR_CRC: error = EIO; break;
46 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
47 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
48 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
49 case ERROR_DIRECTORY: error = EINVAL; break;
50 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
51 case ERROR_DISK_CHANGE: error = EIO; break;
52 case ERROR_DISK_FULL: error = ENOSPC; break;
53 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
54 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
55 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
56 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
57 case ERROR_FILE_EXISTS: error = EEXIST; break;
58 case ERROR_FILE_INVALID: error = ENODEV; break;
59 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
60 case ERROR_GEN_FAILURE: error = EIO; break;
61 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
62 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
63 case ERROR_INVALID_ACCESS: error = EACCES; break;
64 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
65 case ERROR_INVALID_BLOCK: error = EFAULT; break;
66 case ERROR_INVALID_DATA: error = EINVAL; break;
67 case ERROR_INVALID_DRIVE: error = ENODEV; break;
68 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
69 case ERROR_INVALID_FLAGS: error = EINVAL; break;
70 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
71 case ERROR_INVALID_HANDLE: error = EBADF; break;
72 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
73 case ERROR_INVALID_NAME: error = EINVAL; break;
74 case ERROR_INVALID_OWNER: error = EINVAL; break;
75 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
76 case ERROR_INVALID_PASSWORD: error = EPERM; break;
77 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
78 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
79 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
80 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
81 case ERROR_IO_DEVICE: error = EIO; break;
82 case ERROR_IO_INCOMPLETE: error = EINTR; break;
83 case ERROR_LOCKED: error = EBUSY; break;
84 case ERROR_LOCK_VIOLATION: error = EACCES; break;
85 case ERROR_LOGON_FAILURE: error = EACCES; break;
86 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
87 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
88 case ERROR_MORE_DATA: error = EPIPE; break;
89 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
90 case ERROR_NOACCESS: error = EFAULT; break;
91 case ERROR_NONE_MAPPED: error = EINVAL; break;
92 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
93 case ERROR_NOT_READY: error = EAGAIN; break;
94 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
95 case ERROR_NO_DATA: error = EPIPE; break;
96 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
97 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
98 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
99 case ERROR_OPEN_FAILED: error = EIO; break;
100 case ERROR_OPEN_FILES: error = EBUSY; break;
101 case ERROR_OPERATION_ABORTED: error = EINTR; break;
102 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
103 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
104 case ERROR_PATH_BUSY: error = EBUSY; break;
105 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
106 case ERROR_PIPE_BUSY: error = EBUSY; break;
107 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
108 case ERROR_PIPE_LISTENING: error = EPIPE; break;
109 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
110 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
111 case ERROR_READ_FAULT: error = EIO; break;
112 case ERROR_SEEK: error = EIO; break;
113 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
114 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
115 case ERROR_SHARING_VIOLATION: error = EACCES; break;
116 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
117 case ERROR_SWAPERROR: error = ENOENT; break;
118 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
119 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
120 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
121 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
122 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
123 case ERROR_WRITE_FAULT: error = EIO; break;
124 case ERROR_WRITE_PROTECT: error = EROFS; break;
125 }
126 return error;
127}
128
19e12549
HV
129static inline int is_file_in_use_error(DWORD errcode)
130{
131 switch (errcode) {
132 case ERROR_SHARING_VIOLATION:
133 case ERROR_ACCESS_DENIED:
134 return 1;
135 }
136
137 return 0;
138}
139
c9b78400
HV
140static int read_yes_no_answer(void)
141{
142 char answer[1024];
143
144 if (fgets(answer, sizeof(answer), stdin)) {
145 size_t answer_len = strlen(answer);
146 int got_full_line = 0, c;
147
148 /* remove the newline */
149 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
150 answer[answer_len-2] = '\0';
151 got_full_line = 1;
152 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
153 answer[answer_len-1] = '\0';
154 got_full_line = 1;
155 }
156 /* flush the buffer in case we did not get the full line */
157 if (!got_full_line)
158 while ((c = getchar()) != EOF && c != '\n')
159 ;
160 } else
161 /* we could not read, return the
162 * default answer which is no */
163 return 0;
164
165 if (tolower(answer[0]) == 'y' && !answer[1])
166 return 1;
167 if (!strncasecmp(answer, "yes", sizeof(answer)))
168 return 1;
169 if (tolower(answer[0]) == 'n' && !answer[1])
170 return 0;
171 if (!strncasecmp(answer, "no", sizeof(answer)))
172 return 0;
173
174 /* did not find an answer we understand */
175 return -1;
176}
177
178static int ask_yes_no_if_possible(const char *format, ...)
179{
180 char question[4096];
181 const char *retry_hook[] = { NULL, NULL, NULL };
182 va_list args;
183
184 va_start(args, format);
185 vsnprintf(question, sizeof(question), format, args);
186 va_end(args);
187
06bc4b79 188 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
c9b78400
HV
189 retry_hook[1] = question;
190 return !run_command_v_opt(retry_hook, 0);
191 }
192
193 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
194 return 0;
195
196 while (1) {
197 int answer;
198 fprintf(stderr, "%s (y/n) ", question);
199
200 if ((answer = read_yes_no_answer()) >= 0)
201 return answer;
202
203 fprintf(stderr, "Sorry, I did not understand your answer. "
204 "Please type 'y' or 'n'\n");
205 }
206}
207
bdfbb0ea
JS
208/* Windows only */
209enum hide_dotfiles_type {
210 HIDE_DOTFILES_FALSE = 0,
211 HIDE_DOTFILES_TRUE,
212 HIDE_DOTFILES_DOTGITONLY
213};
214
215static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
0e218f91 216static char *unset_environment_variables;
bdfbb0ea 217
70fc5793
JS
218int mingw_core_config(const char *var, const char *value, void *cb)
219{
bdfbb0ea
JS
220 if (!strcmp(var, "core.hidedotfiles")) {
221 if (value && !strcasecmp(value, "dotgitonly"))
222 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
223 else
224 hide_dotfiles = git_config_bool(var, value);
225 return 0;
226 }
227
0e218f91
JS
228 if (!strcmp(var, "core.unsetenvvars")) {
229 free(unset_environment_variables);
230 unset_environment_variables = xstrdup(value);
231 return 0;
232 }
233
70fc5793
JS
234 return 0;
235}
236
4745feeb
AS
237/* Normalizes NT paths as returned by some low-level APIs. */
238static wchar_t *normalize_ntpath(wchar_t *wbuf)
239{
240 int i;
241 /* fix absolute path prefixes */
242 if (wbuf[0] == '\\') {
243 /* strip NT namespace prefixes */
244 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
245 !wcsncmp(wbuf, L"\\\\?\\", 4))
246 wbuf += 4;
247 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
248 wbuf += 12;
249 /* replace remaining '...UNC\' with '\\' */
250 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
251 wbuf += 2;
252 *wbuf = '\\';
253 }
254 }
255 /* convert backslashes to slashes */
256 for (i = 0; wbuf[i]; i++)
257 if (wbuf[i] == '\\')
258 wbuf[i] = '/';
259 return wbuf;
260}
261
337967fb
HV
262int mingw_unlink(const char *pathname)
263{
19e12549 264 int ret, tries = 0;
85faec9d
KB
265 wchar_t wpathname[MAX_PATH];
266 if (xutftowcs_path(wpathname, pathname) < 0)
267 return -1;
19e12549 268
337967fb 269 /* read-only files cannot be removed */
85faec9d
KB
270 _wchmod(wpathname, 0666);
271 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
19e12549
HV
272 if (!is_file_in_use_error(GetLastError()))
273 break;
274 /*
275 * We assume that some other process had the source or
276 * destination file open at the wrong moment and retry.
277 * In order to give the other process a higher chance to
278 * complete its operation, we give up our time slice now.
279 * If we have to retry again, we do sleep a bit.
280 */
281 Sleep(delay[tries]);
282 tries++;
283 }
c9b78400
HV
284 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
285 ask_yes_no_if_possible("Unlink of file '%s' failed. "
286 "Should I try again?", pathname))
85faec9d 287 ret = _wunlink(wpathname);
19e12549 288 return ret;
337967fb
HV
289}
290
85faec9d 291static int is_dir_empty(const wchar_t *wpath)
ab1a11be 292{
85faec9d 293 WIN32_FIND_DATAW findbuf;
ab1a11be 294 HANDLE handle;
85faec9d
KB
295 wchar_t wbuf[MAX_PATH + 2];
296 wcscpy(wbuf, wpath);
297 wcscat(wbuf, L"\\*");
298 handle = FindFirstFileW(wbuf, &findbuf);
299 if (handle == INVALID_HANDLE_VALUE)
ab1a11be 300 return GetLastError() == ERROR_NO_MORE_FILES;
ab1a11be 301
85faec9d
KB
302 while (!wcscmp(findbuf.cFileName, L".") ||
303 !wcscmp(findbuf.cFileName, L".."))
304 if (!FindNextFileW(handle, &findbuf)) {
305 DWORD err = GetLastError();
306 FindClose(handle);
307 return err == ERROR_NO_MORE_FILES;
ab1a11be
JS
308 }
309 FindClose(handle);
ab1a11be
JS
310 return 0;
311}
312
4f288100
HV
313int mingw_rmdir(const char *pathname)
314{
315 int ret, tries = 0;
85faec9d
KB
316 wchar_t wpathname[MAX_PATH];
317 if (xutftowcs_path(wpathname, pathname) < 0)
318 return -1;
4f288100 319
85faec9d 320 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
4f288100 321 if (!is_file_in_use_error(GetLastError()))
a83b2b57
EFL
322 errno = err_win_to_posix(GetLastError());
323 if (errno != EACCES)
4f288100 324 break;
85faec9d 325 if (!is_dir_empty(wpathname)) {
ab1a11be
JS
326 errno = ENOTEMPTY;
327 break;
328 }
4f288100
HV
329 /*
330 * We assume that some other process had the source or
331 * destination file open at the wrong moment and retry.
332 * In order to give the other process a higher chance to
333 * complete its operation, we give up our time slice now.
334 * If we have to retry again, we do sleep a bit.
335 */
336 Sleep(delay[tries]);
337 tries++;
338 }
a83b2b57 339 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
4f288100
HV
340 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
341 "Should I try again?", pathname))
85faec9d
KB
342 ret = _wrmdir(wpathname);
343 return ret;
344}
345
f30afdab
JS
346static inline int needs_hiding(const char *path)
347{
348 const char *basename;
349
350 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
351 return 0;
352
353 /* We cannot use basename(), as it would remove trailing slashes */
1cadad6f 354 win32_skip_dos_drive_prefix((char **)&path);
f30afdab
JS
355 if (!*path)
356 return 0;
357
358 for (basename = path; *path; path++)
359 if (is_dir_sep(*path)) {
360 do {
361 path++;
362 } while (is_dir_sep(*path));
363 /* ignore trailing slashes */
364 if (*path)
365 basename = path;
366 }
367
368 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
369 return *basename == '.';
370
371 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
372 return !strncasecmp(".git", basename, 4) &&
373 (!basename[4] || is_dir_sep(basename[4]));
374}
375
376static int set_hidden_flag(const wchar_t *path, int set)
377{
378 DWORD original = GetFileAttributesW(path), modified;
379 if (set)
380 modified = original | FILE_ATTRIBUTE_HIDDEN;
381 else
382 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
383 if (original == modified || SetFileAttributesW(path, modified))
384 return 0;
385 errno = err_win_to_posix(GetLastError());
386 return -1;
387}
388
85faec9d
KB
389int mingw_mkdir(const char *path, int mode)
390{
391 int ret;
392 wchar_t wpath[MAX_PATH];
393 if (xutftowcs_path(wpath, path) < 0)
394 return -1;
395 ret = _wmkdir(wpath);
f30afdab
JS
396 if (!ret && needs_hiding(path))
397 return set_hidden_flag(wpath, 1);
4f288100
HV
398 return ret;
399}
400
eeaf7dda
JH
401/*
402 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
403 * is documented in [1] as opening a writable file handle in append mode.
404 * (It is believed that) this is atomic since it is maintained by the
405 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
406 *
407 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
408 *
409 * This trick does not appear to work for named pipes. Instead it creates
410 * a named pipe client handle that cannot be written to. Callers should
411 * just use the regular _wopen() for them. (And since client handle gets
412 * bound to a unique server handle, it isn't really an issue.)
413 */
d6410975
JS
414static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
415{
416 HANDLE handle;
417 int fd;
418 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
419
420 /* only these flags are supported */
421 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
422 return errno = ENOSYS, -1;
423
424 /*
425 * FILE_SHARE_WRITE is required to permit child processes
426 * to append to the file.
427 */
428 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
429 FILE_SHARE_WRITE | FILE_SHARE_READ,
430 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
431 if (handle == INVALID_HANDLE_VALUE)
432 return errno = err_win_to_posix(GetLastError()), -1;
eeaf7dda 433
d6410975
JS
434 /*
435 * No O_APPEND here, because the CRT uses it only to reset the
eeaf7dda
JH
436 * file pointer to EOF before each write(); but that is not
437 * necessary (and may lead to races) for a file created with
438 * FILE_APPEND_DATA.
d6410975
JS
439 */
440 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
441 if (fd < 0)
442 CloseHandle(handle);
443 return fd;
444}
445
eeaf7dda
JH
446/*
447 * Does the pathname map to the local named pipe filesystem?
448 * That is, does it have a "//./pipe/" prefix?
449 */
450static int is_local_named_pipe_path(const char *filename)
451{
452 return (is_dir_sep(filename[0]) &&
453 is_dir_sep(filename[1]) &&
454 filename[2] == '.' &&
455 is_dir_sep(filename[3]) &&
456 !strncasecmp(filename+4, "pipe", 4) &&
457 is_dir_sep(filename[8]) &&
458 filename[9]);
459}
460
3e4a1ba0
JS
461int mingw_open (const char *filename, int oflags, ...)
462{
d6410975 463 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
3e4a1ba0
JS
464 va_list args;
465 unsigned mode;
0d30ad71 466 int fd;
85faec9d 467 wchar_t wfilename[MAX_PATH];
d6410975 468 open_fn_t open_fn;
0d30ad71 469
3e4a1ba0
JS
470 va_start(args, oflags);
471 mode = va_arg(args, int);
472 va_end(args);
473
1a404209 474 if (filename && !strcmp(filename, "/dev/null"))
3e4a1ba0 475 filename = "nul";
0d30ad71 476
eeaf7dda 477 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
d6410975
JS
478 open_fn = mingw_open_append;
479 else
480 open_fn = _wopen;
481
85faec9d
KB
482 if (xutftowcs_path(wfilename, filename) < 0)
483 return -1;
d6410975 484 fd = open_fn(wfilename, oflags, mode);
0d30ad71 485
ba6fad02 486 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
85faec9d 487 DWORD attrs = GetFileAttributesW(wfilename);
3e4a1ba0
JS
488 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
489 errno = EISDIR;
490 }
f30afdab
JS
491 if ((oflags & O_CREAT) && needs_hiding(filename)) {
492 /*
493 * Internally, _wopen() uses the CreateFile() API which errors
494 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
495 * specified and an already existing file's attributes do not
496 * match *exactly*. As there is no mode or flag we can set that
497 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
498 * again *without* the O_CREAT flag (that corresponds to the
499 * CREATE_ALWAYS flag of CreateFile()).
500 */
501 if (fd < 0 && errno == EACCES)
d6410975 502 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
f30afdab
JS
503 if (fd >= 0 && set_hidden_flag(wfilename, 1))
504 warning("could not mark '%s' as hidden.", filename);
505 }
3e4a1ba0
JS
506 return fd;
507}
508
176478a8
EFL
509static BOOL WINAPI ctrl_ignore(DWORD type)
510{
511 return TRUE;
512}
513
514#undef fgetc
515int mingw_fgetc(FILE *stream)
516{
517 int ch;
518 if (!isatty(_fileno(stream)))
519 return fgetc(stream);
520
521 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
522 while (1) {
523 ch = fgetc(stream);
524 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
525 break;
526
527 /* Ctrl+C was pressed, simulate SIGINT and retry */
528 mingw_raise(SIGINT);
529 }
530 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
531 return ch;
532}
533
3fdcdbdf
JS
534#undef fopen
535FILE *mingw_fopen (const char *filename, const char *otype)
536{
f30afdab 537 int hide = needs_hiding(filename);
85faec9d
KB
538 FILE *file;
539 wchar_t wfilename[MAX_PATH], wotype[4];
1a404209 540 if (filename && !strcmp(filename, "/dev/null"))
3fdcdbdf 541 filename = "nul";
85faec9d
KB
542 if (xutftowcs_path(wfilename, filename) < 0 ||
543 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
544 return NULL;
f30afdab
JS
545 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
546 error("could not unhide %s", filename);
547 return NULL;
548 }
85faec9d 549 file = _wfopen(wfilename, wotype);
e5b31344
JS
550 if (!file && GetLastError() == ERROR_INVALID_NAME)
551 errno = ENOENT;
f30afdab
JS
552 if (file && hide && set_hidden_flag(wfilename, 1))
553 warning("could not mark '%s' as hidden.", filename);
85faec9d 554 return file;
3fdcdbdf
JS
555}
556
3fdcdbdf
JS
557FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
558{
f30afdab 559 int hide = needs_hiding(filename);
85faec9d
KB
560 FILE *file;
561 wchar_t wfilename[MAX_PATH], wotype[4];
3fdcdbdf
JS
562 if (filename && !strcmp(filename, "/dev/null"))
563 filename = "nul";
85faec9d
KB
564 if (xutftowcs_path(wfilename, filename) < 0 ||
565 xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
566 return NULL;
f30afdab
JS
567 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
568 error("could not unhide %s", filename);
569 return NULL;
570 }
85faec9d 571 file = _wfreopen(wfilename, wotype, stream);
f30afdab
JS
572 if (file && hide && set_hidden_flag(wfilename, 1))
573 warning("could not mark '%s' as hidden.", filename);
85faec9d 574 return file;
3fdcdbdf
JS
575}
576
84adb641
JS
577#undef fflush
578int mingw_fflush(FILE *stream)
579{
580 int ret = fflush(stream);
581
582 /*
583 * write() is used behind the scenes of stdio output functions.
584 * Since git code does not check for errors after each stdio write
585 * operation, it can happen that write() is called by a later
586 * stdio function even if an earlier write() call failed. In the
587 * case of a pipe whose readable end was closed, only the first
588 * call to write() reports EPIPE on Windows. Subsequent write()
589 * calls report EINVAL. It is impossible to notice whether this
590 * fflush invocation triggered such a case, therefore, we have to
591 * catch all EINVAL errors whole-sale.
592 */
593 if (ret && errno == EINVAL)
594 errno = EPIPE;
595
596 return ret;
597}
598
2b86292e
JS
599#undef write
600ssize_t mingw_write(int fd, const void *buf, size_t len)
601{
602 ssize_t result = write(fd, buf, len);
603
604 if (result < 0 && errno == EINVAL && buf) {
605 /* check if fd is a pipe */
606 HANDLE h = (HANDLE) _get_osfhandle(fd);
607 if (GetFileType(h) == FILE_TYPE_PIPE)
608 errno = EPIPE;
609 else
610 errno = EINVAL;
611 }
612
613 return result;
614}
615
85faec9d
KB
616int mingw_access(const char *filename, int mode)
617{
618 wchar_t wfilename[MAX_PATH];
619 if (xutftowcs_path(wfilename, filename) < 0)
620 return -1;
621 /* X_OK is not supported by the MSVCRT version */
622 return _waccess(wfilename, mode & ~X_OK);
623}
624
625int mingw_chdir(const char *dirname)
626{
627 wchar_t wdirname[MAX_PATH];
628 if (xutftowcs_path(wdirname, dirname) < 0)
629 return -1;
630 return _wchdir(wdirname);
631}
632
633int mingw_chmod(const char *filename, int mode)
634{
635 wchar_t wfilename[MAX_PATH];
636 if (xutftowcs_path(wfilename, filename) < 0)
637 return -1;
638 return _wchmod(wfilename, mode);
639}
640
a6d15bc3
JS
641/*
642 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
643 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
644 */
645static inline long long filetime_to_hnsec(const FILETIME *ft)
5411bdc4
MSO
646{
647 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
a6d15bc3
JS
648 /* Windows to Unix Epoch conversion */
649 return winTime - 116444736000000000LL;
650}
651
d7e8c874 652static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
a6d15bc3 653{
d7e8c874
KB
654 long long hnsec = filetime_to_hnsec(ft);
655 ts->tv_sec = (time_t)(hnsec / 10000000);
656 ts->tv_nsec = (hnsec % 10000000) * 100;
5411bdc4
MSO
657}
658
4b0abd5c
JS
659/**
660 * Verifies that safe_create_leading_directories() would succeed.
661 */
662static int has_valid_directory_prefix(wchar_t *wfilename)
663{
664 int n = wcslen(wfilename);
665
666 while (n > 0) {
667 wchar_t c = wfilename[--n];
668 DWORD attributes;
669
670 if (!is_dir_sep(c))
671 continue;
672
673 wfilename[n] = L'\0';
674 attributes = GetFileAttributesW(wfilename);
675 wfilename[n] = c;
676 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
677 attributes == FILE_ATTRIBUTE_DEVICE)
678 return 1;
679 if (attributes == INVALID_FILE_ATTRIBUTES)
680 switch (GetLastError()) {
681 case ERROR_PATH_NOT_FOUND:
682 continue;
683 case ERROR_FILE_NOT_FOUND:
684 /* This implies parent directory exists. */
685 return 1;
686 }
687 return 0;
688 }
689 return 1;
690}
691
5411bdc4
MSO
692/* We keep the do_lstat code in a separate function to avoid recursion.
693 * When a path ends with a slash, the stat will fail with ENOENT. In
694 * this case, we strip the trailing slashes and stat again.
9b9784ca
PT
695 *
696 * If follow is true then act like stat() and report on the link
697 * target. Otherwise report on the link itself.
5411bdc4 698 */
9b9784ca 699static int do_lstat(int follow, const char *file_name, struct stat *buf)
5411bdc4
MSO
700{
701 WIN32_FILE_ATTRIBUTE_DATA fdata;
85faec9d
KB
702 wchar_t wfilename[MAX_PATH];
703 if (xutftowcs_path(wfilename, file_name) < 0)
704 return -1;
5411bdc4 705
85faec9d 706 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
5411bdc4
MSO
707 buf->st_ino = 0;
708 buf->st_gid = 0;
709 buf->st_uid = 0;
180964f0 710 buf->st_nlink = 1;
444dc903 711 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
1d4e4cd4
JS
712 buf->st_size = fdata.nFileSizeLow |
713 (((off_t)fdata.nFileSizeHigh)<<32);
8252df62 714 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
d7e8c874
KB
715 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
716 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
717 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
9b9784ca 718 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
85faec9d
KB
719 WIN32_FIND_DATAW findbuf;
720 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
9b9784ca
PT
721 if (handle != INVALID_HANDLE_VALUE) {
722 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
723 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
724 if (follow) {
725 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
726 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
727 } else {
728 buf->st_mode = S_IFLNK;
729 }
730 buf->st_mode |= S_IREAD;
731 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
732 buf->st_mode |= S_IWRITE;
733 }
734 FindClose(handle);
735 }
736 }
5411bdc4
MSO
737 return 0;
738 }
85faec9d
KB
739 switch (GetLastError()) {
740 case ERROR_ACCESS_DENIED:
741 case ERROR_SHARING_VIOLATION:
742 case ERROR_LOCK_VIOLATION:
743 case ERROR_SHARING_BUFFER_EXCEEDED:
744 errno = EACCES;
745 break;
746 case ERROR_BUFFER_OVERFLOW:
747 errno = ENAMETOOLONG;
748 break;
749 case ERROR_NOT_ENOUGH_MEMORY:
750 errno = ENOMEM;
751 break;
4b0abd5c
JS
752 case ERROR_PATH_NOT_FOUND:
753 if (!has_valid_directory_prefix(wfilename)) {
754 errno = ENOTDIR;
755 break;
756 }
757 /* fallthru */
85faec9d
KB
758 default:
759 errno = ENOENT;
760 break;
761 }
5411bdc4
MSO
762 return -1;
763}
764
765/* We provide our own lstat/fstat functions, since the provided
766 * lstat/fstat functions are so slow. These stat functions are
767 * tailored for Git's usage (read: fast), and are not meant to be
768 * complete. Note that Git stat()s are redirected to mingw_lstat()
769 * too, since Windows doesn't really handle symlinks that well.
770 */
9b9784ca 771static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
5411bdc4
MSO
772{
773 int namelen;
58aa3d2a 774 char alt_name[PATH_MAX];
5411bdc4 775
9b9784ca 776 if (!do_lstat(follow, file_name, buf))
5411bdc4
MSO
777 return 0;
778
779 /* if file_name ended in a '/', Windows returned ENOENT;
780 * try again without trailing slashes
781 */
782 if (errno != ENOENT)
783 return -1;
784
785 namelen = strlen(file_name);
786 if (namelen && file_name[namelen-1] != '/')
787 return -1;
788 while (namelen && file_name[namelen-1] == '/')
789 --namelen;
790 if (!namelen || namelen >= PATH_MAX)
791 return -1;
792
793 memcpy(alt_name, file_name, namelen);
794 alt_name[namelen] = 0;
9b9784ca
PT
795 return do_lstat(follow, alt_name, buf);
796}
797
7bf19838
JS
798static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
799{
800 BY_HANDLE_FILE_INFORMATION fdata;
801
802 if (!GetFileInformationByHandle(hnd, &fdata)) {
803 errno = err_win_to_posix(GetLastError());
804 return -1;
805 }
806
807 buf->st_ino = 0;
808 buf->st_gid = 0;
809 buf->st_uid = 0;
810 buf->st_nlink = 1;
811 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
812 buf->st_size = fdata.nFileSizeLow |
813 (((off_t)fdata.nFileSizeHigh)<<32);
814 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
d7e8c874
KB
815 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
816 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
817 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
7bf19838
JS
818 return 0;
819}
820
9b9784ca
PT
821int mingw_lstat(const char *file_name, struct stat *buf)
822{
823 return do_stat_internal(0, file_name, buf);
824}
825int mingw_stat(const char *file_name, struct stat *buf)
826{
827 return do_stat_internal(1, file_name, buf);
5411bdc4
MSO
828}
829
180964f0 830int mingw_fstat(int fd, struct stat *buf)
5411bdc4
MSO
831{
832 HANDLE fh = (HANDLE)_get_osfhandle(fd);
d75e6973 833 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
5411bdc4 834
d75e6973
KB
835 switch (type) {
836 case FILE_TYPE_DISK:
837 return get_file_info_by_handle(fh, buf);
5411bdc4 838
d75e6973
KB
839 case FILE_TYPE_CHAR:
840 case FILE_TYPE_PIPE:
841 /* initialize stat fields */
842 memset(buf, 0, sizeof(*buf));
180964f0 843 buf->st_nlink = 1;
d75e6973
KB
844
845 if (type == FILE_TYPE_CHAR) {
846 buf->st_mode = _S_IFCHR;
847 } else {
848 buf->st_mode = _S_IFIFO;
849 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
850 buf->st_size = avail;
851 }
5411bdc4 852 return 0;
7bf19838 853
d75e6973
KB
854 default:
855 errno = EBADF;
856 return -1;
5411bdc4 857 }
5411bdc4
MSO
858}
859
7c0ffa1c
JS
860static inline void time_t_to_filetime(time_t t, FILETIME *ft)
861{
862 long long winTime = t * 10000000LL + 116444736000000000LL;
863 ft->dwLowDateTime = winTime;
864 ft->dwHighDateTime = winTime >> 32;
865}
866
867int mingw_utime (const char *file_name, const struct utimbuf *times)
868{
869 FILETIME mft, aft;
870 int fh, rc;
85faec9d
KB
871 DWORD attrs;
872 wchar_t wfilename[MAX_PATH];
873 if (xutftowcs_path(wfilename, file_name) < 0)
874 return -1;
7c0ffa1c
JS
875
876 /* must have write permission */
85faec9d 877 attrs = GetFileAttributesW(wfilename);
852f098c
JS
878 if (attrs != INVALID_FILE_ATTRIBUTES &&
879 (attrs & FILE_ATTRIBUTE_READONLY)) {
880 /* ignore errors here; open() will report them */
85faec9d 881 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
852f098c
JS
882 }
883
85faec9d 884 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
852f098c
JS
885 rc = -1;
886 goto revert_attrs;
887 }
7c0ffa1c 888
ded2d476
SG
889 if (times) {
890 time_t_to_filetime(times->modtime, &mft);
891 time_t_to_filetime(times->actime, &aft);
892 } else {
893 GetSystemTimeAsFileTime(&mft);
894 aft = mft;
895 }
7c0ffa1c
JS
896 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
897 errno = EINVAL;
898 rc = -1;
899 } else
900 rc = 0;
901 close(fh);
852f098c
JS
902
903revert_attrs:
904 if (attrs != INVALID_FILE_ATTRIBUTES &&
905 (attrs & FILE_ATTRIBUTE_READONLY)) {
906 /* ignore errors again */
85faec9d 907 SetFileAttributesW(wfilename, attrs);
852f098c 908 }
7c0ffa1c
JS
909 return rc;
910}
911
9ee0540a
JS
912#undef strftime
913size_t mingw_strftime(char *s, size_t max,
914 const char *format, const struct tm *tm)
915{
916 size_t ret = strftime(s, max, format, tm);
917
918 if (!ret && errno == EINVAL)
919 die("invalid strftime format: '%s'", format);
920 return ret;
921}
922
f4626df5
JS
923unsigned int sleep (unsigned int seconds)
924{
925 Sleep(seconds*1000);
926 return 0;
927}
928
85faec9d
KB
929char *mingw_mktemp(char *template)
930{
931 wchar_t wtemplate[MAX_PATH];
932 if (xutftowcs_path(wtemplate, template) < 0)
933 return NULL;
934 if (!_wmktemp(wtemplate))
935 return NULL;
936 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
937 return NULL;
938 return template;
939}
940
f4626df5
JS
941int mkstemp(char *template)
942{
943 char *filename = mktemp(template);
944 if (filename == NULL)
945 return -1;
946 return open(filename, O_RDWR | O_CREAT, 0600);
947}
948
949int gettimeofday(struct timeval *tv, void *tz)
950{
a6d15bc3
JS
951 FILETIME ft;
952 long long hnsec;
953
954 GetSystemTimeAsFileTime(&ft);
955 hnsec = filetime_to_hnsec(&ft);
956 tv->tv_sec = hnsec / 10000000;
957 tv->tv_usec = (hnsec % 10000000) / 10;
a42a0c2e 958 return 0;
f4626df5
JS
959}
960
897bb8cb
JS
961int pipe(int filedes[2])
962{
3e34d665 963 HANDLE h[2];
897bb8cb 964
3e34d665
JS
965 /* this creates non-inheritable handles */
966 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
967 errno = err_win_to_posix(GetLastError());
897bb8cb
JS
968 return -1;
969 }
7c00bc39 970 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
3e34d665 971 if (filedes[0] < 0) {
897bb8cb
JS
972 CloseHandle(h[0]);
973 CloseHandle(h[1]);
974 return -1;
975 }
7c00bc39 976 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
c3cb7b6f 977 if (filedes[1] < 0) {
897bb8cb 978 close(filedes[0]);
897bb8cb
JS
979 CloseHandle(h[1]);
980 return -1;
981 }
897bb8cb
JS
982 return 0;
983}
984
f4626df5
JS
985struct tm *gmtime_r(const time_t *timep, struct tm *result)
986{
987 /* gmtime() in MSVCRT.DLL is thread-safe, but not reentrant */
988 memcpy(result, gmtime(timep), sizeof(struct tm));
989 return result;
990}
991
992struct tm *localtime_r(const time_t *timep, struct tm *result)
993{
994 /* localtime() in MSVCRT.DLL is thread-safe, but not reentrant */
995 memcpy(result, localtime(timep), sizeof(struct tm));
996 return result;
997}
998
25fe217b
JS
999char *mingw_getcwd(char *pointer, int len)
1000{
937974fc
JS
1001 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1002 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1003
1004 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1005 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1006 return NULL;
1007 }
1008 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
4745feeb
AS
1009 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1010 HANDLE hnd = CreateFileW(cwd, 0,
1011 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1012 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1013 if (hnd == INVALID_HANDLE_VALUE)
1014 return NULL;
1015 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1016 CloseHandle(hnd);
1017 if (!ret || ret >= ARRAY_SIZE(wpointer))
1018 return NULL;
1019 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1020 return NULL;
1021 return pointer;
1022 }
937974fc 1023 if (!ret || ret >= ARRAY_SIZE(wpointer))
85faec9d
KB
1024 return NULL;
1025 if (xwcstoutf(pointer, wpointer, len) < 0)
1026 return NULL;
8e9b2080 1027 convert_slashes(pointer);
85faec9d 1028 return pointer;
25fe217b
JS
1029}
1030
7e5d7768 1031/*
2ef2ae29
JS
1032 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1033 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
7e5d7768 1034 */
9e9da23c 1035static const char *quote_arg_msvc(const char *arg)
7e5d7768
JS
1036{
1037 /* count chars to quote */
1038 int len = 0, n = 0;
1039 int force_quotes = 0;
1040 char *q, *d;
1041 const char *p = arg;
1042 if (!*p) force_quotes = 1;
1043 while (*p) {
3aea1a5a 1044 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
7e5d7768
JS
1045 force_quotes = 1;
1046 else if (*p == '"')
1047 n++;
1048 else if (*p == '\\') {
1049 int count = 0;
1050 while (*p == '\\') {
1051 count++;
1052 p++;
1053 len++;
1054 }
1055 if (*p == '"')
1056 n += count*2 + 1;
1057 continue;
1058 }
1059 len++;
1060 p++;
1061 }
1062 if (!force_quotes && n == 0)
1063 return arg;
1064
1065 /* insert \ where necessary */
50a6c8ef 1066 d = q = xmalloc(st_add3(len, n, 3));
7e5d7768
JS
1067 *d++ = '"';
1068 while (*arg) {
1069 if (*arg == '"')
1070 *d++ = '\\';
1071 else if (*arg == '\\') {
1072 int count = 0;
1073 while (*arg == '\\') {
1074 count++;
1075 *d++ = *arg++;
1076 }
1077 if (*arg == '"') {
1078 while (count-- > 0)
1079 *d++ = '\\';
1080 *d++ = '\\';
1081 }
1082 }
1083 *d++ = *arg++;
1084 }
1085 *d++ = '"';
1086 *d++ = 0;
1087 return q;
1088}
1089
9e9da23c
JS
1090#include "quote.h"
1091
1092static const char *quote_arg_msys2(const char *arg)
1093{
1094 struct strbuf buf = STRBUF_INIT;
1095 const char *p2 = arg, *p;
1096
1097 for (p = arg; *p; p++) {
1098 int ws = isspace(*p);
1099 if (!ws && *p != '\\' && *p != '"' && *p != '{')
1100 continue;
1101 if (!buf.len)
1102 strbuf_addch(&buf, '"');
1103 if (p != p2)
1104 strbuf_add(&buf, p2, p - p2);
1105 if (!ws && *p != '{')
1106 strbuf_addch(&buf, '\\');
1107 p2 = p;
1108 }
1109
1110 if (p == arg)
1111 strbuf_addch(&buf, '"');
1112 else if (!buf.len)
1113 return arg;
1114 else
1115 strbuf_add(&buf, p2, p - p2),
1116
1117 strbuf_addch(&buf, '"');
1118 return strbuf_detach(&buf, 0);
1119}
1120
f1a4dfb8
JS
1121static const char *parse_interpreter(const char *cmd)
1122{
1123 static char buf[100];
1124 char *p, *opt;
1125 int n, fd;
1126
1127 /* don't even try a .exe */
1128 n = strlen(cmd);
1129 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1130 return NULL;
1131
1132 fd = open(cmd, O_RDONLY);
1133 if (fd < 0)
1134 return NULL;
1135 n = read(fd, buf, sizeof(buf)-1);
1136 close(fd);
1137 if (n < 4) /* at least '#!/x' and not error */
1138 return NULL;
1139
1140 if (buf[0] != '#' || buf[1] != '!')
1141 return NULL;
1142 buf[n] = '\0';
bedc4279
PH
1143 p = buf + strcspn(buf, "\r\n");
1144 if (!*p)
f1a4dfb8
JS
1145 return NULL;
1146
1147 *p = '\0';
1148 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1149 return NULL;
1150 /* strip options */
1151 if ((opt = strchr(p+1, ' ')))
1152 *opt = '\0';
1153 return p+1;
1154}
1155
f1a4dfb8
JS
1156/*
1157 * exe_only means that we only want to detect .exe files, but not scripts
1158 * (which do not have an extension)
1159 */
e0ca1ca2
RS
1160static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1161 int isexe, int exe_only)
f1a4dfb8
JS
1162{
1163 char path[MAX_PATH];
e0ca1ca2 1164 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
f1a4dfb8
JS
1165
1166 if (!isexe && access(path, F_OK) == 0)
1167 return xstrdup(path);
1168 path[strlen(path)-4] = '\0';
1169 if ((!exe_only || isexe) && access(path, F_OK) == 0)
fe77b695
ER
1170 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
1171 return xstrdup(path);
f1a4dfb8
JS
1172 return NULL;
1173}
1174
1175/*
22e5e58a 1176 * Determines the absolute path of cmd using the split path in path.
f1a4dfb8
JS
1177 * If cmd contains a slash or backslash, no lookup is performed.
1178 */
e0ca1ca2 1179static char *path_lookup(const char *cmd, int exe_only)
f1a4dfb8 1180{
e0ca1ca2 1181 const char *path;
f1a4dfb8
JS
1182 char *prog = NULL;
1183 int len = strlen(cmd);
1184 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1185
1186 if (strchr(cmd, '/') || strchr(cmd, '\\'))
e0ca1ca2
RS
1187 return xstrdup(cmd);
1188
1189 path = mingw_getenv("PATH");
1190 if (!path)
1191 return NULL;
f1a4dfb8 1192
e0ca1ca2
RS
1193 while (!prog) {
1194 const char *sep = strchrnul(path, ';');
1195 int dirlen = sep - path;
1196 if (dirlen)
1197 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1198 if (!*sep)
1199 break;
1200 path = sep + 1;
1201 }
f1a4dfb8
JS
1202
1203 return prog;
1204}
1205
fe21c6b2
JS
1206static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1207{
1208 while (*s && *s != c)
1209 s++;
1210 return s;
1211}
1212
1213/* Compare only keys */
1214static int wenvcmp(const void *a, const void *b)
1215{
1216 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1217 size_t p_len, q_len;
1218
1219 /* Find the keys */
1220 p_len = wcschrnul(p, L'=') - p;
1221 q_len = wcschrnul(q, L'=') - q;
f279242d 1222
fe21c6b2
JS
1223 /* If the length differs, include the shorter key's NUL */
1224 if (p_len < q_len)
1225 p_len++;
1226 else if (p_len > q_len)
1227 p_len = q_len + 1;
1228
1229 return _wcsnicmp(p, q, p_len);
1230}
f279242d 1231
fe21c6b2
JS
1232/* We need a stable sort to convert the environment between UTF-16 <-> UTF-8 */
1233#ifndef INTERNAL_QSORT
1234#include "qsort.c"
1235#endif
77734da2 1236
df0e998c 1237/*
fe21c6b2
JS
1238 * Build an environment block combining the inherited environment
1239 * merged with the given list of settings.
1240 *
1241 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1242 * Values of the form "KEY" in deltaenv delete inherited values.
1243 *
1244 * Multiple entries in deltaenv for the same key are explicitly allowed.
1245 *
1246 * We return a contiguous block of UNICODE strings with a final trailing
1247 * zero word.
df0e998c 1248 */
77734da2 1249static wchar_t *make_environment_block(char **deltaenv)
7e5d7768 1250{
fe21c6b2
JS
1251 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1252 size_t wlen, s, delta_size, size;
df0e998c 1253
fe21c6b2
JS
1254 wchar_t **array = NULL;
1255 size_t alloc = 0, nr = 0, i;
df0e998c 1256
fe21c6b2
JS
1257 size = 1; /* for extra NUL at the end */
1258
1259 /* If there is no deltaenv to apply, simply return a copy. */
1260 if (!deltaenv || !*deltaenv) {
1261 for (p = wenv; p && *p; ) {
1262 size_t s = wcslen(p) + 1;
1263 size += s;
1264 p += s;
1265 }
77734da2 1266
fe21c6b2
JS
1267 ALLOC_ARRAY(result, size);
1268 memcpy(result, wenv, size * sizeof(*wenv));
1269 FreeEnvironmentStringsW(wenv);
1270 return result;
1271 }
77734da2 1272
fe21c6b2
JS
1273 /*
1274 * If there is a deltaenv, let's accumulate all keys into `array`,
1275 * sort them using the stable git_qsort() and then copy, skipping
1276 * duplicate keys
1277 */
1278 for (p = wenv; p && *p; ) {
1279 ALLOC_GROW(array, nr + 1, alloc);
1280 s = wcslen(p) + 1;
1281 array[nr++] = p;
1282 p += s;
1283 size += s;
df0e998c 1284 }
fe21c6b2
JS
1285
1286 /* (over-)assess size needed for wchar version of deltaenv */
1287 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1288 delta_size += strlen(deltaenv[i]) * 2 + 1;
1289 ALLOC_ARRAY(wdeltaenv, delta_size);
1290
1291 /* convert the deltaenv, appending to array */
1292 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1293 ALLOC_GROW(array, nr + 1, alloc);
1294 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1295 array[nr++] = p;
1296 p += wlen + 1;
1297 }
df0e998c 1298
fe21c6b2
JS
1299 git_qsort(array, nr, sizeof(*array), wenvcmp);
1300 ALLOC_ARRAY(result, size + delta_size);
df0e998c 1301
fe21c6b2
JS
1302 for (p = result, i = 0; i < nr; i++) {
1303 /* Skip any duplicate keys; last one wins */
1304 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1305 i++;
77734da2 1306
fe21c6b2
JS
1307 /* Skip "to delete" entry */
1308 if (!wcschr(array[i], L'='))
1309 continue;
77734da2 1310
fe21c6b2
JS
1311 size = wcslen(array[i]) + 1;
1312 memcpy(p, array[i], size * sizeof(*p));
1313 p += size;
df0e998c 1314 }
fe21c6b2
JS
1315 *p = L'\0';
1316
1317 free(array);
1318 free(wdeltaenv);
1319 FreeEnvironmentStringsW(wenv);
1320 return result;
7e5d7768
JS
1321}
1322
0e218f91
JS
1323static void do_unset_environment_variables(void)
1324{
1325 static int done;
1326 char *p = unset_environment_variables;
1327
1328 if (done || !p)
1329 return;
1330 done = 1;
1331
1332 for (;;) {
1333 char *comma = strchr(p, ',');
1334
1335 if (comma)
1336 *comma = '\0';
1337 unsetenv(p);
1338 if (!comma)
1339 break;
1340 p = comma + 1;
1341 }
1342}
1343
52de4db5
EFL
1344struct pinfo_t {
1345 struct pinfo_t *next;
1346 pid_t pid;
1347 HANDLE proc;
657b35f4
RJ
1348};
1349static struct pinfo_t *pinfo = NULL;
52de4db5
EFL
1350CRITICAL_SECTION pinfo_cs;
1351
9e9da23c
JS
1352/* Used to match and chomp off path components */
1353static inline int match_last_path_component(const char *path, size_t *len,
1354 const char *component)
1355{
1356 size_t component_len = strlen(component);
1357 if (*len < component_len + 1 ||
1358 !is_dir_sep(path[*len - component_len - 1]) ||
1359 fspathncmp(path + *len - component_len, component, component_len))
1360 return 0;
1361 *len -= component_len + 1;
1362 /* chomp off repeated dir separators */
1363 while (*len > 0 && is_dir_sep(path[*len - 1]))
1364 (*len)--;
1365 return 1;
1366}
1367
1368static int is_msys2_sh(const char *cmd)
1369{
1370 if (cmd && !strcmp(cmd, "sh")) {
1371 static int ret = -1;
1372 char *p;
1373
1374 if (ret >= 0)
1375 return ret;
1376
1377 p = path_lookup(cmd, 0);
1378 if (!p)
1379 ret = 0;
1380 else {
1381 size_t len = strlen(p);
1382
1383 ret = match_last_path_component(p, &len, "sh.exe") &&
1384 match_last_path_component(p, &len, "bin") &&
1385 match_last_path_component(p, &len, "usr");
1386 free(p);
1387 }
1388 return ret;
1389 }
1390 return 0;
1391}
1392
77734da2 1393static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1394 const char *dir,
75301f90 1395 int prepend_cmd, int fhin, int fhout, int fherr)
7e5d7768 1396{
99c3c76d 1397 STARTUPINFOW si;
7e5d7768 1398 PROCESS_INFORMATION pi;
7eb2619c
KB
1399 struct strbuf args;
1400 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1401 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
7e5d7768 1402 BOOL ret;
0e218f91 1403 HANDLE cons;
9e9da23c
JS
1404 const char *(*quote_arg)(const char *arg) =
1405 is_msys2_sh(*argv) ? quote_arg_msys2 : quote_arg_msvc;
0e218f91
JS
1406
1407 do_unset_environment_variables();
7e5d7768
JS
1408
1409 /* Determine whether or not we are associated to a console */
0e218f91 1410 cons = CreateFile("CONOUT$", GENERIC_WRITE,
7e5d7768
JS
1411 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1412 FILE_ATTRIBUTE_NORMAL, NULL);
1413 if (cons == INVALID_HANDLE_VALUE) {
1414 /* There is no console associated with this process.
1415 * Since the child is a console process, Windows
1416 * would normally create a console window. But
1417 * since we'll be redirecting std streams, we do
1418 * not need the console.
19fb896f
AG
1419 * It is necessary to use DETACHED_PROCESS
1420 * instead of CREATE_NO_WINDOW to make ssh
1421 * recognize that it has no console.
7e5d7768 1422 */
7eb2619c 1423 flags |= DETACHED_PROCESS;
7e5d7768
JS
1424 } else {
1425 /* There is already a console. If we specified
19fb896f 1426 * DETACHED_PROCESS here, too, Windows would
7e5d7768 1427 * disassociate the child from the console.
19fb896f 1428 * The same is true for CREATE_NO_WINDOW.
7e5d7768
JS
1429 * Go figure!
1430 */
7e5d7768
JS
1431 CloseHandle(cons);
1432 }
1433 memset(&si, 0, sizeof(si));
1434 si.cb = sizeof(si);
1435 si.dwFlags = STARTF_USESTDHANDLES;
eac14f89
KB
1436 si.hStdInput = winansi_get_osfhandle(fhin);
1437 si.hStdOutput = winansi_get_osfhandle(fhout);
1438 si.hStdError = winansi_get_osfhandle(fherr);
7e5d7768 1439
99c3c76d
KB
1440 if (xutftowcs_path(wcmd, cmd) < 0)
1441 return -1;
1442 if (dir && xutftowcs_path(wdir, dir) < 0)
1443 return -1;
1444
7e5d7768
JS
1445 /* concatenate argv, quoting args as we go */
1446 strbuf_init(&args, 0);
1447 if (prepend_cmd) {
1448 char *quoted = (char *)quote_arg(cmd);
1449 strbuf_addstr(&args, quoted);
1450 if (quoted != cmd)
1451 free(quoted);
1452 }
1453 for (; *argv; argv++) {
1454 char *quoted = (char *)quote_arg(*argv);
1455 if (*args.buf)
1456 strbuf_addch(&args, ' ');
1457 strbuf_addstr(&args, quoted);
1458 if (quoted != *argv)
1459 free(quoted);
1460 }
1461
8d5b3325 1462 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
99c3c76d
KB
1463 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1464 strbuf_release(&args);
1465
77734da2 1466 wenvblk = make_environment_block(deltaenv);
7e5d7768
JS
1467
1468 memset(&pi, 0, sizeof(pi));
99c3c76d 1469 ret = CreateProcessW(wcmd, wargs, NULL, NULL, TRUE, flags,
7eb2619c 1470 wenvblk, dir ? wdir : NULL, &si, &pi);
7e5d7768 1471
7eb2619c 1472 free(wenvblk);
99c3c76d 1473 free(wargs);
7e5d7768
JS
1474
1475 if (!ret) {
1476 errno = ENOENT;
1477 return -1;
1478 }
1479 CloseHandle(pi.hThread);
52de4db5
EFL
1480
1481 /*
1482 * The process ID is the human-readable identifier of the process
1483 * that we want to present in log and error messages. The handle
1484 * is not useful for this purpose. But we cannot close it, either,
1485 * because it is not possible to turn a process ID into a process
1486 * handle after the process terminated.
1487 * Keep the handle in a list for waitpid.
1488 */
1489 EnterCriticalSection(&pinfo_cs);
1490 {
1491 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1492 info->pid = pi.dwProcessId;
1493 info->proc = pi.hProcess;
1494 info->next = pinfo;
1495 pinfo = info;
1496 }
1497 LeaveCriticalSection(&pinfo_cs);
1498
1499 return (pid_t)pi.dwProcessId;
7e5d7768
JS
1500}
1501
3e66e47b 1502static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
75301f90 1503{
77734da2 1504 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
75301f90
JS
1505}
1506
77734da2 1507pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1508 const char *dir,
75301f90 1509 int fhin, int fhout, int fherr)
7e5d7768
JS
1510{
1511 pid_t pid;
e0ca1ca2 1512 char *prog = path_lookup(cmd, 0);
7e5d7768
JS
1513
1514 if (!prog) {
1515 errno = ENOENT;
1516 pid = -1;
1517 }
1518 else {
1519 const char *interpr = parse_interpreter(prog);
1520
1521 if (interpr) {
1522 const char *argv0 = argv[0];
e0ca1ca2 1523 char *iprog = path_lookup(interpr, 1);
7e5d7768
JS
1524 argv[0] = prog;
1525 if (!iprog) {
1526 errno = ENOENT;
1527 pid = -1;
1528 }
1529 else {
77734da2 1530 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
75301f90 1531 fhin, fhout, fherr);
7e5d7768
JS
1532 free(iprog);
1533 }
1534 argv[0] = argv0;
1535 }
1536 else
77734da2 1537 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
75301f90 1538 fhin, fhout, fherr);
7e5d7768
JS
1539 free(prog);
1540 }
7e5d7768
JS
1541 return pid;
1542}
1543
3e66e47b 1544static int try_shell_exec(const char *cmd, char *const *argv)
f1a4dfb8
JS
1545{
1546 const char *interpr = parse_interpreter(cmd);
f1a4dfb8
JS
1547 char *prog;
1548 int pid = 0;
1549
1550 if (!interpr)
1551 return 0;
e0ca1ca2 1552 prog = path_lookup(interpr, 1);
f1a4dfb8 1553 if (prog) {
ee4512ed 1554 int exec_id;
f1a4dfb8 1555 int argc = 0;
12fb9bd8
JH
1556#ifndef _MSC_VER
1557 const
1558#endif
1559 char **argv2;
f1a4dfb8 1560 while (argv[argc]) argc++;
b32fa95f 1561 ALLOC_ARRAY(argv2, argc + 1);
7e5d7768
JS
1562 argv2[0] = (char *)cmd; /* full path to the script file */
1563 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
ee4512ed 1564 exec_id = trace2_exec(prog, argv2);
3e66e47b 1565 pid = mingw_spawnv(prog, argv2, 1);
f1a4dfb8
JS
1566 if (pid >= 0) {
1567 int status;
1568 if (waitpid(pid, &status, 0) < 0)
1569 status = 255;
ee4512ed 1570 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1571 exit(status);
1572 }
ee4512ed 1573 trace2_exec_result(exec_id, -1);
f1a4dfb8
JS
1574 pid = 1; /* indicate that we tried but failed */
1575 free(prog);
1576 free(argv2);
1577 }
f1a4dfb8
JS
1578 return pid;
1579}
1580
3e66e47b 1581int mingw_execv(const char *cmd, char *const *argv)
f1a4dfb8
JS
1582{
1583 /* check if git_command is a shell script */
3e66e47b 1584 if (!try_shell_exec(cmd, argv)) {
f1a4dfb8 1585 int pid, status;
ee4512ed 1586 int exec_id;
f1a4dfb8 1587
ee4512ed 1588 exec_id = trace2_exec(cmd, (const char **)argv);
3e66e47b 1589 pid = mingw_spawnv(cmd, (const char **)argv, 0);
ee4512ed
JH
1590 if (pid < 0) {
1591 trace2_exec_result(exec_id, -1);
570f1e6e 1592 return -1;
ee4512ed 1593 }
f1a4dfb8
JS
1594 if (waitpid(pid, &status, 0) < 0)
1595 status = 255;
ee4512ed 1596 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1597 exit(status);
1598 }
570f1e6e 1599 return -1;
f1a4dfb8
JS
1600}
1601
1696d723 1602int mingw_execvp(const char *cmd, char *const *argv)
f1a4dfb8 1603{
e0ca1ca2 1604 char *prog = path_lookup(cmd, 0);
f1a4dfb8
JS
1605
1606 if (prog) {
3e66e47b 1607 mingw_execv(prog, argv);
f1a4dfb8
JS
1608 free(prog);
1609 } else
1610 errno = ENOENT;
1611
1696d723 1612 return -1;
f1a4dfb8
JS
1613}
1614
82fc07b7
EFL
1615int mingw_kill(pid_t pid, int sig)
1616{
1617 if (pid > 0 && sig == SIGTERM) {
1618 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1619
1620 if (TerminateProcess(h, -1)) {
1621 CloseHandle(h);
1622 return 0;
1623 }
1624
1625 errno = err_win_to_posix(GetLastError());
1626 CloseHandle(h);
1627 return -1;
64a99eb4
NTND
1628 } else if (pid > 0 && sig == 0) {
1629 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1630 if (h) {
1631 CloseHandle(h);
1632 return 0;
1633 }
82fc07b7
EFL
1634 }
1635
1636 errno = EINVAL;
1637 return -1;
1638}
1639
343ff06d 1640/*
fe21c6b2
JS
1641 * UTF-8 versions of getenv(), putenv() and unsetenv().
1642 * Internally, they use the CRT's stock UNICODE routines
1643 * to avoid data loss.
343ff06d 1644 */
fe21c6b2 1645char *mingw_getenv(const char *name)
343ff06d 1646{
ca1b4116 1647#define GETENV_MAX_RETAIN 64
fe21c6b2
JS
1648 static char *values[GETENV_MAX_RETAIN];
1649 static int value_counter;
1650 int len_key, len_value;
1651 wchar_t *w_key;
1652 char *value;
1653 wchar_t w_value[32768];
343ff06d 1654
fe21c6b2
JS
1655 if (!name || !*name)
1656 return NULL;
ba26f296 1657
fe21c6b2
JS
1658 len_key = strlen(name) + 1;
1659 /* We cannot use xcalloc() here because that uses getenv() itself */
1660 w_key = calloc(len_key, sizeof(wchar_t));
1661 if (!w_key)
1662 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1663 xutftowcs(w_key, name, len_key);
1664 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1665 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1666 free(w_key);
1667 return NULL;
ba26f296 1668 }
fe21c6b2
JS
1669 free(w_key);
1670
1671 len_value = len_value * 3 + 1;
1672 /* We cannot use xcalloc() here because that uses getenv() itself */
1673 value = calloc(len_value, sizeof(char));
1674 if (!value)
1675 die("Out of memory, (tried to allocate %u bytes)", len_value);
1676 xwcstoutf(value, w_value, len_value);
1677
1678 /*
1679 * We return `value` which is an allocated value and the caller is NOT
1680 * expecting to have to free it, so we keep a round-robin array,
1681 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1682 */
1683 free(values[value_counter]);
1684 values[value_counter++] = value;
1685 if (value_counter >= ARRAY_SIZE(values))
1686 value_counter = 0;
1687
1688 return value;
ba26f296
JS
1689}
1690
fe21c6b2 1691int mingw_putenv(const char *namevalue)
ba26f296 1692{
fe21c6b2
JS
1693 int size;
1694 wchar_t *wide, *equal;
1695 BOOL result;
ba26f296 1696
fe21c6b2
JS
1697 if (!namevalue || !*namevalue)
1698 return 0;
ba26f296 1699
fe21c6b2
JS
1700 size = strlen(namevalue) * 2 + 1;
1701 wide = calloc(size, sizeof(wchar_t));
1702 if (!wide)
1703 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1704 xutftowcs(wide, namevalue, size);
1705 equal = wcschr(wide, L'=');
1706 if (!equal)
1707 result = SetEnvironmentVariableW(wide, NULL);
1708 else {
1709 *equal = L'\0';
1710 result = SetEnvironmentVariableW(wide, equal + 1);
ba26f296 1711 }
fe21c6b2 1712 free(wide);
2affea41 1713
fe21c6b2
JS
1714 if (!result)
1715 errno = err_win_to_posix(GetLastError());
df599e96 1716
fe21c6b2 1717 return result ? 0 : -1;
06bc4b79
JS
1718}
1719
b7cc9f82 1720static void ensure_socket_initialization(void)
746fb857
JS
1721{
1722 WSADATA wsa;
b7cc9f82
MS
1723 static int initialized = 0;
1724
1725 if (initialized)
1726 return;
746fb857
JS
1727
1728 if (WSAStartup(MAKEWORD(2,2), &wsa))
1729 die("unable to initialize winsock subsystem, error %d",
1730 WSAGetLastError());
fe3b2b7b 1731
b9f0193b 1732 atexit((void(*)(void)) WSACleanup);
b7cc9f82
MS
1733 initialized = 1;
1734}
1735
13d24b01
PT
1736#undef gethostname
1737int mingw_gethostname(char *name, int namelen)
1738{
1739 ensure_socket_initialization();
1740 return gethostname(name, namelen);
1741}
1742
b7cc9f82
MS
1743#undef gethostbyname
1744struct hostent *mingw_gethostbyname(const char *host)
1745{
1746 ensure_socket_initialization();
746fb857
JS
1747 return gethostbyname(host);
1748}
1749
b9f0193b 1750#undef getaddrinfo
fe3b2b7b
MS
1751int mingw_getaddrinfo(const char *node, const char *service,
1752 const struct addrinfo *hints, struct addrinfo **res)
1753{
1754 ensure_socket_initialization();
b9f0193b 1755 return getaddrinfo(node, service, hints, res);
fe3b2b7b
MS
1756}
1757
746fb857
JS
1758int mingw_socket(int domain, int type, int protocol)
1759{
1760 int sockfd;
772991af
MP
1761 SOCKET s;
1762
1763 ensure_socket_initialization();
1764 s = WSASocket(domain, type, protocol, NULL, 0, 0);
746fb857
JS
1765 if (s == INVALID_SOCKET) {
1766 /*
1767 * WSAGetLastError() values are regular BSD error codes
1768 * biased by WSABASEERR.
1769 * However, strerror() does not know about networking
1770 * specific errors, which are values beginning at 38 or so.
1771 * Therefore, we choose to leave the biased error code
1772 * in errno so that _if_ someone looks up the code somewhere,
1773 * then it is at least the number that are usually listed.
1774 */
1775 errno = WSAGetLastError();
1776 return -1;
1777 }
1778 /* convert into a file descriptor */
1779 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1780 closesocket(s);
1781 return error("unable to make a socket file descriptor: %s",
1782 strerror(errno));
1783 }
1784 return sockfd;
1785}
1786
1787#undef connect
1788int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1789{
1790 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1791 return connect(s, sa, sz);
1792}
1793
772991af
MP
1794#undef bind
1795int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1796{
1797 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1798 return bind(s, sa, sz);
1799}
1800
1801#undef setsockopt
1802int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1803{
1804 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1805 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1806}
1807
a7941795
JS
1808#undef shutdown
1809int mingw_shutdown(int sockfd, int how)
1810{
1811 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1812 return shutdown(s, how);
1813}
1814
772991af
MP
1815#undef listen
1816int mingw_listen(int sockfd, int backlog)
1817{
1818 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1819 return listen(s, backlog);
1820}
1821
1822#undef accept
1823int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1824{
1825 int sockfd2;
1826
1827 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1828 SOCKET s2 = accept(s1, sa, sz);
1829
1830 /* convert into a file descriptor */
1831 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1832 int err = errno;
1833 closesocket(s2);
1834 return error("unable to make a socket file descriptor: %s",
1835 strerror(err));
1836 }
1837 return sockfd2;
1838}
1839
ea9e98c3
JS
1840#undef rename
1841int mingw_rename(const char *pold, const char *pnew)
1842{
6ac6f878
JS
1843 DWORD attrs, gle;
1844 int tries = 0;
85faec9d
KB
1845 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
1846 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
1847 return -1;
632f7017 1848
ea9e98c3
JS
1849 /*
1850 * Try native rename() first to get errno right.
1851 * It is based on MoveFile(), which cannot overwrite existing files.
1852 */
85faec9d 1853 if (!_wrename(wpold, wpnew))
ea9e98c3
JS
1854 return 0;
1855 if (errno != EEXIST)
1856 return -1;
6ac6f878 1857repeat:
85faec9d 1858 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
ea9e98c3
JS
1859 return 0;
1860 /* TODO: translate more errors */
6ac6f878
JS
1861 gle = GetLastError();
1862 if (gle == ERROR_ACCESS_DENIED &&
85faec9d 1863 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
632f7017 1864 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
4426fb51 1865 DWORD attrsold = GetFileAttributesW(wpold);
1866 if (attrsold == INVALID_FILE_ATTRIBUTES ||
1867 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
1868 errno = EISDIR;
1869 else if (!_wrmdir(wpnew))
1870 goto repeat;
ea9e98c3
JS
1871 return -1;
1872 }
632f7017 1873 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
85faec9d
KB
1874 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1875 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
632f7017 1876 return 0;
6ac6f878 1877 gle = GetLastError();
632f7017 1878 /* revert file attributes on failure */
85faec9d 1879 SetFileAttributesW(wpnew, attrs);
632f7017 1880 }
ea9e98c3 1881 }
6ac6f878
JS
1882 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1883 /*
1884 * We assume that some other process had the source or
1885 * destination file open at the wrong moment and retry.
1886 * In order to give the other process a higher chance to
1887 * complete its operation, we give up our time slice now.
1888 * If we have to retry again, we do sleep a bit.
1889 */
1890 Sleep(delay[tries]);
1891 tries++;
1892 goto repeat;
1893 }
c9b78400
HV
1894 if (gle == ERROR_ACCESS_DENIED &&
1895 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1896 "Should I try again?", pold, pnew))
1897 goto repeat;
1898
ea9e98c3
JS
1899 errno = EACCES;
1900 return -1;
1901}
1902
b1b95204
RJ
1903/*
1904 * Note that this doesn't return the actual pagesize, but
1905 * the allocation granularity. If future Windows specific git code
1906 * needs the real getpagesize function, we need to find another solution.
1907 */
1908int mingw_getpagesize(void)
1909{
1910 SYSTEM_INFO si;
1911 GetSystemInfo(&si);
1912 return si.dwAllocationGranularity;
1913}
1914
564be791
JS
1915/* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
1916enum EXTENDED_NAME_FORMAT {
1917 NameDisplay = 3,
1918 NameUserPrincipal = 8
1919};
1920
1921static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
1922{
1923 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
1924 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
1925 static wchar_t wbuffer[1024];
1926 DWORD len;
1927
1928 if (!INIT_PROC_ADDR(GetUserNameExW))
1929 return NULL;
1930
1931 len = ARRAY_SIZE(wbuffer);
1932 if (GetUserNameExW(type, wbuffer, &len)) {
1933 char *converted = xmalloc((len *= 3));
1934 if (xwcstoutf(converted, wbuffer, len) >= 0)
1935 return converted;
1936 free(converted);
1937 }
1938
1939 return NULL;
1940}
1941
501afcb8
JS
1942char *mingw_query_user_email(void)
1943{
1944 return get_extended_user_info(NameUserPrincipal);
1945}
1946
f4626df5
JS
1947struct passwd *getpwuid(int uid)
1948{
55b6513e 1949 static unsigned initialized;
f7597aca 1950 static char user_name[100];
55b6513e
JS
1951 static struct passwd *p;
1952 DWORD len;
f7597aca 1953
55b6513e
JS
1954 if (initialized)
1955 return p;
f7597aca 1956
55b6513e
JS
1957 len = sizeof(user_name);
1958 if (!GetUserName(user_name, &len)) {
1959 initialized = 1;
f7597aca 1960 return NULL;
55b6513e
JS
1961 }
1962
1963 p = xmalloc(sizeof(*p));
1964 p->pw_name = user_name;
564be791
JS
1965 p->pw_gecos = get_extended_user_info(NameDisplay);
1966 if (!p->pw_gecos)
1967 p->pw_gecos = "unknown";
55b6513e
JS
1968 p->pw_dir = NULL;
1969
1970 initialized = 1;
1971 return p;
f4626df5
JS
1972}
1973
6072fc31
JS
1974static HANDLE timer_event;
1975static HANDLE timer_thread;
1976static int timer_interval;
1977static int one_shot;
176478a8 1978static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
6072fc31
JS
1979
1980/* The timer works like this:
1981 * The thread, ticktack(), is a trivial routine that most of the time
1982 * only waits to receive the signal to terminate. The main thread tells
1983 * the thread to terminate by setting the timer_event to the signalled
1984 * state.
1985 * But ticktack() interrupts the wait state after the timer's interval
1986 * length to call the signal handler.
1987 */
1988
d7fa500f 1989static unsigned __stdcall ticktack(void *dummy)
6072fc31
JS
1990{
1991 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
176478a8 1992 mingw_raise(SIGALRM);
6072fc31
JS
1993 if (one_shot)
1994 break;
1995 }
1996 return 0;
1997}
1998
1999static int start_timer_thread(void)
2000{
2001 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2002 if (timer_event) {
2003 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2004 if (!timer_thread )
2005 return errno = ENOMEM,
2006 error("cannot start timer thread");
2007 } else
2008 return errno = ENOMEM,
2009 error("cannot allocate resources for timer");
2010 return 0;
2011}
2012
2013static void stop_timer_thread(void)
2014{
2015 if (timer_event)
2016 SetEvent(timer_event); /* tell thread to terminate */
2017 if (timer_thread) {
72d63b2f 2018 int rc = WaitForSingleObject(timer_thread, 10000);
6072fc31
JS
2019 if (rc == WAIT_TIMEOUT)
2020 error("timer thread did not terminate timely");
2021 else if (rc != WAIT_OBJECT_0)
2022 error("waiting for timer thread failed: %lu",
2023 GetLastError());
2024 CloseHandle(timer_thread);
2025 }
2026 if (timer_event)
2027 CloseHandle(timer_event);
2028 timer_event = NULL;
2029 timer_thread = NULL;
2030}
2031
2032static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2033{
2034 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2035}
2036
f4626df5
JS
2037int setitimer(int type, struct itimerval *in, struct itimerval *out)
2038{
6072fc31
JS
2039 static const struct timeval zero;
2040 static int atexit_done;
2041
2042 if (out != NULL)
2043 return errno = EINVAL,
2044 error("setitimer param 3 != NULL not implemented");
2045 if (!is_timeval_eq(&in->it_interval, &zero) &&
2046 !is_timeval_eq(&in->it_interval, &in->it_value))
2047 return errno = EINVAL,
2048 error("setitimer: it_interval must be zero or eq it_value");
2049
2050 if (timer_thread)
2051 stop_timer_thread();
2052
2053 if (is_timeval_eq(&in->it_value, &zero) &&
2054 is_timeval_eq(&in->it_interval, &zero))
2055 return 0;
2056
2057 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2058 one_shot = is_timeval_eq(&in->it_interval, &zero);
2059 if (!atexit_done) {
2060 atexit(stop_timer_thread);
2061 atexit_done = 1;
2062 }
2063 return start_timer_thread();
f4626df5
JS
2064}
2065
2066int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2067{
6072fc31
JS
2068 if (sig != SIGALRM)
2069 return errno = EINVAL,
2070 error("sigaction only implemented for SIGALRM");
2071 if (out != NULL)
2072 return errno = EINVAL,
2073 error("sigaction: param 3 != NULL not implemented");
2074
2075 timer_fn = in->sa_handler;
2076 return 0;
2077}
2078
2079#undef signal
2080sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2081{
a4540658 2082 sig_handler_t old;
176478a8
EFL
2083
2084 switch (sig) {
2085 case SIGALRM:
a4540658 2086 old = timer_fn;
176478a8
EFL
2087 timer_fn = handler;
2088 break;
2089
2090 case SIGINT:
a4540658 2091 old = sigint_fn;
176478a8
EFL
2092 sigint_fn = handler;
2093 break;
2094
2095 default:
6072fc31 2096 return signal(sig, handler);
176478a8
EFL
2097 }
2098
6072fc31 2099 return old;
f4626df5 2100}
4804aabc 2101
176478a8
EFL
2102#undef raise
2103int mingw_raise(int sig)
2104{
2105 switch (sig) {
2106 case SIGALRM:
2107 if (timer_fn == SIG_DFL) {
2108 if (isatty(STDERR_FILENO))
2109 fputs("Alarm clock\n", stderr);
2110 exit(128 + SIGALRM);
2111 } else if (timer_fn != SIG_IGN)
2112 timer_fn(SIGALRM);
2113 return 0;
2114
2115 case SIGINT:
2116 if (sigint_fn == SIG_DFL)
2117 exit(128 + SIGINT);
2118 else if (sigint_fn != SIG_IGN)
2119 sigint_fn(SIGINT);
2120 return 0;
2121
2122 default:
2123 return raise(sig);
2124 }
2125}
2126
7be401e0
PK
2127int link(const char *oldpath, const char *newpath)
2128{
85faec9d
KB
2129 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2130 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2131 xutftowcs_path(wnewpath, newpath) < 0)
2132 return -1;
2133
1e1a876b 2134 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
7be401e0
PK
2135 errno = err_win_to_posix(GetLastError());
2136 return -1;
2137 }
2138 return 0;
2139}
0dbbbc1e 2140
956d86d1 2141pid_t waitpid(pid_t pid, int *status, int options)
52de4db5
EFL
2142{
2143 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2144 FALSE, pid);
2145 if (!h) {
2146 errno = ECHILD;
2147 return -1;
2148 }
2149
ef7108ca
EFL
2150 if (pid > 0 && options & WNOHANG) {
2151 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2152 CloseHandle(h);
2153 return 0;
2154 }
2155 options &= ~WNOHANG;
2156 }
2157
52de4db5
EFL
2158 if (options == 0) {
2159 struct pinfo_t **ppinfo;
2160 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2161 CloseHandle(h);
2162 return 0;
2163 }
2164
2165 if (status)
2166 GetExitCodeProcess(h, (LPDWORD)status);
2167
2168 EnterCriticalSection(&pinfo_cs);
2169
2170 ppinfo = &pinfo;
2171 while (*ppinfo) {
2172 struct pinfo_t *info = *ppinfo;
2173 if (info->pid == pid) {
2174 CloseHandle(info->proc);
2175 *ppinfo = info->next;
2176 free(info);
2177 break;
2178 }
2179 ppinfo = &info->next;
2180 }
2181
2182 LeaveCriticalSection(&pinfo_cs);
2183
2184 CloseHandle(h);
2185 return pid;
2186 }
2187 CloseHandle(h);
2188
2189 errno = EINVAL;
2190 return -1;
2191}
c2369bdf 2192
1c950a59
KB
2193int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2194{
2195 int upos = 0, wpos = 0;
2196 const unsigned char *utf = (const unsigned char*) utfs;
2197 if (!utf || !wcs || wcslen < 1) {
2198 errno = EINVAL;
2199 return -1;
2200 }
2201 /* reserve space for \0 */
2202 wcslen--;
2203 if (utflen < 0)
2204 utflen = INT_MAX;
2205
2206 while (upos < utflen) {
2207 int c = utf[upos++] & 0xff;
2208 if (utflen == INT_MAX && c == 0)
2209 break;
2210
2211 if (wpos >= wcslen) {
2212 wcs[wpos] = 0;
2213 errno = ERANGE;
2214 return -1;
2215 }
2216
2217 if (c < 0x80) {
2218 /* ASCII */
2219 wcs[wpos++] = c;
2220 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2221 (utf[upos] & 0xc0) == 0x80) {
2222 /* 2-byte utf-8 */
2223 c = ((c & 0x1f) << 6);
2224 c |= (utf[upos++] & 0x3f);
2225 wcs[wpos++] = c;
2226 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2227 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2228 (utf[upos] & 0xc0) == 0x80 &&
2229 (utf[upos + 1] & 0xc0) == 0x80) {
2230 /* 3-byte utf-8 */
2231 c = ((c & 0x0f) << 12);
2232 c |= ((utf[upos++] & 0x3f) << 6);
2233 c |= (utf[upos++] & 0x3f);
2234 wcs[wpos++] = c;
2235 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2236 wpos + 1 < wcslen &&
2237 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2238 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2239 (utf[upos] & 0xc0) == 0x80 &&
2240 (utf[upos + 1] & 0xc0) == 0x80 &&
2241 (utf[upos + 2] & 0xc0) == 0x80) {
2242 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2243 c = ((c & 0x07) << 18);
2244 c |= ((utf[upos++] & 0x3f) << 12);
2245 c |= ((utf[upos++] & 0x3f) << 6);
2246 c |= (utf[upos++] & 0x3f);
2247 c -= 0x10000;
2248 wcs[wpos++] = 0xd800 | (c >> 10);
2249 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2250 } else if (c >= 0xa0) {
2251 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2252 wcs[wpos++] = c;
2253 } else {
2254 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2255 static const char *hex = "0123456789abcdef";
2256 wcs[wpos++] = hex[c >> 4];
2257 if (wpos < wcslen)
2258 wcs[wpos++] = hex[c & 0x0f];
2259 }
2260 }
2261 wcs[wpos] = 0;
2262 return wpos;
2263}
2264
2265int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2266{
2267 if (!wcs || !utf || utflen < 1) {
2268 errno = EINVAL;
2269 return -1;
2270 }
2271 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2272 if (utflen)
2273 return utflen - 1;
2274 errno = ERANGE;
2275 return -1;
2276}
2277
0767172b 2278static void setup_windows_environment(void)
02e6edc0 2279{
1fc7bf79
JS
2280 char *tmp = getenv("TMPDIR");
2281
02e6edc0 2282 /* on Windows it is TMP and TEMP */
1fc7bf79
JS
2283 if (!tmp) {
2284 if (!(tmp = getenv("TMP")))
02e6edc0 2285 tmp = getenv("TEMP");
1fc7bf79 2286 if (tmp) {
02e6edc0 2287 setenv("TMPDIR", tmp, 1);
1fc7bf79
JS
2288 tmp = getenv("TMPDIR");
2289 }
2290 }
2291
2292 if (tmp) {
2293 /*
2294 * Convert all dir separators to forward slashes,
2295 * to help shell commands called from the Git
2296 * executable (by not mistaking the dir separators
2297 * for escape characters).
2298 */
8e9b2080 2299 convert_slashes(tmp);
02e6edc0
KB
2300 }
2301
2302 /* simulate TERM to enable auto-color (see color.c) */
2303 if (!getenv("TERM"))
2304 setenv("TERM", "cygwin", 1);
2305}
2306
396ff754 2307#if !defined(_MSC_VER)
5901dc66
KB
2308/*
2309 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2310 * mingw startup code, see init.c in mingw runtime).
2311 */
2312int _CRT_glob = 0;
396ff754 2313#endif
3f046148 2314
0767172b 2315static NORETURN void die_startup(void)
3f046148
KB
2316{
2317 fputs("fatal: not enough memory for initialization", stderr);
2318 exit(128);
2319}
2320
6f1c189c
KB
2321static void *malloc_startup(size_t size)
2322{
2323 void *result = malloc(size);
2324 if (!result)
2325 die_startup();
2326 return result;
2327}
2328
2329static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2330{
2331 len = xwcstoutf(buffer, wcs, len) + 1;
2332 return memcpy(malloc_startup(len), buffer, len);
2333}
2334
3f944424
JS
2335static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2336 DWORD desired_access, DWORD flags)
2337{
2338 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2339 wchar_t buf[MAX_PATH];
2340 DWORD max = ARRAY_SIZE(buf);
2341 HANDLE handle;
2342 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2343
2344 if (!ret || ret >= max)
2345 return;
2346
2347 /* make sure this does not leak into child processes */
2348 SetEnvironmentVariableW(key, NULL);
2349 if (!wcscmp(buf, L"off")) {
2350 close(fd);
2351 handle = GetStdHandle(std_id);
2352 if (handle != INVALID_HANDLE_VALUE)
2353 CloseHandle(handle);
2354 return;
2355 }
1a172e4a
JS
2356 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2357 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2358 if (handle == INVALID_HANDLE_VALUE) {
2359 close(fd);
2360 handle = GetStdHandle(std_id);
2361 if (handle != INVALID_HANDLE_VALUE)
2362 CloseHandle(handle);
2363 } else {
2364 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2365 SetStdHandle(std_id, handle);
2366 dup2(new_fd, fd);
2367 /* do *not* close the new_fd: that would close stdout */
2368 }
2369 return;
2370 }
3f944424
JS
2371 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2372 flags, NULL);
2373 if (handle != INVALID_HANDLE_VALUE) {
2374 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2375 SetStdHandle(std_id, handle);
2376 dup2(new_fd, fd);
2377 close(new_fd);
2378 }
2379}
2380
2381static void maybe_redirect_std_handles(void)
2382{
2383 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2384 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2385 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2386 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2387 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2388 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2389}
2390
dce7d295
JH
2391#ifdef _MSC_VER
2392#ifdef _DEBUG
2393#include <crtdbg.h>
2394#endif
2395#endif
2396
396ff754
JS
2397/*
2398 * We implement wmain() and compile with -municode, which would
2399 * normally ignore main(), but we call the latter from the former
2400 * so that we can handle non-ASCII command-line parameters
2401 * appropriately.
2402 *
2403 * To be more compatible with the core git code, we convert
2404 * argv into UTF8 and pass them directly to main().
2405 */
2406int wmain(int argc, const wchar_t **wargv)
13f1df43 2407{
396ff754
JS
2408 int i, maxlen, exit_status;
2409 char *buffer, **save;
2410 const char **argv;
3f046148 2411
a0897249
JH
2412 trace2_initialize_clock();
2413
3f944424
JS
2414 maybe_redirect_std_handles();
2415
3f046148 2416 /* determine size of argv and environ conversion buffer */
86e25458 2417 maxlen = wcslen(wargv[0]);
3f046148
KB
2418 for (i = 1; i < argc; i++)
2419 maxlen = max(maxlen, wcslen(wargv[i]));
2420
2421 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2422 maxlen = 3 * maxlen + 1;
6f1c189c 2423 buffer = malloc_startup(maxlen);
3f046148 2424
396ff754
JS
2425 /*
2426 * Create a UTF-8 version of w_argv. Also create a "save" copy
2427 * to remember all the string pointers because parse_options()
2428 * will remove claimed items from the argv that we pass down.
2429 */
2430 ALLOC_ARRAY(argv, argc + 1);
2431 ALLOC_ARRAY(save, argc + 1);
86e25458 2432 for (i = 0; i < argc; i++)
396ff754
JS
2433 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2434 argv[i] = save[i] = NULL;
3f046148 2435 free(buffer);
13f1df43 2436
6dc71543 2437 /* fix Windows specific environment settings */
02e6edc0 2438 setup_windows_environment();
baea068d 2439
0e218f91
JS
2440 unset_environment_variables = xstrdup("PERL5LIB");
2441
13f1df43
KB
2442 /* initialize critical section for waitpid pinfo_t list */
2443 InitializeCriticalSection(&pinfo_cs);
2444
2445 /* set up default file mode and file modes for stdin/out/err */
2446 _fmode = _O_BINARY;
2447 _setmode(_fileno(stdin), _O_BINARY);
2448 _setmode(_fileno(stdout), _O_BINARY);
2449 _setmode(_fileno(stderr), _O_BINARY);
eac14f89
KB
2450
2451 /* initialize Unicode console */
2452 winansi_init();
396ff754
JS
2453
2454 /* invoke the real main() using our utf8 version of argv. */
2455 exit_status = main(argc, argv);
2456
2457 for (i = 0; i < argc; i++)
2458 free(save[i]);
2459 free(save);
2460 free(argv);
2461
2462 return exit_status;
13f1df43 2463}
7b6aff06
NTND
2464
2465int uname(struct utsname *buf)
2466{
d62c89af 2467 unsigned v = (unsigned)GetVersion();
7b6aff06 2468 memset(buf, 0, sizeof(*buf));
5096d490
JK
2469 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2470 xsnprintf(buf->release, sizeof(buf->release),
2471 "%u.%u", v & 0xff, (v >> 8) & 0xff);
7b6aff06 2472 /* assuming NT variants only.. */
5096d490
JK
2473 xsnprintf(buf->version, sizeof(buf->version),
2474 "%u", (v >> 16) & 0x7fff);
7b6aff06
NTND
2475 return 0;
2476}