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