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