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