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