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