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