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