]> git.ipfire.org Git - thirdparty/git.git/blame - compat/mingw.c
Sync with 2.22.2
[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);
7d8b6769
JS
1123 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1124 *p != '?' && *p != '*' && *p != '~')
9e9da23c
JS
1125 continue;
1126 if (!buf.len)
1127 strbuf_addch(&buf, '"');
1128 if (p != p2)
1129 strbuf_add(&buf, p2, p - p2);
7d8b6769 1130 if (*p == '\\' || *p == '"')
9e9da23c
JS
1131 strbuf_addch(&buf, '\\');
1132 p2 = p;
1133 }
1134
1135 if (p == arg)
1136 strbuf_addch(&buf, '"');
1137 else if (!buf.len)
1138 return arg;
1139 else
04522edb 1140 strbuf_add(&buf, p2, p - p2);
9e9da23c
JS
1141
1142 strbuf_addch(&buf, '"');
1143 return strbuf_detach(&buf, 0);
1144}
1145
f1a4dfb8
JS
1146static const char *parse_interpreter(const char *cmd)
1147{
1148 static char buf[100];
1149 char *p, *opt;
1150 int n, fd;
1151
1152 /* don't even try a .exe */
1153 n = strlen(cmd);
1154 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1155 return NULL;
1156
1157 fd = open(cmd, O_RDONLY);
1158 if (fd < 0)
1159 return NULL;
1160 n = read(fd, buf, sizeof(buf)-1);
1161 close(fd);
1162 if (n < 4) /* at least '#!/x' and not error */
1163 return NULL;
1164
1165 if (buf[0] != '#' || buf[1] != '!')
1166 return NULL;
1167 buf[n] = '\0';
bedc4279
PH
1168 p = buf + strcspn(buf, "\r\n");
1169 if (!*p)
f1a4dfb8
JS
1170 return NULL;
1171
1172 *p = '\0';
1173 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1174 return NULL;
1175 /* strip options */
1176 if ((opt = strchr(p+1, ' ')))
1177 *opt = '\0';
1178 return p+1;
1179}
1180
f1a4dfb8
JS
1181/*
1182 * exe_only means that we only want to detect .exe files, but not scripts
1183 * (which do not have an extension)
1184 */
e0ca1ca2
RS
1185static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1186 int isexe, int exe_only)
f1a4dfb8
JS
1187{
1188 char path[MAX_PATH];
e0ca1ca2 1189 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
f1a4dfb8
JS
1190
1191 if (!isexe && access(path, F_OK) == 0)
1192 return xstrdup(path);
1193 path[strlen(path)-4] = '\0';
1194 if ((!exe_only || isexe) && access(path, F_OK) == 0)
fe77b695
ER
1195 if (!(GetFileAttributes(path) & FILE_ATTRIBUTE_DIRECTORY))
1196 return xstrdup(path);
f1a4dfb8
JS
1197 return NULL;
1198}
1199
1200/*
22e5e58a 1201 * Determines the absolute path of cmd using the split path in path.
f1a4dfb8
JS
1202 * If cmd contains a slash or backslash, no lookup is performed.
1203 */
e0ca1ca2 1204static char *path_lookup(const char *cmd, int exe_only)
f1a4dfb8 1205{
e0ca1ca2 1206 const char *path;
f1a4dfb8
JS
1207 char *prog = NULL;
1208 int len = strlen(cmd);
1209 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1210
1211 if (strchr(cmd, '/') || strchr(cmd, '\\'))
e0ca1ca2
RS
1212 return xstrdup(cmd);
1213
1214 path = mingw_getenv("PATH");
1215 if (!path)
1216 return NULL;
f1a4dfb8 1217
e0ca1ca2
RS
1218 while (!prog) {
1219 const char *sep = strchrnul(path, ';');
1220 int dirlen = sep - path;
1221 if (dirlen)
1222 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1223 if (!*sep)
1224 break;
1225 path = sep + 1;
1226 }
f1a4dfb8
JS
1227
1228 return prog;
1229}
1230
fe21c6b2
JS
1231static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1232{
1233 while (*s && *s != c)
1234 s++;
1235 return s;
1236}
1237
1238/* Compare only keys */
1239static int wenvcmp(const void *a, const void *b)
1240{
1241 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1242 size_t p_len, q_len;
1243
1244 /* Find the keys */
1245 p_len = wcschrnul(p, L'=') - p;
1246 q_len = wcschrnul(q, L'=') - q;
f279242d 1247
fe21c6b2
JS
1248 /* If the length differs, include the shorter key's NUL */
1249 if (p_len < q_len)
1250 p_len++;
1251 else if (p_len > q_len)
1252 p_len = q_len + 1;
1253
1254 return _wcsnicmp(p, q, p_len);
1255}
f279242d 1256
fe21c6b2
JS
1257/* We need a stable sort to convert the environment between UTF-16 <-> UTF-8 */
1258#ifndef INTERNAL_QSORT
1259#include "qsort.c"
1260#endif
77734da2 1261
df0e998c 1262/*
fe21c6b2
JS
1263 * Build an environment block combining the inherited environment
1264 * merged with the given list of settings.
1265 *
1266 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1267 * Values of the form "KEY" in deltaenv delete inherited values.
1268 *
1269 * Multiple entries in deltaenv for the same key are explicitly allowed.
1270 *
1271 * We return a contiguous block of UNICODE strings with a final trailing
1272 * zero word.
df0e998c 1273 */
77734da2 1274static wchar_t *make_environment_block(char **deltaenv)
7e5d7768 1275{
fe21c6b2
JS
1276 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1277 size_t wlen, s, delta_size, size;
df0e998c 1278
fe21c6b2
JS
1279 wchar_t **array = NULL;
1280 size_t alloc = 0, nr = 0, i;
df0e998c 1281
fe21c6b2
JS
1282 size = 1; /* for extra NUL at the end */
1283
1284 /* If there is no deltaenv to apply, simply return a copy. */
1285 if (!deltaenv || !*deltaenv) {
1286 for (p = wenv; p && *p; ) {
1287 size_t s = wcslen(p) + 1;
1288 size += s;
1289 p += s;
1290 }
77734da2 1291
fe21c6b2
JS
1292 ALLOC_ARRAY(result, size);
1293 memcpy(result, wenv, size * sizeof(*wenv));
1294 FreeEnvironmentStringsW(wenv);
1295 return result;
1296 }
77734da2 1297
fe21c6b2
JS
1298 /*
1299 * If there is a deltaenv, let's accumulate all keys into `array`,
1300 * sort them using the stable git_qsort() and then copy, skipping
1301 * duplicate keys
1302 */
1303 for (p = wenv; p && *p; ) {
1304 ALLOC_GROW(array, nr + 1, alloc);
1305 s = wcslen(p) + 1;
1306 array[nr++] = p;
1307 p += s;
1308 size += s;
df0e998c 1309 }
fe21c6b2
JS
1310
1311 /* (over-)assess size needed for wchar version of deltaenv */
1312 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1313 delta_size += strlen(deltaenv[i]) * 2 + 1;
1314 ALLOC_ARRAY(wdeltaenv, delta_size);
1315
1316 /* convert the deltaenv, appending to array */
1317 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1318 ALLOC_GROW(array, nr + 1, alloc);
1319 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1320 array[nr++] = p;
1321 p += wlen + 1;
1322 }
df0e998c 1323
fe21c6b2
JS
1324 git_qsort(array, nr, sizeof(*array), wenvcmp);
1325 ALLOC_ARRAY(result, size + delta_size);
df0e998c 1326
fe21c6b2
JS
1327 for (p = result, i = 0; i < nr; i++) {
1328 /* Skip any duplicate keys; last one wins */
1329 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1330 i++;
77734da2 1331
fe21c6b2
JS
1332 /* Skip "to delete" entry */
1333 if (!wcschr(array[i], L'='))
1334 continue;
77734da2 1335
fe21c6b2
JS
1336 size = wcslen(array[i]) + 1;
1337 memcpy(p, array[i], size * sizeof(*p));
1338 p += size;
df0e998c 1339 }
fe21c6b2
JS
1340 *p = L'\0';
1341
1342 free(array);
1343 free(wdeltaenv);
1344 FreeEnvironmentStringsW(wenv);
1345 return result;
7e5d7768
JS
1346}
1347
0e218f91
JS
1348static void do_unset_environment_variables(void)
1349{
1350 static int done;
1351 char *p = unset_environment_variables;
1352
1353 if (done || !p)
1354 return;
1355 done = 1;
1356
1357 for (;;) {
1358 char *comma = strchr(p, ',');
1359
1360 if (comma)
1361 *comma = '\0';
1362 unsetenv(p);
1363 if (!comma)
1364 break;
1365 p = comma + 1;
1366 }
1367}
1368
52de4db5
EFL
1369struct pinfo_t {
1370 struct pinfo_t *next;
1371 pid_t pid;
1372 HANDLE proc;
657b35f4
RJ
1373};
1374static struct pinfo_t *pinfo = NULL;
52de4db5
EFL
1375CRITICAL_SECTION pinfo_cs;
1376
9e9da23c
JS
1377/* Used to match and chomp off path components */
1378static inline int match_last_path_component(const char *path, size_t *len,
1379 const char *component)
1380{
1381 size_t component_len = strlen(component);
1382 if (*len < component_len + 1 ||
1383 !is_dir_sep(path[*len - component_len - 1]) ||
1384 fspathncmp(path + *len - component_len, component, component_len))
1385 return 0;
1386 *len -= component_len + 1;
1387 /* chomp off repeated dir separators */
1388 while (*len > 0 && is_dir_sep(path[*len - 1]))
1389 (*len)--;
1390 return 1;
1391}
1392
1393static int is_msys2_sh(const char *cmd)
1394{
e2ba3d6f
JS
1395 if (!cmd)
1396 return 0;
1397
1398 if (!strcmp(cmd, "sh")) {
9e9da23c
JS
1399 static int ret = -1;
1400 char *p;
1401
1402 if (ret >= 0)
1403 return ret;
1404
1405 p = path_lookup(cmd, 0);
1406 if (!p)
1407 ret = 0;
1408 else {
1409 size_t len = strlen(p);
1410
1411 ret = match_last_path_component(p, &len, "sh.exe") &&
1412 match_last_path_component(p, &len, "bin") &&
1413 match_last_path_component(p, &len, "usr");
1414 free(p);
1415 }
1416 return ret;
1417 }
e2ba3d6f
JS
1418
1419 if (ends_with(cmd, "\\sh.exe")) {
1420 static char *sh;
1421
1422 if (!sh)
1423 sh = path_lookup("sh", 0);
1424
1425 return !fspathcmp(cmd, sh);
1426 }
1427
9e9da23c
JS
1428 return 0;
1429}
1430
77734da2 1431static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1432 const char *dir,
75301f90 1433 int prepend_cmd, int fhin, int fhout, int fherr)
7e5d7768 1434{
99c3c76d 1435 STARTUPINFOW si;
7e5d7768 1436 PROCESS_INFORMATION pi;
7eb2619c
KB
1437 struct strbuf args;
1438 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1439 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
7e5d7768 1440 BOOL ret;
0e218f91 1441 HANDLE cons;
9e9da23c 1442 const char *(*quote_arg)(const char *arg) =
49f7a76d
JS
1443 is_msys2_sh(cmd ? cmd : *argv) ?
1444 quote_arg_msys2 : quote_arg_msvc;
0e218f91
JS
1445
1446 do_unset_environment_variables();
7e5d7768
JS
1447
1448 /* Determine whether or not we are associated to a console */
94238859 1449 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
7e5d7768
JS
1450 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1451 FILE_ATTRIBUTE_NORMAL, NULL);
1452 if (cons == INVALID_HANDLE_VALUE) {
1453 /* There is no console associated with this process.
1454 * Since the child is a console process, Windows
1455 * would normally create a console window. But
1456 * since we'll be redirecting std streams, we do
1457 * not need the console.
19fb896f
AG
1458 * It is necessary to use DETACHED_PROCESS
1459 * instead of CREATE_NO_WINDOW to make ssh
1460 * recognize that it has no console.
7e5d7768 1461 */
7eb2619c 1462 flags |= DETACHED_PROCESS;
7e5d7768
JS
1463 } else {
1464 /* There is already a console. If we specified
19fb896f 1465 * DETACHED_PROCESS here, too, Windows would
7e5d7768 1466 * disassociate the child from the console.
19fb896f 1467 * The same is true for CREATE_NO_WINDOW.
7e5d7768
JS
1468 * Go figure!
1469 */
7e5d7768
JS
1470 CloseHandle(cons);
1471 }
1472 memset(&si, 0, sizeof(si));
1473 si.cb = sizeof(si);
1474 si.dwFlags = STARTF_USESTDHANDLES;
eac14f89
KB
1475 si.hStdInput = winansi_get_osfhandle(fhin);
1476 si.hStdOutput = winansi_get_osfhandle(fhout);
1477 si.hStdError = winansi_get_osfhandle(fherr);
7e5d7768 1478
eb7c7863
JS
1479 if (*argv && !strcmp(cmd, *argv))
1480 wcmd[0] = L'\0';
1481 else if (xutftowcs_path(wcmd, cmd) < 0)
99c3c76d
KB
1482 return -1;
1483 if (dir && xutftowcs_path(wdir, dir) < 0)
1484 return -1;
1485
7e5d7768
JS
1486 /* concatenate argv, quoting args as we go */
1487 strbuf_init(&args, 0);
1488 if (prepend_cmd) {
1489 char *quoted = (char *)quote_arg(cmd);
1490 strbuf_addstr(&args, quoted);
1491 if (quoted != cmd)
1492 free(quoted);
1493 }
1494 for (; *argv; argv++) {
1495 char *quoted = (char *)quote_arg(*argv);
1496 if (*args.buf)
1497 strbuf_addch(&args, ' ');
1498 strbuf_addstr(&args, quoted);
1499 if (quoted != *argv)
1500 free(quoted);
1501 }
1502
8d5b3325 1503 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
99c3c76d
KB
1504 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1505 strbuf_release(&args);
1506
77734da2 1507 wenvblk = make_environment_block(deltaenv);
7e5d7768
JS
1508
1509 memset(&pi, 0, sizeof(pi));
eb7c7863
JS
1510 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL, TRUE,
1511 flags, wenvblk, dir ? wdir : NULL, &si, &pi);
7e5d7768 1512
7eb2619c 1513 free(wenvblk);
99c3c76d 1514 free(wargs);
7e5d7768
JS
1515
1516 if (!ret) {
1517 errno = ENOENT;
1518 return -1;
1519 }
1520 CloseHandle(pi.hThread);
52de4db5
EFL
1521
1522 /*
1523 * The process ID is the human-readable identifier of the process
1524 * that we want to present in log and error messages. The handle
1525 * is not useful for this purpose. But we cannot close it, either,
1526 * because it is not possible to turn a process ID into a process
1527 * handle after the process terminated.
1528 * Keep the handle in a list for waitpid.
1529 */
1530 EnterCriticalSection(&pinfo_cs);
1531 {
1532 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1533 info->pid = pi.dwProcessId;
1534 info->proc = pi.hProcess;
1535 info->next = pinfo;
1536 pinfo = info;
1537 }
1538 LeaveCriticalSection(&pinfo_cs);
1539
1540 return (pid_t)pi.dwProcessId;
7e5d7768
JS
1541}
1542
3e66e47b 1543static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
75301f90 1544{
77734da2 1545 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
75301f90
JS
1546}
1547
77734da2 1548pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1549 const char *dir,
75301f90 1550 int fhin, int fhout, int fherr)
7e5d7768
JS
1551{
1552 pid_t pid;
e0ca1ca2 1553 char *prog = path_lookup(cmd, 0);
7e5d7768
JS
1554
1555 if (!prog) {
1556 errno = ENOENT;
1557 pid = -1;
1558 }
1559 else {
1560 const char *interpr = parse_interpreter(prog);
1561
1562 if (interpr) {
1563 const char *argv0 = argv[0];
e0ca1ca2 1564 char *iprog = path_lookup(interpr, 1);
7e5d7768
JS
1565 argv[0] = prog;
1566 if (!iprog) {
1567 errno = ENOENT;
1568 pid = -1;
1569 }
1570 else {
77734da2 1571 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
75301f90 1572 fhin, fhout, fherr);
7e5d7768
JS
1573 free(iprog);
1574 }
1575 argv[0] = argv0;
1576 }
1577 else
77734da2 1578 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
75301f90 1579 fhin, fhout, fherr);
7e5d7768
JS
1580 free(prog);
1581 }
7e5d7768
JS
1582 return pid;
1583}
1584
3e66e47b 1585static int try_shell_exec(const char *cmd, char *const *argv)
f1a4dfb8
JS
1586{
1587 const char *interpr = parse_interpreter(cmd);
f1a4dfb8
JS
1588 char *prog;
1589 int pid = 0;
1590
1591 if (!interpr)
1592 return 0;
e0ca1ca2 1593 prog = path_lookup(interpr, 1);
f1a4dfb8 1594 if (prog) {
ee4512ed 1595 int exec_id;
f1a4dfb8 1596 int argc = 0;
12fb9bd8
JH
1597#ifndef _MSC_VER
1598 const
1599#endif
1600 char **argv2;
f1a4dfb8 1601 while (argv[argc]) argc++;
b32fa95f 1602 ALLOC_ARRAY(argv2, argc + 1);
7e5d7768
JS
1603 argv2[0] = (char *)cmd; /* full path to the script file */
1604 memcpy(&argv2[1], &argv[1], sizeof(*argv) * argc);
ee4512ed 1605 exec_id = trace2_exec(prog, argv2);
3e66e47b 1606 pid = mingw_spawnv(prog, argv2, 1);
f1a4dfb8
JS
1607 if (pid >= 0) {
1608 int status;
1609 if (waitpid(pid, &status, 0) < 0)
1610 status = 255;
ee4512ed 1611 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1612 exit(status);
1613 }
ee4512ed 1614 trace2_exec_result(exec_id, -1);
f1a4dfb8
JS
1615 pid = 1; /* indicate that we tried but failed */
1616 free(prog);
1617 free(argv2);
1618 }
f1a4dfb8
JS
1619 return pid;
1620}
1621
3e66e47b 1622int mingw_execv(const char *cmd, char *const *argv)
f1a4dfb8
JS
1623{
1624 /* check if git_command is a shell script */
3e66e47b 1625 if (!try_shell_exec(cmd, argv)) {
f1a4dfb8 1626 int pid, status;
ee4512ed 1627 int exec_id;
f1a4dfb8 1628
ee4512ed 1629 exec_id = trace2_exec(cmd, (const char **)argv);
3e66e47b 1630 pid = mingw_spawnv(cmd, (const char **)argv, 0);
ee4512ed
JH
1631 if (pid < 0) {
1632 trace2_exec_result(exec_id, -1);
570f1e6e 1633 return -1;
ee4512ed 1634 }
f1a4dfb8
JS
1635 if (waitpid(pid, &status, 0) < 0)
1636 status = 255;
ee4512ed 1637 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1638 exit(status);
1639 }
570f1e6e 1640 return -1;
f1a4dfb8
JS
1641}
1642
1696d723 1643int mingw_execvp(const char *cmd, char *const *argv)
f1a4dfb8 1644{
e0ca1ca2 1645 char *prog = path_lookup(cmd, 0);
f1a4dfb8
JS
1646
1647 if (prog) {
3e66e47b 1648 mingw_execv(prog, argv);
f1a4dfb8
JS
1649 free(prog);
1650 } else
1651 errno = ENOENT;
1652
1696d723 1653 return -1;
f1a4dfb8
JS
1654}
1655
82fc07b7
EFL
1656int mingw_kill(pid_t pid, int sig)
1657{
1658 if (pid > 0 && sig == SIGTERM) {
1659 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1660
1661 if (TerminateProcess(h, -1)) {
1662 CloseHandle(h);
1663 return 0;
1664 }
1665
1666 errno = err_win_to_posix(GetLastError());
1667 CloseHandle(h);
1668 return -1;
64a99eb4
NTND
1669 } else if (pid > 0 && sig == 0) {
1670 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1671 if (h) {
1672 CloseHandle(h);
1673 return 0;
1674 }
82fc07b7
EFL
1675 }
1676
1677 errno = EINVAL;
1678 return -1;
1679}
1680
343ff06d 1681/*
fe21c6b2
JS
1682 * UTF-8 versions of getenv(), putenv() and unsetenv().
1683 * Internally, they use the CRT's stock UNICODE routines
1684 * to avoid data loss.
343ff06d 1685 */
fe21c6b2 1686char *mingw_getenv(const char *name)
343ff06d 1687{
ca1b4116 1688#define GETENV_MAX_RETAIN 64
fe21c6b2
JS
1689 static char *values[GETENV_MAX_RETAIN];
1690 static int value_counter;
1691 int len_key, len_value;
1692 wchar_t *w_key;
1693 char *value;
1694 wchar_t w_value[32768];
343ff06d 1695
fe21c6b2
JS
1696 if (!name || !*name)
1697 return NULL;
ba26f296 1698
fe21c6b2
JS
1699 len_key = strlen(name) + 1;
1700 /* We cannot use xcalloc() here because that uses getenv() itself */
1701 w_key = calloc(len_key, sizeof(wchar_t));
1702 if (!w_key)
1703 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1704 xutftowcs(w_key, name, len_key);
1705 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1706 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1707 free(w_key);
1708 return NULL;
ba26f296 1709 }
fe21c6b2
JS
1710 free(w_key);
1711
1712 len_value = len_value * 3 + 1;
1713 /* We cannot use xcalloc() here because that uses getenv() itself */
1714 value = calloc(len_value, sizeof(char));
1715 if (!value)
1716 die("Out of memory, (tried to allocate %u bytes)", len_value);
1717 xwcstoutf(value, w_value, len_value);
1718
1719 /*
1720 * We return `value` which is an allocated value and the caller is NOT
1721 * expecting to have to free it, so we keep a round-robin array,
1722 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1723 */
1724 free(values[value_counter]);
1725 values[value_counter++] = value;
1726 if (value_counter >= ARRAY_SIZE(values))
1727 value_counter = 0;
1728
1729 return value;
ba26f296
JS
1730}
1731
fe21c6b2 1732int mingw_putenv(const char *namevalue)
ba26f296 1733{
fe21c6b2
JS
1734 int size;
1735 wchar_t *wide, *equal;
1736 BOOL result;
ba26f296 1737
fe21c6b2
JS
1738 if (!namevalue || !*namevalue)
1739 return 0;
ba26f296 1740
fe21c6b2
JS
1741 size = strlen(namevalue) * 2 + 1;
1742 wide = calloc(size, sizeof(wchar_t));
1743 if (!wide)
1744 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1745 xutftowcs(wide, namevalue, size);
1746 equal = wcschr(wide, L'=');
1747 if (!equal)
1748 result = SetEnvironmentVariableW(wide, NULL);
1749 else {
1750 *equal = L'\0';
1751 result = SetEnvironmentVariableW(wide, equal + 1);
ba26f296 1752 }
fe21c6b2 1753 free(wide);
2affea41 1754
fe21c6b2
JS
1755 if (!result)
1756 errno = err_win_to_posix(GetLastError());
df599e96 1757
fe21c6b2 1758 return result ? 0 : -1;
06bc4b79
JS
1759}
1760
b7cc9f82 1761static void ensure_socket_initialization(void)
746fb857
JS
1762{
1763 WSADATA wsa;
b7cc9f82
MS
1764 static int initialized = 0;
1765
1766 if (initialized)
1767 return;
746fb857
JS
1768
1769 if (WSAStartup(MAKEWORD(2,2), &wsa))
1770 die("unable to initialize winsock subsystem, error %d",
1771 WSAGetLastError());
fe3b2b7b 1772
b9f0193b 1773 atexit((void(*)(void)) WSACleanup);
b7cc9f82
MS
1774 initialized = 1;
1775}
1776
13d24b01
PT
1777#undef gethostname
1778int mingw_gethostname(char *name, int namelen)
1779{
1780 ensure_socket_initialization();
1781 return gethostname(name, namelen);
1782}
1783
b7cc9f82
MS
1784#undef gethostbyname
1785struct hostent *mingw_gethostbyname(const char *host)
1786{
1787 ensure_socket_initialization();
746fb857
JS
1788 return gethostbyname(host);
1789}
1790
b9f0193b 1791#undef getaddrinfo
fe3b2b7b
MS
1792int mingw_getaddrinfo(const char *node, const char *service,
1793 const struct addrinfo *hints, struct addrinfo **res)
1794{
1795 ensure_socket_initialization();
b9f0193b 1796 return getaddrinfo(node, service, hints, res);
fe3b2b7b
MS
1797}
1798
746fb857
JS
1799int mingw_socket(int domain, int type, int protocol)
1800{
1801 int sockfd;
772991af
MP
1802 SOCKET s;
1803
1804 ensure_socket_initialization();
1805 s = WSASocket(domain, type, protocol, NULL, 0, 0);
746fb857
JS
1806 if (s == INVALID_SOCKET) {
1807 /*
1808 * WSAGetLastError() values are regular BSD error codes
1809 * biased by WSABASEERR.
1810 * However, strerror() does not know about networking
1811 * specific errors, which are values beginning at 38 or so.
1812 * Therefore, we choose to leave the biased error code
1813 * in errno so that _if_ someone looks up the code somewhere,
1814 * then it is at least the number that are usually listed.
1815 */
1816 errno = WSAGetLastError();
1817 return -1;
1818 }
1819 /* convert into a file descriptor */
1820 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
1821 closesocket(s);
1822 return error("unable to make a socket file descriptor: %s",
1823 strerror(errno));
1824 }
1825 return sockfd;
1826}
1827
1828#undef connect
1829int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
1830{
1831 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1832 return connect(s, sa, sz);
1833}
1834
772991af
MP
1835#undef bind
1836int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
1837{
1838 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1839 return bind(s, sa, sz);
1840}
1841
1842#undef setsockopt
1843int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
1844{
1845 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1846 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
1847}
1848
a7941795
JS
1849#undef shutdown
1850int mingw_shutdown(int sockfd, int how)
1851{
1852 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1853 return shutdown(s, how);
1854}
1855
772991af
MP
1856#undef listen
1857int mingw_listen(int sockfd, int backlog)
1858{
1859 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
1860 return listen(s, backlog);
1861}
1862
1863#undef accept
1864int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
1865{
1866 int sockfd2;
1867
1868 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
1869 SOCKET s2 = accept(s1, sa, sz);
1870
1871 /* convert into a file descriptor */
1872 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
1873 int err = errno;
1874 closesocket(s2);
1875 return error("unable to make a socket file descriptor: %s",
1876 strerror(err));
1877 }
1878 return sockfd2;
1879}
1880
ea9e98c3
JS
1881#undef rename
1882int mingw_rename(const char *pold, const char *pnew)
1883{
6ac6f878
JS
1884 DWORD attrs, gle;
1885 int tries = 0;
85faec9d
KB
1886 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
1887 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
1888 return -1;
632f7017 1889
ea9e98c3
JS
1890 /*
1891 * Try native rename() first to get errno right.
1892 * It is based on MoveFile(), which cannot overwrite existing files.
1893 */
85faec9d 1894 if (!_wrename(wpold, wpnew))
ea9e98c3
JS
1895 return 0;
1896 if (errno != EEXIST)
1897 return -1;
6ac6f878 1898repeat:
85faec9d 1899 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
ea9e98c3
JS
1900 return 0;
1901 /* TODO: translate more errors */
6ac6f878
JS
1902 gle = GetLastError();
1903 if (gle == ERROR_ACCESS_DENIED &&
85faec9d 1904 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
632f7017 1905 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
4426fb51 1906 DWORD attrsold = GetFileAttributesW(wpold);
1907 if (attrsold == INVALID_FILE_ATTRIBUTES ||
1908 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
1909 errno = EISDIR;
1910 else if (!_wrmdir(wpnew))
1911 goto repeat;
ea9e98c3
JS
1912 return -1;
1913 }
632f7017 1914 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
85faec9d
KB
1915 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
1916 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
632f7017 1917 return 0;
6ac6f878 1918 gle = GetLastError();
632f7017 1919 /* revert file attributes on failure */
85faec9d 1920 SetFileAttributesW(wpnew, attrs);
632f7017 1921 }
ea9e98c3 1922 }
6ac6f878
JS
1923 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
1924 /*
1925 * We assume that some other process had the source or
1926 * destination file open at the wrong moment and retry.
1927 * In order to give the other process a higher chance to
1928 * complete its operation, we give up our time slice now.
1929 * If we have to retry again, we do sleep a bit.
1930 */
1931 Sleep(delay[tries]);
1932 tries++;
1933 goto repeat;
1934 }
c9b78400
HV
1935 if (gle == ERROR_ACCESS_DENIED &&
1936 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
1937 "Should I try again?", pold, pnew))
1938 goto repeat;
1939
ea9e98c3
JS
1940 errno = EACCES;
1941 return -1;
1942}
1943
b1b95204
RJ
1944/*
1945 * Note that this doesn't return the actual pagesize, but
1946 * the allocation granularity. If future Windows specific git code
1947 * needs the real getpagesize function, we need to find another solution.
1948 */
1949int mingw_getpagesize(void)
1950{
1951 SYSTEM_INFO si;
1952 GetSystemInfo(&si);
1953 return si.dwAllocationGranularity;
1954}
1955
564be791
JS
1956/* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
1957enum EXTENDED_NAME_FORMAT {
1958 NameDisplay = 3,
1959 NameUserPrincipal = 8
1960};
1961
1962static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
1963{
1964 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
1965 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
1966 static wchar_t wbuffer[1024];
1967 DWORD len;
1968
1969 if (!INIT_PROC_ADDR(GetUserNameExW))
1970 return NULL;
1971
1972 len = ARRAY_SIZE(wbuffer);
1973 if (GetUserNameExW(type, wbuffer, &len)) {
1974 char *converted = xmalloc((len *= 3));
1975 if (xwcstoutf(converted, wbuffer, len) >= 0)
1976 return converted;
1977 free(converted);
1978 }
1979
1980 return NULL;
1981}
1982
501afcb8
JS
1983char *mingw_query_user_email(void)
1984{
1985 return get_extended_user_info(NameUserPrincipal);
1986}
1987
f4626df5
JS
1988struct passwd *getpwuid(int uid)
1989{
55b6513e 1990 static unsigned initialized;
f7597aca 1991 static char user_name[100];
55b6513e 1992 static struct passwd *p;
39a98e9b 1993 wchar_t buf[100];
55b6513e 1994 DWORD len;
f7597aca 1995
55b6513e
JS
1996 if (initialized)
1997 return p;
f7597aca 1998
697bdd22 1999 len = ARRAY_SIZE(buf);
39a98e9b
JS
2000 if (!GetUserNameW(buf, &len)) {
2001 initialized = 1;
2002 return NULL;
2003 }
2004
2005 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
55b6513e 2006 initialized = 1;
f7597aca 2007 return NULL;
55b6513e
JS
2008 }
2009
2010 p = xmalloc(sizeof(*p));
2011 p->pw_name = user_name;
564be791
JS
2012 p->pw_gecos = get_extended_user_info(NameDisplay);
2013 if (!p->pw_gecos)
2014 p->pw_gecos = "unknown";
55b6513e
JS
2015 p->pw_dir = NULL;
2016
2017 initialized = 1;
2018 return p;
f4626df5
JS
2019}
2020
6072fc31
JS
2021static HANDLE timer_event;
2022static HANDLE timer_thread;
2023static int timer_interval;
2024static int one_shot;
176478a8 2025static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
6072fc31
JS
2026
2027/* The timer works like this:
2028 * The thread, ticktack(), is a trivial routine that most of the time
2029 * only waits to receive the signal to terminate. The main thread tells
2030 * the thread to terminate by setting the timer_event to the signalled
2031 * state.
2032 * But ticktack() interrupts the wait state after the timer's interval
2033 * length to call the signal handler.
2034 */
2035
d7fa500f 2036static unsigned __stdcall ticktack(void *dummy)
6072fc31
JS
2037{
2038 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
176478a8 2039 mingw_raise(SIGALRM);
6072fc31
JS
2040 if (one_shot)
2041 break;
2042 }
2043 return 0;
2044}
2045
2046static int start_timer_thread(void)
2047{
2048 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2049 if (timer_event) {
2050 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2051 if (!timer_thread )
2052 return errno = ENOMEM,
2053 error("cannot start timer thread");
2054 } else
2055 return errno = ENOMEM,
2056 error("cannot allocate resources for timer");
2057 return 0;
2058}
2059
2060static void stop_timer_thread(void)
2061{
2062 if (timer_event)
2063 SetEvent(timer_event); /* tell thread to terminate */
2064 if (timer_thread) {
72d63b2f 2065 int rc = WaitForSingleObject(timer_thread, 10000);
6072fc31
JS
2066 if (rc == WAIT_TIMEOUT)
2067 error("timer thread did not terminate timely");
2068 else if (rc != WAIT_OBJECT_0)
2069 error("waiting for timer thread failed: %lu",
2070 GetLastError());
2071 CloseHandle(timer_thread);
2072 }
2073 if (timer_event)
2074 CloseHandle(timer_event);
2075 timer_event = NULL;
2076 timer_thread = NULL;
2077}
2078
2079static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2080{
2081 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2082}
2083
f4626df5
JS
2084int setitimer(int type, struct itimerval *in, struct itimerval *out)
2085{
6072fc31
JS
2086 static const struct timeval zero;
2087 static int atexit_done;
2088
2089 if (out != NULL)
2090 return errno = EINVAL,
2091 error("setitimer param 3 != NULL not implemented");
2092 if (!is_timeval_eq(&in->it_interval, &zero) &&
2093 !is_timeval_eq(&in->it_interval, &in->it_value))
2094 return errno = EINVAL,
2095 error("setitimer: it_interval must be zero or eq it_value");
2096
2097 if (timer_thread)
2098 stop_timer_thread();
2099
2100 if (is_timeval_eq(&in->it_value, &zero) &&
2101 is_timeval_eq(&in->it_interval, &zero))
2102 return 0;
2103
2104 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2105 one_shot = is_timeval_eq(&in->it_interval, &zero);
2106 if (!atexit_done) {
2107 atexit(stop_timer_thread);
2108 atexit_done = 1;
2109 }
2110 return start_timer_thread();
f4626df5
JS
2111}
2112
2113int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2114{
6072fc31
JS
2115 if (sig != SIGALRM)
2116 return errno = EINVAL,
2117 error("sigaction only implemented for SIGALRM");
2118 if (out != NULL)
2119 return errno = EINVAL,
2120 error("sigaction: param 3 != NULL not implemented");
2121
2122 timer_fn = in->sa_handler;
2123 return 0;
2124}
2125
2126#undef signal
2127sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2128{
a4540658 2129 sig_handler_t old;
176478a8
EFL
2130
2131 switch (sig) {
2132 case SIGALRM:
a4540658 2133 old = timer_fn;
176478a8
EFL
2134 timer_fn = handler;
2135 break;
2136
2137 case SIGINT:
a4540658 2138 old = sigint_fn;
176478a8
EFL
2139 sigint_fn = handler;
2140 break;
2141
2142 default:
6072fc31 2143 return signal(sig, handler);
176478a8
EFL
2144 }
2145
6072fc31 2146 return old;
f4626df5 2147}
4804aabc 2148
176478a8
EFL
2149#undef raise
2150int mingw_raise(int sig)
2151{
2152 switch (sig) {
2153 case SIGALRM:
2154 if (timer_fn == SIG_DFL) {
2155 if (isatty(STDERR_FILENO))
2156 fputs("Alarm clock\n", stderr);
2157 exit(128 + SIGALRM);
2158 } else if (timer_fn != SIG_IGN)
2159 timer_fn(SIGALRM);
2160 return 0;
2161
2162 case SIGINT:
2163 if (sigint_fn == SIG_DFL)
2164 exit(128 + SIGINT);
2165 else if (sigint_fn != SIG_IGN)
2166 sigint_fn(SIGINT);
2167 return 0;
2168
446df603
JH
2169#if defined(_MSC_VER)
2170 case SIGILL:
2171 case SIGFPE:
2172 case SIGSEGV:
2173 case SIGTERM:
2174 case SIGBREAK:
2175 case SIGABRT:
2176 case SIGABRT_COMPAT:
2177 /*
2178 * The <signal.h> header in the MS C Runtime defines 8 signals
2179 * as being supported on the platform. Anything else causes an
2180 * "Invalid signal or error" (which in DEBUG builds causes the
2181 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2182 * already know will fail.
2183 */
2184 return raise(sig);
2185 default:
2186 errno = EINVAL;
2187 return -1;
2188
2189#else
2190
176478a8
EFL
2191 default:
2192 return raise(sig);
446df603
JH
2193
2194#endif
2195
176478a8
EFL
2196 }
2197}
2198
7be401e0
PK
2199int link(const char *oldpath, const char *newpath)
2200{
85faec9d
KB
2201 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2202 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2203 xutftowcs_path(wnewpath, newpath) < 0)
2204 return -1;
2205
1e1a876b 2206 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
7be401e0
PK
2207 errno = err_win_to_posix(GetLastError());
2208 return -1;
2209 }
2210 return 0;
2211}
0dbbbc1e 2212
956d86d1 2213pid_t waitpid(pid_t pid, int *status, int options)
52de4db5
EFL
2214{
2215 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2216 FALSE, pid);
2217 if (!h) {
2218 errno = ECHILD;
2219 return -1;
2220 }
2221
ef7108ca
EFL
2222 if (pid > 0 && options & WNOHANG) {
2223 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2224 CloseHandle(h);
2225 return 0;
2226 }
2227 options &= ~WNOHANG;
2228 }
2229
52de4db5
EFL
2230 if (options == 0) {
2231 struct pinfo_t **ppinfo;
2232 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2233 CloseHandle(h);
2234 return 0;
2235 }
2236
2237 if (status)
2238 GetExitCodeProcess(h, (LPDWORD)status);
2239
2240 EnterCriticalSection(&pinfo_cs);
2241
2242 ppinfo = &pinfo;
2243 while (*ppinfo) {
2244 struct pinfo_t *info = *ppinfo;
2245 if (info->pid == pid) {
2246 CloseHandle(info->proc);
2247 *ppinfo = info->next;
2248 free(info);
2249 break;
2250 }
2251 ppinfo = &info->next;
2252 }
2253
2254 LeaveCriticalSection(&pinfo_cs);
2255
2256 CloseHandle(h);
2257 return pid;
2258 }
2259 CloseHandle(h);
2260
2261 errno = EINVAL;
2262 return -1;
2263}
c2369bdf 2264
1c950a59
KB
2265int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2266{
2267 int upos = 0, wpos = 0;
2268 const unsigned char *utf = (const unsigned char*) utfs;
2269 if (!utf || !wcs || wcslen < 1) {
2270 errno = EINVAL;
2271 return -1;
2272 }
2273 /* reserve space for \0 */
2274 wcslen--;
2275 if (utflen < 0)
2276 utflen = INT_MAX;
2277
2278 while (upos < utflen) {
2279 int c = utf[upos++] & 0xff;
2280 if (utflen == INT_MAX && c == 0)
2281 break;
2282
2283 if (wpos >= wcslen) {
2284 wcs[wpos] = 0;
2285 errno = ERANGE;
2286 return -1;
2287 }
2288
2289 if (c < 0x80) {
2290 /* ASCII */
2291 wcs[wpos++] = c;
2292 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2293 (utf[upos] & 0xc0) == 0x80) {
2294 /* 2-byte utf-8 */
2295 c = ((c & 0x1f) << 6);
2296 c |= (utf[upos++] & 0x3f);
2297 wcs[wpos++] = c;
2298 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2299 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2300 (utf[upos] & 0xc0) == 0x80 &&
2301 (utf[upos + 1] & 0xc0) == 0x80) {
2302 /* 3-byte utf-8 */
2303 c = ((c & 0x0f) << 12);
2304 c |= ((utf[upos++] & 0x3f) << 6);
2305 c |= (utf[upos++] & 0x3f);
2306 wcs[wpos++] = c;
2307 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2308 wpos + 1 < wcslen &&
2309 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2310 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2311 (utf[upos] & 0xc0) == 0x80 &&
2312 (utf[upos + 1] & 0xc0) == 0x80 &&
2313 (utf[upos + 2] & 0xc0) == 0x80) {
2314 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2315 c = ((c & 0x07) << 18);
2316 c |= ((utf[upos++] & 0x3f) << 12);
2317 c |= ((utf[upos++] & 0x3f) << 6);
2318 c |= (utf[upos++] & 0x3f);
2319 c -= 0x10000;
2320 wcs[wpos++] = 0xd800 | (c >> 10);
2321 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2322 } else if (c >= 0xa0) {
2323 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2324 wcs[wpos++] = c;
2325 } else {
2326 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2327 static const char *hex = "0123456789abcdef";
2328 wcs[wpos++] = hex[c >> 4];
2329 if (wpos < wcslen)
2330 wcs[wpos++] = hex[c & 0x0f];
2331 }
2332 }
2333 wcs[wpos] = 0;
2334 return wpos;
2335}
2336
2337int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2338{
2339 if (!wcs || !utf || utflen < 1) {
2340 errno = EINVAL;
2341 return -1;
2342 }
2343 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2344 if (utflen)
2345 return utflen - 1;
2346 errno = ERANGE;
2347 return -1;
2348}
2349
0767172b 2350static void setup_windows_environment(void)
02e6edc0 2351{
1fc7bf79
JS
2352 char *tmp = getenv("TMPDIR");
2353
02e6edc0 2354 /* on Windows it is TMP and TEMP */
1fc7bf79
JS
2355 if (!tmp) {
2356 if (!(tmp = getenv("TMP")))
02e6edc0 2357 tmp = getenv("TEMP");
1fc7bf79 2358 if (tmp) {
02e6edc0 2359 setenv("TMPDIR", tmp, 1);
1fc7bf79
JS
2360 tmp = getenv("TMPDIR");
2361 }
2362 }
2363
2364 if (tmp) {
2365 /*
2366 * Convert all dir separators to forward slashes,
2367 * to help shell commands called from the Git
2368 * executable (by not mistaking the dir separators
2369 * for escape characters).
2370 */
8e9b2080 2371 convert_slashes(tmp);
02e6edc0
KB
2372 }
2373
2374 /* simulate TERM to enable auto-color (see color.c) */
2375 if (!getenv("TERM"))
2376 setenv("TERM", "cygwin", 1);
e12a9556
KB
2377
2378 /* calculate HOME if not set */
2379 if (!getenv("HOME")) {
2380 /*
2381 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2382 * location, thus also check if the path exists (i.e. is not
2383 * disconnected)
2384 */
2385 if ((tmp = getenv("HOMEDRIVE"))) {
2386 struct strbuf buf = STRBUF_INIT;
2387 strbuf_addstr(&buf, tmp);
2388 if ((tmp = getenv("HOMEPATH"))) {
2389 strbuf_addstr(&buf, tmp);
2390 if (is_directory(buf.buf))
2391 setenv("HOME", buf.buf, 1);
2392 else
2393 tmp = NULL; /* use $USERPROFILE */
2394 }
2395 strbuf_release(&buf);
2396 }
2397 /* use $USERPROFILE if the home share is not available */
2398 if (!tmp && (tmp = getenv("USERPROFILE")))
2399 setenv("HOME", tmp, 1);
2400 }
02e6edc0
KB
2401}
2402
d2c84dad
JS
2403int is_valid_win32_path(const char *path)
2404{
2405 int preceding_space_or_period = 0, i = 0, periods = 0;
2406
2407 if (!protect_ntfs)
2408 return 1;
2409
817ddd64
JS
2410 skip_dos_drive_prefix((char **)&path);
2411
d2c84dad
JS
2412 for (;;) {
2413 char c = *(path++);
2414 switch (c) {
2415 case '\0':
2416 case '/': case '\\':
2417 /* cannot end in ` ` or `.`, except for `.` and `..` */
2418 if (preceding_space_or_period &&
2419 (i != periods || periods > 2))
2420 return 0;
2421 if (!c)
2422 return 1;
2423
2424 i = periods = preceding_space_or_period = 0;
2425 continue;
2426 case '.':
2427 periods++;
2428 /* fallthru */
2429 case ' ':
2430 preceding_space_or_period = 1;
2431 i++;
2432 continue;
817ddd64
JS
2433 case ':': /* DOS drive prefix was already skipped */
2434 case '<': case '>': case '"': case '|': case '?': case '*':
2435 /* illegal character */
2436 return 0;
2437 default:
2438 if (c > '\0' && c < '\x20')
2439 /* illegal character */
2440 return 0;
d2c84dad
JS
2441 }
2442 preceding_space_or_period = 0;
2443 i++;
2444 }
2445}
2446
396ff754 2447#if !defined(_MSC_VER)
5901dc66
KB
2448/*
2449 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2450 * mingw startup code, see init.c in mingw runtime).
2451 */
2452int _CRT_glob = 0;
396ff754 2453#endif
3f046148 2454
0767172b 2455static NORETURN void die_startup(void)
3f046148
KB
2456{
2457 fputs("fatal: not enough memory for initialization", stderr);
2458 exit(128);
2459}
2460
6f1c189c
KB
2461static void *malloc_startup(size_t size)
2462{
2463 void *result = malloc(size);
2464 if (!result)
2465 die_startup();
2466 return result;
2467}
2468
2469static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2470{
2471 len = xwcstoutf(buffer, wcs, len) + 1;
2472 return memcpy(malloc_startup(len), buffer, len);
2473}
2474
3f944424
JS
2475static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2476 DWORD desired_access, DWORD flags)
2477{
2478 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2479 wchar_t buf[MAX_PATH];
2480 DWORD max = ARRAY_SIZE(buf);
2481 HANDLE handle;
2482 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2483
2484 if (!ret || ret >= max)
2485 return;
2486
2487 /* make sure this does not leak into child processes */
2488 SetEnvironmentVariableW(key, NULL);
2489 if (!wcscmp(buf, L"off")) {
2490 close(fd);
2491 handle = GetStdHandle(std_id);
2492 if (handle != INVALID_HANDLE_VALUE)
2493 CloseHandle(handle);
2494 return;
2495 }
1a172e4a
JS
2496 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2497 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2498 if (handle == INVALID_HANDLE_VALUE) {
2499 close(fd);
2500 handle = GetStdHandle(std_id);
2501 if (handle != INVALID_HANDLE_VALUE)
2502 CloseHandle(handle);
2503 } else {
2504 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2505 SetStdHandle(std_id, handle);
2506 dup2(new_fd, fd);
2507 /* do *not* close the new_fd: that would close stdout */
2508 }
2509 return;
2510 }
3f944424
JS
2511 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2512 flags, NULL);
2513 if (handle != INVALID_HANDLE_VALUE) {
2514 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2515 SetStdHandle(std_id, handle);
2516 dup2(new_fd, fd);
2517 close(new_fd);
2518 }
2519}
2520
2521static void maybe_redirect_std_handles(void)
2522{
2523 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2524 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2525 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2526 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2527 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2528 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2529}
2530
dce7d295
JH
2531#ifdef _MSC_VER
2532#ifdef _DEBUG
2533#include <crtdbg.h>
2534#endif
2535#endif
2536
396ff754
JS
2537/*
2538 * We implement wmain() and compile with -municode, which would
2539 * normally ignore main(), but we call the latter from the former
2540 * so that we can handle non-ASCII command-line parameters
2541 * appropriately.
2542 *
2543 * To be more compatible with the core git code, we convert
2544 * argv into UTF8 and pass them directly to main().
2545 */
2546int wmain(int argc, const wchar_t **wargv)
13f1df43 2547{
396ff754
JS
2548 int i, maxlen, exit_status;
2549 char *buffer, **save;
2550 const char **argv;
3f046148 2551
a0897249
JH
2552 trace2_initialize_clock();
2553
556702f8 2554#ifdef _MSC_VER
f6a63937
JS
2555#ifdef _DEBUG
2556 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2557#endif
2558
556702f8
JH
2559#ifdef USE_MSVC_CRTDBG
2560 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2561#endif
2562#endif
2563
3f944424
JS
2564 maybe_redirect_std_handles();
2565
3f046148 2566 /* determine size of argv and environ conversion buffer */
86e25458 2567 maxlen = wcslen(wargv[0]);
3f046148
KB
2568 for (i = 1; i < argc; i++)
2569 maxlen = max(maxlen, wcslen(wargv[i]));
2570
2571 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2572 maxlen = 3 * maxlen + 1;
6f1c189c 2573 buffer = malloc_startup(maxlen);
3f046148 2574
396ff754
JS
2575 /*
2576 * Create a UTF-8 version of w_argv. Also create a "save" copy
2577 * to remember all the string pointers because parse_options()
2578 * will remove claimed items from the argv that we pass down.
2579 */
2580 ALLOC_ARRAY(argv, argc + 1);
2581 ALLOC_ARRAY(save, argc + 1);
86e25458 2582 for (i = 0; i < argc; i++)
396ff754
JS
2583 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2584 argv[i] = save[i] = NULL;
3f046148 2585 free(buffer);
13f1df43 2586
6dc71543 2587 /* fix Windows specific environment settings */
02e6edc0 2588 setup_windows_environment();
baea068d 2589
0e218f91
JS
2590 unset_environment_variables = xstrdup("PERL5LIB");
2591
13f1df43
KB
2592 /* initialize critical section for waitpid pinfo_t list */
2593 InitializeCriticalSection(&pinfo_cs);
2594
2595 /* set up default file mode and file modes for stdin/out/err */
2596 _fmode = _O_BINARY;
2597 _setmode(_fileno(stdin), _O_BINARY);
2598 _setmode(_fileno(stdout), _O_BINARY);
2599 _setmode(_fileno(stderr), _O_BINARY);
eac14f89
KB
2600
2601 /* initialize Unicode console */
2602 winansi_init();
396ff754
JS
2603
2604 /* invoke the real main() using our utf8 version of argv. */
2605 exit_status = main(argc, argv);
2606
2607 for (i = 0; i < argc; i++)
2608 free(save[i]);
2609 free(save);
2610 free(argv);
2611
2612 return exit_status;
13f1df43 2613}
7b6aff06
NTND
2614
2615int uname(struct utsname *buf)
2616{
d62c89af 2617 unsigned v = (unsigned)GetVersion();
7b6aff06 2618 memset(buf, 0, sizeof(*buf));
5096d490
JK
2619 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2620 xsnprintf(buf->release, sizeof(buf->release),
2621 "%u.%u", v & 0xff, (v >> 8) & 0xff);
7b6aff06 2622 /* assuming NT variants only.. */
5096d490
JK
2623 xsnprintf(buf->version, sizeof(buf->version),
2624 "%u", (v >> 16) & 0x7fff);
7b6aff06
NTND
2625 return 0;
2626}