1
#include "../git-compat-util.h"
8
#include "../run-command.h"
11
#include "win32/lazyload.h"
13
#include "../environment.h"
15
#include "../symlinks.h"
16
#include "../wrapper.h"
22
#define HCAST(type, handle) ((type)(intptr_t)handle)
24
static const int delay[] = { 0, 1, 10, 20, 40 };
28
static struct child_process cp = CHILD_PROCESS_INIT;
30
strvec_pushl(&cp.args, "mintty", "gdb", NULL);
31
strvec_pushf(&cp.args, "--pid=%d", getpid());
33
if (start_command(&cp) < 0)
34
die_errno("Could not start gdb");
38
int err_win_to_posix(DWORD winerr)
42
case ERROR_ACCESS_DENIED: error = EACCES; break;
43
case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
44
case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
45
case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
46
case ERROR_ALREADY_EXISTS: error = EEXIST; break;
47
case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
48
case ERROR_BAD_COMMAND: error = EIO; break;
49
case ERROR_BAD_DEVICE: error = ENODEV; break;
50
case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
51
case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
52
case ERROR_BAD_FORMAT: error = ENOEXEC; break;
53
case ERROR_BAD_LENGTH: error = EINVAL; break;
54
case ERROR_BAD_PATHNAME: error = ENOENT; break;
55
case ERROR_BAD_PIPE: error = EPIPE; break;
56
case ERROR_BAD_UNIT: error = ENODEV; break;
57
case ERROR_BAD_USERNAME: error = EINVAL; break;
58
case ERROR_BROKEN_PIPE: error = EPIPE; break;
59
case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
60
case ERROR_BUSY: error = EBUSY; break;
61
case ERROR_BUSY_DRIVE: error = EBUSY; break;
62
case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
63
case ERROR_CANNOT_MAKE: error = EACCES; break;
64
case ERROR_CANTOPEN: error = EIO; break;
65
case ERROR_CANTREAD: error = EIO; break;
66
case ERROR_CANTWRITE: error = EIO; break;
67
case ERROR_CRC: error = EIO; break;
68
case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
69
case ERROR_DEVICE_IN_USE: error = EBUSY; break;
70
case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
71
case ERROR_DIRECTORY: error = EINVAL; break;
72
case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
73
case ERROR_DISK_CHANGE: error = EIO; break;
74
case ERROR_DISK_FULL: error = ENOSPC; break;
75
case ERROR_DRIVE_LOCKED: error = EBUSY; break;
76
case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
77
case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
78
case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
79
case ERROR_FILE_EXISTS: error = EEXIST; break;
80
case ERROR_FILE_INVALID: error = ENODEV; break;
81
case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
82
case ERROR_GEN_FAILURE: error = EIO; break;
83
case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
84
case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
85
case ERROR_INVALID_ACCESS: error = EACCES; break;
86
case ERROR_INVALID_ADDRESS: error = EFAULT; break;
87
case ERROR_INVALID_BLOCK: error = EFAULT; break;
88
case ERROR_INVALID_DATA: error = EINVAL; break;
89
case ERROR_INVALID_DRIVE: error = ENODEV; break;
90
case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
91
case ERROR_INVALID_FLAGS: error = EINVAL; break;
92
case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
93
case ERROR_INVALID_HANDLE: error = EBADF; break;
94
case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
95
case ERROR_INVALID_NAME: error = EINVAL; break;
96
case ERROR_INVALID_OWNER: error = EINVAL; break;
97
case ERROR_INVALID_PARAMETER: error = EINVAL; break;
98
case ERROR_INVALID_PASSWORD: error = EPERM; break;
99
case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
100
case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
101
case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
102
case ERROR_INVALID_WORKSTATION: error = EACCES; break;
103
case ERROR_IO_DEVICE: error = EIO; break;
104
case ERROR_IO_INCOMPLETE: error = EINTR; break;
105
case ERROR_LOCKED: error = EBUSY; break;
106
case ERROR_LOCK_VIOLATION: error = EACCES; break;
107
case ERROR_LOGON_FAILURE: error = EACCES; break;
108
case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
109
case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
110
case ERROR_MORE_DATA: error = EPIPE; break;
111
case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
112
case ERROR_NOACCESS: error = EFAULT; break;
113
case ERROR_NONE_MAPPED: error = EINVAL; break;
114
case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
115
case ERROR_NOT_READY: error = EAGAIN; break;
116
case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
117
case ERROR_NO_DATA: error = EPIPE; break;
118
case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
119
case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
120
case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
121
case ERROR_OPEN_FAILED: error = EIO; break;
122
case ERROR_OPEN_FILES: error = EBUSY; break;
123
case ERROR_OPERATION_ABORTED: error = EINTR; break;
124
case ERROR_OUTOFMEMORY: error = ENOMEM; break;
125
case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
126
case ERROR_PATH_BUSY: error = EBUSY; break;
127
case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
128
case ERROR_PIPE_BUSY: error = EBUSY; break;
129
case ERROR_PIPE_CONNECTED: error = EPIPE; break;
130
case ERROR_PIPE_LISTENING: error = EPIPE; break;
131
case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
132
case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
133
case ERROR_READ_FAULT: error = EIO; break;
134
case ERROR_SEEK: error = EIO; break;
135
case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
136
case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
137
case ERROR_SHARING_VIOLATION: error = EACCES; break;
138
case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
139
case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
140
case ERROR_SWAPERROR: error = ENOENT; break;
141
case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
142
case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
143
case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
144
case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
145
case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
146
case ERROR_WRITE_FAULT: error = EIO; break;
147
case ERROR_WRITE_PROTECT: error = EROFS; break;
152
static inline int is_file_in_use_error(DWORD errcode)
155
case ERROR_SHARING_VIOLATION:
156
case ERROR_ACCESS_DENIED:
163
static int read_yes_no_answer(void)
167
if (fgets(answer, sizeof(answer), stdin)) {
168
size_t answer_len = strlen(answer);
169
int got_full_line = 0, c;
172
if (answer_len >= 2 && answer[answer_len-2] == '\r') {
173
answer[answer_len-2] = '\0';
175
} else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
176
answer[answer_len-1] = '\0';
181
while ((c = getchar()) != EOF && c != '\n')
188
if (tolower(answer[0]) == 'y' && !answer[1])
190
if (!strncasecmp(answer, "yes", sizeof(answer)))
192
if (tolower(answer[0]) == 'n' && !answer[1])
194
if (!strncasecmp(answer, "no", sizeof(answer)))
201
static int ask_yes_no_if_possible(const char *format, ...)
204
const char *retry_hook;
207
va_start(args, format);
208
vsnprintf(question, sizeof(question), format, args);
211
retry_hook = mingw_getenv("GIT_ASK_YESNO");
213
struct child_process cmd = CHILD_PROCESS_INIT;
215
strvec_pushl(&cmd.args, retry_hook, question, NULL);
216
return !run_command(&cmd);
219
if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
224
fprintf(stderr, "%s (y/n) ", question);
226
if ((answer = read_yes_no_answer()) >= 0)
229
fprintf(stderr, "Sorry, I did not understand your answer. "
230
"Please type 'y' or 'n'\n");
235
enum hide_dotfiles_type {
236
HIDE_DOTFILES_FALSE = 0,
238
HIDE_DOTFILES_DOTGITONLY
241
static int core_restrict_inherited_handles = -1;
242
static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
243
static char *unset_environment_variables;
245
int mingw_core_config(const char *var, const char *value,
246
const struct config_context *ctx, void *cb)
248
if (!strcmp(var, "core.hidedotfiles")) {
249
if (value && !strcasecmp(value, "dotgitonly"))
250
hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
252
hide_dotfiles = git_config_bool(var, value);
256
if (!strcmp(var, "core.unsetenvvars")) {
258
return config_error_nonbool(var);
259
free(unset_environment_variables);
260
unset_environment_variables = xstrdup(value);
264
if (!strcmp(var, "core.restrictinheritedhandles")) {
265
if (value && !strcasecmp(value, "auto"))
266
core_restrict_inherited_handles = -1;
268
core_restrict_inherited_handles =
269
git_config_bool(var, value);
277
static wchar_t *normalize_ntpath(wchar_t *wbuf)
281
if (wbuf[0] == '\\') {
283
if (!wcsncmp(wbuf, L"\\??\\", 4) ||
284
!wcsncmp(wbuf, L"\\\\?\\", 4))
286
else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
289
if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
295
for (i = 0; wbuf[i]; i++)
301
int mingw_unlink(const char *pathname)
304
wchar_t wpathname[MAX_PATH];
305
if (xutftowcs_path(wpathname, pathname) < 0)
308
if (DeleteFileW(wpathname))
312
_wchmod(wpathname, 0666);
313
while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
314
if (!is_file_in_use_error(GetLastError()))
326
while (ret == -1 && is_file_in_use_error(GetLastError()) &&
327
ask_yes_no_if_possible("Unlink of file '%s' failed. "
328
"Should I try again?", pathname))
329
ret = _wunlink(wpathname);
333
static int is_dir_empty(const wchar_t *wpath)
335
WIN32_FIND_DATAW findbuf;
337
wchar_t wbuf[MAX_PATH + 2];
339
wcscat(wbuf, L"\\*");
340
handle = FindFirstFileW(wbuf, &findbuf);
341
if (handle == INVALID_HANDLE_VALUE)
342
return GetLastError() == ERROR_NO_MORE_FILES;
344
while (!wcscmp(findbuf.cFileName, L".") ||
345
!wcscmp(findbuf.cFileName, L".."))
346
if (!FindNextFileW(handle, &findbuf)) {
347
DWORD err = GetLastError();
349
return err == ERROR_NO_MORE_FILES;
355
int mingw_rmdir(const char *pathname)
358
wchar_t wpathname[MAX_PATH];
375
if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
380
if (xutftowcs_path(wpathname, pathname) < 0)
383
while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
384
if (!is_file_in_use_error(GetLastError()))
385
errno = err_win_to_posix(GetLastError());
388
if (!is_dir_empty(wpathname)) {
402
while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
403
ask_yes_no_if_possible("Deletion of directory '%s' failed. "
404
"Should I try again?", pathname))
405
ret = _wrmdir(wpathname);
407
invalidate_lstat_cache();
411
static inline int needs_hiding(const char *path)
413
const char *basename;
415
if (hide_dotfiles == HIDE_DOTFILES_FALSE)
419
win32_skip_dos_drive_prefix((char **)&path);
423
for (basename = path; *path; path++)
424
if (is_dir_sep(*path)) {
427
} while (is_dir_sep(*path));
435
if (hide_dotfiles == HIDE_DOTFILES_TRUE)
436
return *basename == '.';
438
assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
439
return !strncasecmp(".git", basename, 4) &&
440
(!basename[4] || is_dir_sep(basename[4]));
443
static int set_hidden_flag(const wchar_t *path, int set)
445
DWORD original = GetFileAttributesW(path), modified;
447
modified = original | FILE_ATTRIBUTE_HIDDEN;
449
modified = original & ~FILE_ATTRIBUTE_HIDDEN;
450
if (original == modified || SetFileAttributesW(path, modified))
452
errno = err_win_to_posix(GetLastError());
456
int mingw_mkdir(const char *path, int mode)
459
wchar_t wpath[MAX_PATH];
461
if (!is_valid_win32_path(path, 0)) {
466
if (xutftowcs_path(wpath, path) < 0)
468
ret = _wmkdir(wpath);
469
if (!ret && needs_hiding(path))
470
return set_hidden_flag(wpath, 1);
487
static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
491
DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
494
if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
495
return errno = ENOSYS, -1;
501
handle = CreateFileW(wfilename, FILE_APPEND_DATA,
502
FILE_SHARE_WRITE | FILE_SHARE_READ,
503
NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
504
if (handle == INVALID_HANDLE_VALUE) {
505
DWORD err = GetLastError();
513
if (err == ERROR_INVALID_PARAMETER)
514
err = ERROR_PATH_NOT_FOUND;
516
errno = err_win_to_posix(err);
526
fd = _open_osfhandle((intptr_t)handle, O_BINARY);
536
static int is_local_named_pipe_path(const char *filename)
538
return (is_dir_sep(filename[0]) &&
539
is_dir_sep(filename[1]) &&
540
filename[2] == '.' &&
541
is_dir_sep(filename[3]) &&
542
!strncasecmp(filename+4, "pipe", 4) &&
543
is_dir_sep(filename[8]) &&
547
int mingw_open (const char *filename, int oflags, ...)
549
typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
552
int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
553
wchar_t wfilename[MAX_PATH];
556
va_start(args, oflags);
557
mode = va_arg(args, int);
560
if (!is_valid_win32_path(filename, !create)) {
561
errno = create ? EINVAL : ENOENT;
565
if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
566
open_fn = mingw_open_append;
570
if (filename && !strcmp(filename, "/dev/null"))
571
wcscpy(wfilename, L"nul");
572
else if (xutftowcs_path(wfilename, filename) < 0)
575
fd = open_fn(wfilename, oflags, mode);
577
if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
578
DWORD attrs = GetFileAttributesW(wfilename);
579
if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
582
if ((oflags & O_CREAT) && needs_hiding(filename)) {
592
if (fd < 0 && errno == EACCES)
593
fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
594
if (fd >= 0 && set_hidden_flag(wfilename, 1))
595
warning("could not mark '%s' as hidden.", filename);
600
static BOOL WINAPI ctrl_ignore(DWORD type)
606
int mingw_fgetc(FILE *stream)
609
if (!isatty(_fileno(stream)))
610
return fgetc(stream);
612
SetConsoleCtrlHandler(ctrl_ignore, TRUE);
615
if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
621
SetConsoleCtrlHandler(ctrl_ignore, FALSE);
626
FILE *mingw_fopen (const char *filename, const char *otype)
628
int hide = needs_hiding(filename);
630
wchar_t wfilename[MAX_PATH], wotype[4];
631
if (filename && !strcmp(filename, "/dev/null"))
632
wcscpy(wfilename, L"nul");
633
else if (!is_valid_win32_path(filename, 1)) {
634
int create = otype && strchr(otype, 'w');
635
errno = create ? EINVAL : ENOENT;
637
} else if (xutftowcs_path(wfilename, filename) < 0)
640
if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
643
if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
644
error("could not unhide %s", filename);
647
file = _wfopen(wfilename, wotype);
648
if (!file && GetLastError() == ERROR_INVALID_NAME)
650
if (file && hide && set_hidden_flag(wfilename, 1))
651
warning("could not mark '%s' as hidden.", filename);
655
FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
657
int hide = needs_hiding(filename);
659
wchar_t wfilename[MAX_PATH], wotype[4];
660
if (filename && !strcmp(filename, "/dev/null"))
661
wcscpy(wfilename, L"nul");
662
else if (!is_valid_win32_path(filename, 1)) {
663
int create = otype && strchr(otype, 'w');
664
errno = create ? EINVAL : ENOENT;
666
} else if (xutftowcs_path(wfilename, filename) < 0)
669
if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
672
if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
673
error("could not unhide %s", filename);
676
file = _wfreopen(wfilename, wotype, stream);
677
if (file && hide && set_hidden_flag(wfilename, 1))
678
warning("could not mark '%s' as hidden.", filename);
683
int mingw_fflush(FILE *stream)
685
int ret = fflush(stream);
698
if (ret && errno == EINVAL)
705
ssize_t mingw_write(int fd, const void *buf, size_t len)
707
ssize_t result = write(fd, buf, len);
709
if (result < 0 && (errno == EINVAL || errno == ENOSPC) && buf) {
713
HANDLE h = (HANDLE) _get_osfhandle(fd);
714
if (GetFileType(h) != FILE_TYPE_PIPE)
716
else if (orig == EINVAL)
721
if (!GetNamedPipeInfo(h, NULL, NULL, &buf_size, NULL))
724
return write(fd, buf, buf_size);
732
int mingw_access(const char *filename, int mode)
734
wchar_t wfilename[MAX_PATH];
735
if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
737
if (xutftowcs_path(wfilename, filename) < 0)
740
return _waccess(wfilename, mode & ~X_OK);
743
int mingw_chdir(const char *dirname)
745
wchar_t wdirname[MAX_PATH];
746
if (xutftowcs_path(wdirname, dirname) < 0)
748
return _wchdir(wdirname);
751
int mingw_chmod(const char *filename, int mode)
753
wchar_t wfilename[MAX_PATH];
754
if (xutftowcs_path(wfilename, filename) < 0)
756
return _wchmod(wfilename, mode);
763
static inline long long filetime_to_hnsec(const FILETIME *ft)
765
long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
767
return winTime - 116444736000000000LL;
770
static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
772
long long hnsec = filetime_to_hnsec(ft);
773
ts->tv_sec = (time_t)(hnsec / 10000000);
774
ts->tv_nsec = (hnsec % 10000000) * 100;
780
static int has_valid_directory_prefix(wchar_t *wfilename)
782
int n = wcslen(wfilename);
785
wchar_t c = wfilename[--n];
791
wfilename[n] = L'\0';
792
attributes = GetFileAttributesW(wfilename);
795
(FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE))
797
if (attributes == INVALID_FILE_ATTRIBUTES)
798
switch (GetLastError()) {
799
case ERROR_PATH_NOT_FOUND:
801
case ERROR_FILE_NOT_FOUND:
817
static int do_lstat(int follow, const char *file_name, struct stat *buf)
819
WIN32_FILE_ATTRIBUTE_DATA fdata;
820
wchar_t wfilename[MAX_PATH];
821
if (xutftowcs_path(wfilename, file_name) < 0)
824
if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
829
buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
830
buf->st_size = fdata.nFileSizeLow |
831
(((off_t)fdata.nFileSizeHigh)<<32);
832
buf->st_dev = buf->st_rdev = 0;
833
filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
834
filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
835
filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
836
if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
837
WIN32_FIND_DATAW findbuf;
838
HANDLE handle = FindFirstFileW(wfilename, &findbuf);
839
if (handle != INVALID_HANDLE_VALUE) {
840
if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
841
(findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
843
char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
844
buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
846
buf->st_mode = S_IFLNK;
848
buf->st_mode |= S_IREAD;
849
if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
850
buf->st_mode |= S_IWRITE;
857
switch (GetLastError()) {
858
case ERROR_ACCESS_DENIED:
859
case ERROR_SHARING_VIOLATION:
860
case ERROR_LOCK_VIOLATION:
861
case ERROR_SHARING_BUFFER_EXCEEDED:
864
case ERROR_BUFFER_OVERFLOW:
865
errno = ENAMETOOLONG;
867
case ERROR_NOT_ENOUGH_MEMORY:
870
case ERROR_PATH_NOT_FOUND:
871
if (!has_valid_directory_prefix(wfilename)) {
889
static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
892
char alt_name[PATH_MAX];
894
if (!do_lstat(follow, file_name, buf))
903
namelen = strlen(file_name);
904
if (namelen && file_name[namelen-1] != '/')
906
while (namelen && file_name[namelen-1] == '/')
908
if (!namelen || namelen >= PATH_MAX)
911
memcpy(alt_name, file_name, namelen);
912
alt_name[namelen] = 0;
913
return do_lstat(follow, alt_name, buf);
916
static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
918
BY_HANDLE_FILE_INFORMATION fdata;
920
if (!GetFileInformationByHandle(hnd, &fdata)) {
921
errno = err_win_to_posix(GetLastError());
929
buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
930
buf->st_size = fdata.nFileSizeLow |
931
(((off_t)fdata.nFileSizeHigh)<<32);
932
buf->st_dev = buf->st_rdev = 0;
933
filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
934
filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
935
filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
939
int mingw_lstat(const char *file_name, struct stat *buf)
941
return do_stat_internal(0, file_name, buf);
943
int mingw_stat(const char *file_name, struct stat *buf)
945
return do_stat_internal(1, file_name, buf);
948
int mingw_fstat(int fd, struct stat *buf)
950
HANDLE fh = (HANDLE)_get_osfhandle(fd);
951
DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
955
return get_file_info_by_handle(fh, buf);
960
memset(buf, 0, sizeof(*buf));
963
if (type == FILE_TYPE_CHAR) {
964
buf->st_mode = _S_IFCHR;
966
buf->st_mode = _S_IFIFO;
967
if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
968
buf->st_size = avail;
978
static inline void time_t_to_filetime(time_t t, FILETIME *ft)
980
long long winTime = t * 10000000LL + 116444736000000000LL;
981
ft->dwLowDateTime = winTime;
982
ft->dwHighDateTime = winTime >> 32;
985
int mingw_utime (const char *file_name, const struct utimbuf *times)
990
wchar_t wfilename[MAX_PATH];
993
if (xutftowcs_path(wfilename, file_name) < 0)
997
attrs = GetFileAttributesW(wfilename);
998
if (attrs != INVALID_FILE_ATTRIBUTES &&
999
(attrs & FILE_ATTRIBUTE_READONLY)) {
1001
SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
1004
osfilehandle = CreateFileW(wfilename,
1005
FILE_WRITE_ATTRIBUTES,
1009
(attrs != INVALID_FILE_ATTRIBUTES &&
1010
(attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
1011
FILE_FLAG_BACKUP_SEMANTICS : 0,
1013
if (osfilehandle == INVALID_HANDLE_VALUE) {
1014
errno = err_win_to_posix(GetLastError());
1020
time_t_to_filetime(times->modtime, &mft);
1021
time_t_to_filetime(times->actime, &aft);
1023
GetSystemTimeAsFileTime(&mft);
1027
if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
1033
if (osfilehandle != INVALID_HANDLE_VALUE)
1034
CloseHandle(osfilehandle);
1037
if (attrs != INVALID_FILE_ATTRIBUTES &&
1038
(attrs & FILE_ATTRIBUTE_READONLY)) {
1040
SetFileAttributesW(wfilename, attrs);
1046
size_t mingw_strftime(char *s, size_t max,
1047
const char *format, const struct tm *tm)
1050
static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1052
DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
1053
const char *, const struct tm *);
1055
if (INIT_PROC_ADDR(strftime))
1056
ret = strftime(s, max, format, tm);
1058
ret = fallback(s, max, format, tm);
1060
if (!ret && errno == EINVAL)
1061
die("invalid strftime format: '%s'", format);
1065
unsigned int sleep (unsigned int seconds)
1067
Sleep(seconds*1000);
1071
char *mingw_mktemp(char *template)
1073
wchar_t wtemplate[MAX_PATH];
1074
if (xutftowcs_path(wtemplate, template) < 0)
1076
if (!_wmktemp(wtemplate))
1078
if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1083
int mkstemp(char *template)
1085
return git_mkstemp_mode(template, 0600);
1088
int gettimeofday(struct timeval *tv, void *tz)
1093
GetSystemTimeAsFileTime(&ft);
1094
hnsec = filetime_to_hnsec(&ft);
1095
tv->tv_sec = hnsec / 10000000;
1096
tv->tv_usec = (hnsec % 10000000) / 10;
1100
int pipe(int filedes[2])
1105
if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1106
errno = err_win_to_posix(GetLastError());
1109
filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
1110
if (filedes[0] < 0) {
1115
filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
1116
if (filedes[1] < 0) {
1125
struct tm *gmtime_r(const time_t *timep, struct tm *result)
1127
if (gmtime_s(result, timep) == 0)
1132
struct tm *localtime_r(const time_t *timep, struct tm *result)
1134
if (localtime_s(result, timep) == 0)
1140
char *mingw_getcwd(char *pointer, int len)
1142
wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1143
DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1145
if (!ret || ret >= ARRAY_SIZE(cwd)) {
1146
errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1149
ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
1150
if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1151
HANDLE hnd = CreateFileW(cwd, 0,
1152
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1153
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1154
if (hnd == INVALID_HANDLE_VALUE)
1156
ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1158
if (!ret || ret >= ARRAY_SIZE(wpointer))
1160
if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1164
if (!ret || ret >= ARRAY_SIZE(wpointer))
1166
if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1170
if (xwcstoutf(pointer, wpointer, len) < 0)
1172
convert_slashes(pointer);
1180
static const char *quote_arg_msvc(const char *arg)
1184
int force_quotes = 0;
1186
const char *p = arg;
1187
if (!*p) force_quotes = 1;
1189
if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
1193
else if (*p == '\\') {
1195
while (*p == '\\') {
1200
if (*p == '"' || !*p)
1207
if (!force_quotes && n == 0)
1211
d = q = xmalloc(st_add3(len, n, 3));
1216
else if (*arg == '\\') {
1218
while (*arg == '\\') {
1222
if (*arg == '"' || !*arg) {
1240
static const char *quote_arg_msys2(const char *arg)
1242
struct strbuf buf = STRBUF_INIT;
1243
const char *p2 = arg, *p;
1245
for (p = arg; *p; p++) {
1246
int ws = isspace(*p);
1247
if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1248
*p != '?' && *p != '*' && *p != '~')
1251
strbuf_addch(&buf, '"');
1253
strbuf_add(&buf, p2, p - p2);
1254
if (*p == '\\' || *p == '"')
1255
strbuf_addch(&buf, '\\');
1260
strbuf_addch(&buf, '"');
1264
strbuf_add(&buf, p2, p - p2);
1266
strbuf_addch(&buf, '"');
1267
return strbuf_detach(&buf, 0);
1270
static const char *parse_interpreter(const char *cmd)
1272
static char buf[100];
1278
if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1281
fd = open(cmd, O_RDONLY);
1284
n = read(fd, buf, sizeof(buf)-1);
1289
if (buf[0] != '#' || buf[1] != '!')
1292
p = buf + strcspn(buf, "\r\n");
1297
if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1300
if ((opt = strchr(p+1, ' ')))
1309
static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1310
int isexe, int exe_only)
1312
char path[MAX_PATH];
1313
wchar_t wpath[MAX_PATH];
1314
snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
1316
if (xutftowcs_path(wpath, path) < 0)
1319
if (!isexe && _waccess(wpath, F_OK) == 0)
1320
return xstrdup(path);
1321
wpath[wcslen(wpath)-4] = '\0';
1322
if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1323
if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1324
path[strlen(path)-4] = '\0';
1325
return xstrdup(path);
1335
static char *path_lookup(const char *cmd, int exe_only)
1339
int len = strlen(cmd);
1340
int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1342
if (strpbrk(cmd, "/\\"))
1343
return xstrdup(cmd);
1345
path = mingw_getenv("PATH");
1350
const char *sep = strchrnul(path, ';');
1351
int dirlen = sep - path;
1353
prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1362
char *mingw_locate_in_PATH(const char *cmd)
1364
return path_lookup(cmd, 0);
1367
static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1369
while (*s && *s != c)
1375
static int wenvcmp(const void *a, const void *b)
1377
wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1378
size_t p_len, q_len;
1381
p_len = wcschrnul(p, L'=') - p;
1382
q_len = wcschrnul(q, L'=') - q;
1387
else if (p_len > q_len)
1390
return _wcsnicmp(p, q, p_len);
1405
static wchar_t *make_environment_block(char **deltaenv)
1407
wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1408
size_t wlen, s, delta_size, size;
1410
wchar_t **array = NULL;
1411
size_t alloc = 0, nr = 0, i;
1416
if (!deltaenv || !*deltaenv) {
1417
for (p = wenv; p && *p; ) {
1418
size_t s = wcslen(p) + 1;
1423
DUP_ARRAY(result, wenv, size);
1424
FreeEnvironmentStringsW(wenv);
1433
for (p = wenv; p && *p; ) {
1434
ALLOC_GROW(array, nr + 1, alloc);
1442
for (delta_size = 0, i = 0; deltaenv[i]; i++)
1443
delta_size += strlen(deltaenv[i]) * 2 + 1;
1444
ALLOC_ARRAY(wdeltaenv, delta_size);
1447
for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1448
ALLOC_GROW(array, nr + 1, alloc);
1449
wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1454
git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
1455
ALLOC_ARRAY(result, size + delta_size);
1457
for (p = result, i = 0; i < nr; i++) {
1459
while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1463
if (!wcschr(array[i], L'='))
1466
size = wcslen(array[i]) + 1;
1467
COPY_ARRAY(p, array[i], size);
1474
FreeEnvironmentStringsW(wenv);
1478
static void do_unset_environment_variables(void)
1481
char *p = unset_environment_variables;
1488
char *comma = strchr(p, ',');
1500
struct pinfo_t *next;
1504
static struct pinfo_t *pinfo = NULL;
1505
CRITICAL_SECTION pinfo_cs;
1508
static inline int match_last_path_component(const char *path, size_t *len,
1509
const char *component)
1511
size_t component_len = strlen(component);
1512
if (*len < component_len + 1 ||
1513
!is_dir_sep(path[*len - component_len - 1]) ||
1514
fspathncmp(path + *len - component_len, component, component_len))
1516
*len -= component_len + 1;
1518
while (*len > 0 && is_dir_sep(path[*len - 1]))
1523
static int is_msys2_sh(const char *cmd)
1528
if (!strcmp(cmd, "sh")) {
1529
static int ret = -1;
1535
p = path_lookup(cmd, 0);
1539
size_t len = strlen(p);
1541
ret = match_last_path_component(p, &len, "sh.exe") &&
1542
match_last_path_component(p, &len, "bin") &&
1543
match_last_path_component(p, &len, "usr");
1549
if (ends_with(cmd, "\\sh.exe") || ends_with(cmd, "/sh.exe")) {
1553
sh = path_lookup("sh", 0);
1555
return !fspathcmp(cmd, sh);
1561
static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
1563
int prepend_cmd, int fhin, int fhout, int fherr)
1565
static int restrict_handle_inheritance = -1;
1567
PROCESS_INFORMATION pi;
1568
LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1569
HANDLE stdhandles[3];
1570
DWORD stdhandles_count = 0;
1573
wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1574
unsigned flags = CREATE_UNICODE_ENVIRONMENT;
1577
const char *(*quote_arg)(const char *arg) =
1578
is_msys2_sh(cmd ? cmd : *argv) ?
1579
quote_arg_msys2 : quote_arg_msvc;
1580
const char *strace_env;
1585
if (restrict_handle_inheritance < 0)
1586
restrict_handle_inheritance = core_restrict_inherited_handles;
1592
if (restrict_handle_inheritance < 0)
1593
restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1595
do_unset_environment_variables();
1598
cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
1599
FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1600
FILE_ATTRIBUTE_NORMAL, NULL);
1601
if (cons == INVALID_HANDLE_VALUE) {
1611
flags |= DETACHED_PROCESS;
1621
memset(&si, 0, sizeof(si));
1622
si.StartupInfo.cb = sizeof(si);
1623
si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1624
si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1625
si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1628
if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1629
stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1630
if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1631
si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1632
stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1633
if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1634
si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1635
si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1636
stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1637
if (stdhandles_count)
1638
si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
1640
if (*argv && !strcmp(cmd, *argv))
1642
else if (xutftowcs_path(wcmd, cmd) < 0)
1644
if (dir && xutftowcs_path(wdir, dir) < 0)
1648
strbuf_init(&args, 0);
1650
char *quoted = (char *)quote_arg(cmd);
1651
strbuf_addstr(&args, quoted);
1655
for (; *argv; argv++) {
1656
char *quoted = (char *)quote_arg(*argv);
1658
strbuf_addch(&args, ' ');
1659
strbuf_addstr(&args, quoted);
1660
if (quoted != *argv)
1664
strace_env = getenv("GIT_STRACE_COMMANDS");
1666
char *p = path_lookup("strace.exe", 1);
1668
return error("strace not found!");
1669
if (xutftowcs_path(wcmd, p) < 0) {
1674
if (!strcmp("1", strace_env) ||
1675
!strcasecmp("yes", strace_env) ||
1676
!strcasecmp("true", strace_env))
1677
strbuf_insert(&args, 0, "strace ", 7);
1679
const char *quoted = quote_arg(strace_env);
1680
struct strbuf buf = STRBUF_INIT;
1681
strbuf_addf(&buf, "strace -o %s ", quoted);
1682
if (quoted != strace_env)
1683
free((char *)quoted);
1684
strbuf_insert(&args, 0, buf.buf, buf.len);
1685
strbuf_release(&buf);
1689
ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
1690
xutftowcs(wargs, args.buf, 2 * args.len + 1);
1691
strbuf_release(&args);
1693
wenvblk = make_environment_block(deltaenv);
1695
memset(&pi, 0, sizeof(pi));
1696
if (restrict_handle_inheritance && stdhandles_count &&
1697
(InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1698
GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1699
(attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1700
(HeapAlloc(GetProcessHeap(), 0, size))) &&
1701
InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1702
UpdateProcThreadAttribute(attr_list, 0,
1703
PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1705
stdhandles_count * sizeof(HANDLE),
1707
si.lpAttributeList = attr_list;
1708
flags |= EXTENDED_STARTUPINFO_PRESENT;
1711
ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1712
stdhandles_count ? TRUE : FALSE,
1713
flags, wenvblk, dir ? wdir : NULL,
1714
&si.StartupInfo, &pi);
1724
if (!ret && restrict_handle_inheritance && stdhandles_count) {
1725
DWORD err = GetLastError();
1726
struct strbuf buf = STRBUF_INIT;
1728
if (err != ERROR_NO_SYSTEM_RESOURCES &&
1738
!(err == ERROR_INVALID_PARAMETER &&
1739
GetVersion() >> 16 < 9200) &&
1740
!getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1744
setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1746
for (i = 0; i < stdhandles_count; i++) {
1747
HANDLE h = stdhandles[i];
1748
strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1749
"handle info (%d) %lx\n", i, h,
1751
GetHandleInformation(h, &fl),
1754
strbuf_addstr(&buf, "\nThis is a bug; please report it "
1755
"at\nhttps://github.com/git-for-windows/"
1756
"git/issues/new\n\n"
1757
"To suppress this warning, please set "
1758
"the environment variable\n\n"
1759
"\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1762
restrict_handle_inheritance = 0;
1763
flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1764
ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1765
TRUE, flags, wenvblk, dir ? wdir : NULL,
1766
&si.StartupInfo, &pi);
1768
errno = err_win_to_posix(GetLastError());
1769
if (ret && buf.len) {
1770
warning("failed to restrict file handles (%ld)\n\n%s",
1773
strbuf_release(&buf);
1775
errno = err_win_to_posix(GetLastError());
1777
if (si.lpAttributeList)
1778
DeleteProcThreadAttributeList(si.lpAttributeList);
1780
HeapFree(GetProcessHeap(), 0, attr_list);
1788
CloseHandle(pi.hThread);
1798
EnterCriticalSection(&pinfo_cs);
1800
struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1801
info->pid = pi.dwProcessId;
1802
info->proc = pi.hProcess;
1806
LeaveCriticalSection(&pinfo_cs);
1808
return (pid_t)pi.dwProcessId;
1811
static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
1813
return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
1816
pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
1818
int fhin, int fhout, int fherr)
1821
char *prog = path_lookup(cmd, 0);
1828
const char *interpr = parse_interpreter(prog);
1831
const char *argv0 = argv[0];
1832
char *iprog = path_lookup(interpr, 1);
1839
pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
1840
fhin, fhout, fherr);
1846
pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
1847
fhin, fhout, fherr);
1853
static int try_shell_exec(const char *cmd, char *const *argv)
1855
const char *interpr = parse_interpreter(cmd);
1861
prog = path_lookup(interpr, 1);
1866
while (argv[argc]) argc++;
1867
ALLOC_ARRAY(argv2, argc + 1);
1868
argv2[0] = (char *)cmd;
1869
COPY_ARRAY(&argv2[1], &argv[1], argc);
1870
exec_id = trace2_exec(prog, (const char **)argv2);
1871
pid = mingw_spawnv(prog, (const char **)argv2, 1);
1874
if (waitpid(pid, &status, 0) < 0)
1876
trace2_exec_result(exec_id, status);
1879
trace2_exec_result(exec_id, -1);
1887
int mingw_execv(const char *cmd, char *const *argv)
1890
if (!try_shell_exec(cmd, argv)) {
1894
exec_id = trace2_exec(cmd, (const char **)argv);
1895
pid = mingw_spawnv(cmd, (const char **)argv, 0);
1897
trace2_exec_result(exec_id, -1);
1900
if (waitpid(pid, &status, 0) < 0)
1902
trace2_exec_result(exec_id, status);
1908
int mingw_execvp(const char *cmd, char *const *argv)
1910
char *prog = path_lookup(cmd, 0);
1913
mingw_execv(prog, argv);
1921
int mingw_kill(pid_t pid, int sig)
1923
if (pid > 0 && sig == SIGTERM) {
1924
HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
1926
if (TerminateProcess(h, -1)) {
1931
errno = err_win_to_posix(GetLastError());
1934
} else if (pid > 0 && sig == 0) {
1935
HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
1951
char *mingw_getenv(const char *name)
1953
#define GETENV_MAX_RETAIN 64
1954
static char *values[GETENV_MAX_RETAIN];
1955
static int value_counter;
1956
int len_key, len_value;
1959
wchar_t w_value[32768];
1961
if (!name || !*name)
1964
len_key = strlen(name) + 1;
1966
w_key = calloc(len_key, sizeof(wchar_t));
1968
die("Out of memory, (tried to allocate %u wchar_t's)", len_key);
1969
xutftowcs(w_key, name, len_key);
1971
SetLastError(ERROR_SUCCESS);
1972
len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
1973
if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
1979
len_value = len_value * 3 + 1;
1981
value = calloc(len_value, sizeof(char));
1983
die("Out of memory, (tried to allocate %u bytes)", len_value);
1984
xwcstoutf(value, w_value, len_value);
1991
free(values[value_counter]);
1992
values[value_counter++] = value;
1993
if (value_counter >= ARRAY_SIZE(values))
1999
int mingw_putenv(const char *namevalue)
2002
wchar_t *wide, *equal;
2005
if (!namevalue || !*namevalue)
2008
size = strlen(namevalue) * 2 + 1;
2009
wide = calloc(size, sizeof(wchar_t));
2011
die("Out of memory, (tried to allocate %u wchar_t's)", size);
2012
xutftowcs(wide, namevalue, size);
2013
equal = wcschr(wide, L'=');
2015
result = SetEnvironmentVariableW(wide, NULL);
2018
result = SetEnvironmentVariableW(wide, equal + 1);
2023
errno = err_win_to_posix(GetLastError());
2025
return result ? 0 : -1;
2028
static void ensure_socket_initialization(void)
2031
static int initialized = 0;
2036
if (WSAStartup(MAKEWORD(2,2), &wsa))
2037
die("unable to initialize winsock subsystem, error %d",
2040
atexit((void(*)(void)) WSACleanup);
2045
int mingw_gethostname(char *name, int namelen)
2047
ensure_socket_initialization();
2048
return gethostname(name, namelen);
2052
struct hostent *mingw_gethostbyname(const char *host)
2054
ensure_socket_initialization();
2055
return gethostbyname(host);
2059
int mingw_getaddrinfo(const char *node, const char *service,
2060
const struct addrinfo *hints, struct addrinfo **res)
2062
ensure_socket_initialization();
2063
return getaddrinfo(node, service, hints, res);
2066
int mingw_socket(int domain, int type, int protocol)
2071
ensure_socket_initialization();
2072
s = WSASocket(domain, type, protocol, NULL, 0, 0);
2073
if (s == INVALID_SOCKET) {
2083
errno = WSAGetLastError();
2087
if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2089
return error("unable to make a socket file descriptor: %s",
2096
int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2098
SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2099
return connect(s, sa, sz);
2103
int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2105
SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2106
return bind(s, sa, sz);
2110
int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2112
SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2113
return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2117
int mingw_shutdown(int sockfd, int how)
2119
SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2120
return shutdown(s, how);
2124
int mingw_listen(int sockfd, int backlog)
2126
SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2127
return listen(s, backlog);
2131
int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2135
SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2136
SOCKET s2 = accept(s1, sa, sz);
2139
if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2142
return error("unable to make a socket file descriptor: %s",
2149
int mingw_rename(const char *pold, const char *pnew)
2153
wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
2154
if (xutftowcs_path(wpold, pold) < 0 || xutftowcs_path(wpnew, pnew) < 0)
2161
if (!_wrename(wpold, wpnew))
2163
if (errno != EEXIST)
2166
if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2169
gle = GetLastError();
2170
if (gle == ERROR_ACCESS_DENIED &&
2171
(attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
2172
if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
2173
DWORD attrsold = GetFileAttributesW(wpold);
2174
if (attrsold == INVALID_FILE_ATTRIBUTES ||
2175
!(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2177
else if (!_wrmdir(wpnew))
2181
if ((attrs & FILE_ATTRIBUTE_READONLY) &&
2182
SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2183
if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2185
gle = GetLastError();
2187
SetFileAttributesW(wpnew, attrs);
2190
if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2198
Sleep(delay[tries]);
2202
if (gle == ERROR_ACCESS_DENIED &&
2203
ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2204
"Should I try again?", pold, pnew))
2216
int mingw_getpagesize(void)
2220
return si.dwAllocationGranularity;
2224
enum EXTENDED_NAME_FORMAT {
2226
NameUserPrincipal = 8
2229
static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2231
DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
2232
enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2233
static wchar_t wbuffer[1024];
2236
if (!INIT_PROC_ADDR(GetUserNameExW))
2239
len = ARRAY_SIZE(wbuffer);
2240
if (GetUserNameExW(type, wbuffer, &len)) {
2241
char *converted = xmalloc((len *= 3));
2242
if (xwcstoutf(converted, wbuffer, len) >= 0)
2250
char *mingw_query_user_email(void)
2252
return get_extended_user_info(NameUserPrincipal);
2255
struct passwd *getpwuid(int uid)
2257
static unsigned initialized;
2258
static char user_name[100];
2259
static struct passwd *p;
2266
len = ARRAY_SIZE(buf);
2267
if (!GetUserNameW(buf, &len)) {
2272
if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
2277
p = xmalloc(sizeof(*p));
2278
p->pw_name = user_name;
2279
p->pw_gecos = get_extended_user_info(NameDisplay);
2285
p->pw_gecos = (char *) "unknown";
2292
static HANDLE timer_event;
2293
static HANDLE timer_thread;
2294
static int timer_interval;
2296
static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
2307
static unsigned __stdcall ticktack(void *dummy)
2309
while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
2310
mingw_raise(SIGALRM);
2317
static int start_timer_thread(void)
2319
timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2321
timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2323
return errno = ENOMEM,
2324
error("cannot start timer thread");
2326
return errno = ENOMEM,
2327
error("cannot allocate resources for timer");
2331
static void stop_timer_thread(void)
2334
SetEvent(timer_event);
2336
int rc = WaitForSingleObject(timer_thread, 10000);
2337
if (rc == WAIT_TIMEOUT)
2338
error("timer thread did not terminate timely");
2339
else if (rc != WAIT_OBJECT_0)
2340
error("waiting for timer thread failed: %lu",
2342
CloseHandle(timer_thread);
2345
CloseHandle(timer_event);
2347
timer_thread = NULL;
2350
static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2352
return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2355
int setitimer(int type, struct itimerval *in, struct itimerval *out)
2357
static const struct timeval zero;
2358
static int atexit_done;
2361
return errno = EINVAL,
2362
error("setitimer param 3 != NULL not implemented");
2363
if (!is_timeval_eq(&in->it_interval, &zero) &&
2364
!is_timeval_eq(&in->it_interval, &in->it_value))
2365
return errno = EINVAL,
2366
error("setitimer: it_interval must be zero or eq it_value");
2369
stop_timer_thread();
2371
if (is_timeval_eq(&in->it_value, &zero) &&
2372
is_timeval_eq(&in->it_interval, &zero))
2375
timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2376
one_shot = is_timeval_eq(&in->it_interval, &zero);
2378
atexit(stop_timer_thread);
2381
return start_timer_thread();
2384
int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2387
return errno = EINVAL,
2388
error("sigaction only implemented for SIGALRM");
2390
return errno = EINVAL,
2391
error("sigaction: param 3 != NULL not implemented");
2393
timer_fn = in->sa_handler;
2398
sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2410
sigint_fn = handler;
2414
return signal(sig, handler);
2421
int mingw_raise(int sig)
2425
if (timer_fn == SIG_DFL) {
2426
if (isatty(STDERR_FILENO))
2427
fputs("Alarm clock\n", stderr);
2428
exit(128 + SIGALRM);
2429
} else if (timer_fn != SIG_IGN)
2434
if (sigint_fn == SIG_DFL)
2436
else if (sigint_fn != SIG_IGN)
2440
#if defined(_MSC_VER)
2447
case SIGABRT_COMPAT:
2470
int link(const char *oldpath, const char *newpath)
2472
wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2473
if (xutftowcs_path(woldpath, oldpath) < 0 ||
2474
xutftowcs_path(wnewpath, newpath) < 0)
2477
if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
2478
errno = err_win_to_posix(GetLastError());
2484
pid_t waitpid(pid_t pid, int *status, int options)
2486
HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2493
if (pid > 0 && options & WNOHANG) {
2494
if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2498
options &= ~WNOHANG;
2502
struct pinfo_t **ppinfo;
2503
if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2509
GetExitCodeProcess(h, (LPDWORD)status);
2511
EnterCriticalSection(&pinfo_cs);
2515
struct pinfo_t *info = *ppinfo;
2516
if (info->pid == pid) {
2517
CloseHandle(info->proc);
2518
*ppinfo = info->next;
2522
ppinfo = &info->next;
2525
LeaveCriticalSection(&pinfo_cs);
2536
int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2538
int upos = 0, wpos = 0;
2539
const unsigned char *utf = (const unsigned char*) utfs;
2540
if (!utf || !wcs || wcslen < 1) {
2549
while (upos < utflen) {
2550
int c = utf[upos++] & 0xff;
2551
if (utflen == INT_MAX && c == 0)
2554
if (wpos >= wcslen) {
2563
} else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2564
(utf[upos] & 0xc0) == 0x80) {
2566
c = ((c & 0x1f) << 6);
2567
c |= (utf[upos++] & 0x3f);
2569
} else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2570
!(c == 0xe0 && utf[upos] < 0xa0) &&
2571
(utf[upos] & 0xc0) == 0x80 &&
2572
(utf[upos + 1] & 0xc0) == 0x80) {
2574
c = ((c & 0x0f) << 12);
2575
c |= ((utf[upos++] & 0x3f) << 6);
2576
c |= (utf[upos++] & 0x3f);
2578
} else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2579
wpos + 1 < wcslen &&
2580
!(c == 0xf0 && utf[upos] < 0x90) &&
2581
!(c == 0xf4 && utf[upos] >= 0x90) &&
2582
(utf[upos] & 0xc0) == 0x80 &&
2583
(utf[upos + 1] & 0xc0) == 0x80 &&
2584
(utf[upos + 2] & 0xc0) == 0x80) {
2586
c = ((c & 0x07) << 18);
2587
c |= ((utf[upos++] & 0x3f) << 12);
2588
c |= ((utf[upos++] & 0x3f) << 6);
2589
c |= (utf[upos++] & 0x3f);
2591
wcs[wpos++] = 0xd800 | (c >> 10);
2592
wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2593
} else if (c >= 0xa0) {
2598
static const char *hex = "0123456789abcdef";
2599
wcs[wpos++] = hex[c >> 4];
2601
wcs[wpos++] = hex[c & 0x0f];
2608
int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2610
if (!wcs || !utf || utflen < 1) {
2614
utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2621
static void setup_windows_environment(void)
2623
char *tmp = getenv("TMPDIR");
2627
if (!(tmp = getenv("TMP")))
2628
tmp = getenv("TEMP");
2630
setenv("TMPDIR", tmp, 1);
2631
tmp = getenv("TMPDIR");
2642
convert_slashes(tmp);
2646
if (!getenv("TERM"))
2647
setenv("TERM", "cygwin", 1);
2650
if (!getenv("HOME")) {
2656
if ((tmp = getenv("HOMEDRIVE"))) {
2657
struct strbuf buf = STRBUF_INIT;
2658
strbuf_addstr(&buf, tmp);
2659
if ((tmp = getenv("HOMEPATH"))) {
2660
strbuf_addstr(&buf, tmp);
2661
if (is_directory(buf.buf))
2662
setenv("HOME", buf.buf, 1);
2666
strbuf_release(&buf);
2669
if (!tmp && (tmp = getenv("USERPROFILE")))
2670
setenv("HOME", tmp, 1);
2674
static PSID get_current_user_sid(void)
2680
if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
2683
if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2684
TOKEN_USER *info = xmalloc((size_t)len);
2685
if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2686
len = GetLengthSid(info->User.Sid);
2687
result = xmalloc(len);
2688
if (!CopySid(len, result, info->User.Sid)) {
2689
error(_("failed to copy SID (%ld)"),
2691
FREE_AND_NULL(result);
2694
FREE_AND_NULL(info);
2701
static BOOL user_sid_to_user_name(PSID sid, LPSTR *str)
2703
SID_NAME_USE pe_use;
2704
DWORD len_user = 0, len_domain = 0;
2705
BOOL translate_sid_to_user;
2710
LookupAccountSidA(NULL, sid, NULL, &len_user, NULL, &len_domain,
2715
ALLOC_ARRAY((*str), (size_t)len_domain + (size_t)len_user);
2716
translate_sid_to_user = LookupAccountSidA(NULL, sid,
2717
(*str) + len_domain, &len_user, *str, &len_domain, &pe_use);
2718
if (!translate_sid_to_user)
2719
FREE_AND_NULL(*str);
2721
(*str)[len_domain] = '/';
2722
return translate_sid_to_user;
2725
static int acls_supported(const char *path)
2727
size_t offset = offset_1st_component(path);
2728
WCHAR wroot[MAX_PATH];
2729
DWORD file_system_flags;
2732
xutftowcsn(wroot, path, MAX_PATH, offset) > 0 &&
2733
GetVolumeInformationW(wroot, NULL, 0, NULL, NULL,
2734
&file_system_flags, NULL, 0))
2735
return !!(file_system_flags & FILE_PERSISTENT_ACLS);
2740
int is_path_owned_by_current_sid(const char *path, struct strbuf *report)
2742
WCHAR wpath[MAX_PATH];
2744
PSECURITY_DESCRIPTOR descriptor = NULL;
2747
static wchar_t home[MAX_PATH];
2751
if (xutftowcs_path(wpath, path) < 0)
2760
DWORD size = ARRAY_SIZE(home);
2761
DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2762
if (!len || len > size)
2763
wcscpy(home, L"::N/A::");
2765
if (!wcsicmp(wpath, home))
2769
err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2770
OWNER_SECURITY_INFORMATION |
2771
DACL_SECURITY_INFORMATION,
2772
&sid, NULL, NULL, NULL, &descriptor);
2774
if (err != ERROR_SUCCESS)
2775
error(_("failed to get owner for '%s' (%ld)"), path, err);
2776
else if (sid && IsValidSid(sid)) {
2778
static PSID current_user_sid;
2781
if (!current_user_sid)
2782
current_user_sid = get_current_user_sid();
2784
if (current_user_sid &&
2785
IsValidSid(current_user_sid) &&
2786
EqualSid(sid, current_user_sid))
2788
else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) &&
2789
CheckTokenMembership(NULL, sid, &is_member) &&
2798
IsWellKnownSid(sid, WinWorldSid) &&
2799
!acls_supported(path)) {
2803
strbuf_addf(report, "'%s' is on a file system that does "
2804
"not record ownership\n", path);
2805
} else if (report) {
2806
PCSTR str1, str2, str3, str4;
2807
LPSTR to_free1 = NULL, to_free3 = NULL,
2808
to_local_free2 = NULL, to_local_free4 = NULL;
2810
if (user_sid_to_user_name(sid, &to_free1))
2813
str1 = "(inconvertible)";
2814
if (ConvertSidToStringSidA(sid, &to_local_free2))
2815
str2 = to_local_free2;
2817
str2 = "(inconvertible)";
2819
if (!current_user_sid) {
2823
else if (!IsValidSid(current_user_sid)) {
2827
if (user_sid_to_user_name(current_user_sid,
2831
str3 = "(inconvertible)";
2832
if (ConvertSidToStringSidA(current_user_sid,
2834
str4 = to_local_free4;
2836
str4 = "(inconvertible)";
2839
"'%s' is owned by:\n"
2840
"\t%s (%s)\nbut the current user is:\n"
2842
path, str1, str2, str3, str4);
2844
LocalFree(to_local_free2);
2846
LocalFree(to_local_free4);
2855
LocalFree(descriptor);
2860
int is_valid_win32_path(const char *path, int allow_literal_nul)
2862
const char *p = path;
2863
int preceding_space_or_period = 0, i = 0, periods = 0;
2868
skip_dos_drive_prefix((char **)&path);
2875
case '/': case '\\':
2877
if (preceding_space_or_period &&
2878
(i != periods || periods > 2))
2883
i = periods = preceding_space_or_period = 0;
2888
if (((c = path[++i]) != 'u' && c != 'U') ||
2889
((c = path[++i]) != 'x' && c != 'X')) {
2897
if ((c = path[++i]) != 'o' && c != 'O')
2898
goto not_a_reserved_name;
2900
if (c == 'm' || c == 'M') {
2902
if (c < '1' || c > '9')
2903
goto not_a_reserved_name;
2904
} else if (c == 'n' || c == 'N') {
2906
if ((c == 'i' || c == 'I') &&
2907
((c = path[i + 2]) == 'n' ||
2911
else if ((c == 'o' || c == 'O') &&
2912
((c = path[i + 2]) == 'u' ||
2914
((c = path[i + 3]) == 't' ||
2919
goto not_a_reserved_name;
2922
if (((c = path[++i]) != 'p' && c != 'P') ||
2923
((c = path[++i]) != 't' && c != 'T') ||
2924
!isdigit(path[++i]))
2925
goto not_a_reserved_name;
2928
if (((c = path[++i]) != 'u' && c != 'U') ||
2929
((c = path[++i]) != 'l' && c != 'L') ||
2930
(allow_literal_nul &&
2931
!path[i + 1] && p == path))
2932
goto not_a_reserved_name;
2935
if (((c = path[++i]) != 'r' && c != 'R') ||
2936
((c = path[++i]) != 'n' && c != 'N'))
2937
goto not_a_reserved_name;
2951
if (path[i] == ' ') {
2952
preceding_space_or_period = 1;
2953
while (path[++i] == ' ')
2958
if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
2959
goto not_a_reserved_name;
2967
preceding_space_or_period = 1;
2971
case '<': case '>': case '"': case '|': case '?': case '*':
2975
if (c > '\0' && c < '\x20')
2979
preceding_space_or_period = 0;
2984
#if !defined(_MSC_VER)
2992
static NORETURN void die_startup(void)
2994
fputs("fatal: not enough memory for initialization", stderr);
2998
static void *malloc_startup(size_t size)
3000
void *result = malloc(size);
3006
static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
3008
len = xwcstoutf(buffer, wcs, len) + 1;
3009
return memcpy(malloc_startup(len), buffer, len);
3012
static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
3013
DWORD desired_access, DWORD flags)
3015
DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
3016
wchar_t buf[MAX_PATH];
3017
DWORD max = ARRAY_SIZE(buf);
3019
DWORD ret = GetEnvironmentVariableW(key, buf, max);
3021
if (!ret || ret >= max)
3025
SetEnvironmentVariableW(key, NULL);
3026
if (!wcscmp(buf, L"off")) {
3028
handle = GetStdHandle(std_id);
3029
if (handle != INVALID_HANDLE_VALUE)
3030
CloseHandle(handle);
3033
if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
3034
handle = GetStdHandle(STD_OUTPUT_HANDLE);
3035
if (handle == INVALID_HANDLE_VALUE) {
3037
handle = GetStdHandle(std_id);
3038
if (handle != INVALID_HANDLE_VALUE)
3039
CloseHandle(handle);
3041
int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3042
SetStdHandle(std_id, handle);
3048
handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
3050
if (handle != INVALID_HANDLE_VALUE) {
3051
int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3052
SetStdHandle(std_id, handle);
3058
static void maybe_redirect_std_handles(void)
3060
maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
3061
GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
3062
maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
3063
GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
3064
maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
3065
GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
3083
int wmain(int argc, const wchar_t **wargv)
3085
int i, maxlen, exit_status;
3086
char *buffer, **save;
3089
trace2_initialize_clock();
3093
_CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
3096
#ifdef USE_MSVC_CRTDBG
3097
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
3101
maybe_redirect_std_handles();
3104
maxlen = wcslen(wargv[0]);
3105
for (i = 1; i < argc; i++)
3106
maxlen = max(maxlen, wcslen(wargv[i]));
3109
maxlen = 3 * maxlen + 1;
3110
buffer = malloc_startup(maxlen);
3117
ALLOC_ARRAY(argv, argc + 1);
3118
ALLOC_ARRAY(save, argc + 1);
3119
for (i = 0; i < argc; i++)
3120
argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
3121
argv[i] = save[i] = NULL;
3125
setup_windows_environment();
3127
unset_environment_variables = xstrdup("PERL5LIB");
3130
InitializeCriticalSection(&pinfo_cs);
3134
_setmode(_fileno(stdin), _O_BINARY);
3135
_setmode(_fileno(stdout), _O_BINARY);
3136
_setmode(_fileno(stderr), _O_BINARY);
3142
exit_status = main(argc, argv);
3144
for (i = 0; i < argc; i++)
3152
int uname(struct utsname *buf)
3154
unsigned v = (unsigned)GetVersion();
3155
memset(buf, 0, sizeof(*buf));
3156
xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3157
xsnprintf(buf->release, sizeof(buf->release),
3158
"%u.%u", v & 0xff, (v >> 8) & 0xff);
3160
xsnprintf(buf->version, sizeof(buf->version),
3161
"%u", (v >> 16) & 0x7fff);
3165
#ifndef NO_UNIX_SOCKETS
3166
int mingw_have_unix_sockets(void)
3168
SC_HANDLE scm, srvc;
3169
SERVICE_STATUS_PROCESS status;
3172
scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT);
3174
srvc = OpenServiceA(scm, "afunix", SERVICE_QUERY_STATUS);
3176
if(QueryServiceStatusEx(srvc, SC_STATUS_PROCESS_INFO, (LPBYTE)&status, sizeof(SERVICE_STATUS_PROCESS), &bytes))
3177
ret = status.dwCurrentState == SERVICE_RUNNING;
3178
CloseServiceHandle(srvc);
3180
CloseServiceHandle(scm);