Add a function to determine whether a path is owned by the current user
[alt-git.git] / compat / mingw.c
blob38ac35913df78ef06aef4a8a49b56aedb5ab489c
1 #include "../git-compat-util.h"
2 #include "win32.h"
3 #include <aclapi.h>
4 #include <conio.h>
5 #include <wchar.h>
6 #include "../strbuf.h"
7 #include "../run-command.h"
8 #include "../cache.h"
9 #include "win32/lazyload.h"
10 #include "../config.h"
11 #include "dir.h"
13 #define HCAST(type, handle) ((type)(intptr_t)handle)
15 static const int delay[] = { 0, 1, 10, 20, 40 };
17 void open_in_gdb(void)
19 static struct child_process cp = CHILD_PROCESS_INIT;
20 extern char *_pgmptr;
22 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
23 strvec_pushf(&cp.args, "--pid=%d", getpid());
24 cp.clean_on_exit = 1;
25 if (start_command(&cp) < 0)
26 die_errno("Could not start gdb");
27 sleep(1);
30 int err_win_to_posix(DWORD winerr)
32 int error = ENOSYS;
33 switch(winerr) {
34 case ERROR_ACCESS_DENIED: error = EACCES; break;
35 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
36 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
37 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
38 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
39 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
40 case ERROR_BAD_COMMAND: error = EIO; break;
41 case ERROR_BAD_DEVICE: error = ENODEV; break;
42 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
43 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
44 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
45 case ERROR_BAD_LENGTH: error = EINVAL; break;
46 case ERROR_BAD_PATHNAME: error = ENOENT; break;
47 case ERROR_BAD_PIPE: error = EPIPE; break;
48 case ERROR_BAD_UNIT: error = ENODEV; break;
49 case ERROR_BAD_USERNAME: error = EINVAL; break;
50 case ERROR_BROKEN_PIPE: error = EPIPE; break;
51 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
52 case ERROR_BUSY: error = EBUSY; break;
53 case ERROR_BUSY_DRIVE: error = EBUSY; break;
54 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
55 case ERROR_CANNOT_MAKE: error = EACCES; break;
56 case ERROR_CANTOPEN: error = EIO; break;
57 case ERROR_CANTREAD: error = EIO; break;
58 case ERROR_CANTWRITE: error = EIO; break;
59 case ERROR_CRC: error = EIO; break;
60 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
61 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
62 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
63 case ERROR_DIRECTORY: error = EINVAL; break;
64 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
65 case ERROR_DISK_CHANGE: error = EIO; break;
66 case ERROR_DISK_FULL: error = ENOSPC; break;
67 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
68 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
69 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
70 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
71 case ERROR_FILE_EXISTS: error = EEXIST; break;
72 case ERROR_FILE_INVALID: error = ENODEV; break;
73 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
74 case ERROR_GEN_FAILURE: error = EIO; break;
75 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
76 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
77 case ERROR_INVALID_ACCESS: error = EACCES; break;
78 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
79 case ERROR_INVALID_BLOCK: error = EFAULT; break;
80 case ERROR_INVALID_DATA: error = EINVAL; break;
81 case ERROR_INVALID_DRIVE: error = ENODEV; break;
82 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
83 case ERROR_INVALID_FLAGS: error = EINVAL; break;
84 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
85 case ERROR_INVALID_HANDLE: error = EBADF; break;
86 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
87 case ERROR_INVALID_NAME: error = EINVAL; break;
88 case ERROR_INVALID_OWNER: error = EINVAL; break;
89 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
90 case ERROR_INVALID_PASSWORD: error = EPERM; break;
91 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
92 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
93 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
94 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
95 case ERROR_IO_DEVICE: error = EIO; break;
96 case ERROR_IO_INCOMPLETE: error = EINTR; break;
97 case ERROR_LOCKED: error = EBUSY; break;
98 case ERROR_LOCK_VIOLATION: error = EACCES; break;
99 case ERROR_LOGON_FAILURE: error = EACCES; break;
100 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
101 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
102 case ERROR_MORE_DATA: error = EPIPE; break;
103 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
104 case ERROR_NOACCESS: error = EFAULT; break;
105 case ERROR_NONE_MAPPED: error = EINVAL; break;
106 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
107 case ERROR_NOT_READY: error = EAGAIN; break;
108 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
109 case ERROR_NO_DATA: error = EPIPE; break;
110 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
111 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
112 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
113 case ERROR_OPEN_FAILED: error = EIO; break;
114 case ERROR_OPEN_FILES: error = EBUSY; break;
115 case ERROR_OPERATION_ABORTED: error = EINTR; break;
116 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
117 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
118 case ERROR_PATH_BUSY: error = EBUSY; break;
119 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
120 case ERROR_PIPE_BUSY: error = EBUSY; break;
121 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
122 case ERROR_PIPE_LISTENING: error = EPIPE; break;
123 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
124 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
125 case ERROR_READ_FAULT: error = EIO; break;
126 case ERROR_SEEK: error = EIO; break;
127 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
128 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
129 case ERROR_SHARING_VIOLATION: error = EACCES; break;
130 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
131 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
132 case ERROR_SWAPERROR: error = ENOENT; break;
133 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
134 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
135 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
136 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
137 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
138 case ERROR_WRITE_FAULT: error = EIO; break;
139 case ERROR_WRITE_PROTECT: error = EROFS; break;
141 return error;
144 static inline int is_file_in_use_error(DWORD errcode)
146 switch (errcode) {
147 case ERROR_SHARING_VIOLATION:
148 case ERROR_ACCESS_DENIED:
149 return 1;
152 return 0;
155 static int read_yes_no_answer(void)
157 char answer[1024];
159 if (fgets(answer, sizeof(answer), stdin)) {
160 size_t answer_len = strlen(answer);
161 int got_full_line = 0, c;
163 /* remove the newline */
164 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
165 answer[answer_len-2] = '\0';
166 got_full_line = 1;
167 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
168 answer[answer_len-1] = '\0';
169 got_full_line = 1;
171 /* flush the buffer in case we did not get the full line */
172 if (!got_full_line)
173 while ((c = getchar()) != EOF && c != '\n')
175 } else
176 /* we could not read, return the
177 * default answer which is no */
178 return 0;
180 if (tolower(answer[0]) == 'y' && !answer[1])
181 return 1;
182 if (!strncasecmp(answer, "yes", sizeof(answer)))
183 return 1;
184 if (tolower(answer[0]) == 'n' && !answer[1])
185 return 0;
186 if (!strncasecmp(answer, "no", sizeof(answer)))
187 return 0;
189 /* did not find an answer we understand */
190 return -1;
193 static int ask_yes_no_if_possible(const char *format, ...)
195 char question[4096];
196 const char *retry_hook[] = { NULL, NULL, NULL };
197 va_list args;
199 va_start(args, format);
200 vsnprintf(question, sizeof(question), format, args);
201 va_end(args);
203 if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
204 retry_hook[1] = question;
205 return !run_command_v_opt(retry_hook, 0);
208 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
209 return 0;
211 while (1) {
212 int answer;
213 fprintf(stderr, "%s (y/n) ", question);
215 if ((answer = read_yes_no_answer()) >= 0)
216 return answer;
218 fprintf(stderr, "Sorry, I did not understand your answer. "
219 "Please type 'y' or 'n'\n");
223 /* Windows only */
224 enum hide_dotfiles_type {
225 HIDE_DOTFILES_FALSE = 0,
226 HIDE_DOTFILES_TRUE,
227 HIDE_DOTFILES_DOTGITONLY
230 static int core_restrict_inherited_handles = -1;
231 static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
232 static char *unset_environment_variables;
234 int mingw_core_config(const char *var, const char *value, void *cb)
236 if (!strcmp(var, "core.hidedotfiles")) {
237 if (value && !strcasecmp(value, "dotgitonly"))
238 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
239 else
240 hide_dotfiles = git_config_bool(var, value);
241 return 0;
244 if (!strcmp(var, "core.unsetenvvars")) {
245 free(unset_environment_variables);
246 unset_environment_variables = xstrdup(value);
247 return 0;
250 if (!strcmp(var, "core.restrictinheritedhandles")) {
251 if (value && !strcasecmp(value, "auto"))
252 core_restrict_inherited_handles = -1;
253 else
254 core_restrict_inherited_handles =
255 git_config_bool(var, value);
256 return 0;
259 return 0;
262 /* Normalizes NT paths as returned by some low-level APIs. */
263 static wchar_t *normalize_ntpath(wchar_t *wbuf)
265 int i;
266 /* fix absolute path prefixes */
267 if (wbuf[0] == '\\') {
268 /* strip NT namespace prefixes */
269 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
270 !wcsncmp(wbuf, L"\\\\?\\", 4))
271 wbuf += 4;
272 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
273 wbuf += 12;
274 /* replace remaining '...UNC\' with '\\' */
275 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
276 wbuf += 2;
277 *wbuf = '\\';
280 /* convert backslashes to slashes */
281 for (i = 0; wbuf[i]; i++)
282 if (wbuf[i] == '\\')
283 wbuf[i] = '/';
284 return wbuf;
287 int mingw_unlink(const char *pathname)
289 int ret, tries = 0;
290 wchar_t wpathname[MAX_PATH];
291 if (xutftowcs_path(wpathname, pathname) < 0)
292 return -1;
294 if (DeleteFileW(wpathname))
295 return 0;
297 /* read-only files cannot be removed */
298 _wchmod(wpathname, 0666);
299 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
300 if (!is_file_in_use_error(GetLastError()))
301 break;
303 * We assume that some other process had the source or
304 * destination file open at the wrong moment and retry.
305 * In order to give the other process a higher chance to
306 * complete its operation, we give up our time slice now.
307 * If we have to retry again, we do sleep a bit.
309 Sleep(delay[tries]);
310 tries++;
312 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
313 ask_yes_no_if_possible("Unlink of file '%s' failed. "
314 "Should I try again?", pathname))
315 ret = _wunlink(wpathname);
316 return ret;
319 static int is_dir_empty(const wchar_t *wpath)
321 WIN32_FIND_DATAW findbuf;
322 HANDLE handle;
323 wchar_t wbuf[MAX_PATH + 2];
324 wcscpy(wbuf, wpath);
325 wcscat(wbuf, L"\\*");
326 handle = FindFirstFileW(wbuf, &findbuf);
327 if (handle == INVALID_HANDLE_VALUE)
328 return GetLastError() == ERROR_NO_MORE_FILES;
330 while (!wcscmp(findbuf.cFileName, L".") ||
331 !wcscmp(findbuf.cFileName, L".."))
332 if (!FindNextFileW(handle, &findbuf)) {
333 DWORD err = GetLastError();
334 FindClose(handle);
335 return err == ERROR_NO_MORE_FILES;
337 FindClose(handle);
338 return 0;
341 int mingw_rmdir(const char *pathname)
343 int ret, tries = 0;
344 wchar_t wpathname[MAX_PATH];
345 if (xutftowcs_path(wpathname, pathname) < 0)
346 return -1;
348 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
349 if (!is_file_in_use_error(GetLastError()))
350 errno = err_win_to_posix(GetLastError());
351 if (errno != EACCES)
352 break;
353 if (!is_dir_empty(wpathname)) {
354 errno = ENOTEMPTY;
355 break;
358 * We assume that some other process had the source or
359 * destination file open at the wrong moment and retry.
360 * In order to give the other process a higher chance to
361 * complete its operation, we give up our time slice now.
362 * If we have to retry again, we do sleep a bit.
364 Sleep(delay[tries]);
365 tries++;
367 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
368 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
369 "Should I try again?", pathname))
370 ret = _wrmdir(wpathname);
371 if (!ret)
372 invalidate_lstat_cache();
373 return ret;
376 static inline int needs_hiding(const char *path)
378 const char *basename;
380 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
381 return 0;
383 /* We cannot use basename(), as it would remove trailing slashes */
384 win32_skip_dos_drive_prefix((char **)&path);
385 if (!*path)
386 return 0;
388 for (basename = path; *path; path++)
389 if (is_dir_sep(*path)) {
390 do {
391 path++;
392 } while (is_dir_sep(*path));
393 /* ignore trailing slashes */
394 if (*path)
395 basename = path;
396 else
397 break;
400 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
401 return *basename == '.';
403 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
404 return !strncasecmp(".git", basename, 4) &&
405 (!basename[4] || is_dir_sep(basename[4]));
408 static int set_hidden_flag(const wchar_t *path, int set)
410 DWORD original = GetFileAttributesW(path), modified;
411 if (set)
412 modified = original | FILE_ATTRIBUTE_HIDDEN;
413 else
414 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
415 if (original == modified || SetFileAttributesW(path, modified))
416 return 0;
417 errno = err_win_to_posix(GetLastError());
418 return -1;
421 int mingw_mkdir(const char *path, int mode)
423 int ret;
424 wchar_t wpath[MAX_PATH];
426 if (!is_valid_win32_path(path, 0)) {
427 errno = EINVAL;
428 return -1;
431 if (xutftowcs_path(wpath, path) < 0)
432 return -1;
433 ret = _wmkdir(wpath);
434 if (!ret && needs_hiding(path))
435 return set_hidden_flag(wpath, 1);
436 return ret;
440 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
441 * is documented in [1] as opening a writable file handle in append mode.
442 * (It is believed that) this is atomic since it is maintained by the
443 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
445 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
447 * This trick does not appear to work for named pipes. Instead it creates
448 * a named pipe client handle that cannot be written to. Callers should
449 * just use the regular _wopen() for them. (And since client handle gets
450 * bound to a unique server handle, it isn't really an issue.)
452 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
454 HANDLE handle;
455 int fd;
456 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
458 /* only these flags are supported */
459 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
460 return errno = ENOSYS, -1;
463 * FILE_SHARE_WRITE is required to permit child processes
464 * to append to the file.
466 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
467 FILE_SHARE_WRITE | FILE_SHARE_READ,
468 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
469 if (handle == INVALID_HANDLE_VALUE) {
470 DWORD err = GetLastError();
473 * Some network storage solutions (e.g. Isilon) might return
474 * ERROR_INVALID_PARAMETER instead of expected error
475 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
476 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
478 if (err == ERROR_INVALID_PARAMETER)
479 err = ERROR_PATH_NOT_FOUND;
481 errno = err_win_to_posix(err);
482 return -1;
486 * No O_APPEND here, because the CRT uses it only to reset the
487 * file pointer to EOF before each write(); but that is not
488 * necessary (and may lead to races) for a file created with
489 * FILE_APPEND_DATA.
491 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
492 if (fd < 0)
493 CloseHandle(handle);
494 return fd;
498 * Does the pathname map to the local named pipe filesystem?
499 * That is, does it have a "//./pipe/" prefix?
501 static int is_local_named_pipe_path(const char *filename)
503 return (is_dir_sep(filename[0]) &&
504 is_dir_sep(filename[1]) &&
505 filename[2] == '.' &&
506 is_dir_sep(filename[3]) &&
507 !strncasecmp(filename+4, "pipe", 4) &&
508 is_dir_sep(filename[8]) &&
509 filename[9]);
512 int mingw_open (const char *filename, int oflags, ...)
514 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
515 va_list args;
516 unsigned mode;
517 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
518 wchar_t wfilename[MAX_PATH];
519 open_fn_t open_fn;
521 va_start(args, oflags);
522 mode = va_arg(args, int);
523 va_end(args);
525 if (!is_valid_win32_path(filename, !create)) {
526 errno = create ? EINVAL : ENOENT;
527 return -1;
530 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
531 open_fn = mingw_open_append;
532 else
533 open_fn = _wopen;
535 if (filename && !strcmp(filename, "/dev/null"))
536 wcscpy(wfilename, L"nul");
537 else if (xutftowcs_path(wfilename, filename) < 0)
538 return -1;
540 fd = open_fn(wfilename, oflags, mode);
542 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
543 DWORD attrs = GetFileAttributesW(wfilename);
544 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
545 errno = EISDIR;
547 if ((oflags & O_CREAT) && needs_hiding(filename)) {
549 * Internally, _wopen() uses the CreateFile() API which errors
550 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
551 * specified and an already existing file's attributes do not
552 * match *exactly*. As there is no mode or flag we can set that
553 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
554 * again *without* the O_CREAT flag (that corresponds to the
555 * CREATE_ALWAYS flag of CreateFile()).
557 if (fd < 0 && errno == EACCES)
558 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
559 if (fd >= 0 && set_hidden_flag(wfilename, 1))
560 warning("could not mark '%s' as hidden.", filename);
562 return fd;
565 static BOOL WINAPI ctrl_ignore(DWORD type)
567 return TRUE;
570 #undef fgetc
571 int mingw_fgetc(FILE *stream)
573 int ch;
574 if (!isatty(_fileno(stream)))
575 return fgetc(stream);
577 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
578 while (1) {
579 ch = fgetc(stream);
580 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
581 break;
583 /* Ctrl+C was pressed, simulate SIGINT and retry */
584 mingw_raise(SIGINT);
586 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
587 return ch;
590 #undef fopen
591 FILE *mingw_fopen (const char *filename, const char *otype)
593 int hide = needs_hiding(filename);
594 FILE *file;
595 wchar_t wfilename[MAX_PATH], wotype[4];
596 if (filename && !strcmp(filename, "/dev/null"))
597 wcscpy(wfilename, L"nul");
598 else if (!is_valid_win32_path(filename, 1)) {
599 int create = otype && strchr(otype, 'w');
600 errno = create ? EINVAL : ENOENT;
601 return NULL;
602 } else if (xutftowcs_path(wfilename, filename) < 0)
603 return NULL;
605 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
606 return NULL;
608 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
609 error("could not unhide %s", filename);
610 return NULL;
612 file = _wfopen(wfilename, wotype);
613 if (!file && GetLastError() == ERROR_INVALID_NAME)
614 errno = ENOENT;
615 if (file && hide && set_hidden_flag(wfilename, 1))
616 warning("could not mark '%s' as hidden.", filename);
617 return file;
620 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
622 int hide = needs_hiding(filename);
623 FILE *file;
624 wchar_t wfilename[MAX_PATH], wotype[4];
625 if (filename && !strcmp(filename, "/dev/null"))
626 wcscpy(wfilename, L"nul");
627 else if (!is_valid_win32_path(filename, 1)) {
628 int create = otype && strchr(otype, 'w');
629 errno = create ? EINVAL : ENOENT;
630 return NULL;
631 } else if (xutftowcs_path(wfilename, filename) < 0)
632 return NULL;
634 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
635 return NULL;
637 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
638 error("could not unhide %s", filename);
639 return NULL;
641 file = _wfreopen(wfilename, wotype, stream);
642 if (file && hide && set_hidden_flag(wfilename, 1))
643 warning("could not mark '%s' as hidden.", filename);
644 return file;
647 #undef fflush
648 int mingw_fflush(FILE *stream)
650 int ret = fflush(stream);
653 * write() is used behind the scenes of stdio output functions.
654 * Since git code does not check for errors after each stdio write
655 * operation, it can happen that write() is called by a later
656 * stdio function even if an earlier write() call failed. In the
657 * case of a pipe whose readable end was closed, only the first
658 * call to write() reports EPIPE on Windows. Subsequent write()
659 * calls report EINVAL. It is impossible to notice whether this
660 * fflush invocation triggered such a case, therefore, we have to
661 * catch all EINVAL errors whole-sale.
663 if (ret && errno == EINVAL)
664 errno = EPIPE;
666 return ret;
669 #undef write
670 ssize_t mingw_write(int fd, const void *buf, size_t len)
672 ssize_t result = write(fd, buf, len);
674 if (result < 0 && errno == EINVAL && buf) {
675 /* check if fd is a pipe */
676 HANDLE h = (HANDLE) _get_osfhandle(fd);
677 if (GetFileType(h) == FILE_TYPE_PIPE)
678 errno = EPIPE;
679 else
680 errno = EINVAL;
683 return result;
686 int mingw_access(const char *filename, int mode)
688 wchar_t wfilename[MAX_PATH];
689 if (xutftowcs_path(wfilename, filename) < 0)
690 return -1;
691 /* X_OK is not supported by the MSVCRT version */
692 return _waccess(wfilename, mode & ~X_OK);
695 int mingw_chdir(const char *dirname)
697 wchar_t wdirname[MAX_PATH];
698 if (xutftowcs_path(wdirname, dirname) < 0)
699 return -1;
700 return _wchdir(wdirname);
703 int mingw_chmod(const char *filename, int mode)
705 wchar_t wfilename[MAX_PATH];
706 if (xutftowcs_path(wfilename, filename) < 0)
707 return -1;
708 return _wchmod(wfilename, mode);
712 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
713 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
715 static inline long long filetime_to_hnsec(const FILETIME *ft)
717 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
718 /* Windows to Unix Epoch conversion */
719 return winTime - 116444736000000000LL;
722 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
724 long long hnsec = filetime_to_hnsec(ft);
725 ts->tv_sec = (time_t)(hnsec / 10000000);
726 ts->tv_nsec = (hnsec % 10000000) * 100;
730 * Verifies that safe_create_leading_directories() would succeed.
732 static int has_valid_directory_prefix(wchar_t *wfilename)
734 int n = wcslen(wfilename);
736 while (n > 0) {
737 wchar_t c = wfilename[--n];
738 DWORD attributes;
740 if (!is_dir_sep(c))
741 continue;
743 wfilename[n] = L'\0';
744 attributes = GetFileAttributesW(wfilename);
745 wfilename[n] = c;
746 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
747 attributes == FILE_ATTRIBUTE_DEVICE)
748 return 1;
749 if (attributes == INVALID_FILE_ATTRIBUTES)
750 switch (GetLastError()) {
751 case ERROR_PATH_NOT_FOUND:
752 continue;
753 case ERROR_FILE_NOT_FOUND:
754 /* This implies parent directory exists. */
755 return 1;
757 return 0;
759 return 1;
762 /* We keep the do_lstat code in a separate function to avoid recursion.
763 * When a path ends with a slash, the stat will fail with ENOENT. In
764 * this case, we strip the trailing slashes and stat again.
766 * If follow is true then act like stat() and report on the link
767 * target. Otherwise report on the link itself.
769 static int do_lstat(int follow, const char *file_name, struct stat *buf)
771 WIN32_FILE_ATTRIBUTE_DATA fdata;
772 wchar_t wfilename[MAX_PATH];
773 if (xutftowcs_path(wfilename, file_name) < 0)
774 return -1;
776 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
777 buf->st_ino = 0;
778 buf->st_gid = 0;
779 buf->st_uid = 0;
780 buf->st_nlink = 1;
781 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
782 buf->st_size = fdata.nFileSizeLow |
783 (((off_t)fdata.nFileSizeHigh)<<32);
784 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
785 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
786 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
787 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
788 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
789 WIN32_FIND_DATAW findbuf;
790 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
791 if (handle != INVALID_HANDLE_VALUE) {
792 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
793 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
794 if (follow) {
795 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
796 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
797 } else {
798 buf->st_mode = S_IFLNK;
800 buf->st_mode |= S_IREAD;
801 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
802 buf->st_mode |= S_IWRITE;
804 FindClose(handle);
807 return 0;
809 switch (GetLastError()) {
810 case ERROR_ACCESS_DENIED:
811 case ERROR_SHARING_VIOLATION:
812 case ERROR_LOCK_VIOLATION:
813 case ERROR_SHARING_BUFFER_EXCEEDED:
814 errno = EACCES;
815 break;
816 case ERROR_BUFFER_OVERFLOW:
817 errno = ENAMETOOLONG;
818 break;
819 case ERROR_NOT_ENOUGH_MEMORY:
820 errno = ENOMEM;
821 break;
822 case ERROR_PATH_NOT_FOUND:
823 if (!has_valid_directory_prefix(wfilename)) {
824 errno = ENOTDIR;
825 break;
827 /* fallthru */
828 default:
829 errno = ENOENT;
830 break;
832 return -1;
835 /* We provide our own lstat/fstat functions, since the provided
836 * lstat/fstat functions are so slow. These stat functions are
837 * tailored for Git's usage (read: fast), and are not meant to be
838 * complete. Note that Git stat()s are redirected to mingw_lstat()
839 * too, since Windows doesn't really handle symlinks that well.
841 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
843 int namelen;
844 char alt_name[PATH_MAX];
846 if (!do_lstat(follow, file_name, buf))
847 return 0;
849 /* if file_name ended in a '/', Windows returned ENOENT;
850 * try again without trailing slashes
852 if (errno != ENOENT)
853 return -1;
855 namelen = strlen(file_name);
856 if (namelen && file_name[namelen-1] != '/')
857 return -1;
858 while (namelen && file_name[namelen-1] == '/')
859 --namelen;
860 if (!namelen || namelen >= PATH_MAX)
861 return -1;
863 memcpy(alt_name, file_name, namelen);
864 alt_name[namelen] = 0;
865 return do_lstat(follow, alt_name, buf);
868 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
870 BY_HANDLE_FILE_INFORMATION fdata;
872 if (!GetFileInformationByHandle(hnd, &fdata)) {
873 errno = err_win_to_posix(GetLastError());
874 return -1;
877 buf->st_ino = 0;
878 buf->st_gid = 0;
879 buf->st_uid = 0;
880 buf->st_nlink = 1;
881 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
882 buf->st_size = fdata.nFileSizeLow |
883 (((off_t)fdata.nFileSizeHigh)<<32);
884 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
885 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
886 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
887 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
888 return 0;
891 int mingw_lstat(const char *file_name, struct stat *buf)
893 return do_stat_internal(0, file_name, buf);
895 int mingw_stat(const char *file_name, struct stat *buf)
897 return do_stat_internal(1, file_name, buf);
900 int mingw_fstat(int fd, struct stat *buf)
902 HANDLE fh = (HANDLE)_get_osfhandle(fd);
903 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
905 switch (type) {
906 case FILE_TYPE_DISK:
907 return get_file_info_by_handle(fh, buf);
909 case FILE_TYPE_CHAR:
910 case FILE_TYPE_PIPE:
911 /* initialize stat fields */
912 memset(buf, 0, sizeof(*buf));
913 buf->st_nlink = 1;
915 if (type == FILE_TYPE_CHAR) {
916 buf->st_mode = _S_IFCHR;
917 } else {
918 buf->st_mode = _S_IFIFO;
919 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
920 buf->st_size = avail;
922 return 0;
924 default:
925 errno = EBADF;
926 return -1;
930 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
932 long long winTime = t * 10000000LL + 116444736000000000LL;
933 ft->dwLowDateTime = winTime;
934 ft->dwHighDateTime = winTime >> 32;
937 int mingw_utime (const char *file_name, const struct utimbuf *times)
939 FILETIME mft, aft;
940 int fh, rc;
941 DWORD attrs;
942 wchar_t wfilename[MAX_PATH];
943 if (xutftowcs_path(wfilename, file_name) < 0)
944 return -1;
946 /* must have write permission */
947 attrs = GetFileAttributesW(wfilename);
948 if (attrs != INVALID_FILE_ATTRIBUTES &&
949 (attrs & FILE_ATTRIBUTE_READONLY)) {
950 /* ignore errors here; open() will report them */
951 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
954 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
955 rc = -1;
956 goto revert_attrs;
959 if (times) {
960 time_t_to_filetime(times->modtime, &mft);
961 time_t_to_filetime(times->actime, &aft);
962 } else {
963 GetSystemTimeAsFileTime(&mft);
964 aft = mft;
966 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
967 errno = EINVAL;
968 rc = -1;
969 } else
970 rc = 0;
971 close(fh);
973 revert_attrs:
974 if (attrs != INVALID_FILE_ATTRIBUTES &&
975 (attrs & FILE_ATTRIBUTE_READONLY)) {
976 /* ignore errors again */
977 SetFileAttributesW(wfilename, attrs);
979 return rc;
982 #undef strftime
983 size_t mingw_strftime(char *s, size_t max,
984 const char *format, const struct tm *tm)
986 /* a pointer to the original strftime in case we can't find the UCRT version */
987 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
988 size_t ret;
989 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, strftime, char *, size_t,
990 const char *, const struct tm *);
992 if (INIT_PROC_ADDR(strftime))
993 ret = strftime(s, max, format, tm);
994 else
995 ret = fallback(s, max, format, tm);
997 if (!ret && errno == EINVAL)
998 die("invalid strftime format: '%s'", format);
999 return ret;
1002 unsigned int sleep (unsigned int seconds)
1004 Sleep(seconds*1000);
1005 return 0;
1008 char *mingw_mktemp(char *template)
1010 wchar_t wtemplate[MAX_PATH];
1011 if (xutftowcs_path(wtemplate, template) < 0)
1012 return NULL;
1013 if (!_wmktemp(wtemplate))
1014 return NULL;
1015 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1016 return NULL;
1017 return template;
1020 int mkstemp(char *template)
1022 char *filename = mktemp(template);
1023 if (filename == NULL)
1024 return -1;
1025 return open(filename, O_RDWR | O_CREAT, 0600);
1028 int gettimeofday(struct timeval *tv, void *tz)
1030 FILETIME ft;
1031 long long hnsec;
1033 GetSystemTimeAsFileTime(&ft);
1034 hnsec = filetime_to_hnsec(&ft);
1035 tv->tv_sec = hnsec / 10000000;
1036 tv->tv_usec = (hnsec % 10000000) / 10;
1037 return 0;
1040 int pipe(int filedes[2])
1042 HANDLE h[2];
1044 /* this creates non-inheritable handles */
1045 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1046 errno = err_win_to_posix(GetLastError());
1047 return -1;
1049 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1050 if (filedes[0] < 0) {
1051 CloseHandle(h[0]);
1052 CloseHandle(h[1]);
1053 return -1;
1055 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1056 if (filedes[1] < 0) {
1057 close(filedes[0]);
1058 CloseHandle(h[1]);
1059 return -1;
1061 return 0;
1064 #ifndef __MINGW64__
1065 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1067 if (gmtime_s(result, timep) == 0)
1068 return result;
1069 return NULL;
1072 struct tm *localtime_r(const time_t *timep, struct tm *result)
1074 if (localtime_s(result, timep) == 0)
1075 return result;
1076 return NULL;
1078 #endif
1080 char *mingw_getcwd(char *pointer, int len)
1082 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1083 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1085 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1086 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1087 return NULL;
1089 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1090 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1091 HANDLE hnd = CreateFileW(cwd, 0,
1092 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1093 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1094 if (hnd == INVALID_HANDLE_VALUE)
1095 return NULL;
1096 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1097 CloseHandle(hnd);
1098 if (!ret || ret >= ARRAY_SIZE(wpointer))
1099 return NULL;
1100 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1101 return NULL;
1102 return pointer;
1104 if (!ret || ret >= ARRAY_SIZE(wpointer))
1105 return NULL;
1106 if (xwcstoutf(pointer, wpointer, len) < 0)
1107 return NULL;
1108 convert_slashes(pointer);
1109 return pointer;
1113 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1114 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1116 static const char *quote_arg_msvc(const char *arg)
1118 /* count chars to quote */
1119 int len = 0, n = 0;
1120 int force_quotes = 0;
1121 char *q, *d;
1122 const char *p = arg;
1123 if (!*p) force_quotes = 1;
1124 while (*p) {
1125 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1126 force_quotes = 1;
1127 else if (*p == '"')
1128 n++;
1129 else if (*p == '\\') {
1130 int count = 0;
1131 while (*p == '\\') {
1132 count++;
1133 p++;
1134 len++;
1136 if (*p == '"' || !*p)
1137 n += count*2 + 1;
1138 continue;
1140 len++;
1141 p++;
1143 if (!force_quotes && n == 0)
1144 return arg;
1146 /* insert \ where necessary */
1147 d = q = xmalloc(st_add3(len, n, 3));
1148 *d++ = '"';
1149 while (*arg) {
1150 if (*arg == '"')
1151 *d++ = '\\';
1152 else if (*arg == '\\') {
1153 int count = 0;
1154 while (*arg == '\\') {
1155 count++;
1156 *d++ = *arg++;
1158 if (*arg == '"' || !*arg) {
1159 while (count-- > 0)
1160 *d++ = '\\';
1161 /* don't escape the surrounding end quote */
1162 if (!*arg)
1163 break;
1164 *d++ = '\\';
1167 *d++ = *arg++;
1169 *d++ = '"';
1170 *d++ = '\0';
1171 return q;
1174 #include "quote.h"
1176 static const char *quote_arg_msys2(const char *arg)
1178 struct strbuf buf = STRBUF_INIT;
1179 const char *p2 = arg, *p;
1181 for (p = arg; *p; p++) {
1182 int ws = isspace(*p);
1183 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1184 *p != '?' && *p != '*' && *p != '~')
1185 continue;
1186 if (!buf.len)
1187 strbuf_addch(&buf, '"');
1188 if (p != p2)
1189 strbuf_add(&buf, p2, p - p2);
1190 if (*p == '\\' || *p == '"')
1191 strbuf_addch(&buf, '\\');
1192 p2 = p;
1195 if (p == arg)
1196 strbuf_addch(&buf, '"');
1197 else if (!buf.len)
1198 return arg;
1199 else
1200 strbuf_add(&buf, p2, p - p2);
1202 strbuf_addch(&buf, '"');
1203 return strbuf_detach(&buf, 0);
1206 static const char *parse_interpreter(const char *cmd)
1208 static char buf[100];
1209 char *p, *opt;
1210 int n, fd;
1212 /* don't even try a .exe */
1213 n = strlen(cmd);
1214 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1215 return NULL;
1217 fd = open(cmd, O_RDONLY);
1218 if (fd < 0)
1219 return NULL;
1220 n = read(fd, buf, sizeof(buf)-1);
1221 close(fd);
1222 if (n < 4) /* at least '#!/x' and not error */
1223 return NULL;
1225 if (buf[0] != '#' || buf[1] != '!')
1226 return NULL;
1227 buf[n] = '\0';
1228 p = buf + strcspn(buf, "\r\n");
1229 if (!*p)
1230 return NULL;
1232 *p = '\0';
1233 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1234 return NULL;
1235 /* strip options */
1236 if ((opt = strchr(p+1, ' ')))
1237 *opt = '\0';
1238 return p+1;
1242 * exe_only means that we only want to detect .exe files, but not scripts
1243 * (which do not have an extension)
1245 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1246 int isexe, int exe_only)
1248 char path[MAX_PATH];
1249 wchar_t wpath[MAX_PATH];
1250 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1252 if (xutftowcs_path(wpath, path) < 0)
1253 return NULL;
1255 if (!isexe && _waccess(wpath, F_OK) == 0)
1256 return xstrdup(path);
1257 wpath[wcslen(wpath)-4] = '\0';
1258 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1259 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1260 path[strlen(path)-4] = '\0';
1261 return xstrdup(path);
1264 return NULL;
1268 * Determines the absolute path of cmd using the split path in path.
1269 * If cmd contains a slash or backslash, no lookup is performed.
1271 static char *path_lookup(const char *cmd, int exe_only)
1273 const char *path;
1274 char *prog = NULL;
1275 int len = strlen(cmd);
1276 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1278 if (strpbrk(cmd, "/\\"))
1279 return xstrdup(cmd);
1281 path = mingw_getenv("PATH");
1282 if (!path)
1283 return NULL;
1285 while (!prog) {
1286 const char *sep = strchrnul(path, ';');
1287 int dirlen = sep - path;
1288 if (dirlen)
1289 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1290 if (!*sep)
1291 break;
1292 path = sep + 1;
1295 return prog;
1298 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1300 while (*s && *s != c)
1301 s++;
1302 return s;
1305 /* Compare only keys */
1306 static int wenvcmp(const void *a, const void *b)
1308 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1309 size_t p_len, q_len;
1311 /* Find the keys */
1312 p_len = wcschrnul(p, L'=') - p;
1313 q_len = wcschrnul(q, L'=') - q;
1315 /* If the length differs, include the shorter key's NUL */
1316 if (p_len < q_len)
1317 p_len++;
1318 else if (p_len > q_len)
1319 p_len = q_len + 1;
1321 return _wcsnicmp(p, q, p_len);
1325 * Build an environment block combining the inherited environment
1326 * merged with the given list of settings.
1328 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1329 * Values of the form "KEY" in deltaenv delete inherited values.
1331 * Multiple entries in deltaenv for the same key are explicitly allowed.
1333 * We return a contiguous block of UNICODE strings with a final trailing
1334 * zero word.
1336 static wchar_t *make_environment_block(char **deltaenv)
1338 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1339 size_t wlen, s, delta_size, size;
1341 wchar_t **array = NULL;
1342 size_t alloc = 0, nr = 0, i;
1344 size = 1; /* for extra NUL at the end */
1346 /* If there is no deltaenv to apply, simply return a copy. */
1347 if (!deltaenv || !*deltaenv) {
1348 for (p = wenv; p && *p; ) {
1349 size_t s = wcslen(p) + 1;
1350 size += s;
1351 p += s;
1354 ALLOC_ARRAY(result, size);
1355 COPY_ARRAY(result, wenv, size);
1356 FreeEnvironmentStringsW(wenv);
1357 return result;
1361 * If there is a deltaenv, let's accumulate all keys into `array`,
1362 * sort them using the stable git_stable_qsort() and then copy,
1363 * skipping duplicate keys
1365 for (p = wenv; p && *p; ) {
1366 ALLOC_GROW(array, nr + 1, alloc);
1367 s = wcslen(p) + 1;
1368 array[nr++] = p;
1369 p += s;
1370 size += s;
1373 /* (over-)assess size needed for wchar version of deltaenv */
1374 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1375 delta_size += strlen(deltaenv[i]) * 2 + 1;
1376 ALLOC_ARRAY(wdeltaenv, delta_size);
1378 /* convert the deltaenv, appending to array */
1379 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1380 ALLOC_GROW(array, nr + 1, alloc);
1381 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1382 array[nr++] = p;
1383 p += wlen + 1;
1386 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1387 ALLOC_ARRAY(result, size + delta_size);
1389 for (p = result, i = 0; i < nr; i++) {
1390 /* Skip any duplicate keys; last one wins */
1391 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1392 i++;
1394 /* Skip "to delete" entry */
1395 if (!wcschr(array[i], L'='))
1396 continue;
1398 size = wcslen(array[i]) + 1;
1399 COPY_ARRAY(p, array[i], size);
1400 p += size;
1402 *p = L'\0';
1404 free(array);
1405 free(wdeltaenv);
1406 FreeEnvironmentStringsW(wenv);
1407 return result;
1410 static void do_unset_environment_variables(void)
1412 static int done;
1413 char *p = unset_environment_variables;
1415 if (done || !p)
1416 return;
1417 done = 1;
1419 for (;;) {
1420 char *comma = strchr(p, ',');
1422 if (comma)
1423 *comma = '\0';
1424 unsetenv(p);
1425 if (!comma)
1426 break;
1427 p = comma + 1;
1431 struct pinfo_t {
1432 struct pinfo_t *next;
1433 pid_t pid;
1434 HANDLE proc;
1436 static struct pinfo_t *pinfo = NULL;
1437 CRITICAL_SECTION pinfo_cs;
1439 /* Used to match and chomp off path components */
1440 static inline int match_last_path_component(const char *path, size_t *len,
1441 const char *component)
1443 size_t component_len = strlen(component);
1444 if (*len < component_len + 1 ||
1445 !is_dir_sep(path[*len - component_len - 1]) ||
1446 fspathncmp(path + *len - component_len, component, component_len))
1447 return 0;
1448 *len -= component_len + 1;
1449 /* chomp off repeated dir separators */
1450 while (*len > 0 && is_dir_sep(path[*len - 1]))
1451 (*len)--;
1452 return 1;
1455 static int is_msys2_sh(const char *cmd)
1457 if (!cmd)
1458 return 0;
1460 if (!strcmp(cmd, "sh")) {
1461 static int ret = -1;
1462 char *p;
1464 if (ret >= 0)
1465 return ret;
1467 p = path_lookup(cmd, 0);
1468 if (!p)
1469 ret = 0;
1470 else {
1471 size_t len = strlen(p);
1473 ret = match_last_path_component(p, &len, "sh.exe") &&
1474 match_last_path_component(p, &len, "bin") &&
1475 match_last_path_component(p, &len, "usr");
1476 free(p);
1478 return ret;
1481 if (ends_with(cmd, "\\sh.exe")) {
1482 static char *sh;
1484 if (!sh)
1485 sh = path_lookup("sh", 0);
1487 return !fspathcmp(cmd, sh);
1490 return 0;
1493 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1494 const char *dir,
1495 int prepend_cmd, int fhin, int fhout, int fherr)
1497 static int restrict_handle_inheritance = -1;
1498 STARTUPINFOEXW si;
1499 PROCESS_INFORMATION pi;
1500 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1501 HANDLE stdhandles[3];
1502 DWORD stdhandles_count = 0;
1503 SIZE_T size;
1504 struct strbuf args;
1505 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1506 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1507 BOOL ret;
1508 HANDLE cons;
1509 const char *(*quote_arg)(const char *arg) =
1510 is_msys2_sh(cmd ? cmd : *argv) ?
1511 quote_arg_msys2 : quote_arg_msvc;
1512 const char *strace_env;
1514 /* Make sure to override previous errors, if any */
1515 errno = 0;
1517 if (restrict_handle_inheritance < 0)
1518 restrict_handle_inheritance = core_restrict_inherited_handles;
1520 * The following code to restrict which handles are inherited seems
1521 * to work properly only on Windows 7 and later, so let's disable it
1522 * on Windows Vista and 2008.
1524 if (restrict_handle_inheritance < 0)
1525 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1527 do_unset_environment_variables();
1529 /* Determine whether or not we are associated to a console */
1530 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1531 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1532 FILE_ATTRIBUTE_NORMAL, NULL);
1533 if (cons == INVALID_HANDLE_VALUE) {
1534 /* There is no console associated with this process.
1535 * Since the child is a console process, Windows
1536 * would normally create a console window. But
1537 * since we'll be redirecting std streams, we do
1538 * not need the console.
1539 * It is necessary to use DETACHED_PROCESS
1540 * instead of CREATE_NO_WINDOW to make ssh
1541 * recognize that it has no console.
1543 flags |= DETACHED_PROCESS;
1544 } else {
1545 /* There is already a console. If we specified
1546 * DETACHED_PROCESS here, too, Windows would
1547 * disassociate the child from the console.
1548 * The same is true for CREATE_NO_WINDOW.
1549 * Go figure!
1551 CloseHandle(cons);
1553 memset(&si, 0, sizeof(si));
1554 si.StartupInfo.cb = sizeof(si);
1555 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1556 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1557 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1559 /* The list of handles cannot contain duplicates */
1560 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1561 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1562 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1563 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1564 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1565 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1566 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1567 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1568 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1569 if (stdhandles_count)
1570 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1572 if (*argv && !strcmp(cmd, *argv))
1573 wcmd[0] = L'\0';
1574 else if (xutftowcs_path(wcmd, cmd) < 0)
1575 return -1;
1576 if (dir && xutftowcs_path(wdir, dir) < 0)
1577 return -1;
1579 /* concatenate argv, quoting args as we go */
1580 strbuf_init(&args, 0);
1581 if (prepend_cmd) {
1582 char *quoted = (char *)quote_arg(cmd);
1583 strbuf_addstr(&args, quoted);
1584 if (quoted != cmd)
1585 free(quoted);
1587 for (; *argv; argv++) {
1588 char *quoted = (char *)quote_arg(*argv);
1589 if (*args.buf)
1590 strbuf_addch(&args, ' ');
1591 strbuf_addstr(&args, quoted);
1592 if (quoted != *argv)
1593 free(quoted);
1596 strace_env = getenv("GIT_STRACE_COMMANDS");
1597 if (strace_env) {
1598 char *p = path_lookup("strace.exe", 1);
1599 if (!p)
1600 return error("strace not found!");
1601 if (xutftowcs_path(wcmd, p) < 0) {
1602 free(p);
1603 return -1;
1605 free(p);
1606 if (!strcmp("1", strace_env) ||
1607 !strcasecmp("yes", strace_env) ||
1608 !strcasecmp("true", strace_env))
1609 strbuf_insert(&args, 0, "strace ", 7);
1610 else {
1611 const char *quoted = quote_arg(strace_env);
1612 struct strbuf buf = STRBUF_INIT;
1613 strbuf_addf(&buf, "strace -o %s ", quoted);
1614 if (quoted != strace_env)
1615 free((char *)quoted);
1616 strbuf_insert(&args, 0, buf.buf, buf.len);
1617 strbuf_release(&buf);
1621 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1622 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1623 strbuf_release(&args);
1625 wenvblk = make_environment_block(deltaenv);
1627 memset(&pi, 0, sizeof(pi));
1628 if (restrict_handle_inheritance && stdhandles_count &&
1629 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1630 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1631 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1632 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1633 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1634 UpdateProcThreadAttribute(attr_list, 0,
1635 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1636 stdhandles,
1637 stdhandles_count * sizeof(HANDLE),
1638 NULL, NULL)) {
1639 si.lpAttributeList = attr_list;
1640 flags |= EXTENDED_STARTUPINFO_PRESENT;
1643 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1644 stdhandles_count ? TRUE : FALSE,
1645 flags, wenvblk, dir ? wdir : NULL,
1646 &si.StartupInfo, &pi);
1649 * On Windows 2008 R2, it seems that specifying certain types of handles
1650 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1651 * error. Rather than playing finicky and fragile games, let's just try
1652 * to detect this situation and simply try again without restricting any
1653 * handle inheritance. This is still better than failing to create
1654 * processes.
1656 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1657 DWORD err = GetLastError();
1658 struct strbuf buf = STRBUF_INIT;
1660 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1662 * On Windows 7 and earlier, handles on pipes and character
1663 * devices are inherited automatically, and cannot be
1664 * specified in the thread handle list. Rather than trying
1665 * to catch each and every corner case (and running the
1666 * chance of *still* forgetting a few), let's just fall
1667 * back to creating the process without trying to limit the
1668 * handle inheritance.
1670 !(err == ERROR_INVALID_PARAMETER &&
1671 GetVersion() >> 16 < 9200) &&
1672 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1673 DWORD fl = 0;
1674 int i;
1676 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1678 for (i = 0; i < stdhandles_count; i++) {
1679 HANDLE h = stdhandles[i];
1680 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1681 "handle info (%d) %lx\n", i, h,
1682 GetFileType(h),
1683 GetHandleInformation(h, &fl),
1684 fl);
1686 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1687 "at\nhttps://github.com/git-for-windows/"
1688 "git/issues/new\n\n"
1689 "To suppress this warning, please set "
1690 "the environment variable\n\n"
1691 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1692 "\n");
1694 restrict_handle_inheritance = 0;
1695 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1696 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1697 TRUE, flags, wenvblk, dir ? wdir : NULL,
1698 &si.StartupInfo, &pi);
1699 if (!ret)
1700 errno = err_win_to_posix(GetLastError());
1701 if (ret && buf.len) {
1702 warning("failed to restrict file handles (%ld)\n\n%s",
1703 err, buf.buf);
1705 strbuf_release(&buf);
1706 } else if (!ret)
1707 errno = err_win_to_posix(GetLastError());
1709 if (si.lpAttributeList)
1710 DeleteProcThreadAttributeList(si.lpAttributeList);
1711 if (attr_list)
1712 HeapFree(GetProcessHeap(), 0, attr_list);
1714 free(wenvblk);
1715 free(wargs);
1717 if (!ret)
1718 return -1;
1720 CloseHandle(pi.hThread);
1723 * The process ID is the human-readable identifier of the process
1724 * that we want to present in log and error messages. The handle
1725 * is not useful for this purpose. But we cannot close it, either,
1726 * because it is not possible to turn a process ID into a process
1727 * handle after the process terminated.
1728 * Keep the handle in a list for waitpid.
1730 EnterCriticalSection(&pinfo_cs);
1732 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1733 info->pid = pi.dwProcessId;
1734 info->proc = pi.hProcess;
1735 info->next = pinfo;
1736 pinfo = info;
1738 LeaveCriticalSection(&pinfo_cs);
1740 return (pid_t)pi.dwProcessId;
1743 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1745 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1748 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1749 const char *dir,
1750 int fhin, int fhout, int fherr)
1752 pid_t pid;
1753 char *prog = path_lookup(cmd, 0);
1755 if (!prog) {
1756 errno = ENOENT;
1757 pid = -1;
1759 else {
1760 const char *interpr = parse_interpreter(prog);
1762 if (interpr) {
1763 const char *argv0 = argv[0];
1764 char *iprog = path_lookup(interpr, 1);
1765 argv[0] = prog;
1766 if (!iprog) {
1767 errno = ENOENT;
1768 pid = -1;
1770 else {
1771 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1772 fhin, fhout, fherr);
1773 free(iprog);
1775 argv[0] = argv0;
1777 else
1778 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1779 fhin, fhout, fherr);
1780 free(prog);
1782 return pid;
1785 static int try_shell_exec(const char *cmd, char *const *argv)
1787 const char *interpr = parse_interpreter(cmd);
1788 char *prog;
1789 int pid = 0;
1791 if (!interpr)
1792 return 0;
1793 prog = path_lookup(interpr, 1);
1794 if (prog) {
1795 int exec_id;
1796 int argc = 0;
1797 #ifndef _MSC_VER
1798 const
1799 #endif
1800 char **argv2;
1801 while (argv[argc]) argc++;
1802 ALLOC_ARRAY(argv2, argc + 1);
1803 argv2[0] = (char *)cmd; /* full path to the script file */
1804 COPY_ARRAY(&argv2[1], &argv[1], argc);
1805 exec_id = trace2_exec(prog, argv2);
1806 pid = mingw_spawnv(prog, argv2, 1);
1807 if (pid >= 0) {
1808 int status;
1809 if (waitpid(pid, &status, 0) < 0)
1810 status = 255;
1811 trace2_exec_result(exec_id, status);
1812 exit(status);
1814 trace2_exec_result(exec_id, -1);
1815 pid = 1; /* indicate that we tried but failed */
1816 free(prog);
1817 free(argv2);
1819 return pid;
1822 int mingw_execv(const char *cmd, char *const *argv)
1824 /* check if git_command is a shell script */
1825 if (!try_shell_exec(cmd, argv)) {
1826 int pid, status;
1827 int exec_id;
1829 exec_id = trace2_exec(cmd, (const char **)argv);
1830 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1831 if (pid < 0) {
1832 trace2_exec_result(exec_id, -1);
1833 return -1;
1835 if (waitpid(pid, &status, 0) < 0)
1836 status = 255;
1837 trace2_exec_result(exec_id, status);
1838 exit(status);
1840 return -1;
1843 int mingw_execvp(const char *cmd, char *const *argv)
1845 char *prog = path_lookup(cmd, 0);
1847 if (prog) {
1848 mingw_execv(prog, argv);
1849 free(prog);
1850 } else
1851 errno = ENOENT;
1853 return -1;
1856 int mingw_kill(pid_t pid, int sig)
1858 if (pid > 0 && sig == SIGTERM) {
1859 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1861 if (TerminateProcess(h, -1)) {
1862 CloseHandle(h);
1863 return 0;
1866 errno = err_win_to_posix(GetLastError());
1867 CloseHandle(h);
1868 return -1;
1869 } else if (pid > 0 && sig == 0) {
1870 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1871 if (h) {
1872 CloseHandle(h);
1873 return 0;
1877 errno = EINVAL;
1878 return -1;
1882 * UTF-8 versions of getenv(), putenv() and unsetenv().
1883 * Internally, they use the CRT's stock UNICODE routines
1884 * to avoid data loss.
1886 char *mingw_getenv(const char *name)
1888 #define GETENV_MAX_RETAIN 64
1889 static char *values[GETENV_MAX_RETAIN];
1890 static int value_counter;
1891 int len_key, len_value;
1892 wchar_t *w_key;
1893 char *value;
1894 wchar_t w_value[32768];
1896 if (!name || !*name)
1897 return NULL;
1899 len_key = strlen(name) + 1;
1900 /* We cannot use xcalloc() here because that uses getenv() itself */
1901 w_key = calloc(len_key, sizeof(wchar_t));
1902 if (!w_key)
1903 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1904 xutftowcs(w_key, name, len_key);
1905 /* GetEnvironmentVariableW() only sets the last error upon failure */
1906 SetLastError(ERROR_SUCCESS);
1907 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1908 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1909 free(w_key);
1910 return NULL;
1912 free(w_key);
1914 len_value = len_value * 3 + 1;
1915 /* We cannot use xcalloc() here because that uses getenv() itself */
1916 value = calloc(len_value, sizeof(char));
1917 if (!value)
1918 die("Out of memory, (tried to allocate %u bytes)", len_value);
1919 xwcstoutf(value, w_value, len_value);
1922 * We return `value` which is an allocated value and the caller is NOT
1923 * expecting to have to free it, so we keep a round-robin array,
1924 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1926 free(values[value_counter]);
1927 values[value_counter++] = value;
1928 if (value_counter >= ARRAY_SIZE(values))
1929 value_counter = 0;
1931 return value;
1934 int mingw_putenv(const char *namevalue)
1936 int size;
1937 wchar_t *wide, *equal;
1938 BOOL result;
1940 if (!namevalue || !*namevalue)
1941 return 0;
1943 size = strlen(namevalue) * 2 + 1;
1944 wide = calloc(size, sizeof(wchar_t));
1945 if (!wide)
1946 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1947 xutftowcs(wide, namevalue, size);
1948 equal = wcschr(wide, L'=');
1949 if (!equal)
1950 result = SetEnvironmentVariableW(wide, NULL);
1951 else {
1952 *equal = L'\0';
1953 result = SetEnvironmentVariableW(wide, equal + 1);
1955 free(wide);
1957 if (!result)
1958 errno = err_win_to_posix(GetLastError());
1960 return result ? 0 : -1;
1963 static void ensure_socket_initialization(void)
1965 WSADATA wsa;
1966 static int initialized = 0;
1968 if (initialized)
1969 return;
1971 if (WSAStartup(MAKEWORD(2,2), &wsa))
1972 die("unable to initialize winsock subsystem, error %d",
1973 WSAGetLastError());
1975 atexit((void(*)(void)) WSACleanup);
1976 initialized = 1;
1979 #undef gethostname
1980 int mingw_gethostname(char *name, int namelen)
1982 ensure_socket_initialization();
1983 return gethostname(name, namelen);
1986 #undef gethostbyname
1987 struct hostent *mingw_gethostbyname(const char *host)
1989 ensure_socket_initialization();
1990 return gethostbyname(host);
1993 #undef getaddrinfo
1994 int mingw_getaddrinfo(const char *node, const char *service,
1995 const struct addrinfo *hints, struct addrinfo **res)
1997 ensure_socket_initialization();
1998 return getaddrinfo(node, service, hints, res);
2001 int mingw_socket(int domain, int type, int protocol)
2003 int sockfd;
2004 SOCKET s;
2006 ensure_socket_initialization();
2007 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2008 if (s == INVALID_SOCKET) {
2010 * WSAGetLastError() values are regular BSD error codes
2011 * biased by WSABASEERR.
2012 * However, strerror() does not know about networking
2013 * specific errors, which are values beginning at 38 or so.
2014 * Therefore, we choose to leave the biased error code
2015 * in errno so that _if_ someone looks up the code somewhere,
2016 * then it is at least the number that are usually listed.
2018 errno = WSAGetLastError();
2019 return -1;
2021 /* convert into a file descriptor */
2022 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2023 closesocket(s);
2024 return error("unable to make a socket file descriptor: %s",
2025 strerror(errno));
2027 return sockfd;
2030 #undef connect
2031 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2033 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2034 return connect(s, sa, sz);
2037 #undef bind
2038 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2040 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2041 return bind(s, sa, sz);
2044 #undef setsockopt
2045 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2047 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2048 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2051 #undef shutdown
2052 int mingw_shutdown(int sockfd, int how)
2054 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2055 return shutdown(s, how);
2058 #undef listen
2059 int mingw_listen(int sockfd, int backlog)
2061 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2062 return listen(s, backlog);
2065 #undef accept
2066 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2068 int sockfd2;
2070 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2071 SOCKET s2 = accept(s1, sa, sz);
2073 /* convert into a file descriptor */
2074 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2075 int err = errno;
2076 closesocket(s2);
2077 return error("unable to make a socket file descriptor: %s",
2078 strerror(err));
2080 return sockfd2;
2083 #undef rename
2084 int mingw_rename(const char *pold, const char *pnew)
2086 DWORD attrs, gle;
2087 int tries = 0;
2088 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2089 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2090 return -1;
2093 * Try native rename() first to get errno right.
2094 * It is based on MoveFile(), which cannot overwrite existing files.
2096 if (!_wrename(wpold, wpnew))
2097 return 0;
2098 if (errno != EEXIST)
2099 return -1;
2100 repeat:
2101 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2102 return 0;
2103 /* TODO: translate more errors */
2104 gle = GetLastError();
2105 if (gle == ERROR_ACCESS_DENIED &&
2106 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2107 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2108 DWORD attrsold = GetFileAttributesW(wpold);
2109 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2110 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2111 errno = EISDIR;
2112 else if (!_wrmdir(wpnew))
2113 goto repeat;
2114 return -1;
2116 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2117 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2118 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2119 return 0;
2120 gle = GetLastError();
2121 /* revert file attributes on failure */
2122 SetFileAttributesW(wpnew, attrs);
2125 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2127 * We assume that some other process had the source or
2128 * destination file open at the wrong moment and retry.
2129 * In order to give the other process a higher chance to
2130 * complete its operation, we give up our time slice now.
2131 * If we have to retry again, we do sleep a bit.
2133 Sleep(delay[tries]);
2134 tries++;
2135 goto repeat;
2137 if (gle == ERROR_ACCESS_DENIED &&
2138 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2139 "Should I try again?", pold, pnew))
2140 goto repeat;
2142 errno = EACCES;
2143 return -1;
2147 * Note that this doesn't return the actual pagesize, but
2148 * the allocation granularity. If future Windows specific git code
2149 * needs the real getpagesize function, we need to find another solution.
2151 int mingw_getpagesize(void)
2153 SYSTEM_INFO si;
2154 GetSystemInfo(&si);
2155 return si.dwAllocationGranularity;
2158 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2159 enum EXTENDED_NAME_FORMAT {
2160 NameDisplay = 3,
2161 NameUserPrincipal = 8
2164 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2166 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
2167 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2168 static wchar_t wbuffer[1024];
2169 DWORD len;
2171 if (!INIT_PROC_ADDR(GetUserNameExW))
2172 return NULL;
2174 len = ARRAY_SIZE(wbuffer);
2175 if (GetUserNameExW(type, wbuffer, &len)) {
2176 char *converted = xmalloc((len *= 3));
2177 if (xwcstoutf(converted, wbuffer, len) >= 0)
2178 return converted;
2179 free(converted);
2182 return NULL;
2185 char *mingw_query_user_email(void)
2187 return get_extended_user_info(NameUserPrincipal);
2190 struct passwd *getpwuid(int uid)
2192 static unsigned initialized;
2193 static char user_name[100];
2194 static struct passwd *p;
2195 wchar_t buf[100];
2196 DWORD len;
2198 if (initialized)
2199 return p;
2201 len = ARRAY_SIZE(buf);
2202 if (!GetUserNameW(buf, &len)) {
2203 initialized = 1;
2204 return NULL;
2207 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2208 initialized = 1;
2209 return NULL;
2212 p = xmalloc(sizeof(*p));
2213 p->pw_name = user_name;
2214 p->pw_gecos = get_extended_user_info(NameDisplay);
2215 if (!p->pw_gecos)
2216 p->pw_gecos = "unknown";
2217 p->pw_dir = NULL;
2219 initialized = 1;
2220 return p;
2223 static HANDLE timer_event;
2224 static HANDLE timer_thread;
2225 static int timer_interval;
2226 static int one_shot;
2227 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2229 /* The timer works like this:
2230 * The thread, ticktack(), is a trivial routine that most of the time
2231 * only waits to receive the signal to terminate. The main thread tells
2232 * the thread to terminate by setting the timer_event to the signalled
2233 * state.
2234 * But ticktack() interrupts the wait state after the timer's interval
2235 * length to call the signal handler.
2238 static unsigned __stdcall ticktack(void *dummy)
2240 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2241 mingw_raise(SIGALRM);
2242 if (one_shot)
2243 break;
2245 return 0;
2248 static int start_timer_thread(void)
2250 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2251 if (timer_event) {
2252 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2253 if (!timer_thread )
2254 return errno = ENOMEM,
2255 error("cannot start timer thread");
2256 } else
2257 return errno = ENOMEM,
2258 error("cannot allocate resources for timer");
2259 return 0;
2262 static void stop_timer_thread(void)
2264 if (timer_event)
2265 SetEvent(timer_event); /* tell thread to terminate */
2266 if (timer_thread) {
2267 int rc = WaitForSingleObject(timer_thread, 10000);
2268 if (rc == WAIT_TIMEOUT)
2269 error("timer thread did not terminate timely");
2270 else if (rc != WAIT_OBJECT_0)
2271 error("waiting for timer thread failed: %lu",
2272 GetLastError());
2273 CloseHandle(timer_thread);
2275 if (timer_event)
2276 CloseHandle(timer_event);
2277 timer_event = NULL;
2278 timer_thread = NULL;
2281 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2283 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2286 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2288 static const struct timeval zero;
2289 static int atexit_done;
2291 if (out != NULL)
2292 return errno = EINVAL,
2293 error("setitimer param 3 != NULL not implemented");
2294 if (!is_timeval_eq(&in->it_interval, &zero) &&
2295 !is_timeval_eq(&in->it_interval, &in->it_value))
2296 return errno = EINVAL,
2297 error("setitimer: it_interval must be zero or eq it_value");
2299 if (timer_thread)
2300 stop_timer_thread();
2302 if (is_timeval_eq(&in->it_value, &zero) &&
2303 is_timeval_eq(&in->it_interval, &zero))
2304 return 0;
2306 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2307 one_shot = is_timeval_eq(&in->it_interval, &zero);
2308 if (!atexit_done) {
2309 atexit(stop_timer_thread);
2310 atexit_done = 1;
2312 return start_timer_thread();
2315 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2317 if (sig != SIGALRM)
2318 return errno = EINVAL,
2319 error("sigaction only implemented for SIGALRM");
2320 if (out != NULL)
2321 return errno = EINVAL,
2322 error("sigaction: param 3 != NULL not implemented");
2324 timer_fn = in->sa_handler;
2325 return 0;
2328 #undef signal
2329 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2331 sig_handler_t old;
2333 switch (sig) {
2334 case SIGALRM:
2335 old = timer_fn;
2336 timer_fn = handler;
2337 break;
2339 case SIGINT:
2340 old = sigint_fn;
2341 sigint_fn = handler;
2342 break;
2344 default:
2345 return signal(sig, handler);
2348 return old;
2351 #undef raise
2352 int mingw_raise(int sig)
2354 switch (sig) {
2355 case SIGALRM:
2356 if (timer_fn == SIG_DFL) {
2357 if (isatty(STDERR_FILENO))
2358 fputs("Alarm clock\n", stderr);
2359 exit(128 + SIGALRM);
2360 } else if (timer_fn != SIG_IGN)
2361 timer_fn(SIGALRM);
2362 return 0;
2364 case SIGINT:
2365 if (sigint_fn == SIG_DFL)
2366 exit(128 + SIGINT);
2367 else if (sigint_fn != SIG_IGN)
2368 sigint_fn(SIGINT);
2369 return 0;
2371 #if defined(_MSC_VER)
2372 case SIGILL:
2373 case SIGFPE:
2374 case SIGSEGV:
2375 case SIGTERM:
2376 case SIGBREAK:
2377 case SIGABRT:
2378 case SIGABRT_COMPAT:
2380 * The <signal.h> header in the MS C Runtime defines 8 signals
2381 * as being supported on the platform. Anything else causes an
2382 * "Invalid signal or error" (which in DEBUG builds causes the
2383 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2384 * already know will fail.
2386 return raise(sig);
2387 default:
2388 errno = EINVAL;
2389 return -1;
2391 #else
2393 default:
2394 return raise(sig);
2396 #endif
2401 int link(const char *oldpath, const char *newpath)
2403 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2404 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2405 xutftowcs_path(wnewpath, newpath) < 0)
2406 return -1;
2408 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2409 errno = err_win_to_posix(GetLastError());
2410 return -1;
2412 return 0;
2415 pid_t waitpid(pid_t pid, int *status, int options)
2417 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2418 FALSE, pid);
2419 if (!h) {
2420 errno = ECHILD;
2421 return -1;
2424 if (pid > 0 && options & WNOHANG) {
2425 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2426 CloseHandle(h);
2427 return 0;
2429 options &= ~WNOHANG;
2432 if (options == 0) {
2433 struct pinfo_t **ppinfo;
2434 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2435 CloseHandle(h);
2436 return 0;
2439 if (status)
2440 GetExitCodeProcess(h, (LPDWORD)status);
2442 EnterCriticalSection(&pinfo_cs);
2444 ppinfo = &pinfo;
2445 while (*ppinfo) {
2446 struct pinfo_t *info = *ppinfo;
2447 if (info->pid == pid) {
2448 CloseHandle(info->proc);
2449 *ppinfo = info->next;
2450 free(info);
2451 break;
2453 ppinfo = &info->next;
2456 LeaveCriticalSection(&pinfo_cs);
2458 CloseHandle(h);
2459 return pid;
2461 CloseHandle(h);
2463 errno = EINVAL;
2464 return -1;
2467 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2469 int upos = 0, wpos = 0;
2470 const unsigned char *utf = (const unsigned char*) utfs;
2471 if (!utf || !wcs || wcslen < 1) {
2472 errno = EINVAL;
2473 return -1;
2475 /* reserve space for \0 */
2476 wcslen--;
2477 if (utflen < 0)
2478 utflen = INT_MAX;
2480 while (upos < utflen) {
2481 int c = utf[upos++] & 0xff;
2482 if (utflen == INT_MAX && c == 0)
2483 break;
2485 if (wpos >= wcslen) {
2486 wcs[wpos] = 0;
2487 errno = ERANGE;
2488 return -1;
2491 if (c < 0x80) {
2492 /* ASCII */
2493 wcs[wpos++] = c;
2494 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2495 (utf[upos] & 0xc0) == 0x80) {
2496 /* 2-byte utf-8 */
2497 c = ((c & 0x1f) << 6);
2498 c |= (utf[upos++] & 0x3f);
2499 wcs[wpos++] = c;
2500 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2501 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2502 (utf[upos] & 0xc0) == 0x80 &&
2503 (utf[upos + 1] & 0xc0) == 0x80) {
2504 /* 3-byte utf-8 */
2505 c = ((c & 0x0f) << 12);
2506 c |= ((utf[upos++] & 0x3f) << 6);
2507 c |= (utf[upos++] & 0x3f);
2508 wcs[wpos++] = c;
2509 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2510 wpos + 1 < wcslen &&
2511 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2512 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2513 (utf[upos] & 0xc0) == 0x80 &&
2514 (utf[upos + 1] & 0xc0) == 0x80 &&
2515 (utf[upos + 2] & 0xc0) == 0x80) {
2516 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2517 c = ((c & 0x07) << 18);
2518 c |= ((utf[upos++] & 0x3f) << 12);
2519 c |= ((utf[upos++] & 0x3f) << 6);
2520 c |= (utf[upos++] & 0x3f);
2521 c -= 0x10000;
2522 wcs[wpos++] = 0xd800 | (c >> 10);
2523 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2524 } else if (c >= 0xa0) {
2525 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2526 wcs[wpos++] = c;
2527 } else {
2528 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2529 static const char *hex = "0123456789abcdef";
2530 wcs[wpos++] = hex[c >> 4];
2531 if (wpos < wcslen)
2532 wcs[wpos++] = hex[c & 0x0f];
2535 wcs[wpos] = 0;
2536 return wpos;
2539 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2541 if (!wcs || !utf || utflen < 1) {
2542 errno = EINVAL;
2543 return -1;
2545 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2546 if (utflen)
2547 return utflen - 1;
2548 errno = ERANGE;
2549 return -1;
2552 static void setup_windows_environment(void)
2554 char *tmp = getenv("TMPDIR");
2556 /* on Windows it is TMP and TEMP */
2557 if (!tmp) {
2558 if (!(tmp = getenv("TMP")))
2559 tmp = getenv("TEMP");
2560 if (tmp) {
2561 setenv("TMPDIR", tmp, 1);
2562 tmp = getenv("TMPDIR");
2566 if (tmp) {
2568 * Convert all dir separators to forward slashes,
2569 * to help shell commands called from the Git
2570 * executable (by not mistaking the dir separators
2571 * for escape characters).
2573 convert_slashes(tmp);
2576 /* simulate TERM to enable auto-color (see color.c) */
2577 if (!getenv("TERM"))
2578 setenv("TERM", "cygwin", 1);
2580 /* calculate HOME if not set */
2581 if (!getenv("HOME")) {
2583 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2584 * location, thus also check if the path exists (i.e. is not
2585 * disconnected)
2587 if ((tmp = getenv("HOMEDRIVE"))) {
2588 struct strbuf buf = STRBUF_INIT;
2589 strbuf_addstr(&buf, tmp);
2590 if ((tmp = getenv("HOMEPATH"))) {
2591 strbuf_addstr(&buf, tmp);
2592 if (is_directory(buf.buf))
2593 setenv("HOME", buf.buf, 1);
2594 else
2595 tmp = NULL; /* use $USERPROFILE */
2597 strbuf_release(&buf);
2599 /* use $USERPROFILE if the home share is not available */
2600 if (!tmp && (tmp = getenv("USERPROFILE")))
2601 setenv("HOME", tmp, 1);
2605 static PSID get_current_user_sid(void)
2607 HANDLE token;
2608 DWORD len = 0;
2609 PSID result = NULL;
2611 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2612 return NULL;
2614 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2615 TOKEN_USER *info = xmalloc((size_t)len);
2616 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2617 len = GetLengthSid(info->User.Sid);
2618 result = xmalloc(len);
2619 if (!CopySid(len, result, info->User.Sid)) {
2620 error(_("failed to copy SID (%ld)"),
2621 GetLastError());
2622 FREE_AND_NULL(result);
2625 FREE_AND_NULL(info);
2627 CloseHandle(token);
2629 return result;
2632 int is_path_owned_by_current_sid(const char *path)
2634 WCHAR wpath[MAX_PATH];
2635 PSID sid = NULL;
2636 PSECURITY_DESCRIPTOR descriptor = NULL;
2637 DWORD err;
2639 static wchar_t home[MAX_PATH];
2641 int result = 0;
2643 if (xutftowcs_path(wpath, path) < 0)
2644 return 0;
2647 * On Windows, the home directory is owned by the administrator, but for
2648 * all practical purposes, it belongs to the user. Do pretend that it is
2649 * owned by the user.
2651 if (!*home) {
2652 DWORD size = ARRAY_SIZE(home);
2653 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2654 if (!len || len > size)
2655 wcscpy(home, L"::N/A::");
2657 if (!wcsicmp(wpath, home))
2658 return 1;
2660 /* Get the owner SID */
2661 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2662 OWNER_SECURITY_INFORMATION |
2663 DACL_SECURITY_INFORMATION,
2664 &sid, NULL, NULL, NULL, &descriptor);
2666 if (err != ERROR_SUCCESS)
2667 error(_("failed to get owner for '%s' (%ld)"), path, err);
2668 else if (sid && IsValidSid(sid)) {
2669 /* Now, verify that the SID matches the current user's */
2670 static PSID current_user_sid;
2672 if (!current_user_sid)
2673 current_user_sid = get_current_user_sid();
2675 if (current_user_sid &&
2676 IsValidSid(current_user_sid) &&
2677 EqualSid(sid, current_user_sid))
2678 result = 1;
2682 * We can release the security descriptor struct only now because `sid`
2683 * actually points into this struct.
2685 if (descriptor)
2686 LocalFree(descriptor);
2688 return result;
2691 int is_valid_win32_path(const char *path, int allow_literal_nul)
2693 const char *p = path;
2694 int preceding_space_or_period = 0, i = 0, periods = 0;
2696 if (!protect_ntfs)
2697 return 1;
2699 skip_dos_drive_prefix((char **)&path);
2700 goto segment_start;
2702 for (;;) {
2703 char c = *(path++);
2704 switch (c) {
2705 case '\0':
2706 case '/': case '\\':
2707 /* cannot end in ` ` or `.`, except for `.` and `..` */
2708 if (preceding_space_or_period &&
2709 (i != periods || periods > 2))
2710 return 0;
2711 if (!c)
2712 return 1;
2714 i = periods = preceding_space_or_period = 0;
2716 segment_start:
2717 switch (*path) {
2718 case 'a': case 'A': /* AUX */
2719 if (((c = path[++i]) != 'u' && c != 'U') ||
2720 ((c = path[++i]) != 'x' && c != 'X')) {
2721 not_a_reserved_name:
2722 path += i;
2723 continue;
2725 break;
2726 case 'c': case 'C':
2727 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2728 if ((c = path[++i]) != 'o' && c != 'O')
2729 goto not_a_reserved_name;
2730 c = path[++i];
2731 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2732 c = path[++i];
2733 if (c < '1' || c > '9')
2734 goto not_a_reserved_name;
2735 } else if (c == 'n' || c == 'N') { /* CON */
2736 c = path[i + 1];
2737 if ((c == 'i' || c == 'I') &&
2738 ((c = path[i + 2]) == 'n' ||
2739 c == 'N') &&
2740 path[i + 3] == '$')
2741 i += 3; /* CONIN$ */
2742 else if ((c == 'o' || c == 'O') &&
2743 ((c = path[i + 2]) == 'u' ||
2744 c == 'U') &&
2745 ((c = path[i + 3]) == 't' ||
2746 c == 'T') &&
2747 path[i + 4] == '$')
2748 i += 4; /* CONOUT$ */
2749 } else
2750 goto not_a_reserved_name;
2751 break;
2752 case 'l': case 'L': /* LPT<N> */
2753 if (((c = path[++i]) != 'p' && c != 'P') ||
2754 ((c = path[++i]) != 't' && c != 'T') ||
2755 !isdigit(path[++i]))
2756 goto not_a_reserved_name;
2757 break;
2758 case 'n': case 'N': /* NUL */
2759 if (((c = path[++i]) != 'u' && c != 'U') ||
2760 ((c = path[++i]) != 'l' && c != 'L') ||
2761 (allow_literal_nul &&
2762 !path[i + 1] && p == path))
2763 goto not_a_reserved_name;
2764 break;
2765 case 'p': case 'P': /* PRN */
2766 if (((c = path[++i]) != 'r' && c != 'R') ||
2767 ((c = path[++i]) != 'n' && c != 'N'))
2768 goto not_a_reserved_name;
2769 break;
2770 default:
2771 continue;
2775 * So far, this looks like a reserved name. Let's see
2776 * whether it actually is one: trailing spaces, a file
2777 * extension, or an NTFS Alternate Data Stream do not
2778 * matter, the name is still reserved if any of those
2779 * follow immediately after the actual name.
2781 i++;
2782 if (path[i] == ' ') {
2783 preceding_space_or_period = 1;
2784 while (path[++i] == ' ')
2785 ; /* skip all spaces */
2788 c = path[i];
2789 if (c && c != '.' && c != ':' && c != '/' && c != '\\')
2790 goto not_a_reserved_name;
2792 /* contains reserved name */
2793 return 0;
2794 case '.':
2795 periods++;
2796 /* fallthru */
2797 case ' ':
2798 preceding_space_or_period = 1;
2799 i++;
2800 continue;
2801 case ':': /* DOS drive prefix was already skipped */
2802 case '<': case '>': case '"': case '|': case '?': case '*':
2803 /* illegal character */
2804 return 0;
2805 default:
2806 if (c > '\0' && c < '\x20')
2807 /* illegal character */
2808 return 0;
2810 preceding_space_or_period = 0;
2811 i++;
2815 #if !defined(_MSC_VER)
2817 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2818 * mingw startup code, see init.c in mingw runtime).
2820 int _CRT_glob = 0;
2821 #endif
2823 static NORETURN void die_startup(void)
2825 fputs("fatal: not enough memory for initialization", stderr);
2826 exit(128);
2829 static void *malloc_startup(size_t size)
2831 void *result = malloc(size);
2832 if (!result)
2833 die_startup();
2834 return result;
2837 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2839 len = xwcstoutf(buffer, wcs, len) + 1;
2840 return memcpy(malloc_startup(len), buffer, len);
2843 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2844 DWORD desired_access, DWORD flags)
2846 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2847 wchar_t buf[MAX_PATH];
2848 DWORD max = ARRAY_SIZE(buf);
2849 HANDLE handle;
2850 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2852 if (!ret || ret >= max)
2853 return;
2855 /* make sure this does not leak into child processes */
2856 SetEnvironmentVariableW(key, NULL);
2857 if (!wcscmp(buf, L"off")) {
2858 close(fd);
2859 handle = GetStdHandle(std_id);
2860 if (handle != INVALID_HANDLE_VALUE)
2861 CloseHandle(handle);
2862 return;
2864 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2865 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2866 if (handle == INVALID_HANDLE_VALUE) {
2867 close(fd);
2868 handle = GetStdHandle(std_id);
2869 if (handle != INVALID_HANDLE_VALUE)
2870 CloseHandle(handle);
2871 } else {
2872 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2873 SetStdHandle(std_id, handle);
2874 dup2(new_fd, fd);
2875 /* do *not* close the new_fd: that would close stdout */
2877 return;
2879 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2880 flags, NULL);
2881 if (handle != INVALID_HANDLE_VALUE) {
2882 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2883 SetStdHandle(std_id, handle);
2884 dup2(new_fd, fd);
2885 close(new_fd);
2889 static void maybe_redirect_std_handles(void)
2891 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2892 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2893 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2894 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2895 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2896 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2899 #ifdef _MSC_VER
2900 #ifdef _DEBUG
2901 #include <crtdbg.h>
2902 #endif
2903 #endif
2906 * We implement wmain() and compile with -municode, which would
2907 * normally ignore main(), but we call the latter from the former
2908 * so that we can handle non-ASCII command-line parameters
2909 * appropriately.
2911 * To be more compatible with the core git code, we convert
2912 * argv into UTF8 and pass them directly to main().
2914 int wmain(int argc, const wchar_t **wargv)
2916 int i, maxlen, exit_status;
2917 char *buffer, **save;
2918 const char **argv;
2920 trace2_initialize_clock();
2922 #ifdef _MSC_VER
2923 #ifdef _DEBUG
2924 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2925 #endif
2927 #ifdef USE_MSVC_CRTDBG
2928 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2929 #endif
2930 #endif
2932 maybe_redirect_std_handles();
2934 /* determine size of argv and environ conversion buffer */
2935 maxlen = wcslen(wargv[0]);
2936 for (i = 1; i < argc; i++)
2937 maxlen = max(maxlen, wcslen(wargv[i]));
2939 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2940 maxlen = 3 * maxlen + 1;
2941 buffer = malloc_startup(maxlen);
2944 * Create a UTF-8 version of w_argv. Also create a "save" copy
2945 * to remember all the string pointers because parse_options()
2946 * will remove claimed items from the argv that we pass down.
2948 ALLOC_ARRAY(argv, argc + 1);
2949 ALLOC_ARRAY(save, argc + 1);
2950 for (i = 0; i < argc; i++)
2951 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2952 argv[i] = save[i] = NULL;
2953 free(buffer);
2955 /* fix Windows specific environment settings */
2956 setup_windows_environment();
2958 unset_environment_variables = xstrdup("PERL5LIB");
2960 /* initialize critical section for waitpid pinfo_t list */
2961 InitializeCriticalSection(&pinfo_cs);
2963 /* set up default file mode and file modes for stdin/out/err */
2964 _fmode = _O_BINARY;
2965 _setmode(_fileno(stdin), _O_BINARY);
2966 _setmode(_fileno(stdout), _O_BINARY);
2967 _setmode(_fileno(stderr), _O_BINARY);
2969 /* initialize Unicode console */
2970 winansi_init();
2972 /* invoke the real main() using our utf8 version of argv. */
2973 exit_status = main(argc, argv);
2975 for (i = 0; i < argc; i++)
2976 free(save[i]);
2977 free(save);
2978 free(argv);
2980 return exit_status;
2983 int uname(struct utsname *buf)
2985 unsigned v = (unsigned)GetVersion();
2986 memset(buf, 0, sizeof(*buf));
2987 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
2988 xsnprintf(buf->release, sizeof(buf->release),
2989 "%u.%u", v & 0xff, (v >> 8) & 0xff);
2990 /* assuming NT variants only.. */
2991 xsnprintf(buf->version, sizeof(buf->version),
2992 "%u", (v >> 16) & 0x7fff);
2993 return 0;