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