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