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