]> git.ipfire.org Git - thirdparty/git.git/blame - compat/mingw.c
alloc.h: move ALLOC_GROW() functions from cache.h
[thirdparty/git.git] / compat / mingw.c
CommitLineData
f4626df5 1#include "../git-compat-util.h"
444dc903 2#include "win32.h"
bdc77d1d 3#include <aclapi.h>
e883e04b 4#include <sddl.h>
28a559c0 5#include <conio.h>
85faec9d 6#include <wchar.h>
7e5d7768 7#include "../strbuf.h"
c9b78400 8#include "../run-command.h"
7eb2619c 9#include "../cache.h"
36bf1958 10#include "../alloc.h"
564be791 11#include "win32/lazyload.h"
bdfbb0ea 12#include "../config.h"
9e9da23c 13#include "dir.h"
4a9b2049
MA
14#define SECURITY_WIN32
15#include <sspi.h>
f4626df5 16
7c00bc39
JS
17#define HCAST(type, handle) ((type)(intptr_t)handle)
18
19e12549
HV
19static const int delay[] = { 0, 1, 10, 20, 40 };
20
08809c09
JS
21void open_in_gdb(void)
22{
23 static struct child_process cp = CHILD_PROCESS_INIT;
24 extern char *_pgmptr;
25
ef8d7ac4
JK
26 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
27 strvec_pushf(&cp.args, "--pid=%d", getpid());
08809c09
JS
28 cp.clean_on_exit = 1;
29 if (start_command(&cp) < 0)
30 die_errno("Could not start gdb");
31 sleep(1);
32}
33
44626dc7 34int err_win_to_posix(DWORD winerr)
b3debd2b
PK
35{
36 int error = ENOSYS;
37 switch(winerr) {
38 case ERROR_ACCESS_DENIED: error = EACCES; break;
39 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
40 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
41 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
42 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
43 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
44 case ERROR_BAD_COMMAND: error = EIO; break;
45 case ERROR_BAD_DEVICE: error = ENODEV; break;
46 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
47 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
48 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
49 case ERROR_BAD_LENGTH: error = EINVAL; break;
50 case ERROR_BAD_PATHNAME: error = ENOENT; break;
51 case ERROR_BAD_PIPE: error = EPIPE; break;
52 case ERROR_BAD_UNIT: error = ENODEV; break;
53 case ERROR_BAD_USERNAME: error = EINVAL; break;
54 case ERROR_BROKEN_PIPE: error = EPIPE; break;
55 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
56 case ERROR_BUSY: error = EBUSY; break;
57 case ERROR_BUSY_DRIVE: error = EBUSY; break;
58 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
59 case ERROR_CANNOT_MAKE: error = EACCES; break;
60 case ERROR_CANTOPEN: error = EIO; break;
61 case ERROR_CANTREAD: error = EIO; break;
62 case ERROR_CANTWRITE: error = EIO; break;
63 case ERROR_CRC: error = EIO; break;
64 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
65 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
66 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
67 case ERROR_DIRECTORY: error = EINVAL; break;
68 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
69 case ERROR_DISK_CHANGE: error = EIO; break;
70 case ERROR_DISK_FULL: error = ENOSPC; break;
71 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
72 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
73 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
74 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
75 case ERROR_FILE_EXISTS: error = EEXIST; break;
76 case ERROR_FILE_INVALID: error = ENODEV; break;
77 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
78 case ERROR_GEN_FAILURE: error = EIO; break;
79 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
80 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
81 case ERROR_INVALID_ACCESS: error = EACCES; break;
82 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
83 case ERROR_INVALID_BLOCK: error = EFAULT; break;
84 case ERROR_INVALID_DATA: error = EINVAL; break;
85 case ERROR_INVALID_DRIVE: error = ENODEV; break;
86 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
87 case ERROR_INVALID_FLAGS: error = EINVAL; break;
88 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
89 case ERROR_INVALID_HANDLE: error = EBADF; break;
90 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
91 case ERROR_INVALID_NAME: error = EINVAL; break;
92 case ERROR_INVALID_OWNER: error = EINVAL; break;
93 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
94 case ERROR_INVALID_PASSWORD: error = EPERM; break;
95 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
96 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
97 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
98 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
99 case ERROR_IO_DEVICE: error = EIO; break;
100 case ERROR_IO_INCOMPLETE: error = EINTR; break;
101 case ERROR_LOCKED: error = EBUSY; break;
102 case ERROR_LOCK_VIOLATION: error = EACCES; break;
103 case ERROR_LOGON_FAILURE: error = EACCES; break;
104 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
105 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
106 case ERROR_MORE_DATA: error = EPIPE; break;
107 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
108 case ERROR_NOACCESS: error = EFAULT; break;
109 case ERROR_NONE_MAPPED: error = EINVAL; break;
110 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
111 case ERROR_NOT_READY: error = EAGAIN; break;
112 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
113 case ERROR_NO_DATA: error = EPIPE; break;
114 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
115 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
116 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
117 case ERROR_OPEN_FAILED: error = EIO; break;
118 case ERROR_OPEN_FILES: error = EBUSY; break;
119 case ERROR_OPERATION_ABORTED: error = EINTR; break;
120 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
121 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
122 case ERROR_PATH_BUSY: error = EBUSY; break;
123 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
124 case ERROR_PIPE_BUSY: error = EBUSY; break;
125 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
126 case ERROR_PIPE_LISTENING: error = EPIPE; break;
127 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
128 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
129 case ERROR_READ_FAULT: error = EIO; break;
130 case ERROR_SEEK: error = EIO; break;
131 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
132 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
133 case ERROR_SHARING_VIOLATION: error = EACCES; break;
134 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
3ba3720b 135 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
b3debd2b
PK
136 case ERROR_SWAPERROR: error = ENOENT; break;
137 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
138 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
139 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
140 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
141 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
142 case ERROR_WRITE_FAULT: error = EIO; break;
143 case ERROR_WRITE_PROTECT: error = EROFS; break;
144 }
145 return error;
146}
147
19e12549
HV
148static inline int is_file_in_use_error(DWORD errcode)
149{
150 switch (errcode) {
151 case ERROR_SHARING_VIOLATION:
152 case ERROR_ACCESS_DENIED:
153 return 1;
154 }
155
156 return 0;
157}
158
c9b78400
HV
159static int read_yes_no_answer(void)
160{
161 char answer[1024];
162
163 if (fgets(answer, sizeof(answer), stdin)) {
164 size_t answer_len = strlen(answer);
165 int got_full_line = 0, c;
166
167 /* remove the newline */
168 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
169 answer[answer_len-2] = '\0';
170 got_full_line = 1;
171 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
172 answer[answer_len-1] = '\0';
173 got_full_line = 1;
174 }
175 /* flush the buffer in case we did not get the full line */
176 if (!got_full_line)
177 while ((c = getchar()) != EOF && c != '\n')
178 ;
179 } else
180 /* we could not read, return the
181 * default answer which is no */
182 return 0;
183
184 if (tolower(answer[0]) == 'y' && !answer[1])
185 return 1;
186 if (!strncasecmp(answer, "yes", sizeof(answer)))
187 return 1;
188 if (tolower(answer[0]) == 'n' && !answer[1])
189 return 0;
190 if (!strncasecmp(answer, "no", sizeof(answer)))
191 return 0;
192
193 /* did not find an answer we understand */
194 return -1;
195}
196
197static int ask_yes_no_if_possible(const char *format, ...)
198{
199 char question[4096];
4120294c 200 const char *retry_hook;
c9b78400
HV
201 va_list args;
202
203 va_start(args, format);
204 vsnprintf(question, sizeof(question), format, args);
205 va_end(args);
206
4120294c
RS
207 retry_hook = mingw_getenv("GIT_ASK_YESNO");
208 if (retry_hook) {
209 struct child_process cmd = CHILD_PROCESS_INIT;
210
211 strvec_pushl(&cmd.args, retry_hook, question, NULL);
212 return !run_command(&cmd);
c9b78400
HV
213 }
214
215 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
216 return 0;
217
218 while (1) {
219 int answer;
220 fprintf(stderr, "%s (y/n) ", question);
221
222 if ((answer = read_yes_no_answer()) >= 0)
223 return answer;
224
225 fprintf(stderr, "Sorry, I did not understand your answer. "
226 "Please type 'y' or 'n'\n");
227 }
228}
229
bdfbb0ea
JS
230/* Windows only */
231enum hide_dotfiles_type {
232 HIDE_DOTFILES_FALSE = 0,
233 HIDE_DOTFILES_TRUE,
234 HIDE_DOTFILES_DOTGITONLY
235};
236
ac33519d 237static int core_restrict_inherited_handles = -1;
bdfbb0ea 238static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
0e218f91 239static char *unset_environment_variables;
bdfbb0ea 240
70fc5793
JS
241int mingw_core_config(const char *var, const char *value, void *cb)
242{
bdfbb0ea
JS
243 if (!strcmp(var, "core.hidedotfiles")) {
244 if (value && !strcasecmp(value, "dotgitonly"))
245 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
246 else
247 hide_dotfiles = git_config_bool(var, value);
248 return 0;
249 }
250
0e218f91
JS
251 if (!strcmp(var, "core.unsetenvvars")) {
252 free(unset_environment_variables);
253 unset_environment_variables = xstrdup(value);
254 return 0;
255 }
256
ac33519d
JS
257 if (!strcmp(var, "core.restrictinheritedhandles")) {
258 if (value && !strcasecmp(value, "auto"))
259 core_restrict_inherited_handles = -1;
260 else
261 core_restrict_inherited_handles =
262 git_config_bool(var, value);
263 return 0;
264 }
265
70fc5793
JS
266 return 0;
267}
268
4745feeb
AS
269/* Normalizes NT paths as returned by some low-level APIs. */
270static wchar_t *normalize_ntpath(wchar_t *wbuf)
271{
272 int i;
273 /* fix absolute path prefixes */
274 if (wbuf[0] == '\\') {
275 /* strip NT namespace prefixes */
276 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
277 !wcsncmp(wbuf, L"\\\\?\\", 4))
278 wbuf += 4;
279 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
280 wbuf += 12;
281 /* replace remaining '...UNC\' with '\\' */
282 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
283 wbuf += 2;
284 *wbuf = '\\';
285 }
286 }
287 /* convert backslashes to slashes */
288 for (i = 0; wbuf[i]; i++)
289 if (wbuf[i] == '\\')
290 wbuf[i] = '/';
291 return wbuf;
292}
293
337967fb
HV
294int mingw_unlink(const char *pathname)
295{
19e12549 296 int ret, tries = 0;
85faec9d
KB
297 wchar_t wpathname[MAX_PATH];
298 if (xutftowcs_path(wpathname, pathname) < 0)
299 return -1;
19e12549 300
680e0b45
JH
301 if (DeleteFileW(wpathname))
302 return 0;
303
337967fb 304 /* read-only files cannot be removed */
85faec9d
KB
305 _wchmod(wpathname, 0666);
306 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
19e12549
HV
307 if (!is_file_in_use_error(GetLastError()))
308 break;
309 /*
310 * We assume that some other process had the source or
311 * destination file open at the wrong moment and retry.
312 * In order to give the other process a higher chance to
313 * complete its operation, we give up our time slice now.
314 * If we have to retry again, we do sleep a bit.
315 */
316 Sleep(delay[tries]);
317 tries++;
318 }
c9b78400
HV
319 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
320 ask_yes_no_if_possible("Unlink of file '%s' failed. "
321 "Should I try again?", pathname))
85faec9d 322 ret = _wunlink(wpathname);
19e12549 323 return ret;
337967fb
HV
324}
325
85faec9d 326static int is_dir_empty(const wchar_t *wpath)
ab1a11be 327{
85faec9d 328 WIN32_FIND_DATAW findbuf;
ab1a11be 329 HANDLE handle;
85faec9d
KB
330 wchar_t wbuf[MAX_PATH + 2];
331 wcscpy(wbuf, wpath);
332 wcscat(wbuf, L"\\*");
333 handle = FindFirstFileW(wbuf, &findbuf);
334 if (handle == INVALID_HANDLE_VALUE)
ab1a11be 335 return GetLastError() == ERROR_NO_MORE_FILES;
ab1a11be 336
85faec9d
KB
337 while (!wcscmp(findbuf.cFileName, L".") ||
338 !wcscmp(findbuf.cFileName, L".."))
339 if (!FindNextFileW(handle, &findbuf)) {
340 DWORD err = GetLastError();
341 FindClose(handle);
342 return err == ERROR_NO_MORE_FILES;
ab1a11be
JS
343 }
344 FindClose(handle);
ab1a11be
JS
345 return 0;
346}
347
4f288100
HV
348int mingw_rmdir(const char *pathname)
349{
350 int ret, tries = 0;
85faec9d 351 wchar_t wpathname[MAX_PATH];
3e7d4888
TB
352 struct stat st;
353
354 /*
355 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
356 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
357 * symbolic link (if it points to a directory).
358 *
359 * This behavior breaks the assumption of e.g. `remove_path()` which
360 * upon successful deletion of a file will attempt to remove its parent
361 * directories recursively until failure (which usually happens when
362 * the directory is not empty).
363 *
364 * Therefore, before calling `_wrmdir()`, we first check if the path is
365 * a symbolic link. If it is, we exit and return the same error as
366 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
367 */
368 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
369 errno = ENOTDIR;
370 return -1;
371 }
372
85faec9d
KB
373 if (xutftowcs_path(wpathname, pathname) < 0)
374 return -1;
4f288100 375
85faec9d 376 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
4f288100 377 if (!is_file_in_use_error(GetLastError()))
a83b2b57
EFL
378 errno = err_win_to_posix(GetLastError());
379 if (errno != EACCES)
4f288100 380 break;
85faec9d 381 if (!is_dir_empty(wpathname)) {
ab1a11be
JS
382 errno = ENOTEMPTY;
383 break;
384 }
4f288100
HV
385 /*
386 * We assume that some other process had the source or
387 * destination file open at the wrong moment and retry.
388 * In order to give the other process a higher chance to
389 * complete its operation, we give up our time slice now.
390 * If we have to retry again, we do sleep a bit.
391 */
392 Sleep(delay[tries]);
393 tries++;
394 }
a83b2b57 395 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
4f288100
HV
396 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
397 "Should I try again?", pathname))
85faec9d 398 ret = _wrmdir(wpathname);
684dd4c2
MT
399 if (!ret)
400 invalidate_lstat_cache();
85faec9d
KB
401 return ret;
402}
403
f30afdab
JS
404static inline int needs_hiding(const char *path)
405{
406 const char *basename;
407
408 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
409 return 0;
410
411 /* We cannot use basename(), as it would remove trailing slashes */
1cadad6f 412 win32_skip_dos_drive_prefix((char **)&path);
f30afdab
JS
413 if (!*path)
414 return 0;
415
416 for (basename = path; *path; path++)
417 if (is_dir_sep(*path)) {
418 do {
419 path++;
420 } while (is_dir_sep(*path));
421 /* ignore trailing slashes */
422 if (*path)
423 basename = path;
60e6569a
JS
424 else
425 break;
f30afdab
JS
426 }
427
428 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
429 return *basename == '.';
430
431 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
432 return !strncasecmp(".git", basename, 4) &&
433 (!basename[4] || is_dir_sep(basename[4]));
434}
435
436static int set_hidden_flag(const wchar_t *path, int set)
437{
438 DWORD original = GetFileAttributesW(path), modified;
439 if (set)
440 modified = original | FILE_ATTRIBUTE_HIDDEN;
441 else
442 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
443 if (original == modified || SetFileAttributesW(path, modified))
444 return 0;
445 errno = err_win_to_posix(GetLastError());
446 return -1;
447}
448
85faec9d
KB
449int mingw_mkdir(const char *path, int mode)
450{
451 int ret;
452 wchar_t wpath[MAX_PATH];
d2c84dad 453
4dc42c6c 454 if (!is_valid_win32_path(path, 0)) {
d2c84dad
JS
455 errno = EINVAL;
456 return -1;
457 }
458
85faec9d
KB
459 if (xutftowcs_path(wpath, path) < 0)
460 return -1;
461 ret = _wmkdir(wpath);
f30afdab
JS
462 if (!ret && needs_hiding(path))
463 return set_hidden_flag(wpath, 1);
4f288100
HV
464 return ret;
465}
466
eeaf7dda
JH
467/*
468 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
469 * is documented in [1] as opening a writable file handle in append mode.
470 * (It is believed that) this is atomic since it is maintained by the
471 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
472 *
473 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
474 *
475 * This trick does not appear to work for named pipes. Instead it creates
476 * a named pipe client handle that cannot be written to. Callers should
477 * just use the regular _wopen() for them. (And since client handle gets
478 * bound to a unique server handle, it isn't really an issue.)
479 */
d6410975
JS
480static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
481{
482 HANDLE handle;
483 int fd;
484 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
485
486 /* only these flags are supported */
487 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
488 return errno = ENOSYS, -1;
489
490 /*
491 * FILE_SHARE_WRITE is required to permit child processes
492 * to append to the file.
493 */
494 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
495 FILE_SHARE_WRITE | FILE_SHARE_READ,
496 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
23eafd92
NS
497 if (handle == INVALID_HANDLE_VALUE) {
498 DWORD err = GetLastError();
499
500 /*
501 * Some network storage solutions (e.g. Isilon) might return
502 * ERROR_INVALID_PARAMETER instead of expected error
503 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
504 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
505 */
506 if (err == ERROR_INVALID_PARAMETER)
507 err = ERROR_PATH_NOT_FOUND;
508
509 errno = err_win_to_posix(err);
510 return -1;
511 }
eeaf7dda 512
d6410975
JS
513 /*
514 * No O_APPEND here, because the CRT uses it only to reset the
eeaf7dda
JH
515 * file pointer to EOF before each write(); but that is not
516 * necessary (and may lead to races) for a file created with
517 * FILE_APPEND_DATA.
d6410975
JS
518 */
519 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
520 if (fd < 0)
521 CloseHandle(handle);
522 return fd;
523}
524
eeaf7dda
JH
525/*
526 * Does the pathname map to the local named pipe filesystem?
527 * That is, does it have a "//./pipe/" prefix?
528 */
529static int is_local_named_pipe_path(const char *filename)
530{
531 return (is_dir_sep(filename[0]) &&
532 is_dir_sep(filename[1]) &&
533 filename[2] == '.' &&
534 is_dir_sep(filename[3]) &&
535 !strncasecmp(filename+4, "pipe", 4) &&
536 is_dir_sep(filename[8]) &&
537 filename[9]);
538}
539
3e4a1ba0
JS
540int mingw_open (const char *filename, int oflags, ...)
541{
d6410975 542 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
3e4a1ba0
JS
543 va_list args;
544 unsigned mode;
d2c84dad 545 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
85faec9d 546 wchar_t wfilename[MAX_PATH];
d6410975 547 open_fn_t open_fn;
0d30ad71 548
3e4a1ba0
JS
549 va_start(args, oflags);
550 mode = va_arg(args, int);
551 va_end(args);
552
4dc42c6c 553 if (!is_valid_win32_path(filename, !create)) {
d2c84dad
JS
554 errno = create ? EINVAL : ENOENT;
555 return -1;
556 }
557
eeaf7dda 558 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
d6410975
JS
559 open_fn = mingw_open_append;
560 else
561 open_fn = _wopen;
562
98d9b23e
JS
563 if (filename && !strcmp(filename, "/dev/null"))
564 wcscpy(wfilename, L"nul");
565 else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 566 return -1;
98d9b23e 567
d6410975 568 fd = open_fn(wfilename, oflags, mode);
0d30ad71 569
ba6fad02 570 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
85faec9d 571 DWORD attrs = GetFileAttributesW(wfilename);
3e4a1ba0
JS
572 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
573 errno = EISDIR;
574 }
f30afdab
JS
575 if ((oflags & O_CREAT) && needs_hiding(filename)) {
576 /*
577 * Internally, _wopen() uses the CreateFile() API which errors
578 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
579 * specified and an already existing file's attributes do not
580 * match *exactly*. As there is no mode or flag we can set that
581 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
582 * again *without* the O_CREAT flag (that corresponds to the
583 * CREATE_ALWAYS flag of CreateFile()).
584 */
585 if (fd < 0 && errno == EACCES)
d6410975 586 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
f30afdab
JS
587 if (fd >= 0 && set_hidden_flag(wfilename, 1))
588 warning("could not mark '%s' as hidden.", filename);
589 }
3e4a1ba0
JS
590 return fd;
591}
592
176478a8
EFL
593static BOOL WINAPI ctrl_ignore(DWORD type)
594{
595 return TRUE;
596}
597
598#undef fgetc
599int mingw_fgetc(FILE *stream)
600{
601 int ch;
602 if (!isatty(_fileno(stream)))
603 return fgetc(stream);
604
605 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
606 while (1) {
607 ch = fgetc(stream);
608 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
609 break;
610
611 /* Ctrl+C was pressed, simulate SIGINT and retry */
612 mingw_raise(SIGINT);
613 }
614 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
615 return ch;
616}
617
3fdcdbdf
JS
618#undef fopen
619FILE *mingw_fopen (const char *filename, const char *otype)
620{
f30afdab 621 int hide = needs_hiding(filename);
85faec9d
KB
622 FILE *file;
623 wchar_t wfilename[MAX_PATH], wotype[4];
4dc42c6c
JS
624 if (filename && !strcmp(filename, "/dev/null"))
625 wcscpy(wfilename, L"nul");
626 else if (!is_valid_win32_path(filename, 1)) {
d2c84dad
JS
627 int create = otype && strchr(otype, 'w');
628 errno = create ? EINVAL : ENOENT;
629 return NULL;
4dc42c6c 630 } else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 631 return NULL;
98d9b23e
JS
632
633 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
85faec9d 634 return NULL;
98d9b23e 635
f30afdab
JS
636 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
637 error("could not unhide %s", filename);
638 return NULL;
639 }
85faec9d 640 file = _wfopen(wfilename, wotype);
e5b31344
JS
641 if (!file && GetLastError() == ERROR_INVALID_NAME)
642 errno = ENOENT;
f30afdab
JS
643 if (file && hide && set_hidden_flag(wfilename, 1))
644 warning("could not mark '%s' as hidden.", filename);
85faec9d 645 return file;
3fdcdbdf
JS
646}
647
3fdcdbdf
JS
648FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
649{
f30afdab 650 int hide = needs_hiding(filename);
85faec9d
KB
651 FILE *file;
652 wchar_t wfilename[MAX_PATH], wotype[4];
4dc42c6c
JS
653 if (filename && !strcmp(filename, "/dev/null"))
654 wcscpy(wfilename, L"nul");
655 else if (!is_valid_win32_path(filename, 1)) {
d2c84dad
JS
656 int create = otype && strchr(otype, 'w');
657 errno = create ? EINVAL : ENOENT;
658 return NULL;
4dc42c6c 659 } else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 660 return NULL;
98d9b23e
JS
661
662 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
85faec9d 663 return NULL;
98d9b23e 664
f30afdab
JS
665 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
666 error("could not unhide %s", filename);
667 return NULL;
668 }
85faec9d 669 file = _wfreopen(wfilename, wotype, stream);
f30afdab
JS
670 if (file && hide && set_hidden_flag(wfilename, 1))
671 warning("could not mark '%s' as hidden.", filename);
85faec9d 672 return file;
3fdcdbdf
JS
673}
674
84adb641
JS
675#undef fflush
676int mingw_fflush(FILE *stream)
677{
678 int ret = fflush(stream);
679
680 /*
681 * write() is used behind the scenes of stdio output functions.
682 * Since git code does not check for errors after each stdio write
683 * operation, it can happen that write() is called by a later
684 * stdio function even if an earlier write() call failed. In the
685 * case of a pipe whose readable end was closed, only the first
686 * call to write() reports EPIPE on Windows. Subsequent write()
687 * calls report EINVAL. It is impossible to notice whether this
688 * fflush invocation triggered such a case, therefore, we have to
689 * catch all EINVAL errors whole-sale.
690 */
691 if (ret && errno == EINVAL)
692 errno = EPIPE;
693
694 return ret;
695}
696
2b86292e
JS
697#undef write
698ssize_t mingw_write(int fd, const void *buf, size_t len)
699{
700 ssize_t result = write(fd, buf, len);
701
702 if (result < 0 && errno == EINVAL && buf) {
703 /* check if fd is a pipe */
704 HANDLE h = (HANDLE) _get_osfhandle(fd);
705 if (GetFileType(h) == FILE_TYPE_PIPE)
706 errno = EPIPE;
707 else
708 errno = EINVAL;
709 }
710
711 return result;
712}
713
85faec9d
KB
714int mingw_access(const char *filename, int mode)
715{
716 wchar_t wfilename[MAX_PATH];
9160068a
JS
717 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
718 return 0;
85faec9d
KB
719 if (xutftowcs_path(wfilename, filename) < 0)
720 return -1;
721 /* X_OK is not supported by the MSVCRT version */
722 return _waccess(wfilename, mode & ~X_OK);
723}
724
725int mingw_chdir(const char *dirname)
726{
727 wchar_t wdirname[MAX_PATH];
728 if (xutftowcs_path(wdirname, dirname) < 0)
729 return -1;
730 return _wchdir(wdirname);
731}
732
733int mingw_chmod(const char *filename, int mode)
734{
735 wchar_t wfilename[MAX_PATH];
736 if (xutftowcs_path(wfilename, filename) < 0)
737 return -1;
738 return _wchmod(wfilename, mode);
739}
740
a6d15bc3
JS
741/*
742 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
743 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
744 */
745static inline long long filetime_to_hnsec(const FILETIME *ft)
5411bdc4
MSO
746{
747 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
a6d15bc3
JS
748 /* Windows to Unix Epoch conversion */
749 return winTime - 116444736000000000LL;
750}
751
d7e8c874 752static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
a6d15bc3 753{
d7e8c874
KB
754 long long hnsec = filetime_to_hnsec(ft);
755 ts->tv_sec = (time_t)(hnsec / 10000000);
756 ts->tv_nsec = (hnsec % 10000000) * 100;
5411bdc4
MSO
757}
758
4b0abd5c
JS
759/**
760 * Verifies that safe_create_leading_directories() would succeed.
761 */
762static int has_valid_directory_prefix(wchar_t *wfilename)
763{
764 int n = wcslen(wfilename);
765
766 while (n > 0) {
767 wchar_t c = wfilename[--n];
768 DWORD attributes;
769
770 if (!is_dir_sep(c))
771 continue;
772
773 wfilename[n] = L'\0';
774 attributes = GetFileAttributesW(wfilename);
775 wfilename[n] = c;
82ba1191
JS
776 if (attributes &
777 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE))
4b0abd5c
JS
778 return 1;
779 if (attributes == INVALID_FILE_ATTRIBUTES)
780 switch (GetLastError()) {
781 case ERROR_PATH_NOT_FOUND:
782 continue;
783 case ERROR_FILE_NOT_FOUND:
784 /* This implies parent directory exists. */
785 return 1;
786 }
787 return 0;
788 }
789 return 1;
790}
791
5411bdc4
MSO
792/* We keep the do_lstat code in a separate function to avoid recursion.
793 * When a path ends with a slash, the stat will fail with ENOENT. In
794 * this case, we strip the trailing slashes and stat again.
9b9784ca
PT
795 *
796 * If follow is true then act like stat() and report on the link
797 * target. Otherwise report on the link itself.
5411bdc4 798 */
9b9784ca 799static int do_lstat(int follow, const char *file_name, struct stat *buf)
5411bdc4
MSO
800{
801 WIN32_FILE_ATTRIBUTE_DATA fdata;
85faec9d
KB
802 wchar_t wfilename[MAX_PATH];
803 if (xutftowcs_path(wfilename, file_name) < 0)
804 return -1;
5411bdc4 805
85faec9d 806 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
5411bdc4
MSO
807 buf->st_ino = 0;
808 buf->st_gid = 0;
809 buf->st_uid = 0;
180964f0 810 buf->st_nlink = 1;
444dc903 811 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
1d4e4cd4
JS
812 buf->st_size = fdata.nFileSizeLow |
813 (((off_t)fdata.nFileSizeHigh)<<32);
8252df62 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));
9b9784ca 818 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
85faec9d
KB
819 WIN32_FIND_DATAW findbuf;
820 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
9b9784ca
PT
821 if (handle != INVALID_HANDLE_VALUE) {
822 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
823 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
824 if (follow) {
825 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
826 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
827 } else {
828 buf->st_mode = S_IFLNK;
829 }
830 buf->st_mode |= S_IREAD;
831 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
832 buf->st_mode |= S_IWRITE;
833 }
834 FindClose(handle);
835 }
836 }
5411bdc4
MSO
837 return 0;
838 }
85faec9d
KB
839 switch (GetLastError()) {
840 case ERROR_ACCESS_DENIED:
841 case ERROR_SHARING_VIOLATION:
842 case ERROR_LOCK_VIOLATION:
843 case ERROR_SHARING_BUFFER_EXCEEDED:
844 errno = EACCES;
845 break;
846 case ERROR_BUFFER_OVERFLOW:
847 errno = ENAMETOOLONG;
848 break;
849 case ERROR_NOT_ENOUGH_MEMORY:
850 errno = ENOMEM;
851 break;
4b0abd5c
JS
852 case ERROR_PATH_NOT_FOUND:
853 if (!has_valid_directory_prefix(wfilename)) {
854 errno = ENOTDIR;
855 break;
856 }
857 /* fallthru */
85faec9d
KB
858 default:
859 errno = ENOENT;
860 break;
861 }
5411bdc4
MSO
862 return -1;
863}
864
865/* We provide our own lstat/fstat functions, since the provided
866 * lstat/fstat functions are so slow. These stat functions are
867 * tailored for Git's usage (read: fast), and are not meant to be
868 * complete. Note that Git stat()s are redirected to mingw_lstat()
869 * too, since Windows doesn't really handle symlinks that well.
870 */
9b9784ca 871static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
5411bdc4
MSO
872{
873 int namelen;
58aa3d2a 874 char alt_name[PATH_MAX];
5411bdc4 875
9b9784ca 876 if (!do_lstat(follow, file_name, buf))
5411bdc4
MSO
877 return 0;
878
879 /* if file_name ended in a '/', Windows returned ENOENT;
880 * try again without trailing slashes
881 */
882 if (errno != ENOENT)
883 return -1;
884
885 namelen = strlen(file_name);
886 if (namelen && file_name[namelen-1] != '/')
887 return -1;
888 while (namelen && file_name[namelen-1] == '/')
889 --namelen;
890 if (!namelen || namelen >= PATH_MAX)
891 return -1;
892
893 memcpy(alt_name, file_name, namelen);
894 alt_name[namelen] = 0;
9b9784ca
PT
895 return do_lstat(follow, alt_name, buf);
896}
897
7bf19838
JS
898static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
899{
900 BY_HANDLE_FILE_INFORMATION fdata;
901
902 if (!GetFileInformationByHandle(hnd, &fdata)) {
903 errno = err_win_to_posix(GetLastError());
904 return -1;
905 }
906
907 buf->st_ino = 0;
908 buf->st_gid = 0;
909 buf->st_uid = 0;
910 buf->st_nlink = 1;
911 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
912 buf->st_size = fdata.nFileSizeLow |
913 (((off_t)fdata.nFileSizeHigh)<<32);
914 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
d7e8c874
KB
915 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
916 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
917 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
7bf19838
JS
918 return 0;
919}
920
9b9784ca
PT
921int mingw_lstat(const char *file_name, struct stat *buf)
922{
923 return do_stat_internal(0, file_name, buf);
924}
925int mingw_stat(const char *file_name, struct stat *buf)
926{
927 return do_stat_internal(1, file_name, buf);
5411bdc4
MSO
928}
929
180964f0 930int mingw_fstat(int fd, struct stat *buf)
5411bdc4
MSO
931{
932 HANDLE fh = (HANDLE)_get_osfhandle(fd);
d75e6973 933 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
5411bdc4 934
d75e6973
KB
935 switch (type) {
936 case FILE_TYPE_DISK:
937 return get_file_info_by_handle(fh, buf);
5411bdc4 938
d75e6973
KB
939 case FILE_TYPE_CHAR:
940 case FILE_TYPE_PIPE:
941 /* initialize stat fields */
942 memset(buf, 0, sizeof(*buf));
180964f0 943 buf->st_nlink = 1;
d75e6973
KB
944
945 if (type == FILE_TYPE_CHAR) {
946 buf->st_mode = _S_IFCHR;
947 } else {
948 buf->st_mode = _S_IFIFO;
949 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
950 buf->st_size = avail;
951 }
5411bdc4 952 return 0;
7bf19838 953
d75e6973
KB
954 default:
955 errno = EBADF;
956 return -1;
5411bdc4 957 }
5411bdc4
MSO
958}
959
7c0ffa1c
JS
960static inline void time_t_to_filetime(time_t t, FILETIME *ft)
961{
962 long long winTime = t * 10000000LL + 116444736000000000LL;
963 ft->dwLowDateTime = winTime;
964 ft->dwHighDateTime = winTime >> 32;
965}
966
967int mingw_utime (const char *file_name, const struct utimbuf *times)
968{
969 FILETIME mft, aft;
090a3085 970 int rc;
85faec9d
KB
971 DWORD attrs;
972 wchar_t wfilename[MAX_PATH];
090a3085
TK
973 HANDLE osfilehandle;
974
85faec9d
KB
975 if (xutftowcs_path(wfilename, file_name) < 0)
976 return -1;
7c0ffa1c
JS
977
978 /* must have write permission */
85faec9d 979 attrs = GetFileAttributesW(wfilename);
852f098c
JS
980 if (attrs != INVALID_FILE_ATTRIBUTES &&
981 (attrs & FILE_ATTRIBUTE_READONLY)) {
982 /* ignore errors here; open() will report them */
85faec9d 983 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
852f098c
JS
984 }
985
090a3085
TK
986 osfilehandle = CreateFileW(wfilename,
987 FILE_WRITE_ATTRIBUTES,
988 0 /*FileShare.None*/,
989 NULL,
990 OPEN_EXISTING,
991 (attrs != INVALID_FILE_ATTRIBUTES &&
992 (attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
993 FILE_FLAG_BACKUP_SEMANTICS : 0,
994 NULL);
995 if (osfilehandle == INVALID_HANDLE_VALUE) {
996 errno = err_win_to_posix(GetLastError());
852f098c
JS
997 rc = -1;
998 goto revert_attrs;
999 }
7c0ffa1c 1000
ded2d476
SG
1001 if (times) {
1002 time_t_to_filetime(times->modtime, &mft);
1003 time_t_to_filetime(times->actime, &aft);
1004 } else {
1005 GetSystemTimeAsFileTime(&mft);
1006 aft = mft;
1007 }
090a3085
TK
1008
1009 if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
7c0ffa1c
JS
1010 errno = EINVAL;
1011 rc = -1;
1012 } else
1013 rc = 0;
090a3085
TK
1014
1015 if (osfilehandle != INVALID_HANDLE_VALUE)
1016 CloseHandle(osfilehandle);
852f098c
JS
1017
1018revert_attrs:
1019 if (attrs != INVALID_FILE_ATTRIBUTES &&
1020 (attrs & FILE_ATTRIBUTE_READONLY)) {
1021 /* ignore errors again */
85faec9d 1022 SetFileAttributesW(wfilename, attrs);
852f098c 1023 }
7c0ffa1c
JS
1024 return rc;
1025}
1026
9ee0540a
JS
1027#undef strftime
1028size_t mingw_strftime(char *s, size_t max,
1029 const char *format, const struct tm *tm)
1030{
a748f3f3
MA
1031 /* a pointer to the original strftime in case we can't find the UCRT version */
1032 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1033 size_t ret;
4a9b2049 1034 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
a748f3f3
MA
1035 const char *, const struct tm *);
1036
1037 if (INIT_PROC_ADDR(strftime))
1038 ret = strftime(s, max, format, tm);
1039 else
1040 ret = fallback(s, max, format, tm);
9ee0540a
JS
1041
1042 if (!ret && errno == EINVAL)
1043 die("invalid strftime format: '%s'", format);
1044 return ret;
1045}
1046
f4626df5
JS
1047unsigned int sleep (unsigned int seconds)
1048{
1049 Sleep(seconds*1000);
1050 return 0;
1051}
1052
85faec9d
KB
1053char *mingw_mktemp(char *template)
1054{
1055 wchar_t wtemplate[MAX_PATH];
1056 if (xutftowcs_path(wtemplate, template) < 0)
1057 return NULL;
1058 if (!_wmktemp(wtemplate))
1059 return NULL;
1060 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1061 return NULL;
1062 return template;
1063}
1064
f4626df5
JS
1065int mkstemp(char *template)
1066{
ae25974d 1067 return git_mkstemp_mode(template, 0600);
f4626df5
JS
1068}
1069
1070int gettimeofday(struct timeval *tv, void *tz)
1071{
a6d15bc3
JS
1072 FILETIME ft;
1073 long long hnsec;
1074
1075 GetSystemTimeAsFileTime(&ft);
1076 hnsec = filetime_to_hnsec(&ft);
1077 tv->tv_sec = hnsec / 10000000;
1078 tv->tv_usec = (hnsec % 10000000) / 10;
a42a0c2e 1079 return 0;
f4626df5
JS
1080}
1081
897bb8cb
JS
1082int pipe(int filedes[2])
1083{
3e34d665 1084 HANDLE h[2];
897bb8cb 1085
3e34d665
JS
1086 /* this creates non-inheritable handles */
1087 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1088 errno = err_win_to_posix(GetLastError());
897bb8cb
JS
1089 return -1;
1090 }
7c00bc39 1091 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
3e34d665 1092 if (filedes[0] < 0) {
897bb8cb
JS
1093 CloseHandle(h[0]);
1094 CloseHandle(h[1]);
1095 return -1;
1096 }
7c00bc39 1097 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
c3cb7b6f 1098 if (filedes[1] < 0) {
897bb8cb 1099 close(filedes[0]);
897bb8cb
JS
1100 CloseHandle(h[1]);
1101 return -1;
1102 }
897bb8cb
JS
1103 return 0;
1104}
1105
9e12400d 1106#ifndef __MINGW64__
f4626df5
JS
1107struct tm *gmtime_r(const time_t *timep, struct tm *result)
1108{
0109d676
ĐTCD
1109 if (gmtime_s(result, timep) == 0)
1110 return result;
1111 return NULL;
f4626df5
JS
1112}
1113
1114struct tm *localtime_r(const time_t *timep, struct tm *result)
1115{
0109d676
ĐTCD
1116 if (localtime_s(result, timep) == 0)
1117 return result;
1118 return NULL;
f4626df5 1119}
9e12400d 1120#endif
f4626df5 1121
25fe217b
JS
1122char *mingw_getcwd(char *pointer, int len)
1123{
937974fc
JS
1124 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1125 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1126
1127 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1128 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1129 return NULL;
1130 }
1131 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
4745feeb
AS
1132 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1133 HANDLE hnd = CreateFileW(cwd, 0,
1134 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1135 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1136 if (hnd == INVALID_HANDLE_VALUE)
1137 return NULL;
1138 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1139 CloseHandle(hnd);
1140 if (!ret || ret >= ARRAY_SIZE(wpointer))
1141 return NULL;
1142 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1143 return NULL;
1144 return pointer;
1145 }
937974fc 1146 if (!ret || ret >= ARRAY_SIZE(wpointer))
85faec9d 1147 return NULL;
e2724c1e
JS
1148 if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1149 errno = ENOENT;
1150 return NULL;
1151 }
85faec9d
KB
1152 if (xwcstoutf(pointer, wpointer, len) < 0)
1153 return NULL;
8e9b2080 1154 convert_slashes(pointer);
85faec9d 1155 return pointer;
25fe217b
JS
1156}
1157
7e5d7768 1158/*
2ef2ae29
JS
1159 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1160 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
7e5d7768 1161 */
9e9da23c 1162static const char *quote_arg_msvc(const char *arg)
7e5d7768
JS
1163{
1164 /* count chars to quote */
1165 int len = 0, n = 0;
1166 int force_quotes = 0;
1167 char *q, *d;
1168 const char *p = arg;
1169 if (!*p) force_quotes = 1;
1170 while (*p) {
3aea1a5a 1171 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
7e5d7768
JS
1172 force_quotes = 1;
1173 else if (*p == '"')
1174 n++;
1175 else if (*p == '\\') {
1176 int count = 0;
1177 while (*p == '\\') {
1178 count++;
1179 p++;
1180 len++;
1181 }
6d868416 1182 if (*p == '"' || !*p)
7e5d7768
JS
1183 n += count*2 + 1;
1184 continue;
1185 }
1186 len++;
1187 p++;
1188 }
1189 if (!force_quotes && n == 0)
1190 return arg;
1191
1192 /* insert \ where necessary */
50a6c8ef 1193 d = q = xmalloc(st_add3(len, n, 3));
7e5d7768
JS
1194 *d++ = '"';
1195 while (*arg) {
1196 if (*arg == '"')
1197 *d++ = '\\';
1198 else if (*arg == '\\') {
1199 int count = 0;
1200 while (*arg == '\\') {
1201 count++;
1202 *d++ = *arg++;
1203 }
6d868416 1204 if (*arg == '"' || !*arg) {
7e5d7768
JS
1205 while (count-- > 0)
1206 *d++ = '\\';
6d868416
JS
1207 /* don't escape the surrounding end quote */
1208 if (!*arg)
1209 break;
7e5d7768
JS
1210 *d++ = '\\';
1211 }
1212 }
1213 *d++ = *arg++;
1214 }
1215 *d++ = '"';
6d868416 1216 *d++ = '\0';
7e5d7768
JS
1217 return q;
1218}
1219
9e9da23c
JS
1220#include "quote.h"
1221
1222static const char *quote_arg_msys2(const char *arg)
1223{
1224 struct strbuf buf = STRBUF_INIT;
1225 const char *p2 = arg, *p;
1226
1227 for (p = arg; *p; p++) {
1228 int ws = isspace(*p);
7d8b6769
JS
1229 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1230 *p != '?' && *p != '*' && *p != '~')
9e9da23c
JS
1231 continue;
1232 if (!buf.len)
1233 strbuf_addch(&buf, '"');
1234 if (p != p2)
1235 strbuf_add(&buf, p2, p - p2);
7d8b6769 1236 if (*p == '\\' || *p == '"')
9e9da23c
JS
1237 strbuf_addch(&buf, '\\');
1238 p2 = p;
1239 }
1240
1241 if (p == arg)
1242 strbuf_addch(&buf, '"');
1243 else if (!buf.len)
1244 return arg;
1245 else
04522edb 1246 strbuf_add(&buf, p2, p - p2);
9e9da23c
JS
1247
1248 strbuf_addch(&buf, '"');
1249 return strbuf_detach(&buf, 0);
1250}
1251
f1a4dfb8
JS
1252static const char *parse_interpreter(const char *cmd)
1253{
1254 static char buf[100];
1255 char *p, *opt;
1256 int n, fd;
1257
1258 /* don't even try a .exe */
1259 n = strlen(cmd);
1260 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1261 return NULL;
1262
1263 fd = open(cmd, O_RDONLY);
1264 if (fd < 0)
1265 return NULL;
1266 n = read(fd, buf, sizeof(buf)-1);
1267 close(fd);
1268 if (n < 4) /* at least '#!/x' and not error */
1269 return NULL;
1270
1271 if (buf[0] != '#' || buf[1] != '!')
1272 return NULL;
1273 buf[n] = '\0';
bedc4279
PH
1274 p = buf + strcspn(buf, "\r\n");
1275 if (!*p)
f1a4dfb8
JS
1276 return NULL;
1277
1278 *p = '\0';
1279 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1280 return NULL;
1281 /* strip options */
1282 if ((opt = strchr(p+1, ' ')))
1283 *opt = '\0';
1284 return p+1;
1285}
1286
f1a4dfb8
JS
1287/*
1288 * exe_only means that we only want to detect .exe files, but not scripts
1289 * (which do not have an extension)
1290 */
e0ca1ca2
RS
1291static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1292 int isexe, int exe_only)
f1a4dfb8
JS
1293{
1294 char path[MAX_PATH];
4e1a641e 1295 wchar_t wpath[MAX_PATH];
e0ca1ca2 1296 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
f1a4dfb8 1297
4e1a641e
AR
1298 if (xutftowcs_path(wpath, path) < 0)
1299 return NULL;
1300
1301 if (!isexe && _waccess(wpath, F_OK) == 0)
f1a4dfb8 1302 return xstrdup(path);
4e1a641e
AR
1303 wpath[wcslen(wpath)-4] = '\0';
1304 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1305 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1306 path[strlen(path)-4] = '\0';
fe77b695 1307 return xstrdup(path);
4e1a641e
AR
1308 }
1309 }
f1a4dfb8
JS
1310 return NULL;
1311}
1312
1313/*
22e5e58a 1314 * Determines the absolute path of cmd using the split path in path.
f1a4dfb8
JS
1315 * If cmd contains a slash or backslash, no lookup is performed.
1316 */
e0ca1ca2 1317static char *path_lookup(const char *cmd, int exe_only)
f1a4dfb8 1318{
e0ca1ca2 1319 const char *path;
f1a4dfb8
JS
1320 char *prog = NULL;
1321 int len = strlen(cmd);
1322 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1323
2ce6d075 1324 if (strpbrk(cmd, "/\\"))
e0ca1ca2
RS
1325 return xstrdup(cmd);
1326
1327 path = mingw_getenv("PATH");
1328 if (!path)
1329 return NULL;
f1a4dfb8 1330
e0ca1ca2
RS
1331 while (!prog) {
1332 const char *sep = strchrnul(path, ';');
1333 int dirlen = sep - path;
1334 if (dirlen)
1335 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1336 if (!*sep)
1337 break;
1338 path = sep + 1;
1339 }
f1a4dfb8
JS
1340
1341 return prog;
1342}
1343
fe21c6b2
JS
1344static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1345{
1346 while (*s && *s != c)
1347 s++;
1348 return s;
1349}
1350
1351/* Compare only keys */
1352static int wenvcmp(const void *a, const void *b)
1353{
1354 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1355 size_t p_len, q_len;
1356
1357 /* Find the keys */
1358 p_len = wcschrnul(p, L'=') - p;
1359 q_len = wcschrnul(q, L'=') - q;
f279242d 1360
fe21c6b2
JS
1361 /* If the length differs, include the shorter key's NUL */
1362 if (p_len < q_len)
1363 p_len++;
1364 else if (p_len > q_len)
1365 p_len = q_len + 1;
1366
1367 return _wcsnicmp(p, q, p_len);
1368}
f279242d 1369
df0e998c 1370/*
fe21c6b2
JS
1371 * Build an environment block combining the inherited environment
1372 * merged with the given list of settings.
1373 *
1374 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1375 * Values of the form "KEY" in deltaenv delete inherited values.
1376 *
1377 * Multiple entries in deltaenv for the same key are explicitly allowed.
1378 *
1379 * We return a contiguous block of UNICODE strings with a final trailing
1380 * zero word.
df0e998c 1381 */
77734da2 1382static wchar_t *make_environment_block(char **deltaenv)
7e5d7768 1383{
fe21c6b2
JS
1384 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1385 size_t wlen, s, delta_size, size;
df0e998c 1386
fe21c6b2
JS
1387 wchar_t **array = NULL;
1388 size_t alloc = 0, nr = 0, i;
df0e998c 1389
fe21c6b2
JS
1390 size = 1; /* for extra NUL at the end */
1391
1392 /* If there is no deltaenv to apply, simply return a copy. */
1393 if (!deltaenv || !*deltaenv) {
1394 for (p = wenv; p && *p; ) {
1395 size_t s = wcslen(p) + 1;
1396 size += s;
1397 p += s;
1398 }
77734da2 1399
6e578410 1400 DUP_ARRAY(result, wenv, size);
fe21c6b2
JS
1401 FreeEnvironmentStringsW(wenv);
1402 return result;
1403 }
77734da2 1404
fe21c6b2
JS
1405 /*
1406 * If there is a deltaenv, let's accumulate all keys into `array`,
97fff610
JS
1407 * sort them using the stable git_stable_qsort() and then copy,
1408 * skipping duplicate keys
fe21c6b2
JS
1409 */
1410 for (p = wenv; p && *p; ) {
1411 ALLOC_GROW(array, nr + 1, alloc);
1412 s = wcslen(p) + 1;
1413 array[nr++] = p;
1414 p += s;
1415 size += s;
df0e998c 1416 }
fe21c6b2
JS
1417
1418 /* (over-)assess size needed for wchar version of deltaenv */
1419 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1420 delta_size += strlen(deltaenv[i]) * 2 + 1;
1421 ALLOC_ARRAY(wdeltaenv, delta_size);
1422
1423 /* convert the deltaenv, appending to array */
1424 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1425 ALLOC_GROW(array, nr + 1, alloc);
1426 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1427 array[nr++] = p;
1428 p += wlen + 1;
1429 }
df0e998c 1430
97fff610 1431 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
fe21c6b2 1432 ALLOC_ARRAY(result, size + delta_size);
df0e998c 1433
fe21c6b2
JS
1434 for (p = result, i = 0; i < nr; i++) {
1435 /* Skip any duplicate keys; last one wins */
1436 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1437 i++;
77734da2 1438
fe21c6b2
JS
1439 /* Skip "to delete" entry */
1440 if (!wcschr(array[i], L'='))
1441 continue;
77734da2 1442
fe21c6b2 1443 size = wcslen(array[i]) + 1;
552fc501 1444 COPY_ARRAY(p, array[i], size);
fe21c6b2 1445 p += size;
df0e998c 1446 }
fe21c6b2
JS
1447 *p = L'\0';
1448
1449 free(array);
1450 free(wdeltaenv);
1451 FreeEnvironmentStringsW(wenv);
1452 return result;
7e5d7768
JS
1453}
1454
0e218f91
JS
1455static void do_unset_environment_variables(void)
1456{
1457 static int done;
1458 char *p = unset_environment_variables;
1459
1460 if (done || !p)
1461 return;
1462 done = 1;
1463
1464 for (;;) {
1465 char *comma = strchr(p, ',');
1466
1467 if (comma)
1468 *comma = '\0';
1469 unsetenv(p);
1470 if (!comma)
1471 break;
1472 p = comma + 1;
1473 }
1474}
1475
52de4db5
EFL
1476struct pinfo_t {
1477 struct pinfo_t *next;
1478 pid_t pid;
1479 HANDLE proc;
657b35f4
RJ
1480};
1481static struct pinfo_t *pinfo = NULL;
52de4db5
EFL
1482CRITICAL_SECTION pinfo_cs;
1483
9e9da23c
JS
1484/* Used to match and chomp off path components */
1485static inline int match_last_path_component(const char *path, size_t *len,
1486 const char *component)
1487{
1488 size_t component_len = strlen(component);
1489 if (*len < component_len + 1 ||
1490 !is_dir_sep(path[*len - component_len - 1]) ||
1491 fspathncmp(path + *len - component_len, component, component_len))
1492 return 0;
1493 *len -= component_len + 1;
1494 /* chomp off repeated dir separators */
1495 while (*len > 0 && is_dir_sep(path[*len - 1]))
1496 (*len)--;
1497 return 1;
1498}
1499
1500static int is_msys2_sh(const char *cmd)
1501{
e2ba3d6f
JS
1502 if (!cmd)
1503 return 0;
1504
1505 if (!strcmp(cmd, "sh")) {
9e9da23c
JS
1506 static int ret = -1;
1507 char *p;
1508
1509 if (ret >= 0)
1510 return ret;
1511
1512 p = path_lookup(cmd, 0);
1513 if (!p)
1514 ret = 0;
1515 else {
1516 size_t len = strlen(p);
1517
1518 ret = match_last_path_component(p, &len, "sh.exe") &&
1519 match_last_path_component(p, &len, "bin") &&
1520 match_last_path_component(p, &len, "usr");
1521 free(p);
1522 }
1523 return ret;
1524 }
e2ba3d6f
JS
1525
1526 if (ends_with(cmd, "\\sh.exe")) {
1527 static char *sh;
1528
1529 if (!sh)
1530 sh = path_lookup("sh", 0);
1531
1532 return !fspathcmp(cmd, sh);
1533 }
1534
9e9da23c
JS
1535 return 0;
1536}
1537
77734da2 1538static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1539 const char *dir,
75301f90 1540 int prepend_cmd, int fhin, int fhout, int fherr)
7e5d7768 1541{
ac33519d 1542 static int restrict_handle_inheritance = -1;
9a780a38 1543 STARTUPINFOEXW si;
7e5d7768 1544 PROCESS_INFORMATION pi;
9a780a38
JS
1545 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1546 HANDLE stdhandles[3];
1547 DWORD stdhandles_count = 0;
1548 SIZE_T size;
7eb2619c
KB
1549 struct strbuf args;
1550 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1551 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
7e5d7768 1552 BOOL ret;
0e218f91 1553 HANDLE cons;
9e9da23c 1554 const char *(*quote_arg)(const char *arg) =
49f7a76d
JS
1555 is_msys2_sh(cmd ? cmd : *argv) ?
1556 quote_arg_msys2 : quote_arg_msvc;
3efc128c 1557 const char *strace_env;
0e218f91 1558
4d0375ca
JS
1559 /* Make sure to override previous errors, if any */
1560 errno = 0;
1561
ac33519d
JS
1562 if (restrict_handle_inheritance < 0)
1563 restrict_handle_inheritance = core_restrict_inherited_handles;
1564 /*
1565 * The following code to restrict which handles are inherited seems
1566 * to work properly only on Windows 7 and later, so let's disable it
1567 * on Windows Vista and 2008.
1568 */
1569 if (restrict_handle_inheritance < 0)
1570 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1571
0e218f91 1572 do_unset_environment_variables();
7e5d7768
JS
1573
1574 /* Determine whether or not we are associated to a console */
94238859 1575 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
7e5d7768
JS
1576 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1577 FILE_ATTRIBUTE_NORMAL, NULL);
1578 if (cons == INVALID_HANDLE_VALUE) {
1579 /* There is no console associated with this process.
1580 * Since the child is a console process, Windows
1581 * would normally create a console window. But
1582 * since we'll be redirecting std streams, we do
1583 * not need the console.
19fb896f
AG
1584 * It is necessary to use DETACHED_PROCESS
1585 * instead of CREATE_NO_WINDOW to make ssh
1586 * recognize that it has no console.
7e5d7768 1587 */
7eb2619c 1588 flags |= DETACHED_PROCESS;
7e5d7768
JS
1589 } else {
1590 /* There is already a console. If we specified
19fb896f 1591 * DETACHED_PROCESS here, too, Windows would
7e5d7768 1592 * disassociate the child from the console.
19fb896f 1593 * The same is true for CREATE_NO_WINDOW.
7e5d7768
JS
1594 * Go figure!
1595 */
7e5d7768
JS
1596 CloseHandle(cons);
1597 }
1598 memset(&si, 0, sizeof(si));
9a780a38
JS
1599 si.StartupInfo.cb = sizeof(si);
1600 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1601 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1602 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1603
1604 /* The list of handles cannot contain duplicates */
1605 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1606 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1607 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1608 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1609 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1610 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1611 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1612 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1613 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1614 if (stdhandles_count)
1615 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
7e5d7768 1616
eb7c7863
JS
1617 if (*argv && !strcmp(cmd, *argv))
1618 wcmd[0] = L'\0';
1619 else if (xutftowcs_path(wcmd, cmd) < 0)
99c3c76d
KB
1620 return -1;
1621 if (dir && xutftowcs_path(wdir, dir) < 0)
1622 return -1;
1623
7e5d7768
JS
1624 /* concatenate argv, quoting args as we go */
1625 strbuf_init(&args, 0);
1626 if (prepend_cmd) {
1627 char *quoted = (char *)quote_arg(cmd);
1628 strbuf_addstr(&args, quoted);
1629 if (quoted != cmd)
1630 free(quoted);
1631 }
1632 for (; *argv; argv++) {
1633 char *quoted = (char *)quote_arg(*argv);
1634 if (*args.buf)
1635 strbuf_addch(&args, ' ');
1636 strbuf_addstr(&args, quoted);
1637 if (quoted != *argv)
1638 free(quoted);
1639 }
1640
3efc128c
JS
1641 strace_env = getenv("GIT_STRACE_COMMANDS");
1642 if (strace_env) {
1643 char *p = path_lookup("strace.exe", 1);
1644 if (!p)
1645 return error("strace not found!");
1646 if (xutftowcs_path(wcmd, p) < 0) {
1647 free(p);
1648 return -1;
1649 }
1650 free(p);
1651 if (!strcmp("1", strace_env) ||
1652 !strcasecmp("yes", strace_env) ||
1653 !strcasecmp("true", strace_env))
1654 strbuf_insert(&args, 0, "strace ", 7);
1655 else {
1656 const char *quoted = quote_arg(strace_env);
1657 struct strbuf buf = STRBUF_INIT;
1658 strbuf_addf(&buf, "strace -o %s ", quoted);
1659 if (quoted != strace_env)
1660 free((char *)quoted);
1661 strbuf_insert(&args, 0, buf.buf, buf.len);
1662 strbuf_release(&buf);
1663 }
1664 }
1665
8d5b3325 1666 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
99c3c76d
KB
1667 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1668 strbuf_release(&args);
1669
77734da2 1670 wenvblk = make_environment_block(deltaenv);
7e5d7768
JS
1671
1672 memset(&pi, 0, sizeof(pi));
9a780a38
JS
1673 if (restrict_handle_inheritance && stdhandles_count &&
1674 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1675 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1676 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1677 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1678 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1679 UpdateProcThreadAttribute(attr_list, 0,
1680 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1681 stdhandles,
1682 stdhandles_count * sizeof(HANDLE),
1683 NULL, NULL)) {
1684 si.lpAttributeList = attr_list;
1685 flags |= EXTENDED_STARTUPINFO_PRESENT;
1686 }
1687
1688 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1689 stdhandles_count ? TRUE : FALSE,
1690 flags, wenvblk, dir ? wdir : NULL,
1691 &si.StartupInfo, &pi);
1692
1693 /*
1694 * On Windows 2008 R2, it seems that specifying certain types of handles
1695 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1696 * error. Rather than playing finicky and fragile games, let's just try
1697 * to detect this situation and simply try again without restricting any
1698 * handle inheritance. This is still better than failing to create
1699 * processes.
1700 */
1701 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1702 DWORD err = GetLastError();
1703 struct strbuf buf = STRBUF_INIT;
1704
1705 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1706 /*
1707 * On Windows 7 and earlier, handles on pipes and character
1708 * devices are inherited automatically, and cannot be
1709 * specified in the thread handle list. Rather than trying
1710 * to catch each and every corner case (and running the
1711 * chance of *still* forgetting a few), let's just fall
1712 * back to creating the process without trying to limit the
1713 * handle inheritance.
1714 */
1715 !(err == ERROR_INVALID_PARAMETER &&
1716 GetVersion() >> 16 < 9200) &&
1717 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1718 DWORD fl = 0;
1719 int i;
1720
1721 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1722
1723 for (i = 0; i < stdhandles_count; i++) {
1724 HANDLE h = stdhandles[i];
1725 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1726 "handle info (%d) %lx\n", i, h,
1727 GetFileType(h),
1728 GetHandleInformation(h, &fl),
1729 fl);
1730 }
1731 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1732 "at\nhttps://github.com/git-for-windows/"
1733 "git/issues/new\n\n"
1734 "To suppress this warning, please set "
1735 "the environment variable\n\n"
1736 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1737 "\n");
1738 }
1739 restrict_handle_inheritance = 0;
1740 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1741 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1742 TRUE, flags, wenvblk, dir ? wdir : NULL,
1743 &si.StartupInfo, &pi);
4d0375ca 1744 if (!ret)
9a780a38 1745 errno = err_win_to_posix(GetLastError());
4d0375ca 1746 if (ret && buf.len) {
9a780a38
JS
1747 warning("failed to restrict file handles (%ld)\n\n%s",
1748 err, buf.buf);
1749 }
1750 strbuf_release(&buf);
1751 } else if (!ret)
1752 errno = err_win_to_posix(GetLastError());
1753
1754 if (si.lpAttributeList)
1755 DeleteProcThreadAttributeList(si.lpAttributeList);
1756 if (attr_list)
1757 HeapFree(GetProcessHeap(), 0, attr_list);
7e5d7768 1758
7eb2619c 1759 free(wenvblk);
99c3c76d 1760 free(wargs);
7e5d7768 1761
9a780a38 1762 if (!ret)
7e5d7768 1763 return -1;
9a780a38 1764
7e5d7768 1765 CloseHandle(pi.hThread);
52de4db5
EFL
1766
1767 /*
1768 * The process ID is the human-readable identifier of the process
1769 * that we want to present in log and error messages. The handle
1770 * is not useful for this purpose. But we cannot close it, either,
1771 * because it is not possible to turn a process ID into a process
1772 * handle after the process terminated.
1773 * Keep the handle in a list for waitpid.
1774 */
1775 EnterCriticalSection(&pinfo_cs);
1776 {
1777 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1778 info->pid = pi.dwProcessId;
1779 info->proc = pi.hProcess;
1780 info->next = pinfo;
1781 pinfo = info;
1782 }
1783 LeaveCriticalSection(&pinfo_cs);
1784
1785 return (pid_t)pi.dwProcessId;
7e5d7768
JS
1786}
1787
3e66e47b 1788static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
75301f90 1789{
77734da2 1790 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
75301f90
JS
1791}
1792
77734da2 1793pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1794 const char *dir,
75301f90 1795 int fhin, int fhout, int fherr)
7e5d7768
JS
1796{
1797 pid_t pid;
e0ca1ca2 1798 char *prog = path_lookup(cmd, 0);
7e5d7768
JS
1799
1800 if (!prog) {
1801 errno = ENOENT;
1802 pid = -1;
1803 }
1804 else {
1805 const char *interpr = parse_interpreter(prog);
1806
1807 if (interpr) {
1808 const char *argv0 = argv[0];
e0ca1ca2 1809 char *iprog = path_lookup(interpr, 1);
7e5d7768
JS
1810 argv[0] = prog;
1811 if (!iprog) {
1812 errno = ENOENT;
1813 pid = -1;
1814 }
1815 else {
77734da2 1816 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
75301f90 1817 fhin, fhout, fherr);
7e5d7768
JS
1818 free(iprog);
1819 }
1820 argv[0] = argv0;
1821 }
1822 else
77734da2 1823 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
75301f90 1824 fhin, fhout, fherr);
7e5d7768
JS
1825 free(prog);
1826 }
7e5d7768
JS
1827 return pid;
1828}
1829
3e66e47b 1830static int try_shell_exec(const char *cmd, char *const *argv)
f1a4dfb8
JS
1831{
1832 const char *interpr = parse_interpreter(cmd);
f1a4dfb8
JS
1833 char *prog;
1834 int pid = 0;
1835
1836 if (!interpr)
1837 return 0;
e0ca1ca2 1838 prog = path_lookup(interpr, 1);
f1a4dfb8 1839 if (prog) {
ee4512ed 1840 int exec_id;
f1a4dfb8 1841 int argc = 0;
12fb9bd8 1842 char **argv2;
f1a4dfb8 1843 while (argv[argc]) argc++;
b32fa95f 1844 ALLOC_ARRAY(argv2, argc + 1);
7e5d7768 1845 argv2[0] = (char *)cmd; /* full path to the script file */
51bd6be3 1846 COPY_ARRAY(&argv2[1], &argv[1], argc);
09884f35
RS
1847 exec_id = trace2_exec(prog, (const char **)argv2);
1848 pid = mingw_spawnv(prog, (const char **)argv2, 1);
f1a4dfb8
JS
1849 if (pid >= 0) {
1850 int status;
1851 if (waitpid(pid, &status, 0) < 0)
1852 status = 255;
ee4512ed 1853 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1854 exit(status);
1855 }
ee4512ed 1856 trace2_exec_result(exec_id, -1);
f1a4dfb8
JS
1857 pid = 1; /* indicate that we tried but failed */
1858 free(prog);
1859 free(argv2);
1860 }
f1a4dfb8
JS
1861 return pid;
1862}
1863
3e66e47b 1864int mingw_execv(const char *cmd, char *const *argv)
f1a4dfb8
JS
1865{
1866 /* check if git_command is a shell script */
3e66e47b 1867 if (!try_shell_exec(cmd, argv)) {
f1a4dfb8 1868 int pid, status;
ee4512ed 1869 int exec_id;
f1a4dfb8 1870
ee4512ed 1871 exec_id = trace2_exec(cmd, (const char **)argv);
3e66e47b 1872 pid = mingw_spawnv(cmd, (const char **)argv, 0);
ee4512ed
JH
1873 if (pid < 0) {
1874 trace2_exec_result(exec_id, -1);
570f1e6e 1875 return -1;
ee4512ed 1876 }
f1a4dfb8
JS
1877 if (waitpid(pid, &status, 0) < 0)
1878 status = 255;
ee4512ed 1879 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1880 exit(status);
1881 }
570f1e6e 1882 return -1;
f1a4dfb8
JS
1883}
1884
1696d723 1885int mingw_execvp(const char *cmd, char *const *argv)
f1a4dfb8 1886{
e0ca1ca2 1887 char *prog = path_lookup(cmd, 0);
f1a4dfb8
JS
1888
1889 if (prog) {
3e66e47b 1890 mingw_execv(prog, argv);
f1a4dfb8
JS
1891 free(prog);
1892 } else
1893 errno = ENOENT;
1894
1696d723 1895 return -1;
f1a4dfb8
JS
1896}
1897
82fc07b7
EFL
1898int mingw_kill(pid_t pid, int sig)
1899{
1900 if (pid > 0 && sig == SIGTERM) {
1901 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1902
1903 if (TerminateProcess(h, -1)) {
1904 CloseHandle(h);
1905 return 0;
1906 }
1907
1908 errno = err_win_to_posix(GetLastError());
1909 CloseHandle(h);
1910 return -1;
64a99eb4
NTND
1911 } else if (pid > 0 && sig == 0) {
1912 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1913 if (h) {
1914 CloseHandle(h);
1915 return 0;
1916 }
82fc07b7
EFL
1917 }
1918
1919 errno = EINVAL;
1920 return -1;
1921}
1922
343ff06d 1923/*
fe21c6b2
JS
1924 * UTF-8 versions of getenv(), putenv() and unsetenv().
1925 * Internally, they use the CRT's stock UNICODE routines
1926 * to avoid data loss.
343ff06d 1927 */
fe21c6b2 1928char *mingw_getenv(const char *name)
343ff06d 1929{
ca1b4116 1930#define GETENV_MAX_RETAIN 64
fe21c6b2
JS
1931 static char *values[GETENV_MAX_RETAIN];
1932 static int value_counter;
1933 int len_key, len_value;
1934 wchar_t *w_key;
1935 char *value;
1936 wchar_t w_value[32768];
343ff06d 1937
fe21c6b2
JS
1938 if (!name || !*name)
1939 return NULL;
ba26f296 1940
fe21c6b2
JS
1941 len_key = strlen(name) + 1;
1942 /* We cannot use xcalloc() here because that uses getenv() itself */
1943 w_key = calloc(len_key, sizeof(wchar_t));
1944 if (!w_key)
1945 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1946 xutftowcs(w_key, name, len_key);
61d1d92a
JS
1947 /* GetEnvironmentVariableW() only sets the last error upon failure */
1948 SetLastError(ERROR_SUCCESS);
fe21c6b2
JS
1949 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1950 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1951 free(w_key);
1952 return NULL;
ba26f296 1953 }
fe21c6b2
JS
1954 free(w_key);
1955
1956 len_value = len_value * 3 + 1;
1957 /* We cannot use xcalloc() here because that uses getenv() itself */
1958 value = calloc(len_value, sizeof(char));
1959 if (!value)
1960 die("Out of memory, (tried to allocate %u bytes)", len_value);
1961 xwcstoutf(value, w_value, len_value);
1962
1963 /*
1964 * We return `value` which is an allocated value and the caller is NOT
1965 * expecting to have to free it, so we keep a round-robin array,
1966 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1967 */
1968 free(values[value_counter]);
1969 values[value_counter++] = value;
1970 if (value_counter >= ARRAY_SIZE(values))
1971 value_counter = 0;
1972
1973 return value;
ba26f296
JS
1974}
1975
fe21c6b2 1976int mingw_putenv(const char *namevalue)
ba26f296 1977{
fe21c6b2
JS
1978 int size;
1979 wchar_t *wide, *equal;
1980 BOOL result;
ba26f296 1981
fe21c6b2
JS
1982 if (!namevalue || !*namevalue)
1983 return 0;
ba26f296 1984
fe21c6b2
JS
1985 size = strlen(namevalue) * 2 + 1;
1986 wide = calloc(size, sizeof(wchar_t));
1987 if (!wide)
1988 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1989 xutftowcs(wide, namevalue, size);
1990 equal = wcschr(wide, L'=');
1991 if (!equal)
1992 result = SetEnvironmentVariableW(wide, NULL);
1993 else {
1994 *equal = L'\0';
1995 result = SetEnvironmentVariableW(wide, equal + 1);
ba26f296 1996 }
fe21c6b2 1997 free(wide);
2affea41 1998
fe21c6b2
JS
1999 if (!result)
2000 errno = err_win_to_posix(GetLastError());
df599e96 2001
fe21c6b2 2002 return result ? 0 : -1;
06bc4b79
JS
2003}
2004
b7cc9f82 2005static void ensure_socket_initialization(void)
746fb857
JS
2006{
2007 WSADATA wsa;
b7cc9f82
MS
2008 static int initialized = 0;
2009
2010 if (initialized)
2011 return;
746fb857
JS
2012
2013 if (WSAStartup(MAKEWORD(2,2), &wsa))
2014 die("unable to initialize winsock subsystem, error %d",
2015 WSAGetLastError());
fe3b2b7b 2016
b9f0193b 2017 atexit((void(*)(void)) WSACleanup);
b7cc9f82
MS
2018 initialized = 1;
2019}
2020
13d24b01
PT
2021#undef gethostname
2022int mingw_gethostname(char *name, int namelen)
2023{
2024 ensure_socket_initialization();
2025 return gethostname(name, namelen);
2026}
2027
b7cc9f82
MS
2028#undef gethostbyname
2029struct hostent *mingw_gethostbyname(const char *host)
2030{
2031 ensure_socket_initialization();
746fb857
JS
2032 return gethostbyname(host);
2033}
2034
b9f0193b 2035#undef getaddrinfo
fe3b2b7b
MS
2036int mingw_getaddrinfo(const char *node, const char *service,
2037 const struct addrinfo *hints, struct addrinfo **res)
2038{
2039 ensure_socket_initialization();
b9f0193b 2040 return getaddrinfo(node, service, hints, res);
fe3b2b7b
MS
2041}
2042
746fb857
JS
2043int mingw_socket(int domain, int type, int protocol)
2044{
2045 int sockfd;
772991af
MP
2046 SOCKET s;
2047
2048 ensure_socket_initialization();
2049 s = WSASocket(domain, type, protocol, NULL, 0, 0);
746fb857
JS
2050 if (s == INVALID_SOCKET) {
2051 /*
2052 * WSAGetLastError() values are regular BSD error codes
2053 * biased by WSABASEERR.
2054 * However, strerror() does not know about networking
2055 * specific errors, which are values beginning at 38 or so.
2056 * Therefore, we choose to leave the biased error code
2057 * in errno so that _if_ someone looks up the code somewhere,
2058 * then it is at least the number that are usually listed.
2059 */
2060 errno = WSAGetLastError();
2061 return -1;
2062 }
2063 /* convert into a file descriptor */
2064 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2065 closesocket(s);
2066 return error("unable to make a socket file descriptor: %s",
2067 strerror(errno));
2068 }
2069 return sockfd;
2070}
2071
2072#undef connect
2073int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2074{
2075 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2076 return connect(s, sa, sz);
2077}
2078
772991af
MP
2079#undef bind
2080int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2081{
2082 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2083 return bind(s, sa, sz);
2084}
2085
2086#undef setsockopt
2087int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2088{
2089 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2090 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2091}
2092
a7941795
JS
2093#undef shutdown
2094int mingw_shutdown(int sockfd, int how)
2095{
2096 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2097 return shutdown(s, how);
2098}
2099
772991af
MP
2100#undef listen
2101int mingw_listen(int sockfd, int backlog)
2102{
2103 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2104 return listen(s, backlog);
2105}
2106
2107#undef accept
2108int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2109{
2110 int sockfd2;
2111
2112 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2113 SOCKET s2 = accept(s1, sa, sz);
2114
2115 /* convert into a file descriptor */
2116 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2117 int err = errno;
2118 closesocket(s2);
2119 return error("unable to make a socket file descriptor: %s",
2120 strerror(err));
2121 }
2122 return sockfd2;
2123}
2124
ea9e98c3
JS
2125#undef rename
2126int mingw_rename(const char *pold, const char *pnew)
2127{
6ac6f878
JS
2128 DWORD attrs, gle;
2129 int tries = 0;
85faec9d
KB
2130 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2131 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2132 return -1;
632f7017 2133
ea9e98c3
JS
2134 /*
2135 * Try native rename() first to get errno right.
2136 * It is based on MoveFile(), which cannot overwrite existing files.
2137 */
85faec9d 2138 if (!_wrename(wpold, wpnew))
ea9e98c3
JS
2139 return 0;
2140 if (errno != EEXIST)
2141 return -1;
6ac6f878 2142repeat:
85faec9d 2143 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
ea9e98c3
JS
2144 return 0;
2145 /* TODO: translate more errors */
6ac6f878
JS
2146 gle = GetLastError();
2147 if (gle == ERROR_ACCESS_DENIED &&
85faec9d 2148 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
632f7017 2149 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
4426fb51 2150 DWORD attrsold = GetFileAttributesW(wpold);
2151 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2152 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2153 errno = EISDIR;
2154 else if (!_wrmdir(wpnew))
2155 goto repeat;
ea9e98c3
JS
2156 return -1;
2157 }
632f7017 2158 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
85faec9d
KB
2159 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2160 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
632f7017 2161 return 0;
6ac6f878 2162 gle = GetLastError();
632f7017 2163 /* revert file attributes on failure */
85faec9d 2164 SetFileAttributesW(wpnew, attrs);
632f7017 2165 }
ea9e98c3 2166 }
6ac6f878
JS
2167 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2168 /*
2169 * We assume that some other process had the source or
2170 * destination file open at the wrong moment and retry.
2171 * In order to give the other process a higher chance to
2172 * complete its operation, we give up our time slice now.
2173 * If we have to retry again, we do sleep a bit.
2174 */
2175 Sleep(delay[tries]);
2176 tries++;
2177 goto repeat;
2178 }
c9b78400
HV
2179 if (gle == ERROR_ACCESS_DENIED &&
2180 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2181 "Should I try again?", pold, pnew))
2182 goto repeat;
2183
ea9e98c3
JS
2184 errno = EACCES;
2185 return -1;
2186}
2187
b1b95204
RJ
2188/*
2189 * Note that this doesn't return the actual pagesize, but
2190 * the allocation granularity. If future Windows specific git code
2191 * needs the real getpagesize function, we need to find another solution.
2192 */
2193int mingw_getpagesize(void)
2194{
2195 SYSTEM_INFO si;
2196 GetSystemInfo(&si);
2197 return si.dwAllocationGranularity;
2198}
2199
564be791
JS
2200/* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2201enum EXTENDED_NAME_FORMAT {
2202 NameDisplay = 3,
2203 NameUserPrincipal = 8
2204};
2205
2206static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2207{
4a9b2049 2208 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
564be791
JS
2209 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2210 static wchar_t wbuffer[1024];
2211 DWORD len;
2212
2213 if (!INIT_PROC_ADDR(GetUserNameExW))
2214 return NULL;
2215
2216 len = ARRAY_SIZE(wbuffer);
2217 if (GetUserNameExW(type, wbuffer, &len)) {
2218 char *converted = xmalloc((len *= 3));
2219 if (xwcstoutf(converted, wbuffer, len) >= 0)
2220 return converted;
2221 free(converted);
2222 }
2223
2224 return NULL;
2225}
2226
501afcb8
JS
2227char *mingw_query_user_email(void)
2228{
2229 return get_extended_user_info(NameUserPrincipal);
2230}
2231
f4626df5
JS
2232struct passwd *getpwuid(int uid)
2233{
55b6513e 2234 static unsigned initialized;
f7597aca 2235 static char user_name[100];
55b6513e 2236 static struct passwd *p;
39a98e9b 2237 wchar_t buf[100];
55b6513e 2238 DWORD len;
f7597aca 2239
55b6513e
JS
2240 if (initialized)
2241 return p;
f7597aca 2242
697bdd22 2243 len = ARRAY_SIZE(buf);
39a98e9b
JS
2244 if (!GetUserNameW(buf, &len)) {
2245 initialized = 1;
2246 return NULL;
2247 }
2248
2249 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
55b6513e 2250 initialized = 1;
f7597aca 2251 return NULL;
55b6513e
JS
2252 }
2253
2254 p = xmalloc(sizeof(*p));
2255 p->pw_name = user_name;
564be791
JS
2256 p->pw_gecos = get_extended_user_info(NameDisplay);
2257 if (!p->pw_gecos)
2258 p->pw_gecos = "unknown";
55b6513e
JS
2259 p->pw_dir = NULL;
2260
2261 initialized = 1;
2262 return p;
f4626df5
JS
2263}
2264
6072fc31
JS
2265static HANDLE timer_event;
2266static HANDLE timer_thread;
2267static int timer_interval;
2268static int one_shot;
176478a8 2269static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
6072fc31
JS
2270
2271/* The timer works like this:
2272 * The thread, ticktack(), is a trivial routine that most of the time
2273 * only waits to receive the signal to terminate. The main thread tells
2274 * the thread to terminate by setting the timer_event to the signalled
2275 * state.
2276 * But ticktack() interrupts the wait state after the timer's interval
2277 * length to call the signal handler.
2278 */
2279
d7fa500f 2280static unsigned __stdcall ticktack(void *dummy)
6072fc31
JS
2281{
2282 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
176478a8 2283 mingw_raise(SIGALRM);
6072fc31
JS
2284 if (one_shot)
2285 break;
2286 }
2287 return 0;
2288}
2289
2290static int start_timer_thread(void)
2291{
2292 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2293 if (timer_event) {
2294 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2295 if (!timer_thread )
2296 return errno = ENOMEM,
2297 error("cannot start timer thread");
2298 } else
2299 return errno = ENOMEM,
2300 error("cannot allocate resources for timer");
2301 return 0;
2302}
2303
2304static void stop_timer_thread(void)
2305{
2306 if (timer_event)
2307 SetEvent(timer_event); /* tell thread to terminate */
2308 if (timer_thread) {
72d63b2f 2309 int rc = WaitForSingleObject(timer_thread, 10000);
6072fc31
JS
2310 if (rc == WAIT_TIMEOUT)
2311 error("timer thread did not terminate timely");
2312 else if (rc != WAIT_OBJECT_0)
2313 error("waiting for timer thread failed: %lu",
2314 GetLastError());
2315 CloseHandle(timer_thread);
2316 }
2317 if (timer_event)
2318 CloseHandle(timer_event);
2319 timer_event = NULL;
2320 timer_thread = NULL;
2321}
2322
2323static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2324{
2325 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2326}
2327
f4626df5
JS
2328int setitimer(int type, struct itimerval *in, struct itimerval *out)
2329{
6072fc31
JS
2330 static const struct timeval zero;
2331 static int atexit_done;
2332
afe8a907 2333 if (out)
6072fc31
JS
2334 return errno = EINVAL,
2335 error("setitimer param 3 != NULL not implemented");
2336 if (!is_timeval_eq(&in->it_interval, &zero) &&
2337 !is_timeval_eq(&in->it_interval, &in->it_value))
2338 return errno = EINVAL,
2339 error("setitimer: it_interval must be zero or eq it_value");
2340
2341 if (timer_thread)
2342 stop_timer_thread();
2343
2344 if (is_timeval_eq(&in->it_value, &zero) &&
2345 is_timeval_eq(&in->it_interval, &zero))
2346 return 0;
2347
2348 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2349 one_shot = is_timeval_eq(&in->it_interval, &zero);
2350 if (!atexit_done) {
2351 atexit(stop_timer_thread);
2352 atexit_done = 1;
2353 }
2354 return start_timer_thread();
f4626df5
JS
2355}
2356
2357int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2358{
6072fc31
JS
2359 if (sig != SIGALRM)
2360 return errno = EINVAL,
2361 error("sigaction only implemented for SIGALRM");
afe8a907 2362 if (out)
6072fc31
JS
2363 return errno = EINVAL,
2364 error("sigaction: param 3 != NULL not implemented");
2365
2366 timer_fn = in->sa_handler;
2367 return 0;
2368}
2369
2370#undef signal
2371sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2372{
a4540658 2373 sig_handler_t old;
176478a8
EFL
2374
2375 switch (sig) {
2376 case SIGALRM:
a4540658 2377 old = timer_fn;
176478a8
EFL
2378 timer_fn = handler;
2379 break;
2380
2381 case SIGINT:
a4540658 2382 old = sigint_fn;
176478a8
EFL
2383 sigint_fn = handler;
2384 break;
2385
2386 default:
6072fc31 2387 return signal(sig, handler);
176478a8
EFL
2388 }
2389
6072fc31 2390 return old;
f4626df5 2391}
4804aabc 2392
176478a8
EFL
2393#undef raise
2394int mingw_raise(int sig)
2395{
2396 switch (sig) {
2397 case SIGALRM:
2398 if (timer_fn == SIG_DFL) {
2399 if (isatty(STDERR_FILENO))
2400 fputs("Alarm clock\n", stderr);
2401 exit(128 + SIGALRM);
2402 } else if (timer_fn != SIG_IGN)
2403 timer_fn(SIGALRM);
2404 return 0;
2405
2406 case SIGINT:
2407 if (sigint_fn == SIG_DFL)
2408 exit(128 + SIGINT);
2409 else if (sigint_fn != SIG_IGN)
2410 sigint_fn(SIGINT);
2411 return 0;
2412
446df603
JH
2413#if defined(_MSC_VER)
2414 case SIGILL:
2415 case SIGFPE:
2416 case SIGSEGV:
2417 case SIGTERM:
2418 case SIGBREAK:
2419 case SIGABRT:
2420 case SIGABRT_COMPAT:
2421 /*
2422 * The <signal.h> header in the MS C Runtime defines 8 signals
2423 * as being supported on the platform. Anything else causes an
2424 * "Invalid signal or error" (which in DEBUG builds causes the
2425 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2426 * already know will fail.
2427 */
2428 return raise(sig);
2429 default:
2430 errno = EINVAL;
2431 return -1;
2432
2433#else
2434
176478a8
EFL
2435 default:
2436 return raise(sig);
446df603
JH
2437
2438#endif
2439
176478a8
EFL
2440 }
2441}
2442
7be401e0
PK
2443int link(const char *oldpath, const char *newpath)
2444{
85faec9d
KB
2445 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2446 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2447 xutftowcs_path(wnewpath, newpath) < 0)
2448 return -1;
2449
1e1a876b 2450 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
7be401e0
PK
2451 errno = err_win_to_posix(GetLastError());
2452 return -1;
2453 }
2454 return 0;
2455}
0dbbbc1e 2456
956d86d1 2457pid_t waitpid(pid_t pid, int *status, int options)
52de4db5
EFL
2458{
2459 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2460 FALSE, pid);
2461 if (!h) {
2462 errno = ECHILD;
2463 return -1;
2464 }
2465
ef7108ca
EFL
2466 if (pid > 0 && options & WNOHANG) {
2467 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2468 CloseHandle(h);
2469 return 0;
2470 }
2471 options &= ~WNOHANG;
2472 }
2473
52de4db5
EFL
2474 if (options == 0) {
2475 struct pinfo_t **ppinfo;
2476 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2477 CloseHandle(h);
2478 return 0;
2479 }
2480
2481 if (status)
2482 GetExitCodeProcess(h, (LPDWORD)status);
2483
2484 EnterCriticalSection(&pinfo_cs);
2485
2486 ppinfo = &pinfo;
2487 while (*ppinfo) {
2488 struct pinfo_t *info = *ppinfo;
2489 if (info->pid == pid) {
2490 CloseHandle(info->proc);
2491 *ppinfo = info->next;
2492 free(info);
2493 break;
2494 }
2495 ppinfo = &info->next;
2496 }
2497
2498 LeaveCriticalSection(&pinfo_cs);
2499
2500 CloseHandle(h);
2501 return pid;
2502 }
2503 CloseHandle(h);
2504
2505 errno = EINVAL;
2506 return -1;
2507}
c2369bdf 2508
1c950a59
KB
2509int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2510{
2511 int upos = 0, wpos = 0;
2512 const unsigned char *utf = (const unsigned char*) utfs;
2513 if (!utf || !wcs || wcslen < 1) {
2514 errno = EINVAL;
2515 return -1;
2516 }
2517 /* reserve space for \0 */
2518 wcslen--;
2519 if (utflen < 0)
2520 utflen = INT_MAX;
2521
2522 while (upos < utflen) {
2523 int c = utf[upos++] & 0xff;
2524 if (utflen == INT_MAX && c == 0)
2525 break;
2526
2527 if (wpos >= wcslen) {
2528 wcs[wpos] = 0;
2529 errno = ERANGE;
2530 return -1;
2531 }
2532
2533 if (c < 0x80) {
2534 /* ASCII */
2535 wcs[wpos++] = c;
2536 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2537 (utf[upos] & 0xc0) == 0x80) {
2538 /* 2-byte utf-8 */
2539 c = ((c & 0x1f) << 6);
2540 c |= (utf[upos++] & 0x3f);
2541 wcs[wpos++] = c;
2542 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2543 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2544 (utf[upos] & 0xc0) == 0x80 &&
2545 (utf[upos + 1] & 0xc0) == 0x80) {
2546 /* 3-byte utf-8 */
2547 c = ((c & 0x0f) << 12);
2548 c |= ((utf[upos++] & 0x3f) << 6);
2549 c |= (utf[upos++] & 0x3f);
2550 wcs[wpos++] = c;
2551 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2552 wpos + 1 < wcslen &&
2553 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2554 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2555 (utf[upos] & 0xc0) == 0x80 &&
2556 (utf[upos + 1] & 0xc0) == 0x80 &&
2557 (utf[upos + 2] & 0xc0) == 0x80) {
2558 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2559 c = ((c & 0x07) << 18);
2560 c |= ((utf[upos++] & 0x3f) << 12);
2561 c |= ((utf[upos++] & 0x3f) << 6);
2562 c |= (utf[upos++] & 0x3f);
2563 c -= 0x10000;
2564 wcs[wpos++] = 0xd800 | (c >> 10);
2565 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2566 } else if (c >= 0xa0) {
2567 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2568 wcs[wpos++] = c;
2569 } else {
2570 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2571 static const char *hex = "0123456789abcdef";
2572 wcs[wpos++] = hex[c >> 4];
2573 if (wpos < wcslen)
2574 wcs[wpos++] = hex[c & 0x0f];
2575 }
2576 }
2577 wcs[wpos] = 0;
2578 return wpos;
2579}
2580
2581int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2582{
2583 if (!wcs || !utf || utflen < 1) {
2584 errno = EINVAL;
2585 return -1;
2586 }
2587 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2588 if (utflen)
2589 return utflen - 1;
2590 errno = ERANGE;
2591 return -1;
2592}
2593
0767172b 2594static void setup_windows_environment(void)
02e6edc0 2595{
1fc7bf79
JS
2596 char *tmp = getenv("TMPDIR");
2597
02e6edc0 2598 /* on Windows it is TMP and TEMP */
1fc7bf79
JS
2599 if (!tmp) {
2600 if (!(tmp = getenv("TMP")))
02e6edc0 2601 tmp = getenv("TEMP");
1fc7bf79 2602 if (tmp) {
02e6edc0 2603 setenv("TMPDIR", tmp, 1);
1fc7bf79
JS
2604 tmp = getenv("TMPDIR");
2605 }
2606 }
2607
2608 if (tmp) {
2609 /*
2610 * Convert all dir separators to forward slashes,
2611 * to help shell commands called from the Git
2612 * executable (by not mistaking the dir separators
2613 * for escape characters).
2614 */
8e9b2080 2615 convert_slashes(tmp);
02e6edc0
KB
2616 }
2617
2618 /* simulate TERM to enable auto-color (see color.c) */
2619 if (!getenv("TERM"))
2620 setenv("TERM", "cygwin", 1);
e12a9556
KB
2621
2622 /* calculate HOME if not set */
2623 if (!getenv("HOME")) {
2624 /*
2625 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2626 * location, thus also check if the path exists (i.e. is not
2627 * disconnected)
2628 */
2629 if ((tmp = getenv("HOMEDRIVE"))) {
2630 struct strbuf buf = STRBUF_INIT;
2631 strbuf_addstr(&buf, tmp);
2632 if ((tmp = getenv("HOMEPATH"))) {
2633 strbuf_addstr(&buf, tmp);
2634 if (is_directory(buf.buf))
2635 setenv("HOME", buf.buf, 1);
2636 else
2637 tmp = NULL; /* use $USERPROFILE */
2638 }
2639 strbuf_release(&buf);
2640 }
2641 /* use $USERPROFILE if the home share is not available */
2642 if (!tmp && (tmp = getenv("USERPROFILE")))
2643 setenv("HOME", tmp, 1);
2644 }
02e6edc0
KB
2645}
2646
bdc77d1d
JS
2647static PSID get_current_user_sid(void)
2648{
2649 HANDLE token;
2650 DWORD len = 0;
2651 PSID result = NULL;
2652
2653 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2654 return NULL;
2655
2656 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2657 TOKEN_USER *info = xmalloc((size_t)len);
2658 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2659 len = GetLengthSid(info->User.Sid);
2660 result = xmalloc(len);
2661 if (!CopySid(len, result, info->User.Sid)) {
2662 error(_("failed to copy SID (%ld)"),
2663 GetLastError());
2664 FREE_AND_NULL(result);
2665 }
2666 }
2667 FREE_AND_NULL(info);
2668 }
2669 CloseHandle(token);
2670
2671 return result;
2672}
2673
7c83470e
JS
2674static int acls_supported(const char *path)
2675{
2676 size_t offset = offset_1st_component(path);
2677 WCHAR wroot[MAX_PATH];
2678 DWORD file_system_flags;
2679
2680 if (offset &&
2681 xutftowcsn(wroot, path, MAX_PATH, offset) > 0 &&
2682 GetVolumeInformationW(wroot, NULL, 0, NULL, NULL,
2683 &file_system_flags, NULL, 0))
2684 return !!(file_system_flags & FILE_PERSISTENT_ACLS);
2685
2686 return 0;
2687}
2688
17d3883f 2689int is_path_owned_by_current_sid(const char *path, struct strbuf *report)
bdc77d1d
JS
2690{
2691 WCHAR wpath[MAX_PATH];
2692 PSID sid = NULL;
2693 PSECURITY_DESCRIPTOR descriptor = NULL;
2694 DWORD err;
2695
2696 static wchar_t home[MAX_PATH];
2697
2698 int result = 0;
2699
2700 if (xutftowcs_path(wpath, path) < 0)
2701 return 0;
2702
2703 /*
2704 * On Windows, the home directory is owned by the administrator, but for
2705 * all practical purposes, it belongs to the user. Do pretend that it is
2706 * owned by the user.
2707 */
2708 if (!*home) {
2709 DWORD size = ARRAY_SIZE(home);
2710 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2711 if (!len || len > size)
2712 wcscpy(home, L"::N/A::");
2713 }
2714 if (!wcsicmp(wpath, home))
2715 return 1;
2716
2717 /* Get the owner SID */
2718 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2719 OWNER_SECURITY_INFORMATION |
2720 DACL_SECURITY_INFORMATION,
2721 &sid, NULL, NULL, NULL, &descriptor);
2722
2723 if (err != ERROR_SUCCESS)
2724 error(_("failed to get owner for '%s' (%ld)"), path, err);
2725 else if (sid && IsValidSid(sid)) {
2726 /* Now, verify that the SID matches the current user's */
2727 static PSID current_user_sid;
3f7207e2 2728 BOOL is_member;
bdc77d1d
JS
2729
2730 if (!current_user_sid)
2731 current_user_sid = get_current_user_sid();
2732
2733 if (current_user_sid &&
2734 IsValidSid(current_user_sid) &&
2735 EqualSid(sid, current_user_sid))
2736 result = 1;
3f7207e2
JS
2737 else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) &&
2738 CheckTokenMembership(NULL, sid, &is_member) &&
2739 is_member)
2740 /*
2741 * If owned by the Administrators group, and the
2742 * current user is an administrator, we consider that
2743 * okay, too.
2744 */
2745 result = 1;
7c83470e
JS
2746 else if (report &&
2747 IsWellKnownSid(sid, WinWorldSid) &&
2748 !acls_supported(path)) {
2749 /*
2750 * On FAT32 volumes, ownership is not actually recorded.
2751 */
4eb1ccec 2752 strbuf_addf(report, "'%s' is on a file system that does "
7c83470e
JS
2753 "not record ownership\n", path);
2754 } else if (report) {
e883e04b
JS
2755 LPSTR str1, str2, to_free1 = NULL, to_free2 = NULL;
2756
2757 if (ConvertSidToStringSidA(sid, &str1))
2758 to_free1 = str1;
2759 else
2760 str1 = "(inconvertible)";
2761
2762 if (!current_user_sid)
2763 str2 = "(none)";
2764 else if (!IsValidSid(current_user_sid))
2765 str2 = "(invalid)";
2766 else if (ConvertSidToStringSidA(current_user_sid, &str2))
2767 to_free2 = str2;
2768 else
2769 str2 = "(inconvertible)";
2770 strbuf_addf(report,
2771 "'%s' is owned by:\n"
2772 "\t'%s'\nbut the current user is:\n"
2773 "\t'%s'\n", path, str1, str2);
2774 LocalFree(to_free1);
2775 LocalFree(to_free2);
2776 }
bdc77d1d
JS
2777 }
2778
2779 /*
2780 * We can release the security descriptor struct only now because `sid`
2781 * actually points into this struct.
2782 */
2783 if (descriptor)
2784 LocalFree(descriptor);
2785
2786 return result;
2787}
2788
4dc42c6c 2789int is_valid_win32_path(const char *path, int allow_literal_nul)
d2c84dad 2790{
4dc42c6c 2791 const char *p = path;
d2c84dad
JS
2792 int preceding_space_or_period = 0, i = 0, periods = 0;
2793
2794 if (!protect_ntfs)
2795 return 1;
2796
817ddd64 2797 skip_dos_drive_prefix((char **)&path);
4dc42c6c 2798 goto segment_start;
817ddd64 2799
d2c84dad
JS
2800 for (;;) {
2801 char c = *(path++);
2802 switch (c) {
2803 case '\0':
2804 case '/': case '\\':
2805 /* cannot end in ` ` or `.`, except for `.` and `..` */
2806 if (preceding_space_or_period &&
2807 (i != periods || periods > 2))
2808 return 0;
2809 if (!c)
2810 return 1;
2811
2812 i = periods = preceding_space_or_period = 0;
4dc42c6c
JS
2813
2814segment_start:
2815 switch (*path) {
2816 case 'a': case 'A': /* AUX */
2817 if (((c = path[++i]) != 'u' && c != 'U') ||
2818 ((c = path[++i]) != 'x' && c != 'X')) {
2819not_a_reserved_name:
2820 path += i;
2821 continue;
2822 }
2823 break;
b6852e19
JS
2824 case 'c': case 'C':
2825 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
4dc42c6c
JS
2826 if ((c = path[++i]) != 'o' && c != 'O')
2827 goto not_a_reserved_name;
2828 c = path[++i];
b6852e19
JS
2829 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2830 c = path[++i];
2831 if (c < '1' || c > '9')
4dc42c6c
JS
2832 goto not_a_reserved_name;
2833 } else if (c == 'n' || c == 'N') { /* CON */
2834 c = path[i + 1];
2835 if ((c == 'i' || c == 'I') &&
2836 ((c = path[i + 2]) == 'n' ||
2837 c == 'N') &&
2838 path[i + 3] == '$')
2839 i += 3; /* CONIN$ */
2840 else if ((c == 'o' || c == 'O') &&
2841 ((c = path[i + 2]) == 'u' ||
2842 c == 'U') &&
2843 ((c = path[i + 3]) == 't' ||
2844 c == 'T') &&
2845 path[i + 4] == '$')
2846 i += 4; /* CONOUT$ */
2847 } else
2848 goto not_a_reserved_name;
2849 break;
2850 case 'l': case 'L': /* LPT<N> */
2851 if (((c = path[++i]) != 'p' && c != 'P') ||
2852 ((c = path[++i]) != 't' && c != 'T') ||
2853 !isdigit(path[++i]))
2854 goto not_a_reserved_name;
2855 break;
2856 case 'n': case 'N': /* NUL */
2857 if (((c = path[++i]) != 'u' && c != 'U') ||
2858 ((c = path[++i]) != 'l' && c != 'L') ||
2859 (allow_literal_nul &&
2860 !path[i + 1] && p == path))
2861 goto not_a_reserved_name;
2862 break;
2863 case 'p': case 'P': /* PRN */
2864 if (((c = path[++i]) != 'r' && c != 'R') ||
2865 ((c = path[++i]) != 'n' && c != 'N'))
2866 goto not_a_reserved_name;
2867 break;
2868 default:
2869 continue;
2870 }
2871
2872 /*
2873 * So far, this looks like a reserved name. Let's see
2874 * whether it actually is one: trailing spaces, a file
2875 * extension, or an NTFS Alternate Data Stream do not
2876 * matter, the name is still reserved if any of those
2877 * follow immediately after the actual name.
2878 */
2879 i++;
2880 if (path[i] == ' ') {
2881 preceding_space_or_period = 1;
2882 while (path[++i] == ' ')
2883 ; /* skip all spaces */
2884 }
2885
2886 c = path[i];
9fd512c8 2887 if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
4dc42c6c
JS
2888 goto not_a_reserved_name;
2889
2890 /* contains reserved name */
2891 return 0;
d2c84dad
JS
2892 case '.':
2893 periods++;
2894 /* fallthru */
2895 case ' ':
2896 preceding_space_or_period = 1;
2897 i++;
2898 continue;
817ddd64
JS
2899 case ':': /* DOS drive prefix was already skipped */
2900 case '<': case '>': case '"': case '|': case '?': case '*':
2901 /* illegal character */
2902 return 0;
2903 default:
2904 if (c > '\0' && c < '\x20')
2905 /* illegal character */
2906 return 0;
d2c84dad
JS
2907 }
2908 preceding_space_or_period = 0;
2909 i++;
2910 }
2911}
2912
396ff754 2913#if !defined(_MSC_VER)
5901dc66
KB
2914/*
2915 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2916 * mingw startup code, see init.c in mingw runtime).
2917 */
2918int _CRT_glob = 0;
396ff754 2919#endif
3f046148 2920
0767172b 2921static NORETURN void die_startup(void)
3f046148
KB
2922{
2923 fputs("fatal: not enough memory for initialization", stderr);
2924 exit(128);
2925}
2926
6f1c189c
KB
2927static void *malloc_startup(size_t size)
2928{
2929 void *result = malloc(size);
2930 if (!result)
2931 die_startup();
2932 return result;
2933}
2934
2935static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2936{
2937 len = xwcstoutf(buffer, wcs, len) + 1;
2938 return memcpy(malloc_startup(len), buffer, len);
2939}
2940
3f944424
JS
2941static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2942 DWORD desired_access, DWORD flags)
2943{
2944 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2945 wchar_t buf[MAX_PATH];
2946 DWORD max = ARRAY_SIZE(buf);
2947 HANDLE handle;
2948 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2949
2950 if (!ret || ret >= max)
2951 return;
2952
2953 /* make sure this does not leak into child processes */
2954 SetEnvironmentVariableW(key, NULL);
2955 if (!wcscmp(buf, L"off")) {
2956 close(fd);
2957 handle = GetStdHandle(std_id);
2958 if (handle != INVALID_HANDLE_VALUE)
2959 CloseHandle(handle);
2960 return;
2961 }
1a172e4a
JS
2962 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2963 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2964 if (handle == INVALID_HANDLE_VALUE) {
2965 close(fd);
2966 handle = GetStdHandle(std_id);
2967 if (handle != INVALID_HANDLE_VALUE)
2968 CloseHandle(handle);
2969 } else {
2970 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2971 SetStdHandle(std_id, handle);
2972 dup2(new_fd, fd);
2973 /* do *not* close the new_fd: that would close stdout */
2974 }
2975 return;
2976 }
3f944424
JS
2977 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2978 flags, NULL);
2979 if (handle != INVALID_HANDLE_VALUE) {
2980 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2981 SetStdHandle(std_id, handle);
2982 dup2(new_fd, fd);
2983 close(new_fd);
2984 }
2985}
2986
2987static void maybe_redirect_std_handles(void)
2988{
2989 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2990 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2991 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2992 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2993 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2994 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2995}
2996
dce7d295
JH
2997#ifdef _MSC_VER
2998#ifdef _DEBUG
2999#include <crtdbg.h>
3000#endif
3001#endif
3002
396ff754
JS
3003/*
3004 * We implement wmain() and compile with -municode, which would
3005 * normally ignore main(), but we call the latter from the former
3006 * so that we can handle non-ASCII command-line parameters
3007 * appropriately.
3008 *
3009 * To be more compatible with the core git code, we convert
3010 * argv into UTF8 and pass them directly to main().
3011 */
3012int wmain(int argc, const wchar_t **wargv)
13f1df43 3013{
396ff754
JS
3014 int i, maxlen, exit_status;
3015 char *buffer, **save;
3016 const char **argv;
3f046148 3017
a0897249
JH
3018 trace2_initialize_clock();
3019
556702f8 3020#ifdef _MSC_VER
f6a63937
JS
3021#ifdef _DEBUG
3022 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
3023#endif
3024
556702f8
JH
3025#ifdef USE_MSVC_CRTDBG
3026 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
3027#endif
3028#endif
3029
3f944424
JS
3030 maybe_redirect_std_handles();
3031
3f046148 3032 /* determine size of argv and environ conversion buffer */
86e25458 3033 maxlen = wcslen(wargv[0]);
3f046148
KB
3034 for (i = 1; i < argc; i++)
3035 maxlen = max(maxlen, wcslen(wargv[i]));
3036
3037 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3038 maxlen = 3 * maxlen + 1;
6f1c189c 3039 buffer = malloc_startup(maxlen);
3f046148 3040
396ff754
JS
3041 /*
3042 * Create a UTF-8 version of w_argv. Also create a "save" copy
3043 * to remember all the string pointers because parse_options()
3044 * will remove claimed items from the argv that we pass down.
3045 */
3046 ALLOC_ARRAY(argv, argc + 1);
3047 ALLOC_ARRAY(save, argc + 1);
86e25458 3048 for (i = 0; i < argc; i++)
396ff754
JS
3049 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
3050 argv[i] = save[i] = NULL;
3f046148 3051 free(buffer);
13f1df43 3052
6dc71543 3053 /* fix Windows specific environment settings */
02e6edc0 3054 setup_windows_environment();
baea068d 3055
0e218f91
JS
3056 unset_environment_variables = xstrdup("PERL5LIB");
3057
13f1df43
KB
3058 /* initialize critical section for waitpid pinfo_t list */
3059 InitializeCriticalSection(&pinfo_cs);
3060
3061 /* set up default file mode and file modes for stdin/out/err */
3062 _fmode = _O_BINARY;
3063 _setmode(_fileno(stdin), _O_BINARY);
3064 _setmode(_fileno(stdout), _O_BINARY);
3065 _setmode(_fileno(stderr), _O_BINARY);
eac14f89
KB
3066
3067 /* initialize Unicode console */
3068 winansi_init();
396ff754
JS
3069
3070 /* invoke the real main() using our utf8 version of argv. */
3071 exit_status = main(argc, argv);
3072
3073 for (i = 0; i < argc; i++)
3074 free(save[i]);
3075 free(save);
3076 free(argv);
3077
3078 return exit_status;
13f1df43 3079}
7b6aff06
NTND
3080
3081int uname(struct utsname *buf)
3082{
d62c89af 3083 unsigned v = (unsigned)GetVersion();
7b6aff06 3084 memset(buf, 0, sizeof(*buf));
5096d490
JK
3085 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3086 xsnprintf(buf->release, sizeof(buf->release),
3087 "%u.%u", v & 0xff, (v >> 8) & 0xff);
7b6aff06 3088 /* assuming NT variants only.. */
5096d490
JK
3089 xsnprintf(buf->version, sizeof(buf->version),
3090 "%u", (v >> 16) & 0x7fff);
7b6aff06
NTND
3091 return 0;
3092}