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