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