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