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