Sync with 2.33.8
[git/debian.git] / compat / mingw.c
blob5e42191fa4acb4ec353df177488ec4d7d1555a05
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 struct stat st;
348 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
349 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
350 * symbolic link (if it points to a directory).
352 * This behavior breaks the assumption of e.g. `remove_path()` which
353 * upon successful deletion of a file will attempt to remove its parent
354 * directories recursively until failure (which usually happens when
355 * the directory is not empty).
357 * Therefore, before calling `_wrmdir()`, we first check if the path is
358 * a symbolic link. If it is, we exit and return the same error as
359 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
361 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
362 errno = ENOTDIR;
363 return -1;
366 if (xutftowcs_path(wpathname, pathname) < 0)
367 return -1;
369 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
370 if (!is_file_in_use_error(GetLastError()))
371 errno = err_win_to_posix(GetLastError());
372 if (errno != EACCES)
373 break;
374 if (!is_dir_empty(wpathname)) {
375 errno = ENOTEMPTY;
376 break;
379 * We assume that some other process had the source or
380 * destination file open at the wrong moment and retry.
381 * In order to give the other process a higher chance to
382 * complete its operation, we give up our time slice now.
383 * If we have to retry again, we do sleep a bit.
385 Sleep(delay[tries]);
386 tries++;
388 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
389 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
390 "Should I try again?", pathname))
391 ret = _wrmdir(wpathname);
392 if (!ret)
393 invalidate_lstat_cache();
394 return ret;
397 static inline int needs_hiding(const char *path)
399 const char *basename;
401 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
402 return 0;
404 /* We cannot use basename(), as it would remove trailing slashes */
405 win32_skip_dos_drive_prefix((char **)&path);
406 if (!*path)
407 return 0;
409 for (basename = path; *path; path++)
410 if (is_dir_sep(*path)) {
411 do {
412 path++;
413 } while (is_dir_sep(*path));
414 /* ignore trailing slashes */
415 if (*path)
416 basename = path;
417 else
418 break;
421 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
422 return *basename == '.';
424 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
425 return !strncasecmp(".git", basename, 4) &&
426 (!basename[4] || is_dir_sep(basename[4]));
429 static int set_hidden_flag(const wchar_t *path, int set)
431 DWORD original = GetFileAttributesW(path), modified;
432 if (set)
433 modified = original | FILE_ATTRIBUTE_HIDDEN;
434 else
435 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
436 if (original == modified || SetFileAttributesW(path, modified))
437 return 0;
438 errno = err_win_to_posix(GetLastError());
439 return -1;
442 int mingw_mkdir(const char *path, int mode)
444 int ret;
445 wchar_t wpath[MAX_PATH];
447 if (!is_valid_win32_path(path, 0)) {
448 errno = EINVAL;
449 return -1;
452 if (xutftowcs_path(wpath, path) < 0)
453 return -1;
454 ret = _wmkdir(wpath);
455 if (!ret && needs_hiding(path))
456 return set_hidden_flag(wpath, 1);
457 return ret;
461 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
462 * is documented in [1] as opening a writable file handle in append mode.
463 * (It is believed that) this is atomic since it is maintained by the
464 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
466 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
468 * This trick does not appear to work for named pipes. Instead it creates
469 * a named pipe client handle that cannot be written to. Callers should
470 * just use the regular _wopen() for them. (And since client handle gets
471 * bound to a unique server handle, it isn't really an issue.)
473 static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
475 HANDLE handle;
476 int fd;
477 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
479 /* only these flags are supported */
480 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
481 return errno = ENOSYS, -1;
484 * FILE_SHARE_WRITE is required to permit child processes
485 * to append to the file.
487 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
488 FILE_SHARE_WRITE | FILE_SHARE_READ,
489 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
490 if (handle == INVALID_HANDLE_VALUE) {
491 DWORD err = GetLastError();
494 * Some network storage solutions (e.g. Isilon) might return
495 * ERROR_INVALID_PARAMETER instead of expected error
496 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
497 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
499 if (err == ERROR_INVALID_PARAMETER)
500 err = ERROR_PATH_NOT_FOUND;
502 errno = err_win_to_posix(err);
503 return -1;
507 * No O_APPEND here, because the CRT uses it only to reset the
508 * file pointer to EOF before each write(); but that is not
509 * necessary (and may lead to races) for a file created with
510 * FILE_APPEND_DATA.
512 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
513 if (fd < 0)
514 CloseHandle(handle);
515 return fd;
519 * Does the pathname map to the local named pipe filesystem?
520 * That is, does it have a "//./pipe/" prefix?
522 static int is_local_named_pipe_path(const char *filename)
524 return (is_dir_sep(filename[0]) &&
525 is_dir_sep(filename[1]) &&
526 filename[2] == '.' &&
527 is_dir_sep(filename[3]) &&
528 !strncasecmp(filename+4, "pipe", 4) &&
529 is_dir_sep(filename[8]) &&
530 filename[9]);
533 int mingw_open (const char *filename, int oflags, ...)
535 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
536 va_list args;
537 unsigned mode;
538 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
539 wchar_t wfilename[MAX_PATH];
540 open_fn_t open_fn;
542 va_start(args, oflags);
543 mode = va_arg(args, int);
544 va_end(args);
546 if (!is_valid_win32_path(filename, !create)) {
547 errno = create ? EINVAL : ENOENT;
548 return -1;
551 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
552 open_fn = mingw_open_append;
553 else
554 open_fn = _wopen;
556 if (filename && !strcmp(filename, "/dev/null"))
557 wcscpy(wfilename, L"nul");
558 else if (xutftowcs_path(wfilename, filename) < 0)
559 return -1;
561 fd = open_fn(wfilename, oflags, mode);
563 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
564 DWORD attrs = GetFileAttributesW(wfilename);
565 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
566 errno = EISDIR;
568 if ((oflags & O_CREAT) && needs_hiding(filename)) {
570 * Internally, _wopen() uses the CreateFile() API which errors
571 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
572 * specified and an already existing file's attributes do not
573 * match *exactly*. As there is no mode or flag we can set that
574 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
575 * again *without* the O_CREAT flag (that corresponds to the
576 * CREATE_ALWAYS flag of CreateFile()).
578 if (fd < 0 && errno == EACCES)
579 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
580 if (fd >= 0 && set_hidden_flag(wfilename, 1))
581 warning("could not mark '%s' as hidden.", filename);
583 return fd;
586 static BOOL WINAPI ctrl_ignore(DWORD type)
588 return TRUE;
591 #undef fgetc
592 int mingw_fgetc(FILE *stream)
594 int ch;
595 if (!isatty(_fileno(stream)))
596 return fgetc(stream);
598 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
599 while (1) {
600 ch = fgetc(stream);
601 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
602 break;
604 /* Ctrl+C was pressed, simulate SIGINT and retry */
605 mingw_raise(SIGINT);
607 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
608 return ch;
611 #undef fopen
612 FILE *mingw_fopen (const char *filename, const char *otype)
614 int hide = needs_hiding(filename);
615 FILE *file;
616 wchar_t wfilename[MAX_PATH], wotype[4];
617 if (filename && !strcmp(filename, "/dev/null"))
618 wcscpy(wfilename, L"nul");
619 else if (!is_valid_win32_path(filename, 1)) {
620 int create = otype && strchr(otype, 'w');
621 errno = create ? EINVAL : ENOENT;
622 return NULL;
623 } else if (xutftowcs_path(wfilename, filename) < 0)
624 return NULL;
626 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
627 return NULL;
629 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
630 error("could not unhide %s", filename);
631 return NULL;
633 file = _wfopen(wfilename, wotype);
634 if (!file && GetLastError() == ERROR_INVALID_NAME)
635 errno = ENOENT;
636 if (file && hide && set_hidden_flag(wfilename, 1))
637 warning("could not mark '%s' as hidden.", filename);
638 return file;
641 FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
643 int hide = needs_hiding(filename);
644 FILE *file;
645 wchar_t wfilename[MAX_PATH], wotype[4];
646 if (filename && !strcmp(filename, "/dev/null"))
647 wcscpy(wfilename, L"nul");
648 else if (!is_valid_win32_path(filename, 1)) {
649 int create = otype && strchr(otype, 'w');
650 errno = create ? EINVAL : ENOENT;
651 return NULL;
652 } else if (xutftowcs_path(wfilename, filename) < 0)
653 return NULL;
655 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
656 return NULL;
658 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
659 error("could not unhide %s", filename);
660 return NULL;
662 file = _wfreopen(wfilename, wotype, stream);
663 if (file && hide && set_hidden_flag(wfilename, 1))
664 warning("could not mark '%s' as hidden.", filename);
665 return file;
668 #undef fflush
669 int mingw_fflush(FILE *stream)
671 int ret = fflush(stream);
674 * write() is used behind the scenes of stdio output functions.
675 * Since git code does not check for errors after each stdio write
676 * operation, it can happen that write() is called by a later
677 * stdio function even if an earlier write() call failed. In the
678 * case of a pipe whose readable end was closed, only the first
679 * call to write() reports EPIPE on Windows. Subsequent write()
680 * calls report EINVAL. It is impossible to notice whether this
681 * fflush invocation triggered such a case, therefore, we have to
682 * catch all EINVAL errors whole-sale.
684 if (ret && errno == EINVAL)
685 errno = EPIPE;
687 return ret;
690 #undef write
691 ssize_t mingw_write(int fd, const void *buf, size_t len)
693 ssize_t result = write(fd, buf, len);
695 if (result < 0 && errno == EINVAL && buf) {
696 /* check if fd is a pipe */
697 HANDLE h = (HANDLE) _get_osfhandle(fd);
698 if (GetFileType(h) == FILE_TYPE_PIPE)
699 errno = EPIPE;
700 else
701 errno = EINVAL;
704 return result;
707 int mingw_access(const char *filename, int mode)
709 wchar_t wfilename[MAX_PATH];
710 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
711 return 0;
712 if (xutftowcs_path(wfilename, filename) < 0)
713 return -1;
714 /* X_OK is not supported by the MSVCRT version */
715 return _waccess(wfilename, mode & ~X_OK);
718 int mingw_chdir(const char *dirname)
720 wchar_t wdirname[MAX_PATH];
721 if (xutftowcs_path(wdirname, dirname) < 0)
722 return -1;
723 return _wchdir(wdirname);
726 int mingw_chmod(const char *filename, int mode)
728 wchar_t wfilename[MAX_PATH];
729 if (xutftowcs_path(wfilename, filename) < 0)
730 return -1;
731 return _wchmod(wfilename, mode);
735 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
736 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
738 static inline long long filetime_to_hnsec(const FILETIME *ft)
740 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
741 /* Windows to Unix Epoch conversion */
742 return winTime - 116444736000000000LL;
745 static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
747 long long hnsec = filetime_to_hnsec(ft);
748 ts->tv_sec = (time_t)(hnsec / 10000000);
749 ts->tv_nsec = (hnsec % 10000000) * 100;
753 * Verifies that safe_create_leading_directories() would succeed.
755 static int has_valid_directory_prefix(wchar_t *wfilename)
757 int n = wcslen(wfilename);
759 while (n > 0) {
760 wchar_t c = wfilename[--n];
761 DWORD attributes;
763 if (!is_dir_sep(c))
764 continue;
766 wfilename[n] = L'\0';
767 attributes = GetFileAttributesW(wfilename);
768 wfilename[n] = c;
769 if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
770 attributes == FILE_ATTRIBUTE_DEVICE)
771 return 1;
772 if (attributes == INVALID_FILE_ATTRIBUTES)
773 switch (GetLastError()) {
774 case ERROR_PATH_NOT_FOUND:
775 continue;
776 case ERROR_FILE_NOT_FOUND:
777 /* This implies parent directory exists. */
778 return 1;
780 return 0;
782 return 1;
785 /* We keep the do_lstat code in a separate function to avoid recursion.
786 * When a path ends with a slash, the stat will fail with ENOENT. In
787 * this case, we strip the trailing slashes and stat again.
789 * If follow is true then act like stat() and report on the link
790 * target. Otherwise report on the link itself.
792 static int do_lstat(int follow, const char *file_name, struct stat *buf)
794 WIN32_FILE_ATTRIBUTE_DATA fdata;
795 wchar_t wfilename[MAX_PATH];
796 if (xutftowcs_path(wfilename, file_name) < 0)
797 return -1;
799 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
800 buf->st_ino = 0;
801 buf->st_gid = 0;
802 buf->st_uid = 0;
803 buf->st_nlink = 1;
804 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
805 buf->st_size = fdata.nFileSizeLow |
806 (((off_t)fdata.nFileSizeHigh)<<32);
807 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
808 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
809 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
810 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
811 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
812 WIN32_FIND_DATAW findbuf;
813 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
814 if (handle != INVALID_HANDLE_VALUE) {
815 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
816 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
817 if (follow) {
818 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
819 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
820 } else {
821 buf->st_mode = S_IFLNK;
823 buf->st_mode |= S_IREAD;
824 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
825 buf->st_mode |= S_IWRITE;
827 FindClose(handle);
830 return 0;
832 switch (GetLastError()) {
833 case ERROR_ACCESS_DENIED:
834 case ERROR_SHARING_VIOLATION:
835 case ERROR_LOCK_VIOLATION:
836 case ERROR_SHARING_BUFFER_EXCEEDED:
837 errno = EACCES;
838 break;
839 case ERROR_BUFFER_OVERFLOW:
840 errno = ENAMETOOLONG;
841 break;
842 case ERROR_NOT_ENOUGH_MEMORY:
843 errno = ENOMEM;
844 break;
845 case ERROR_PATH_NOT_FOUND:
846 if (!has_valid_directory_prefix(wfilename)) {
847 errno = ENOTDIR;
848 break;
850 /* fallthru */
851 default:
852 errno = ENOENT;
853 break;
855 return -1;
858 /* We provide our own lstat/fstat functions, since the provided
859 * lstat/fstat functions are so slow. These stat functions are
860 * tailored for Git's usage (read: fast), and are not meant to be
861 * complete. Note that Git stat()s are redirected to mingw_lstat()
862 * too, since Windows doesn't really handle symlinks that well.
864 static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
866 int namelen;
867 char alt_name[PATH_MAX];
869 if (!do_lstat(follow, file_name, buf))
870 return 0;
872 /* if file_name ended in a '/', Windows returned ENOENT;
873 * try again without trailing slashes
875 if (errno != ENOENT)
876 return -1;
878 namelen = strlen(file_name);
879 if (namelen && file_name[namelen-1] != '/')
880 return -1;
881 while (namelen && file_name[namelen-1] == '/')
882 --namelen;
883 if (!namelen || namelen >= PATH_MAX)
884 return -1;
886 memcpy(alt_name, file_name, namelen);
887 alt_name[namelen] = 0;
888 return do_lstat(follow, alt_name, buf);
891 static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
893 BY_HANDLE_FILE_INFORMATION fdata;
895 if (!GetFileInformationByHandle(hnd, &fdata)) {
896 errno = err_win_to_posix(GetLastError());
897 return -1;
900 buf->st_ino = 0;
901 buf->st_gid = 0;
902 buf->st_uid = 0;
903 buf->st_nlink = 1;
904 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
905 buf->st_size = fdata.nFileSizeLow |
906 (((off_t)fdata.nFileSizeHigh)<<32);
907 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
908 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
909 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
910 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
911 return 0;
914 int mingw_lstat(const char *file_name, struct stat *buf)
916 return do_stat_internal(0, file_name, buf);
918 int mingw_stat(const char *file_name, struct stat *buf)
920 return do_stat_internal(1, file_name, buf);
923 int mingw_fstat(int fd, struct stat *buf)
925 HANDLE fh = (HANDLE)_get_osfhandle(fd);
926 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
928 switch (type) {
929 case FILE_TYPE_DISK:
930 return get_file_info_by_handle(fh, buf);
932 case FILE_TYPE_CHAR:
933 case FILE_TYPE_PIPE:
934 /* initialize stat fields */
935 memset(buf, 0, sizeof(*buf));
936 buf->st_nlink = 1;
938 if (type == FILE_TYPE_CHAR) {
939 buf->st_mode = _S_IFCHR;
940 } else {
941 buf->st_mode = _S_IFIFO;
942 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
943 buf->st_size = avail;
945 return 0;
947 default:
948 errno = EBADF;
949 return -1;
953 static inline void time_t_to_filetime(time_t t, FILETIME *ft)
955 long long winTime = t * 10000000LL + 116444736000000000LL;
956 ft->dwLowDateTime = winTime;
957 ft->dwHighDateTime = winTime >> 32;
960 int mingw_utime (const char *file_name, const struct utimbuf *times)
962 FILETIME mft, aft;
963 int fh, rc;
964 DWORD attrs;
965 wchar_t wfilename[MAX_PATH];
966 if (xutftowcs_path(wfilename, file_name) < 0)
967 return -1;
969 /* must have write permission */
970 attrs = GetFileAttributesW(wfilename);
971 if (attrs != INVALID_FILE_ATTRIBUTES &&
972 (attrs & FILE_ATTRIBUTE_READONLY)) {
973 /* ignore errors here; open() will report them */
974 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
977 if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
978 rc = -1;
979 goto revert_attrs;
982 if (times) {
983 time_t_to_filetime(times->modtime, &mft);
984 time_t_to_filetime(times->actime, &aft);
985 } else {
986 GetSystemTimeAsFileTime(&mft);
987 aft = mft;
989 if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
990 errno = EINVAL;
991 rc = -1;
992 } else
993 rc = 0;
994 close(fh);
996 revert_attrs:
997 if (attrs != INVALID_FILE_ATTRIBUTES &&
998 (attrs & FILE_ATTRIBUTE_READONLY)) {
999 /* ignore errors again */
1000 SetFileAttributesW(wfilename, attrs);
1002 return rc;
1005 #undef strftime
1006 size_t mingw_strftime(char *s, size_t max,
1007 const char *format, const struct tm *tm)
1009 /* a pointer to the original strftime in case we can't find the UCRT version */
1010 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1011 size_t ret;
1012 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, strftime, char *, size_t,
1013 const char *, const struct tm *);
1015 if (INIT_PROC_ADDR(strftime))
1016 ret = strftime(s, max, format, tm);
1017 else
1018 ret = fallback(s, max, format, tm);
1020 if (!ret && errno == EINVAL)
1021 die("invalid strftime format: '%s'", format);
1022 return ret;
1025 unsigned int sleep (unsigned int seconds)
1027 Sleep(seconds*1000);
1028 return 0;
1031 char *mingw_mktemp(char *template)
1033 wchar_t wtemplate[MAX_PATH];
1034 if (xutftowcs_path(wtemplate, template) < 0)
1035 return NULL;
1036 if (!_wmktemp(wtemplate))
1037 return NULL;
1038 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1039 return NULL;
1040 return template;
1043 int mkstemp(char *template)
1045 char *filename = mktemp(template);
1046 if (filename == NULL)
1047 return -1;
1048 return open(filename, O_RDWR | O_CREAT, 0600);
1051 int gettimeofday(struct timeval *tv, void *tz)
1053 FILETIME ft;
1054 long long hnsec;
1056 GetSystemTimeAsFileTime(&ft);
1057 hnsec = filetime_to_hnsec(&ft);
1058 tv->tv_sec = hnsec / 10000000;
1059 tv->tv_usec = (hnsec % 10000000) / 10;
1060 return 0;
1063 int pipe(int filedes[2])
1065 HANDLE h[2];
1067 /* this creates non-inheritable handles */
1068 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1069 errno = err_win_to_posix(GetLastError());
1070 return -1;
1072 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1073 if (filedes[0] < 0) {
1074 CloseHandle(h[0]);
1075 CloseHandle(h[1]);
1076 return -1;
1078 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1079 if (filedes[1] < 0) {
1080 close(filedes[0]);
1081 CloseHandle(h[1]);
1082 return -1;
1084 return 0;
1087 #ifndef __MINGW64__
1088 struct tm *gmtime_r(const time_t *timep, struct tm *result)
1090 if (gmtime_s(result, timep) == 0)
1091 return result;
1092 return NULL;
1095 struct tm *localtime_r(const time_t *timep, struct tm *result)
1097 if (localtime_s(result, timep) == 0)
1098 return result;
1099 return NULL;
1101 #endif
1103 char *mingw_getcwd(char *pointer, int len)
1105 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1106 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1108 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1109 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1110 return NULL;
1112 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1113 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1114 HANDLE hnd = CreateFileW(cwd, 0,
1115 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1116 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1117 if (hnd == INVALID_HANDLE_VALUE)
1118 return NULL;
1119 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1120 CloseHandle(hnd);
1121 if (!ret || ret >= ARRAY_SIZE(wpointer))
1122 return NULL;
1123 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1124 return NULL;
1125 return pointer;
1127 if (!ret || ret >= ARRAY_SIZE(wpointer))
1128 return NULL;
1129 if (xwcstoutf(pointer, wpointer, len) < 0)
1130 return NULL;
1131 convert_slashes(pointer);
1132 return pointer;
1136 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1137 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
1139 static const char *quote_arg_msvc(const char *arg)
1141 /* count chars to quote */
1142 int len = 0, n = 0;
1143 int force_quotes = 0;
1144 char *q, *d;
1145 const char *p = arg;
1146 if (!*p) force_quotes = 1;
1147 while (*p) {
1148 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1149 force_quotes = 1;
1150 else if (*p == '"')
1151 n++;
1152 else if (*p == '\\') {
1153 int count = 0;
1154 while (*p == '\\') {
1155 count++;
1156 p++;
1157 len++;
1159 if (*p == '"' || !*p)
1160 n += count*2 + 1;
1161 continue;
1163 len++;
1164 p++;
1166 if (!force_quotes && n == 0)
1167 return arg;
1169 /* insert \ where necessary */
1170 d = q = xmalloc(st_add3(len, n, 3));
1171 *d++ = '"';
1172 while (*arg) {
1173 if (*arg == '"')
1174 *d++ = '\\';
1175 else if (*arg == '\\') {
1176 int count = 0;
1177 while (*arg == '\\') {
1178 count++;
1179 *d++ = *arg++;
1181 if (*arg == '"' || !*arg) {
1182 while (count-- > 0)
1183 *d++ = '\\';
1184 /* don't escape the surrounding end quote */
1185 if (!*arg)
1186 break;
1187 *d++ = '\\';
1190 *d++ = *arg++;
1192 *d++ = '"';
1193 *d++ = '\0';
1194 return q;
1197 #include "quote.h"
1199 static const char *quote_arg_msys2(const char *arg)
1201 struct strbuf buf = STRBUF_INIT;
1202 const char *p2 = arg, *p;
1204 for (p = arg; *p; p++) {
1205 int ws = isspace(*p);
1206 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1207 *p != '?' && *p != '*' && *p != '~')
1208 continue;
1209 if (!buf.len)
1210 strbuf_addch(&buf, '"');
1211 if (p != p2)
1212 strbuf_add(&buf, p2, p - p2);
1213 if (*p == '\\' || *p == '"')
1214 strbuf_addch(&buf, '\\');
1215 p2 = p;
1218 if (p == arg)
1219 strbuf_addch(&buf, '"');
1220 else if (!buf.len)
1221 return arg;
1222 else
1223 strbuf_add(&buf, p2, p - p2);
1225 strbuf_addch(&buf, '"');
1226 return strbuf_detach(&buf, 0);
1229 static const char *parse_interpreter(const char *cmd)
1231 static char buf[100];
1232 char *p, *opt;
1233 int n, fd;
1235 /* don't even try a .exe */
1236 n = strlen(cmd);
1237 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1238 return NULL;
1240 fd = open(cmd, O_RDONLY);
1241 if (fd < 0)
1242 return NULL;
1243 n = read(fd, buf, sizeof(buf)-1);
1244 close(fd);
1245 if (n < 4) /* at least '#!/x' and not error */
1246 return NULL;
1248 if (buf[0] != '#' || buf[1] != '!')
1249 return NULL;
1250 buf[n] = '\0';
1251 p = buf + strcspn(buf, "\r\n");
1252 if (!*p)
1253 return NULL;
1255 *p = '\0';
1256 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1257 return NULL;
1258 /* strip options */
1259 if ((opt = strchr(p+1, ' ')))
1260 *opt = '\0';
1261 return p+1;
1265 * exe_only means that we only want to detect .exe files, but not scripts
1266 * (which do not have an extension)
1268 static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1269 int isexe, int exe_only)
1271 char path[MAX_PATH];
1272 wchar_t wpath[MAX_PATH];
1273 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1275 if (xutftowcs_path(wpath, path) < 0)
1276 return NULL;
1278 if (!isexe && _waccess(wpath, F_OK) == 0)
1279 return xstrdup(path);
1280 wpath[wcslen(wpath)-4] = '\0';
1281 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1282 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1283 path[strlen(path)-4] = '\0';
1284 return xstrdup(path);
1287 return NULL;
1291 * Determines the absolute path of cmd using the split path in path.
1292 * If cmd contains a slash or backslash, no lookup is performed.
1294 static char *path_lookup(const char *cmd, int exe_only)
1296 const char *path;
1297 char *prog = NULL;
1298 int len = strlen(cmd);
1299 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1301 if (strpbrk(cmd, "/\\"))
1302 return xstrdup(cmd);
1304 path = mingw_getenv("PATH");
1305 if (!path)
1306 return NULL;
1308 while (!prog) {
1309 const char *sep = strchrnul(path, ';');
1310 int dirlen = sep - path;
1311 if (dirlen)
1312 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1313 if (!*sep)
1314 break;
1315 path = sep + 1;
1318 return prog;
1321 static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1323 while (*s && *s != c)
1324 s++;
1325 return s;
1328 /* Compare only keys */
1329 static int wenvcmp(const void *a, const void *b)
1331 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1332 size_t p_len, q_len;
1334 /* Find the keys */
1335 p_len = wcschrnul(p, L'=') - p;
1336 q_len = wcschrnul(q, L'=') - q;
1338 /* If the length differs, include the shorter key's NUL */
1339 if (p_len < q_len)
1340 p_len++;
1341 else if (p_len > q_len)
1342 p_len = q_len + 1;
1344 return _wcsnicmp(p, q, p_len);
1348 * Build an environment block combining the inherited environment
1349 * merged with the given list of settings.
1351 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1352 * Values of the form "KEY" in deltaenv delete inherited values.
1354 * Multiple entries in deltaenv for the same key are explicitly allowed.
1356 * We return a contiguous block of UNICODE strings with a final trailing
1357 * zero word.
1359 static wchar_t *make_environment_block(char **deltaenv)
1361 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1362 size_t wlen, s, delta_size, size;
1364 wchar_t **array = NULL;
1365 size_t alloc = 0, nr = 0, i;
1367 size = 1; /* for extra NUL at the end */
1369 /* If there is no deltaenv to apply, simply return a copy. */
1370 if (!deltaenv || !*deltaenv) {
1371 for (p = wenv; p && *p; ) {
1372 size_t s = wcslen(p) + 1;
1373 size += s;
1374 p += s;
1377 ALLOC_ARRAY(result, size);
1378 COPY_ARRAY(result, wenv, size);
1379 FreeEnvironmentStringsW(wenv);
1380 return result;
1384 * If there is a deltaenv, let's accumulate all keys into `array`,
1385 * sort them using the stable git_stable_qsort() and then copy,
1386 * skipping duplicate keys
1388 for (p = wenv; p && *p; ) {
1389 ALLOC_GROW(array, nr + 1, alloc);
1390 s = wcslen(p) + 1;
1391 array[nr++] = p;
1392 p += s;
1393 size += s;
1396 /* (over-)assess size needed for wchar version of deltaenv */
1397 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1398 delta_size += strlen(deltaenv[i]) * 2 + 1;
1399 ALLOC_ARRAY(wdeltaenv, delta_size);
1401 /* convert the deltaenv, appending to array */
1402 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1403 ALLOC_GROW(array, nr + 1, alloc);
1404 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1405 array[nr++] = p;
1406 p += wlen + 1;
1409 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1410 ALLOC_ARRAY(result, size + delta_size);
1412 for (p = result, i = 0; i < nr; i++) {
1413 /* Skip any duplicate keys; last one wins */
1414 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1415 i++;
1417 /* Skip "to delete" entry */
1418 if (!wcschr(array[i], L'='))
1419 continue;
1421 size = wcslen(array[i]) + 1;
1422 COPY_ARRAY(p, array[i], size);
1423 p += size;
1425 *p = L'\0';
1427 free(array);
1428 free(wdeltaenv);
1429 FreeEnvironmentStringsW(wenv);
1430 return result;
1433 static void do_unset_environment_variables(void)
1435 static int done;
1436 char *p = unset_environment_variables;
1438 if (done || !p)
1439 return;
1440 done = 1;
1442 for (;;) {
1443 char *comma = strchr(p, ',');
1445 if (comma)
1446 *comma = '\0';
1447 unsetenv(p);
1448 if (!comma)
1449 break;
1450 p = comma + 1;
1454 struct pinfo_t {
1455 struct pinfo_t *next;
1456 pid_t pid;
1457 HANDLE proc;
1459 static struct pinfo_t *pinfo = NULL;
1460 CRITICAL_SECTION pinfo_cs;
1462 /* Used to match and chomp off path components */
1463 static inline int match_last_path_component(const char *path, size_t *len,
1464 const char *component)
1466 size_t component_len = strlen(component);
1467 if (*len < component_len + 1 ||
1468 !is_dir_sep(path[*len - component_len - 1]) ||
1469 fspathncmp(path + *len - component_len, component, component_len))
1470 return 0;
1471 *len -= component_len + 1;
1472 /* chomp off repeated dir separators */
1473 while (*len > 0 && is_dir_sep(path[*len - 1]))
1474 (*len)--;
1475 return 1;
1478 static int is_msys2_sh(const char *cmd)
1480 if (!cmd)
1481 return 0;
1483 if (!strcmp(cmd, "sh")) {
1484 static int ret = -1;
1485 char *p;
1487 if (ret >= 0)
1488 return ret;
1490 p = path_lookup(cmd, 0);
1491 if (!p)
1492 ret = 0;
1493 else {
1494 size_t len = strlen(p);
1496 ret = match_last_path_component(p, &len, "sh.exe") &&
1497 match_last_path_component(p, &len, "bin") &&
1498 match_last_path_component(p, &len, "usr");
1499 free(p);
1501 return ret;
1504 if (ends_with(cmd, "\\sh.exe")) {
1505 static char *sh;
1507 if (!sh)
1508 sh = path_lookup("sh", 0);
1510 return !fspathcmp(cmd, sh);
1513 return 0;
1516 static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1517 const char *dir,
1518 int prepend_cmd, int fhin, int fhout, int fherr)
1520 static int restrict_handle_inheritance = -1;
1521 STARTUPINFOEXW si;
1522 PROCESS_INFORMATION pi;
1523 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1524 HANDLE stdhandles[3];
1525 DWORD stdhandles_count = 0;
1526 SIZE_T size;
1527 struct strbuf args;
1528 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1529 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1530 BOOL ret;
1531 HANDLE cons;
1532 const char *(*quote_arg)(const char *arg) =
1533 is_msys2_sh(cmd ? cmd : *argv) ?
1534 quote_arg_msys2 : quote_arg_msvc;
1535 const char *strace_env;
1537 /* Make sure to override previous errors, if any */
1538 errno = 0;
1540 if (restrict_handle_inheritance < 0)
1541 restrict_handle_inheritance = core_restrict_inherited_handles;
1543 * The following code to restrict which handles are inherited seems
1544 * to work properly only on Windows 7 and later, so let's disable it
1545 * on Windows Vista and 2008.
1547 if (restrict_handle_inheritance < 0)
1548 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1550 do_unset_environment_variables();
1552 /* Determine whether or not we are associated to a console */
1553 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1554 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1555 FILE_ATTRIBUTE_NORMAL, NULL);
1556 if (cons == INVALID_HANDLE_VALUE) {
1557 /* There is no console associated with this process.
1558 * Since the child is a console process, Windows
1559 * would normally create a console window. But
1560 * since we'll be redirecting std streams, we do
1561 * not need the console.
1562 * It is necessary to use DETACHED_PROCESS
1563 * instead of CREATE_NO_WINDOW to make ssh
1564 * recognize that it has no console.
1566 flags |= DETACHED_PROCESS;
1567 } else {
1568 /* There is already a console. If we specified
1569 * DETACHED_PROCESS here, too, Windows would
1570 * disassociate the child from the console.
1571 * The same is true for CREATE_NO_WINDOW.
1572 * Go figure!
1574 CloseHandle(cons);
1576 memset(&si, 0, sizeof(si));
1577 si.StartupInfo.cb = sizeof(si);
1578 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1579 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1580 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1582 /* The list of handles cannot contain duplicates */
1583 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1584 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1585 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1586 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1587 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1588 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1589 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1590 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1591 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1592 if (stdhandles_count)
1593 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1595 if (*argv && !strcmp(cmd, *argv))
1596 wcmd[0] = L'\0';
1597 else if (xutftowcs_path(wcmd, cmd) < 0)
1598 return -1;
1599 if (dir && xutftowcs_path(wdir, dir) < 0)
1600 return -1;
1602 /* concatenate argv, quoting args as we go */
1603 strbuf_init(&args, 0);
1604 if (prepend_cmd) {
1605 char *quoted = (char *)quote_arg(cmd);
1606 strbuf_addstr(&args, quoted);
1607 if (quoted != cmd)
1608 free(quoted);
1610 for (; *argv; argv++) {
1611 char *quoted = (char *)quote_arg(*argv);
1612 if (*args.buf)
1613 strbuf_addch(&args, ' ');
1614 strbuf_addstr(&args, quoted);
1615 if (quoted != *argv)
1616 free(quoted);
1619 strace_env = getenv("GIT_STRACE_COMMANDS");
1620 if (strace_env) {
1621 char *p = path_lookup("strace.exe", 1);
1622 if (!p)
1623 return error("strace not found!");
1624 if (xutftowcs_path(wcmd, p) < 0) {
1625 free(p);
1626 return -1;
1628 free(p);
1629 if (!strcmp("1", strace_env) ||
1630 !strcasecmp("yes", strace_env) ||
1631 !strcasecmp("true", strace_env))
1632 strbuf_insert(&args, 0, "strace ", 7);
1633 else {
1634 const char *quoted = quote_arg(strace_env);
1635 struct strbuf buf = STRBUF_INIT;
1636 strbuf_addf(&buf, "strace -o %s ", quoted);
1637 if (quoted != strace_env)
1638 free((char *)quoted);
1639 strbuf_insert(&args, 0, buf.buf, buf.len);
1640 strbuf_release(&buf);
1644 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1645 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1646 strbuf_release(&args);
1648 wenvblk = make_environment_block(deltaenv);
1650 memset(&pi, 0, sizeof(pi));
1651 if (restrict_handle_inheritance && stdhandles_count &&
1652 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1653 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1654 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1655 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1656 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1657 UpdateProcThreadAttribute(attr_list, 0,
1658 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1659 stdhandles,
1660 stdhandles_count * sizeof(HANDLE),
1661 NULL, NULL)) {
1662 si.lpAttributeList = attr_list;
1663 flags |= EXTENDED_STARTUPINFO_PRESENT;
1666 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1667 stdhandles_count ? TRUE : FALSE,
1668 flags, wenvblk, dir ? wdir : NULL,
1669 &si.StartupInfo, &pi);
1672 * On Windows 2008 R2, it seems that specifying certain types of handles
1673 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1674 * error. Rather than playing finicky and fragile games, let's just try
1675 * to detect this situation and simply try again without restricting any
1676 * handle inheritance. This is still better than failing to create
1677 * processes.
1679 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1680 DWORD err = GetLastError();
1681 struct strbuf buf = STRBUF_INIT;
1683 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1685 * On Windows 7 and earlier, handles on pipes and character
1686 * devices are inherited automatically, and cannot be
1687 * specified in the thread handle list. Rather than trying
1688 * to catch each and every corner case (and running the
1689 * chance of *still* forgetting a few), let's just fall
1690 * back to creating the process without trying to limit the
1691 * handle inheritance.
1693 !(err == ERROR_INVALID_PARAMETER &&
1694 GetVersion() >> 16 < 9200) &&
1695 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1696 DWORD fl = 0;
1697 int i;
1699 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1701 for (i = 0; i < stdhandles_count; i++) {
1702 HANDLE h = stdhandles[i];
1703 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1704 "handle info (%d) %lx\n", i, h,
1705 GetFileType(h),
1706 GetHandleInformation(h, &fl),
1707 fl);
1709 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1710 "at\nhttps://github.com/git-for-windows/"
1711 "git/issues/new\n\n"
1712 "To suppress this warning, please set "
1713 "the environment variable\n\n"
1714 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1715 "\n");
1717 restrict_handle_inheritance = 0;
1718 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1719 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1720 TRUE, flags, wenvblk, dir ? wdir : NULL,
1721 &si.StartupInfo, &pi);
1722 if (!ret)
1723 errno = err_win_to_posix(GetLastError());
1724 if (ret && buf.len) {
1725 warning("failed to restrict file handles (%ld)\n\n%s",
1726 err, buf.buf);
1728 strbuf_release(&buf);
1729 } else if (!ret)
1730 errno = err_win_to_posix(GetLastError());
1732 if (si.lpAttributeList)
1733 DeleteProcThreadAttributeList(si.lpAttributeList);
1734 if (attr_list)
1735 HeapFree(GetProcessHeap(), 0, attr_list);
1737 free(wenvblk);
1738 free(wargs);
1740 if (!ret)
1741 return -1;
1743 CloseHandle(pi.hThread);
1746 * The process ID is the human-readable identifier of the process
1747 * that we want to present in log and error messages. The handle
1748 * is not useful for this purpose. But we cannot close it, either,
1749 * because it is not possible to turn a process ID into a process
1750 * handle after the process terminated.
1751 * Keep the handle in a list for waitpid.
1753 EnterCriticalSection(&pinfo_cs);
1755 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1756 info->pid = pi.dwProcessId;
1757 info->proc = pi.hProcess;
1758 info->next = pinfo;
1759 pinfo = info;
1761 LeaveCriticalSection(&pinfo_cs);
1763 return (pid_t)pi.dwProcessId;
1766 static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1768 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1771 pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1772 const char *dir,
1773 int fhin, int fhout, int fherr)
1775 pid_t pid;
1776 char *prog = path_lookup(cmd, 0);
1778 if (!prog) {
1779 errno = ENOENT;
1780 pid = -1;
1782 else {
1783 const char *interpr = parse_interpreter(prog);
1785 if (interpr) {
1786 const char *argv0 = argv[0];
1787 char *iprog = path_lookup(interpr, 1);
1788 argv[0] = prog;
1789 if (!iprog) {
1790 errno = ENOENT;
1791 pid = -1;
1793 else {
1794 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1795 fhin, fhout, fherr);
1796 free(iprog);
1798 argv[0] = argv0;
1800 else
1801 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1802 fhin, fhout, fherr);
1803 free(prog);
1805 return pid;
1808 static int try_shell_exec(const char *cmd, char *const *argv)
1810 const char *interpr = parse_interpreter(cmd);
1811 char *prog;
1812 int pid = 0;
1814 if (!interpr)
1815 return 0;
1816 prog = path_lookup(interpr, 1);
1817 if (prog) {
1818 int exec_id;
1819 int argc = 0;
1820 #ifndef _MSC_VER
1821 const
1822 #endif
1823 char **argv2;
1824 while (argv[argc]) argc++;
1825 ALLOC_ARRAY(argv2, argc + 1);
1826 argv2[0] = (char *)cmd; /* full path to the script file */
1827 COPY_ARRAY(&argv2[1], &argv[1], argc);
1828 exec_id = trace2_exec(prog, argv2);
1829 pid = mingw_spawnv(prog, argv2, 1);
1830 if (pid >= 0) {
1831 int status;
1832 if (waitpid(pid, &status, 0) < 0)
1833 status = 255;
1834 trace2_exec_result(exec_id, status);
1835 exit(status);
1837 trace2_exec_result(exec_id, -1);
1838 pid = 1; /* indicate that we tried but failed */
1839 free(prog);
1840 free(argv2);
1842 return pid;
1845 int mingw_execv(const char *cmd, char *const *argv)
1847 /* check if git_command is a shell script */
1848 if (!try_shell_exec(cmd, argv)) {
1849 int pid, status;
1850 int exec_id;
1852 exec_id = trace2_exec(cmd, (const char **)argv);
1853 pid = mingw_spawnv(cmd, (const char **)argv, 0);
1854 if (pid < 0) {
1855 trace2_exec_result(exec_id, -1);
1856 return -1;
1858 if (waitpid(pid, &status, 0) < 0)
1859 status = 255;
1860 trace2_exec_result(exec_id, status);
1861 exit(status);
1863 return -1;
1866 int mingw_execvp(const char *cmd, char *const *argv)
1868 char *prog = path_lookup(cmd, 0);
1870 if (prog) {
1871 mingw_execv(prog, argv);
1872 free(prog);
1873 } else
1874 errno = ENOENT;
1876 return -1;
1879 int mingw_kill(pid_t pid, int sig)
1881 if (pid > 0 && sig == SIGTERM) {
1882 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1884 if (TerminateProcess(h, -1)) {
1885 CloseHandle(h);
1886 return 0;
1889 errno = err_win_to_posix(GetLastError());
1890 CloseHandle(h);
1891 return -1;
1892 } else if (pid > 0 && sig == 0) {
1893 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1894 if (h) {
1895 CloseHandle(h);
1896 return 0;
1900 errno = EINVAL;
1901 return -1;
1905 * UTF-8 versions of getenv(), putenv() and unsetenv().
1906 * Internally, they use the CRT's stock UNICODE routines
1907 * to avoid data loss.
1909 char *mingw_getenv(const char *name)
1911 #define GETENV_MAX_RETAIN 64
1912 static char *values[GETENV_MAX_RETAIN];
1913 static int value_counter;
1914 int len_key, len_value;
1915 wchar_t *w_key;
1916 char *value;
1917 wchar_t w_value[32768];
1919 if (!name || !*name)
1920 return NULL;
1922 len_key = strlen(name) + 1;
1923 /* We cannot use xcalloc() here because that uses getenv() itself */
1924 w_key = calloc(len_key, sizeof(wchar_t));
1925 if (!w_key)
1926 die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1927 xutftowcs(w_key, name, len_key);
1928 /* GetEnvironmentVariableW() only sets the last error upon failure */
1929 SetLastError(ERROR_SUCCESS);
1930 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1931 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1932 free(w_key);
1933 return NULL;
1935 free(w_key);
1937 len_value = len_value * 3 + 1;
1938 /* We cannot use xcalloc() here because that uses getenv() itself */
1939 value = calloc(len_value, sizeof(char));
1940 if (!value)
1941 die("Out of memory, (tried to allocate %u bytes)", len_value);
1942 xwcstoutf(value, w_value, len_value);
1945 * We return `value` which is an allocated value and the caller is NOT
1946 * expecting to have to free it, so we keep a round-robin array,
1947 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
1949 free(values[value_counter]);
1950 values[value_counter++] = value;
1951 if (value_counter >= ARRAY_SIZE(values))
1952 value_counter = 0;
1954 return value;
1957 int mingw_putenv(const char *namevalue)
1959 int size;
1960 wchar_t *wide, *equal;
1961 BOOL result;
1963 if (!namevalue || !*namevalue)
1964 return 0;
1966 size = strlen(namevalue) * 2 + 1;
1967 wide = calloc(size, sizeof(wchar_t));
1968 if (!wide)
1969 die("Out of memory, (tried to allocate %u wchar_t's)", size);
1970 xutftowcs(wide, namevalue, size);
1971 equal = wcschr(wide, L'=');
1972 if (!equal)
1973 result = SetEnvironmentVariableW(wide, NULL);
1974 else {
1975 *equal = L'\0';
1976 result = SetEnvironmentVariableW(wide, equal + 1);
1978 free(wide);
1980 if (!result)
1981 errno = err_win_to_posix(GetLastError());
1983 return result ? 0 : -1;
1986 static void ensure_socket_initialization(void)
1988 WSADATA wsa;
1989 static int initialized = 0;
1991 if (initialized)
1992 return;
1994 if (WSAStartup(MAKEWORD(2,2), &wsa))
1995 die("unable to initialize winsock subsystem, error %d",
1996 WSAGetLastError());
1998 atexit((void(*)(void)) WSACleanup);
1999 initialized = 1;
2002 #undef gethostname
2003 int mingw_gethostname(char *name, int namelen)
2005 ensure_socket_initialization();
2006 return gethostname(name, namelen);
2009 #undef gethostbyname
2010 struct hostent *mingw_gethostbyname(const char *host)
2012 ensure_socket_initialization();
2013 return gethostbyname(host);
2016 #undef getaddrinfo
2017 int mingw_getaddrinfo(const char *node, const char *service,
2018 const struct addrinfo *hints, struct addrinfo **res)
2020 ensure_socket_initialization();
2021 return getaddrinfo(node, service, hints, res);
2024 int mingw_socket(int domain, int type, int protocol)
2026 int sockfd;
2027 SOCKET s;
2029 ensure_socket_initialization();
2030 s = WSASocket(domain, type, protocol, NULL, 0, 0);
2031 if (s == INVALID_SOCKET) {
2033 * WSAGetLastError() values are regular BSD error codes
2034 * biased by WSABASEERR.
2035 * However, strerror() does not know about networking
2036 * specific errors, which are values beginning at 38 or so.
2037 * Therefore, we choose to leave the biased error code
2038 * in errno so that _if_ someone looks up the code somewhere,
2039 * then it is at least the number that are usually listed.
2041 errno = WSAGetLastError();
2042 return -1;
2044 /* convert into a file descriptor */
2045 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2046 closesocket(s);
2047 return error("unable to make a socket file descriptor: %s",
2048 strerror(errno));
2050 return sockfd;
2053 #undef connect
2054 int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2056 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2057 return connect(s, sa, sz);
2060 #undef bind
2061 int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2063 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2064 return bind(s, sa, sz);
2067 #undef setsockopt
2068 int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2070 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2071 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2074 #undef shutdown
2075 int mingw_shutdown(int sockfd, int how)
2077 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2078 return shutdown(s, how);
2081 #undef listen
2082 int mingw_listen(int sockfd, int backlog)
2084 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2085 return listen(s, backlog);
2088 #undef accept
2089 int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2091 int sockfd2;
2093 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2094 SOCKET s2 = accept(s1, sa, sz);
2096 /* convert into a file descriptor */
2097 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2098 int err = errno;
2099 closesocket(s2);
2100 return error("unable to make a socket file descriptor: %s",
2101 strerror(err));
2103 return sockfd2;
2106 #undef rename
2107 int mingw_rename(const char *pold, const char *pnew)
2109 DWORD attrs, gle;
2110 int tries = 0;
2111 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2112 if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2113 return -1;
2116 * Try native rename() first to get errno right.
2117 * It is based on MoveFile(), which cannot overwrite existing files.
2119 if (!_wrename(wpold, wpnew))
2120 return 0;
2121 if (errno != EEXIST)
2122 return -1;
2123 repeat:
2124 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2125 return 0;
2126 /* TODO: translate more errors */
2127 gle = GetLastError();
2128 if (gle == ERROR_ACCESS_DENIED &&
2129 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2130 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2131 DWORD attrsold = GetFileAttributesW(wpold);
2132 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2133 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2134 errno = EISDIR;
2135 else if (!_wrmdir(wpnew))
2136 goto repeat;
2137 return -1;
2139 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2140 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2141 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2142 return 0;
2143 gle = GetLastError();
2144 /* revert file attributes on failure */
2145 SetFileAttributesW(wpnew, attrs);
2148 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2150 * We assume that some other process had the source or
2151 * destination file open at the wrong moment and retry.
2152 * In order to give the other process a higher chance to
2153 * complete its operation, we give up our time slice now.
2154 * If we have to retry again, we do sleep a bit.
2156 Sleep(delay[tries]);
2157 tries++;
2158 goto repeat;
2160 if (gle == ERROR_ACCESS_DENIED &&
2161 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2162 "Should I try again?", pold, pnew))
2163 goto repeat;
2165 errno = EACCES;
2166 return -1;
2170 * Note that this doesn't return the actual pagesize, but
2171 * the allocation granularity. If future Windows specific git code
2172 * needs the real getpagesize function, we need to find another solution.
2174 int mingw_getpagesize(void)
2176 SYSTEM_INFO si;
2177 GetSystemInfo(&si);
2178 return si.dwAllocationGranularity;
2181 /* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2182 enum EXTENDED_NAME_FORMAT {
2183 NameDisplay = 3,
2184 NameUserPrincipal = 8
2187 static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2189 DECLARE_PROC_ADDR(secur32.dll, BOOL, GetUserNameExW,
2190 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2191 static wchar_t wbuffer[1024];
2192 DWORD len;
2194 if (!INIT_PROC_ADDR(GetUserNameExW))
2195 return NULL;
2197 len = ARRAY_SIZE(wbuffer);
2198 if (GetUserNameExW(type, wbuffer, &len)) {
2199 char *converted = xmalloc((len *= 3));
2200 if (xwcstoutf(converted, wbuffer, len) >= 0)
2201 return converted;
2202 free(converted);
2205 return NULL;
2208 char *mingw_query_user_email(void)
2210 return get_extended_user_info(NameUserPrincipal);
2213 struct passwd *getpwuid(int uid)
2215 static unsigned initialized;
2216 static char user_name[100];
2217 static struct passwd *p;
2218 wchar_t buf[100];
2219 DWORD len;
2221 if (initialized)
2222 return p;
2224 len = ARRAY_SIZE(buf);
2225 if (!GetUserNameW(buf, &len)) {
2226 initialized = 1;
2227 return NULL;
2230 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2231 initialized = 1;
2232 return NULL;
2235 p = xmalloc(sizeof(*p));
2236 p->pw_name = user_name;
2237 p->pw_gecos = get_extended_user_info(NameDisplay);
2238 if (!p->pw_gecos)
2239 p->pw_gecos = "unknown";
2240 p->pw_dir = NULL;
2242 initialized = 1;
2243 return p;
2246 static HANDLE timer_event;
2247 static HANDLE timer_thread;
2248 static int timer_interval;
2249 static int one_shot;
2250 static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2252 /* The timer works like this:
2253 * The thread, ticktack(), is a trivial routine that most of the time
2254 * only waits to receive the signal to terminate. The main thread tells
2255 * the thread to terminate by setting the timer_event to the signalled
2256 * state.
2257 * But ticktack() interrupts the wait state after the timer's interval
2258 * length to call the signal handler.
2261 static unsigned __stdcall ticktack(void *dummy)
2263 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2264 mingw_raise(SIGALRM);
2265 if (one_shot)
2266 break;
2268 return 0;
2271 static int start_timer_thread(void)
2273 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2274 if (timer_event) {
2275 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2276 if (!timer_thread )
2277 return errno = ENOMEM,
2278 error("cannot start timer thread");
2279 } else
2280 return errno = ENOMEM,
2281 error("cannot allocate resources for timer");
2282 return 0;
2285 static void stop_timer_thread(void)
2287 if (timer_event)
2288 SetEvent(timer_event); /* tell thread to terminate */
2289 if (timer_thread) {
2290 int rc = WaitForSingleObject(timer_thread, 10000);
2291 if (rc == WAIT_TIMEOUT)
2292 error("timer thread did not terminate timely");
2293 else if (rc != WAIT_OBJECT_0)
2294 error("waiting for timer thread failed: %lu",
2295 GetLastError());
2296 CloseHandle(timer_thread);
2298 if (timer_event)
2299 CloseHandle(timer_event);
2300 timer_event = NULL;
2301 timer_thread = NULL;
2304 static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2306 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2309 int setitimer(int type, struct itimerval *in, struct itimerval *out)
2311 static const struct timeval zero;
2312 static int atexit_done;
2314 if (out != NULL)
2315 return errno = EINVAL,
2316 error("setitimer param 3 != NULL not implemented");
2317 if (!is_timeval_eq(&in->it_interval, &zero) &&
2318 !is_timeval_eq(&in->it_interval, &in->it_value))
2319 return errno = EINVAL,
2320 error("setitimer: it_interval must be zero or eq it_value");
2322 if (timer_thread)
2323 stop_timer_thread();
2325 if (is_timeval_eq(&in->it_value, &zero) &&
2326 is_timeval_eq(&in->it_interval, &zero))
2327 return 0;
2329 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2330 one_shot = is_timeval_eq(&in->it_interval, &zero);
2331 if (!atexit_done) {
2332 atexit(stop_timer_thread);
2333 atexit_done = 1;
2335 return start_timer_thread();
2338 int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2340 if (sig != SIGALRM)
2341 return errno = EINVAL,
2342 error("sigaction only implemented for SIGALRM");
2343 if (out != NULL)
2344 return errno = EINVAL,
2345 error("sigaction: param 3 != NULL not implemented");
2347 timer_fn = in->sa_handler;
2348 return 0;
2351 #undef signal
2352 sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2354 sig_handler_t old;
2356 switch (sig) {
2357 case SIGALRM:
2358 old = timer_fn;
2359 timer_fn = handler;
2360 break;
2362 case SIGINT:
2363 old = sigint_fn;
2364 sigint_fn = handler;
2365 break;
2367 default:
2368 return signal(sig, handler);
2371 return old;
2374 #undef raise
2375 int mingw_raise(int sig)
2377 switch (sig) {
2378 case SIGALRM:
2379 if (timer_fn == SIG_DFL) {
2380 if (isatty(STDERR_FILENO))
2381 fputs("Alarm clock\n", stderr);
2382 exit(128 + SIGALRM);
2383 } else if (timer_fn != SIG_IGN)
2384 timer_fn(SIGALRM);
2385 return 0;
2387 case SIGINT:
2388 if (sigint_fn == SIG_DFL)
2389 exit(128 + SIGINT);
2390 else if (sigint_fn != SIG_IGN)
2391 sigint_fn(SIGINT);
2392 return 0;
2394 #if defined(_MSC_VER)
2395 case SIGILL:
2396 case SIGFPE:
2397 case SIGSEGV:
2398 case SIGTERM:
2399 case SIGBREAK:
2400 case SIGABRT:
2401 case SIGABRT_COMPAT:
2403 * The <signal.h> header in the MS C Runtime defines 8 signals
2404 * as being supported on the platform. Anything else causes an
2405 * "Invalid signal or error" (which in DEBUG builds causes the
2406 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2407 * already know will fail.
2409 return raise(sig);
2410 default:
2411 errno = EINVAL;
2412 return -1;
2414 #else
2416 default:
2417 return raise(sig);
2419 #endif
2424 int link(const char *oldpath, const char *newpath)
2426 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2427 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2428 xutftowcs_path(wnewpath, newpath) < 0)
2429 return -1;
2431 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2432 errno = err_win_to_posix(GetLastError());
2433 return -1;
2435 return 0;
2438 pid_t waitpid(pid_t pid, int *status, int options)
2440 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2441 FALSE, pid);
2442 if (!h) {
2443 errno = ECHILD;
2444 return -1;
2447 if (pid > 0 && options & WNOHANG) {
2448 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2449 CloseHandle(h);
2450 return 0;
2452 options &= ~WNOHANG;
2455 if (options == 0) {
2456 struct pinfo_t **ppinfo;
2457 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2458 CloseHandle(h);
2459 return 0;
2462 if (status)
2463 GetExitCodeProcess(h, (LPDWORD)status);
2465 EnterCriticalSection(&pinfo_cs);
2467 ppinfo = &pinfo;
2468 while (*ppinfo) {
2469 struct pinfo_t *info = *ppinfo;
2470 if (info->pid == pid) {
2471 CloseHandle(info->proc);
2472 *ppinfo = info->next;
2473 free(info);
2474 break;
2476 ppinfo = &info->next;
2479 LeaveCriticalSection(&pinfo_cs);
2481 CloseHandle(h);
2482 return pid;
2484 CloseHandle(h);
2486 errno = EINVAL;
2487 return -1;
2490 int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2492 int upos = 0, wpos = 0;
2493 const unsigned char *utf = (const unsigned char*) utfs;
2494 if (!utf || !wcs || wcslen < 1) {
2495 errno = EINVAL;
2496 return -1;
2498 /* reserve space for \0 */
2499 wcslen--;
2500 if (utflen < 0)
2501 utflen = INT_MAX;
2503 while (upos < utflen) {
2504 int c = utf[upos++] & 0xff;
2505 if (utflen == INT_MAX && c == 0)
2506 break;
2508 if (wpos >= wcslen) {
2509 wcs[wpos] = 0;
2510 errno = ERANGE;
2511 return -1;
2514 if (c < 0x80) {
2515 /* ASCII */
2516 wcs[wpos++] = c;
2517 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2518 (utf[upos] & 0xc0) == 0x80) {
2519 /* 2-byte utf-8 */
2520 c = ((c & 0x1f) << 6);
2521 c |= (utf[upos++] & 0x3f);
2522 wcs[wpos++] = c;
2523 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2524 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2525 (utf[upos] & 0xc0) == 0x80 &&
2526 (utf[upos + 1] & 0xc0) == 0x80) {
2527 /* 3-byte utf-8 */
2528 c = ((c & 0x0f) << 12);
2529 c |= ((utf[upos++] & 0x3f) << 6);
2530 c |= (utf[upos++] & 0x3f);
2531 wcs[wpos++] = c;
2532 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2533 wpos + 1 < wcslen &&
2534 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2535 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2536 (utf[upos] & 0xc0) == 0x80 &&
2537 (utf[upos + 1] & 0xc0) == 0x80 &&
2538 (utf[upos + 2] & 0xc0) == 0x80) {
2539 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2540 c = ((c & 0x07) << 18);
2541 c |= ((utf[upos++] & 0x3f) << 12);
2542 c |= ((utf[upos++] & 0x3f) << 6);
2543 c |= (utf[upos++] & 0x3f);
2544 c -= 0x10000;
2545 wcs[wpos++] = 0xd800 | (c >> 10);
2546 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2547 } else if (c >= 0xa0) {
2548 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2549 wcs[wpos++] = c;
2550 } else {
2551 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2552 static const char *hex = "0123456789abcdef";
2553 wcs[wpos++] = hex[c >> 4];
2554 if (wpos < wcslen)
2555 wcs[wpos++] = hex[c & 0x0f];
2558 wcs[wpos] = 0;
2559 return wpos;
2562 int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2564 if (!wcs || !utf || utflen < 1) {
2565 errno = EINVAL;
2566 return -1;
2568 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2569 if (utflen)
2570 return utflen - 1;
2571 errno = ERANGE;
2572 return -1;
2575 static void setup_windows_environment(void)
2577 char *tmp = getenv("TMPDIR");
2579 /* on Windows it is TMP and TEMP */
2580 if (!tmp) {
2581 if (!(tmp = getenv("TMP")))
2582 tmp = getenv("TEMP");
2583 if (tmp) {
2584 setenv("TMPDIR", tmp, 1);
2585 tmp = getenv("TMPDIR");
2589 if (tmp) {
2591 * Convert all dir separators to forward slashes,
2592 * to help shell commands called from the Git
2593 * executable (by not mistaking the dir separators
2594 * for escape characters).
2596 convert_slashes(tmp);
2599 /* simulate TERM to enable auto-color (see color.c) */
2600 if (!getenv("TERM"))
2601 setenv("TERM", "cygwin", 1);
2603 /* calculate HOME if not set */
2604 if (!getenv("HOME")) {
2606 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2607 * location, thus also check if the path exists (i.e. is not
2608 * disconnected)
2610 if ((tmp = getenv("HOMEDRIVE"))) {
2611 struct strbuf buf = STRBUF_INIT;
2612 strbuf_addstr(&buf, tmp);
2613 if ((tmp = getenv("HOMEPATH"))) {
2614 strbuf_addstr(&buf, tmp);
2615 if (is_directory(buf.buf))
2616 setenv("HOME", buf.buf, 1);
2617 else
2618 tmp = NULL; /* use $USERPROFILE */
2620 strbuf_release(&buf);
2622 /* use $USERPROFILE if the home share is not available */
2623 if (!tmp && (tmp = getenv("USERPROFILE")))
2624 setenv("HOME", tmp, 1);
2628 static PSID get_current_user_sid(void)
2630 HANDLE token;
2631 DWORD len = 0;
2632 PSID result = NULL;
2634 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2635 return NULL;
2637 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2638 TOKEN_USER *info = xmalloc((size_t)len);
2639 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2640 len = GetLengthSid(info->User.Sid);
2641 result = xmalloc(len);
2642 if (!CopySid(len, result, info->User.Sid)) {
2643 error(_("failed to copy SID (%ld)"),
2644 GetLastError());
2645 FREE_AND_NULL(result);
2648 FREE_AND_NULL(info);
2650 CloseHandle(token);
2652 return result;
2655 int is_path_owned_by_current_sid(const char *path)
2657 WCHAR wpath[MAX_PATH];
2658 PSID sid = NULL;
2659 PSECURITY_DESCRIPTOR descriptor = NULL;
2660 DWORD err;
2662 static wchar_t home[MAX_PATH];
2664 int result = 0;
2666 if (xutftowcs_path(wpath, path) < 0)
2667 return 0;
2670 * On Windows, the home directory is owned by the administrator, but for
2671 * all practical purposes, it belongs to the user. Do pretend that it is
2672 * owned by the user.
2674 if (!*home) {
2675 DWORD size = ARRAY_SIZE(home);
2676 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2677 if (!len || len > size)
2678 wcscpy(home, L"::N/A::");
2680 if (!wcsicmp(wpath, home))
2681 return 1;
2683 /* Get the owner SID */
2684 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2685 OWNER_SECURITY_INFORMATION |
2686 DACL_SECURITY_INFORMATION,
2687 &sid, NULL, NULL, NULL, &descriptor);
2689 if (err != ERROR_SUCCESS)
2690 error(_("failed to get owner for '%s' (%ld)"), path, err);
2691 else if (sid && IsValidSid(sid)) {
2692 /* Now, verify that the SID matches the current user's */
2693 static PSID current_user_sid;
2695 if (!current_user_sid)
2696 current_user_sid = get_current_user_sid();
2698 if (current_user_sid &&
2699 IsValidSid(current_user_sid) &&
2700 EqualSid(sid, current_user_sid))
2701 result = 1;
2705 * We can release the security descriptor struct only now because `sid`
2706 * actually points into this struct.
2708 if (descriptor)
2709 LocalFree(descriptor);
2711 return result;
2714 int is_valid_win32_path(const char *path, int allow_literal_nul)
2716 const char *p = path;
2717 int preceding_space_or_period = 0, i = 0, periods = 0;
2719 if (!protect_ntfs)
2720 return 1;
2722 skip_dos_drive_prefix((char **)&path);
2723 goto segment_start;
2725 for (;;) {
2726 char c = *(path++);
2727 switch (c) {
2728 case '\0':
2729 case '/': case '\\':
2730 /* cannot end in ` ` or `.`, except for `.` and `..` */
2731 if (preceding_space_or_period &&
2732 (i != periods || periods > 2))
2733 return 0;
2734 if (!c)
2735 return 1;
2737 i = periods = preceding_space_or_period = 0;
2739 segment_start:
2740 switch (*path) {
2741 case 'a': case 'A': /* AUX */
2742 if (((c = path[++i]) != 'u' && c != 'U') ||
2743 ((c = path[++i]) != 'x' && c != 'X')) {
2744 not_a_reserved_name:
2745 path += i;
2746 continue;
2748 break;
2749 case 'c': case 'C':
2750 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
2751 if ((c = path[++i]) != 'o' && c != 'O')
2752 goto not_a_reserved_name;
2753 c = path[++i];
2754 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
2755 c = path[++i];
2756 if (c < '1' || c > '9')
2757 goto not_a_reserved_name;
2758 } else if (c == 'n' || c == 'N') { /* CON */
2759 c = path[i + 1];
2760 if ((c == 'i' || c == 'I') &&
2761 ((c = path[i + 2]) == 'n' ||
2762 c == 'N') &&
2763 path[i + 3] == '$')
2764 i += 3; /* CONIN$ */
2765 else if ((c == 'o' || c == 'O') &&
2766 ((c = path[i + 2]) == 'u' ||
2767 c == 'U') &&
2768 ((c = path[i + 3]) == 't' ||
2769 c == 'T') &&
2770 path[i + 4] == '$')
2771 i += 4; /* CONOUT$ */
2772 } else
2773 goto not_a_reserved_name;
2774 break;
2775 case 'l': case 'L': /* LPT<N> */
2776 if (((c = path[++i]) != 'p' && c != 'P') ||
2777 ((c = path[++i]) != 't' && c != 'T') ||
2778 !isdigit(path[++i]))
2779 goto not_a_reserved_name;
2780 break;
2781 case 'n': case 'N': /* NUL */
2782 if (((c = path[++i]) != 'u' && c != 'U') ||
2783 ((c = path[++i]) != 'l' && c != 'L') ||
2784 (allow_literal_nul &&
2785 !path[i + 1] && p == path))
2786 goto not_a_reserved_name;
2787 break;
2788 case 'p': case 'P': /* PRN */
2789 if (((c = path[++i]) != 'r' && c != 'R') ||
2790 ((c = path[++i]) != 'n' && c != 'N'))
2791 goto not_a_reserved_name;
2792 break;
2793 default:
2794 continue;
2798 * So far, this looks like a reserved name. Let's see
2799 * whether it actually is one: trailing spaces, a file
2800 * extension, or an NTFS Alternate Data Stream do not
2801 * matter, the name is still reserved if any of those
2802 * follow immediately after the actual name.
2804 i++;
2805 if (path[i] == ' ') {
2806 preceding_space_or_period = 1;
2807 while (path[++i] == ' ')
2808 ; /* skip all spaces */
2811 c = path[i];
2812 if (c && c != '.' && c != ':' && c != '/' && c != '\\')
2813 goto not_a_reserved_name;
2815 /* contains reserved name */
2816 return 0;
2817 case '.':
2818 periods++;
2819 /* fallthru */
2820 case ' ':
2821 preceding_space_or_period = 1;
2822 i++;
2823 continue;
2824 case ':': /* DOS drive prefix was already skipped */
2825 case '<': case '>': case '"': case '|': case '?': case '*':
2826 /* illegal character */
2827 return 0;
2828 default:
2829 if (c > '\0' && c < '\x20')
2830 /* illegal character */
2831 return 0;
2833 preceding_space_or_period = 0;
2834 i++;
2838 #if !defined(_MSC_VER)
2840 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
2841 * mingw startup code, see init.c in mingw runtime).
2843 int _CRT_glob = 0;
2844 #endif
2846 static NORETURN void die_startup(void)
2848 fputs("fatal: not enough memory for initialization", stderr);
2849 exit(128);
2852 static void *malloc_startup(size_t size)
2854 void *result = malloc(size);
2855 if (!result)
2856 die_startup();
2857 return result;
2860 static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
2862 len = xwcstoutf(buffer, wcs, len) + 1;
2863 return memcpy(malloc_startup(len), buffer, len);
2866 static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
2867 DWORD desired_access, DWORD flags)
2869 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
2870 wchar_t buf[MAX_PATH];
2871 DWORD max = ARRAY_SIZE(buf);
2872 HANDLE handle;
2873 DWORD ret = GetEnvironmentVariableW(key, buf, max);
2875 if (!ret || ret >= max)
2876 return;
2878 /* make sure this does not leak into child processes */
2879 SetEnvironmentVariableW(key, NULL);
2880 if (!wcscmp(buf, L"off")) {
2881 close(fd);
2882 handle = GetStdHandle(std_id);
2883 if (handle != INVALID_HANDLE_VALUE)
2884 CloseHandle(handle);
2885 return;
2887 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
2888 handle = GetStdHandle(STD_OUTPUT_HANDLE);
2889 if (handle == INVALID_HANDLE_VALUE) {
2890 close(fd);
2891 handle = GetStdHandle(std_id);
2892 if (handle != INVALID_HANDLE_VALUE)
2893 CloseHandle(handle);
2894 } else {
2895 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2896 SetStdHandle(std_id, handle);
2897 dup2(new_fd, fd);
2898 /* do *not* close the new_fd: that would close stdout */
2900 return;
2902 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
2903 flags, NULL);
2904 if (handle != INVALID_HANDLE_VALUE) {
2905 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
2906 SetStdHandle(std_id, handle);
2907 dup2(new_fd, fd);
2908 close(new_fd);
2912 static void maybe_redirect_std_handles(void)
2914 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
2915 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
2916 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
2917 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
2918 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
2919 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
2922 #ifdef _MSC_VER
2923 #ifdef _DEBUG
2924 #include <crtdbg.h>
2925 #endif
2926 #endif
2929 * We implement wmain() and compile with -municode, which would
2930 * normally ignore main(), but we call the latter from the former
2931 * so that we can handle non-ASCII command-line parameters
2932 * appropriately.
2934 * To be more compatible with the core git code, we convert
2935 * argv into UTF8 and pass them directly to main().
2937 int wmain(int argc, const wchar_t **wargv)
2939 int i, maxlen, exit_status;
2940 char *buffer, **save;
2941 const char **argv;
2943 trace2_initialize_clock();
2945 #ifdef _MSC_VER
2946 #ifdef _DEBUG
2947 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
2948 #endif
2950 #ifdef USE_MSVC_CRTDBG
2951 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
2952 #endif
2953 #endif
2955 maybe_redirect_std_handles();
2957 /* determine size of argv and environ conversion buffer */
2958 maxlen = wcslen(wargv[0]);
2959 for (i = 1; i < argc; i++)
2960 maxlen = max(maxlen, wcslen(wargv[i]));
2962 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
2963 maxlen = 3 * maxlen + 1;
2964 buffer = malloc_startup(maxlen);
2967 * Create a UTF-8 version of w_argv. Also create a "save" copy
2968 * to remember all the string pointers because parse_options()
2969 * will remove claimed items from the argv that we pass down.
2971 ALLOC_ARRAY(argv, argc + 1);
2972 ALLOC_ARRAY(save, argc + 1);
2973 for (i = 0; i < argc; i++)
2974 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
2975 argv[i] = save[i] = NULL;
2976 free(buffer);
2978 /* fix Windows specific environment settings */
2979 setup_windows_environment();
2981 unset_environment_variables = xstrdup("PERL5LIB");
2983 /* initialize critical section for waitpid pinfo_t list */
2984 InitializeCriticalSection(&pinfo_cs);
2986 /* set up default file mode and file modes for stdin/out/err */
2987 _fmode = _O_BINARY;
2988 _setmode(_fileno(stdin), _O_BINARY);
2989 _setmode(_fileno(stdout), _O_BINARY);
2990 _setmode(_fileno(stderr), _O_BINARY);
2992 /* initialize Unicode console */
2993 winansi_init();
2995 /* invoke the real main() using our utf8 version of argv. */
2996 exit_status = main(argc, argv);
2998 for (i = 0; i < argc; i++)
2999 free(save[i]);
3000 free(save);
3001 free(argv);
3003 return exit_status;
3006 int uname(struct utsname *buf)
3008 unsigned v = (unsigned)GetVersion();
3009 memset(buf, 0, sizeof(*buf));
3010 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3011 xsnprintf(buf->release, sizeof(buf->release),
3012 "%u.%u", v & 0xff, (v >> 8) & 0xff);
3013 /* assuming NT variants only.. */
3014 xsnprintf(buf->version, sizeof(buf->version),
3015 "%u", (v >> 16) & 0x7fff);
3016 return 0;