]> git.ipfire.org Git - thirdparty/git.git/blame - compat/mingw.c
The sixth batch
[thirdparty/git.git] / compat / mingw.c
CommitLineData
673af418 1#define USE_THE_REPOSITORY_VARIABLE
41f43b82 2#define DISABLE_SIGN_COMPARE_WARNINGS
673af418 3
f4626df5 4#include "../git-compat-util.h"
444dc903 5#include "win32.h"
bdc77d1d 6#include <aclapi.h>
e883e04b 7#include <sddl.h>
28a559c0 8#include <conio.h>
85faec9d 9#include <wchar.h>
7e5d7768 10#include "../strbuf.h"
c9b78400 11#include "../run-command.h"
0b027f6c 12#include "../abspath.h"
36bf1958 13#include "../alloc.h"
564be791 14#include "win32/lazyload.h"
bdfbb0ea 15#include "../config.h"
32a8f510 16#include "../environment.h"
74ea5c95 17#include "../trace2.h"
cb2a5135 18#include "../symlinks.h"
d5ebb50d 19#include "../wrapper.h"
9e9da23c 20#include "dir.h"
f394e093 21#include "gettext.h"
4a9b2049
MA
22#define SECURITY_WIN32
23#include <sspi.h>
0a3dceab
PS
24#include <winternl.h>
25
26#define STATUS_DELETE_PENDING ((NTSTATUS) 0xC0000056)
f4626df5 27
7c00bc39
JS
28#define HCAST(type, handle) ((type)(intptr_t)handle)
29
19e12549
HV
30static const int delay[] = { 0, 1, 10, 20, 40 };
31
08809c09
JS
32void open_in_gdb(void)
33{
34 static struct child_process cp = CHILD_PROCESS_INIT;
08809c09 35
ef8d7ac4
JK
36 strvec_pushl(&cp.args, "mintty", "gdb", NULL);
37 strvec_pushf(&cp.args, "--pid=%d", getpid());
08809c09
JS
38 cp.clean_on_exit = 1;
39 if (start_command(&cp) < 0)
40 die_errno("Could not start gdb");
41 sleep(1);
42}
43
44626dc7 44int err_win_to_posix(DWORD winerr)
b3debd2b
PK
45{
46 int error = ENOSYS;
47 switch(winerr) {
48 case ERROR_ACCESS_DENIED: error = EACCES; break;
49 case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
50 case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
51 case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
52 case ERROR_ALREADY_EXISTS: error = EEXIST; break;
53 case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
54 case ERROR_BAD_COMMAND: error = EIO; break;
55 case ERROR_BAD_DEVICE: error = ENODEV; break;
56 case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
57 case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
58 case ERROR_BAD_FORMAT: error = ENOEXEC; break;
59 case ERROR_BAD_LENGTH: error = EINVAL; break;
60 case ERROR_BAD_PATHNAME: error = ENOENT; break;
61 case ERROR_BAD_PIPE: error = EPIPE; break;
62 case ERROR_BAD_UNIT: error = ENODEV; break;
63 case ERROR_BAD_USERNAME: error = EINVAL; break;
64 case ERROR_BROKEN_PIPE: error = EPIPE; break;
65 case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
66 case ERROR_BUSY: error = EBUSY; break;
67 case ERROR_BUSY_DRIVE: error = EBUSY; break;
68 case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
69 case ERROR_CANNOT_MAKE: error = EACCES; break;
70 case ERROR_CANTOPEN: error = EIO; break;
71 case ERROR_CANTREAD: error = EIO; break;
72 case ERROR_CANTWRITE: error = EIO; break;
73 case ERROR_CRC: error = EIO; break;
74 case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
75 case ERROR_DEVICE_IN_USE: error = EBUSY; break;
76 case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
77 case ERROR_DIRECTORY: error = EINVAL; break;
78 case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
79 case ERROR_DISK_CHANGE: error = EIO; break;
80 case ERROR_DISK_FULL: error = ENOSPC; break;
81 case ERROR_DRIVE_LOCKED: error = EBUSY; break;
82 case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
83 case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
84 case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
85 case ERROR_FILE_EXISTS: error = EEXIST; break;
86 case ERROR_FILE_INVALID: error = ENODEV; break;
87 case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
88 case ERROR_GEN_FAILURE: error = EIO; break;
89 case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
90 case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
91 case ERROR_INVALID_ACCESS: error = EACCES; break;
92 case ERROR_INVALID_ADDRESS: error = EFAULT; break;
93 case ERROR_INVALID_BLOCK: error = EFAULT; break;
94 case ERROR_INVALID_DATA: error = EINVAL; break;
95 case ERROR_INVALID_DRIVE: error = ENODEV; break;
96 case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
97 case ERROR_INVALID_FLAGS: error = EINVAL; break;
98 case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
99 case ERROR_INVALID_HANDLE: error = EBADF; break;
100 case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
101 case ERROR_INVALID_NAME: error = EINVAL; break;
102 case ERROR_INVALID_OWNER: error = EINVAL; break;
103 case ERROR_INVALID_PARAMETER: error = EINVAL; break;
104 case ERROR_INVALID_PASSWORD: error = EPERM; break;
105 case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
106 case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
107 case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
108 case ERROR_INVALID_WORKSTATION: error = EACCES; break;
109 case ERROR_IO_DEVICE: error = EIO; break;
110 case ERROR_IO_INCOMPLETE: error = EINTR; break;
111 case ERROR_LOCKED: error = EBUSY; break;
112 case ERROR_LOCK_VIOLATION: error = EACCES; break;
113 case ERROR_LOGON_FAILURE: error = EACCES; break;
114 case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
115 case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
116 case ERROR_MORE_DATA: error = EPIPE; break;
117 case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
118 case ERROR_NOACCESS: error = EFAULT; break;
119 case ERROR_NONE_MAPPED: error = EINVAL; break;
120 case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
121 case ERROR_NOT_READY: error = EAGAIN; break;
122 case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
123 case ERROR_NO_DATA: error = EPIPE; break;
124 case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
125 case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
126 case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
127 case ERROR_OPEN_FAILED: error = EIO; break;
128 case ERROR_OPEN_FILES: error = EBUSY; break;
129 case ERROR_OPERATION_ABORTED: error = EINTR; break;
130 case ERROR_OUTOFMEMORY: error = ENOMEM; break;
131 case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
132 case ERROR_PATH_BUSY: error = EBUSY; break;
133 case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
134 case ERROR_PIPE_BUSY: error = EBUSY; break;
135 case ERROR_PIPE_CONNECTED: error = EPIPE; break;
136 case ERROR_PIPE_LISTENING: error = EPIPE; break;
137 case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
138 case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
139 case ERROR_READ_FAULT: error = EIO; break;
140 case ERROR_SEEK: error = EIO; break;
141 case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
142 case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
143 case ERROR_SHARING_VIOLATION: error = EACCES; break;
144 case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
3ba3720b 145 case ERROR_SUCCESS: BUG("err_win_to_posix() called without an error!");
b3debd2b
PK
146 case ERROR_SWAPERROR: error = ENOENT; break;
147 case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
148 case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
149 case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
150 case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
151 case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
152 case ERROR_WRITE_FAULT: error = EIO; break;
153 case ERROR_WRITE_PROTECT: error = EROFS; break;
154 }
155 return error;
156}
157
19e12549
HV
158static inline int is_file_in_use_error(DWORD errcode)
159{
160 switch (errcode) {
161 case ERROR_SHARING_VIOLATION:
162 case ERROR_ACCESS_DENIED:
163 return 1;
164 }
165
166 return 0;
167}
168
c9b78400
HV
169static int read_yes_no_answer(void)
170{
171 char answer[1024];
172
173 if (fgets(answer, sizeof(answer), stdin)) {
174 size_t answer_len = strlen(answer);
175 int got_full_line = 0, c;
176
177 /* remove the newline */
178 if (answer_len >= 2 && answer[answer_len-2] == '\r') {
179 answer[answer_len-2] = '\0';
180 got_full_line = 1;
181 } else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
182 answer[answer_len-1] = '\0';
183 got_full_line = 1;
184 }
185 /* flush the buffer in case we did not get the full line */
186 if (!got_full_line)
187 while ((c = getchar()) != EOF && c != '\n')
188 ;
189 } else
190 /* we could not read, return the
191 * default answer which is no */
192 return 0;
193
194 if (tolower(answer[0]) == 'y' && !answer[1])
195 return 1;
196 if (!strncasecmp(answer, "yes", sizeof(answer)))
197 return 1;
198 if (tolower(answer[0]) == 'n' && !answer[1])
199 return 0;
200 if (!strncasecmp(answer, "no", sizeof(answer)))
201 return 0;
202
203 /* did not find an answer we understand */
204 return -1;
205}
206
207static int ask_yes_no_if_possible(const char *format, ...)
208{
209 char question[4096];
4120294c 210 const char *retry_hook;
c9b78400
HV
211 va_list args;
212
213 va_start(args, format);
214 vsnprintf(question, sizeof(question), format, args);
215 va_end(args);
216
4120294c
RS
217 retry_hook = mingw_getenv("GIT_ASK_YESNO");
218 if (retry_hook) {
219 struct child_process cmd = CHILD_PROCESS_INIT;
220
221 strvec_pushl(&cmd.args, retry_hook, question, NULL);
222 return !run_command(&cmd);
c9b78400
HV
223 }
224
225 if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
226 return 0;
227
228 while (1) {
229 int answer;
230 fprintf(stderr, "%s (y/n) ", question);
231
232 if ((answer = read_yes_no_answer()) >= 0)
233 return answer;
234
235 fprintf(stderr, "Sorry, I did not understand your answer. "
236 "Please type 'y' or 'n'\n");
237 }
238}
239
bdfbb0ea
JS
240/* Windows only */
241enum hide_dotfiles_type {
242 HIDE_DOTFILES_FALSE = 0,
243 HIDE_DOTFILES_TRUE,
244 HIDE_DOTFILES_DOTGITONLY
245};
246
ac33519d 247static int core_restrict_inherited_handles = -1;
bdfbb0ea 248static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
0e218f91 249static char *unset_environment_variables;
bdfbb0ea 250
a4e7e317 251int mingw_core_config(const char *var, const char *value,
b652382d
JK
252 const struct config_context *ctx UNUSED,
253 void *cb UNUSED)
70fc5793 254{
bdfbb0ea
JS
255 if (!strcmp(var, "core.hidedotfiles")) {
256 if (value && !strcasecmp(value, "dotgitonly"))
257 hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
258 else
259 hide_dotfiles = git_config_bool(var, value);
260 return 0;
261 }
262
0e218f91 263 if (!strcmp(var, "core.unsetenvvars")) {
ba176db5
JK
264 if (!value)
265 return config_error_nonbool(var);
0e218f91
JS
266 free(unset_environment_variables);
267 unset_environment_variables = xstrdup(value);
268 return 0;
269 }
270
ac33519d
JS
271 if (!strcmp(var, "core.restrictinheritedhandles")) {
272 if (value && !strcasecmp(value, "auto"))
273 core_restrict_inherited_handles = -1;
274 else
275 core_restrict_inherited_handles =
276 git_config_bool(var, value);
277 return 0;
278 }
279
70fc5793
JS
280 return 0;
281}
282
4745feeb
AS
283/* Normalizes NT paths as returned by some low-level APIs. */
284static wchar_t *normalize_ntpath(wchar_t *wbuf)
285{
286 int i;
287 /* fix absolute path prefixes */
288 if (wbuf[0] == '\\') {
289 /* strip NT namespace prefixes */
290 if (!wcsncmp(wbuf, L"\\??\\", 4) ||
291 !wcsncmp(wbuf, L"\\\\?\\", 4))
292 wbuf += 4;
293 else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
294 wbuf += 12;
295 /* replace remaining '...UNC\' with '\\' */
296 if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
297 wbuf += 2;
298 *wbuf = '\\';
299 }
300 }
301 /* convert backslashes to slashes */
302 for (i = 0; wbuf[i]; i++)
303 if (wbuf[i] == '\\')
304 wbuf[i] = '/';
305 return wbuf;
306}
307
3262a53c 308int mingw_unlink(const char *pathname, int handle_in_use_error)
337967fb 309{
19e12549 310 int ret, tries = 0;
85faec9d
KB
311 wchar_t wpathname[MAX_PATH];
312 if (xutftowcs_path(wpathname, pathname) < 0)
313 return -1;
19e12549 314
680e0b45
JH
315 if (DeleteFileW(wpathname))
316 return 0;
317
337967fb 318 /* read-only files cannot be removed */
85faec9d
KB
319 _wchmod(wpathname, 0666);
320 while ((ret = _wunlink(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
19e12549
HV
321 if (!is_file_in_use_error(GetLastError()))
322 break;
3262a53c
PS
323 if (!handle_in_use_error)
324 return ret;
325
19e12549
HV
326 /*
327 * We assume that some other process had the source or
328 * destination file open at the wrong moment and retry.
329 * In order to give the other process a higher chance to
330 * complete its operation, we give up our time slice now.
331 * If we have to retry again, we do sleep a bit.
332 */
333 Sleep(delay[tries]);
334 tries++;
335 }
c9b78400
HV
336 while (ret == -1 && is_file_in_use_error(GetLastError()) &&
337 ask_yes_no_if_possible("Unlink of file '%s' failed. "
338 "Should I try again?", pathname))
85faec9d 339 ret = _wunlink(wpathname);
19e12549 340 return ret;
337967fb
HV
341}
342
85faec9d 343static int is_dir_empty(const wchar_t *wpath)
ab1a11be 344{
85faec9d 345 WIN32_FIND_DATAW findbuf;
ab1a11be 346 HANDLE handle;
85faec9d
KB
347 wchar_t wbuf[MAX_PATH + 2];
348 wcscpy(wbuf, wpath);
349 wcscat(wbuf, L"\\*");
350 handle = FindFirstFileW(wbuf, &findbuf);
351 if (handle == INVALID_HANDLE_VALUE)
ab1a11be 352 return GetLastError() == ERROR_NO_MORE_FILES;
ab1a11be 353
85faec9d
KB
354 while (!wcscmp(findbuf.cFileName, L".") ||
355 !wcscmp(findbuf.cFileName, L".."))
356 if (!FindNextFileW(handle, &findbuf)) {
357 DWORD err = GetLastError();
358 FindClose(handle);
359 return err == ERROR_NO_MORE_FILES;
ab1a11be
JS
360 }
361 FindClose(handle);
ab1a11be
JS
362 return 0;
363}
364
4f288100
HV
365int mingw_rmdir(const char *pathname)
366{
367 int ret, tries = 0;
85faec9d 368 wchar_t wpathname[MAX_PATH];
3e7d4888
TB
369 struct stat st;
370
371 /*
372 * Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
373 * (and `RemoveDirectoryW()`) will attempt to remove the target of a
374 * symbolic link (if it points to a directory).
375 *
376 * This behavior breaks the assumption of e.g. `remove_path()` which
377 * upon successful deletion of a file will attempt to remove its parent
378 * directories recursively until failure (which usually happens when
379 * the directory is not empty).
380 *
381 * Therefore, before calling `_wrmdir()`, we first check if the path is
382 * a symbolic link. If it is, we exit and return the same error as
383 * Linux' `rmdir()` would, i.e. `ENOTDIR`.
384 */
385 if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
386 errno = ENOTDIR;
387 return -1;
388 }
389
85faec9d
KB
390 if (xutftowcs_path(wpathname, pathname) < 0)
391 return -1;
4f288100 392
85faec9d 393 while ((ret = _wrmdir(wpathname)) == -1 && tries < ARRAY_SIZE(delay)) {
4f288100 394 if (!is_file_in_use_error(GetLastError()))
a83b2b57
EFL
395 errno = err_win_to_posix(GetLastError());
396 if (errno != EACCES)
4f288100 397 break;
85faec9d 398 if (!is_dir_empty(wpathname)) {
ab1a11be
JS
399 errno = ENOTEMPTY;
400 break;
401 }
4f288100
HV
402 /*
403 * We assume that some other process had the source or
404 * destination file open at the wrong moment and retry.
405 * In order to give the other process a higher chance to
406 * complete its operation, we give up our time slice now.
407 * If we have to retry again, we do sleep a bit.
408 */
409 Sleep(delay[tries]);
410 tries++;
411 }
a83b2b57 412 while (ret == -1 && errno == EACCES && is_file_in_use_error(GetLastError()) &&
4f288100
HV
413 ask_yes_no_if_possible("Deletion of directory '%s' failed. "
414 "Should I try again?", pathname))
85faec9d 415 ret = _wrmdir(wpathname);
684dd4c2
MT
416 if (!ret)
417 invalidate_lstat_cache();
85faec9d
KB
418 return ret;
419}
420
f30afdab
JS
421static inline int needs_hiding(const char *path)
422{
423 const char *basename;
424
425 if (hide_dotfiles == HIDE_DOTFILES_FALSE)
426 return 0;
427
428 /* We cannot use basename(), as it would remove trailing slashes */
1cadad6f 429 win32_skip_dos_drive_prefix((char **)&path);
f30afdab
JS
430 if (!*path)
431 return 0;
432
433 for (basename = path; *path; path++)
434 if (is_dir_sep(*path)) {
435 do {
436 path++;
437 } while (is_dir_sep(*path));
438 /* ignore trailing slashes */
439 if (*path)
440 basename = path;
60e6569a
JS
441 else
442 break;
f30afdab
JS
443 }
444
445 if (hide_dotfiles == HIDE_DOTFILES_TRUE)
446 return *basename == '.';
447
448 assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
449 return !strncasecmp(".git", basename, 4) &&
450 (!basename[4] || is_dir_sep(basename[4]));
451}
452
453static int set_hidden_flag(const wchar_t *path, int set)
454{
455 DWORD original = GetFileAttributesW(path), modified;
456 if (set)
457 modified = original | FILE_ATTRIBUTE_HIDDEN;
458 else
459 modified = original & ~FILE_ATTRIBUTE_HIDDEN;
460 if (original == modified || SetFileAttributesW(path, modified))
461 return 0;
462 errno = err_win_to_posix(GetLastError());
463 return -1;
464}
465
b652382d 466int mingw_mkdir(const char *path, int mode UNUSED)
85faec9d
KB
467{
468 int ret;
469 wchar_t wpath[MAX_PATH];
d2c84dad 470
4dc42c6c 471 if (!is_valid_win32_path(path, 0)) {
d2c84dad
JS
472 errno = EINVAL;
473 return -1;
474 }
475
85faec9d
KB
476 if (xutftowcs_path(wpath, path) < 0)
477 return -1;
478 ret = _wmkdir(wpath);
f30afdab
JS
479 if (!ret && needs_hiding(path))
480 return set_hidden_flag(wpath, 1);
4f288100
HV
481 return ret;
482}
483
eeaf7dda
JH
484/*
485 * Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
486 * is documented in [1] as opening a writable file handle in append mode.
487 * (It is believed that) this is atomic since it is maintained by the
488 * kernel unlike the O_APPEND flag which is racily maintained by the CRT.
489 *
490 * [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
491 *
492 * This trick does not appear to work for named pipes. Instead it creates
493 * a named pipe client handle that cannot be written to. Callers should
494 * just use the regular _wopen() for them. (And since client handle gets
495 * bound to a unique server handle, it isn't really an issue.)
496 */
d6410975
JS
497static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
498{
499 HANDLE handle;
500 int fd;
501 DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
502
503 /* only these flags are supported */
504 if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
505 return errno = ENOSYS, -1;
506
507 /*
508 * FILE_SHARE_WRITE is required to permit child processes
509 * to append to the file.
510 */
511 handle = CreateFileW(wfilename, FILE_APPEND_DATA,
b0b65ec5 512 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
d6410975 513 NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
23eafd92
NS
514 if (handle == INVALID_HANDLE_VALUE) {
515 DWORD err = GetLastError();
516
517 /*
518 * Some network storage solutions (e.g. Isilon) might return
519 * ERROR_INVALID_PARAMETER instead of expected error
520 * ERROR_PATH_NOT_FOUND, which results in an unknown error. If
521 * so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
522 */
523 if (err == ERROR_INVALID_PARAMETER)
524 err = ERROR_PATH_NOT_FOUND;
525
526 errno = err_win_to_posix(err);
527 return -1;
528 }
eeaf7dda 529
d6410975
JS
530 /*
531 * No O_APPEND here, because the CRT uses it only to reset the
eeaf7dda
JH
532 * file pointer to EOF before each write(); but that is not
533 * necessary (and may lead to races) for a file created with
534 * FILE_APPEND_DATA.
d6410975
JS
535 */
536 fd = _open_osfhandle((intptr_t)handle, O_BINARY);
537 if (fd < 0)
538 CloseHandle(handle);
539 return fd;
540}
541
a270cb15
PS
542/*
543 * Ideally, we'd use `_wopen()` to implement this functionality so that we
544 * don't have to reimplement it, but unfortunately we do not have tight control
545 * over the share mode there. And while `_wsopen()` and friends exist that give
546 * us _some_ control over the share mode, this family of functions doesn't give
547 * us the ability to enable FILE_SHARE_DELETE, either. But this is a strict
548 * requirement for us though so that we can unlink or rename over files that
549 * are held open by another process.
550 *
551 * We are thus forced to implement our own emulation of `open()`. To make our
552 * life simpler we only implement basic support for this, namely opening
553 * existing files for reading and/or writing. This means that newly created
554 * files won't have their sharing mode set up correctly, but for now I couldn't
555 * find any case where this matters. We may have to revisit that in the future
556 * though based on our needs.
557 */
558static int mingw_open_existing(const wchar_t *filename, int oflags, ...)
559{
560 SECURITY_ATTRIBUTES security_attributes = {
561 .nLength = sizeof(security_attributes),
562 .bInheritHandle = !(oflags & O_NOINHERIT),
563 };
564 HANDLE handle;
565 DWORD access;
566 int fd;
567
568 /* We only support basic flags. */
569 if (oflags & ~(O_ACCMODE | O_NOINHERIT)) {
570 errno = ENOSYS;
571 return -1;
572 }
573
574 switch (oflags & O_ACCMODE) {
575 case O_RDWR:
576 access = GENERIC_READ | GENERIC_WRITE;
577 break;
578 case O_WRONLY:
579 access = GENERIC_WRITE;
580 break;
581 default:
582 access = GENERIC_READ;
583 break;
584 }
585
586 handle = CreateFileW(filename, access,
587 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
588 &security_attributes, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
589 if (handle == INVALID_HANDLE_VALUE) {
590 DWORD err = GetLastError();
591
592 /* See `mingw_open_append()` for why we have this conversion. */
593 if (err == ERROR_INVALID_PARAMETER)
594 err = ERROR_PATH_NOT_FOUND;
595
596 errno = err_win_to_posix(err);
597 return -1;
598 }
599
600 fd = _open_osfhandle((intptr_t)handle, oflags | O_BINARY);
601 if (fd < 0)
602 CloseHandle(handle);
603 return fd;
604}
605
eeaf7dda
JH
606/*
607 * Does the pathname map to the local named pipe filesystem?
608 * That is, does it have a "//./pipe/" prefix?
609 */
610static int is_local_named_pipe_path(const char *filename)
611{
612 return (is_dir_sep(filename[0]) &&
613 is_dir_sep(filename[1]) &&
614 filename[2] == '.' &&
615 is_dir_sep(filename[3]) &&
616 !strncasecmp(filename+4, "pipe", 4) &&
617 is_dir_sep(filename[8]) &&
618 filename[9]);
619}
620
3e4a1ba0
JS
621int mingw_open (const char *filename, int oflags, ...)
622{
d6410975 623 typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
3e4a1ba0
JS
624 va_list args;
625 unsigned mode;
d2c84dad 626 int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
85faec9d 627 wchar_t wfilename[MAX_PATH];
d6410975 628 open_fn_t open_fn;
0d30ad71 629
0a3dceab
PS
630 DECLARE_PROC_ADDR(ntdll.dll, NTSTATUS, NTAPI, RtlGetLastNtStatus, void);
631
3e4a1ba0
JS
632 va_start(args, oflags);
633 mode = va_arg(args, int);
634 va_end(args);
635
4dc42c6c 636 if (!is_valid_win32_path(filename, !create)) {
d2c84dad
JS
637 errno = create ? EINVAL : ENOENT;
638 return -1;
639 }
640
eeaf7dda 641 if ((oflags & O_APPEND) && !is_local_named_pipe_path(filename))
d6410975 642 open_fn = mingw_open_append;
a270cb15
PS
643 else if (!(oflags & ~(O_ACCMODE | O_NOINHERIT)))
644 open_fn = mingw_open_existing;
d6410975
JS
645 else
646 open_fn = _wopen;
647
98d9b23e
JS
648 if (filename && !strcmp(filename, "/dev/null"))
649 wcscpy(wfilename, L"nul");
650 else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 651 return -1;
98d9b23e 652
d6410975 653 fd = open_fn(wfilename, oflags, mode);
0d30ad71 654
0a3dceab
PS
655 /*
656 * Internally, `_wopen()` uses the `CreateFile()` API with CREATE_NEW,
657 * which may error out with ERROR_ACCESS_DENIED and an NtStatus of
658 * STATUS_DELETE_PENDING when the file is scheduled for deletion via
659 * `DeleteFileW()`. The file essentially exists, so we map errno to
660 * EEXIST instead of EACCESS so that callers don't have to special-case
661 * this.
662 *
663 * This fixes issues for example with the lockfile interface when one
664 * process has a lock that it is about to commit or release while
665 * another process wants to acquire it.
666 */
667 if (fd < 0 && create && GetLastError() == ERROR_ACCESS_DENIED &&
668 INIT_PROC_ADDR(RtlGetLastNtStatus) && RtlGetLastNtStatus() == STATUS_DELETE_PENDING)
669 errno = EEXIST;
ba6fad02 670 if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
85faec9d 671 DWORD attrs = GetFileAttributesW(wfilename);
3e4a1ba0
JS
672 if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
673 errno = EISDIR;
674 }
f30afdab
JS
675 if ((oflags & O_CREAT) && needs_hiding(filename)) {
676 /*
677 * Internally, _wopen() uses the CreateFile() API which errors
678 * out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
679 * specified and an already existing file's attributes do not
680 * match *exactly*. As there is no mode or flag we can set that
681 * would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
682 * again *without* the O_CREAT flag (that corresponds to the
683 * CREATE_ALWAYS flag of CreateFile()).
684 */
685 if (fd < 0 && errno == EACCES)
d6410975 686 fd = open_fn(wfilename, oflags & ~O_CREAT, mode);
f30afdab
JS
687 if (fd >= 0 && set_hidden_flag(wfilename, 1))
688 warning("could not mark '%s' as hidden.", filename);
689 }
3e4a1ba0
JS
690 return fd;
691}
692
b652382d 693static BOOL WINAPI ctrl_ignore(DWORD type UNUSED)
176478a8
EFL
694{
695 return TRUE;
696}
697
698#undef fgetc
699int mingw_fgetc(FILE *stream)
700{
701 int ch;
702 if (!isatty(_fileno(stream)))
703 return fgetc(stream);
704
705 SetConsoleCtrlHandler(ctrl_ignore, TRUE);
706 while (1) {
707 ch = fgetc(stream);
708 if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
709 break;
710
711 /* Ctrl+C was pressed, simulate SIGINT and retry */
712 mingw_raise(SIGINT);
713 }
714 SetConsoleCtrlHandler(ctrl_ignore, FALSE);
715 return ch;
716}
717
3fdcdbdf
JS
718#undef fopen
719FILE *mingw_fopen (const char *filename, const char *otype)
720{
f30afdab 721 int hide = needs_hiding(filename);
85faec9d
KB
722 FILE *file;
723 wchar_t wfilename[MAX_PATH], wotype[4];
4dc42c6c
JS
724 if (filename && !strcmp(filename, "/dev/null"))
725 wcscpy(wfilename, L"nul");
726 else if (!is_valid_win32_path(filename, 1)) {
d2c84dad
JS
727 int create = otype && strchr(otype, 'w');
728 errno = create ? EINVAL : ENOENT;
729 return NULL;
4dc42c6c 730 } else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 731 return NULL;
98d9b23e
JS
732
733 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
85faec9d 734 return NULL;
98d9b23e 735
f30afdab
JS
736 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
737 error("could not unhide %s", filename);
738 return NULL;
739 }
85faec9d 740 file = _wfopen(wfilename, wotype);
e5b31344
JS
741 if (!file && GetLastError() == ERROR_INVALID_NAME)
742 errno = ENOENT;
f30afdab
JS
743 if (file && hide && set_hidden_flag(wfilename, 1))
744 warning("could not mark '%s' as hidden.", filename);
85faec9d 745 return file;
3fdcdbdf
JS
746}
747
3fdcdbdf
JS
748FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
749{
f30afdab 750 int hide = needs_hiding(filename);
85faec9d
KB
751 FILE *file;
752 wchar_t wfilename[MAX_PATH], wotype[4];
4dc42c6c
JS
753 if (filename && !strcmp(filename, "/dev/null"))
754 wcscpy(wfilename, L"nul");
755 else if (!is_valid_win32_path(filename, 1)) {
d2c84dad
JS
756 int create = otype && strchr(otype, 'w');
757 errno = create ? EINVAL : ENOENT;
758 return NULL;
4dc42c6c 759 } else if (xutftowcs_path(wfilename, filename) < 0)
85faec9d 760 return NULL;
98d9b23e
JS
761
762 if (xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
85faec9d 763 return NULL;
98d9b23e 764
f30afdab
JS
765 if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
766 error("could not unhide %s", filename);
767 return NULL;
768 }
85faec9d 769 file = _wfreopen(wfilename, wotype, stream);
f30afdab
JS
770 if (file && hide && set_hidden_flag(wfilename, 1))
771 warning("could not mark '%s' as hidden.", filename);
85faec9d 772 return file;
3fdcdbdf
JS
773}
774
84adb641
JS
775#undef fflush
776int mingw_fflush(FILE *stream)
777{
778 int ret = fflush(stream);
779
780 /*
781 * write() is used behind the scenes of stdio output functions.
782 * Since git code does not check for errors after each stdio write
783 * operation, it can happen that write() is called by a later
784 * stdio function even if an earlier write() call failed. In the
785 * case of a pipe whose readable end was closed, only the first
786 * call to write() reports EPIPE on Windows. Subsequent write()
787 * calls report EINVAL. It is impossible to notice whether this
788 * fflush invocation triggered such a case, therefore, we have to
789 * catch all EINVAL errors whole-sale.
790 */
791 if (ret && errno == EINVAL)
792 errno = EPIPE;
793
794 return ret;
795}
796
2b86292e
JS
797#undef write
798ssize_t mingw_write(int fd, const void *buf, size_t len)
799{
800 ssize_t result = write(fd, buf, len);
801
19ed0dff
JS
802 if (result < 0 && (errno == EINVAL || errno == ENOSPC) && buf) {
803 int orig = errno;
804
2b86292e
JS
805 /* check if fd is a pipe */
806 HANDLE h = (HANDLE) _get_osfhandle(fd);
19ed0dff
JS
807 if (GetFileType(h) != FILE_TYPE_PIPE)
808 errno = orig;
809 else if (orig == EINVAL)
2b86292e 810 errno = EPIPE;
19ed0dff
JS
811 else {
812 DWORD buf_size;
813
814 if (!GetNamedPipeInfo(h, NULL, NULL, &buf_size, NULL))
815 buf_size = 4096;
816 if (len > buf_size)
817 return write(fd, buf, buf_size);
818 errno = orig;
819 }
2b86292e
JS
820 }
821
822 return result;
823}
824
85faec9d
KB
825int mingw_access(const char *filename, int mode)
826{
827 wchar_t wfilename[MAX_PATH];
9160068a
JS
828 if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))
829 return 0;
85faec9d
KB
830 if (xutftowcs_path(wfilename, filename) < 0)
831 return -1;
832 /* X_OK is not supported by the MSVCRT version */
833 return _waccess(wfilename, mode & ~X_OK);
834}
835
836int mingw_chdir(const char *dirname)
837{
838 wchar_t wdirname[MAX_PATH];
839 if (xutftowcs_path(wdirname, dirname) < 0)
840 return -1;
841 return _wchdir(wdirname);
842}
843
844int mingw_chmod(const char *filename, int mode)
845{
846 wchar_t wfilename[MAX_PATH];
847 if (xutftowcs_path(wfilename, filename) < 0)
848 return -1;
849 return _wchmod(wfilename, mode);
850}
851
a6d15bc3
JS
852/*
853 * The unit of FILETIME is 100-nanoseconds since January 1, 1601, UTC.
854 * Returns the 100-nanoseconds ("hekto nanoseconds") since the epoch.
855 */
856static inline long long filetime_to_hnsec(const FILETIME *ft)
5411bdc4
MSO
857{
858 long long winTime = ((long long)ft->dwHighDateTime << 32) + ft->dwLowDateTime;
a6d15bc3
JS
859 /* Windows to Unix Epoch conversion */
860 return winTime - 116444736000000000LL;
861}
862
d7e8c874 863static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts)
a6d15bc3 864{
d7e8c874
KB
865 long long hnsec = filetime_to_hnsec(ft);
866 ts->tv_sec = (time_t)(hnsec / 10000000);
867 ts->tv_nsec = (hnsec % 10000000) * 100;
5411bdc4
MSO
868}
869
4b0abd5c
JS
870/**
871 * Verifies that safe_create_leading_directories() would succeed.
872 */
873static int has_valid_directory_prefix(wchar_t *wfilename)
874{
386d3720 875 size_t n = wcslen(wfilename);
4b0abd5c
JS
876
877 while (n > 0) {
878 wchar_t c = wfilename[--n];
879 DWORD attributes;
880
881 if (!is_dir_sep(c))
882 continue;
883
884 wfilename[n] = L'\0';
885 attributes = GetFileAttributesW(wfilename);
886 wfilename[n] = c;
82ba1191
JS
887 if (attributes &
888 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE))
4b0abd5c
JS
889 return 1;
890 if (attributes == INVALID_FILE_ATTRIBUTES)
891 switch (GetLastError()) {
892 case ERROR_PATH_NOT_FOUND:
893 continue;
894 case ERROR_FILE_NOT_FOUND:
895 /* This implies parent directory exists. */
896 return 1;
897 }
898 return 0;
899 }
900 return 1;
901}
902
5411bdc4
MSO
903/* We keep the do_lstat code in a separate function to avoid recursion.
904 * When a path ends with a slash, the stat will fail with ENOENT. In
905 * this case, we strip the trailing slashes and stat again.
9b9784ca
PT
906 *
907 * If follow is true then act like stat() and report on the link
908 * target. Otherwise report on the link itself.
5411bdc4 909 */
9b9784ca 910static int do_lstat(int follow, const char *file_name, struct stat *buf)
5411bdc4
MSO
911{
912 WIN32_FILE_ATTRIBUTE_DATA fdata;
85faec9d
KB
913 wchar_t wfilename[MAX_PATH];
914 if (xutftowcs_path(wfilename, file_name) < 0)
915 return -1;
5411bdc4 916
85faec9d 917 if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
5411bdc4
MSO
918 buf->st_ino = 0;
919 buf->st_gid = 0;
920 buf->st_uid = 0;
180964f0 921 buf->st_nlink = 1;
444dc903 922 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
1d4e4cd4
JS
923 buf->st_size = fdata.nFileSizeLow |
924 (((off_t)fdata.nFileSizeHigh)<<32);
8252df62 925 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
d7e8c874
KB
926 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
927 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
928 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
9b9784ca 929 if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
85faec9d
KB
930 WIN32_FIND_DATAW findbuf;
931 HANDLE handle = FindFirstFileW(wfilename, &findbuf);
9b9784ca
PT
932 if (handle != INVALID_HANDLE_VALUE) {
933 if ((findbuf.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) &&
934 (findbuf.dwReserved0 == IO_REPARSE_TAG_SYMLINK)) {
935 if (follow) {
936 char buffer[MAXIMUM_REPARSE_DATA_BUFFER_SIZE];
937 buf->st_size = readlink(file_name, buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE);
938 } else {
939 buf->st_mode = S_IFLNK;
940 }
941 buf->st_mode |= S_IREAD;
942 if (!(findbuf.dwFileAttributes & FILE_ATTRIBUTE_READONLY))
943 buf->st_mode |= S_IWRITE;
944 }
945 FindClose(handle);
946 }
947 }
5411bdc4
MSO
948 return 0;
949 }
85faec9d
KB
950 switch (GetLastError()) {
951 case ERROR_ACCESS_DENIED:
952 case ERROR_SHARING_VIOLATION:
953 case ERROR_LOCK_VIOLATION:
954 case ERROR_SHARING_BUFFER_EXCEEDED:
955 errno = EACCES;
956 break;
957 case ERROR_BUFFER_OVERFLOW:
958 errno = ENAMETOOLONG;
959 break;
960 case ERROR_NOT_ENOUGH_MEMORY:
961 errno = ENOMEM;
962 break;
4b0abd5c
JS
963 case ERROR_PATH_NOT_FOUND:
964 if (!has_valid_directory_prefix(wfilename)) {
965 errno = ENOTDIR;
966 break;
967 }
968 /* fallthru */
85faec9d
KB
969 default:
970 errno = ENOENT;
971 break;
972 }
5411bdc4
MSO
973 return -1;
974}
975
976/* We provide our own lstat/fstat functions, since the provided
977 * lstat/fstat functions are so slow. These stat functions are
978 * tailored for Git's usage (read: fast), and are not meant to be
979 * complete. Note that Git stat()s are redirected to mingw_lstat()
980 * too, since Windows doesn't really handle symlinks that well.
981 */
9b9784ca 982static int do_stat_internal(int follow, const char *file_name, struct stat *buf)
5411bdc4 983{
386d3720 984 size_t namelen;
58aa3d2a 985 char alt_name[PATH_MAX];
5411bdc4 986
9b9784ca 987 if (!do_lstat(follow, file_name, buf))
5411bdc4
MSO
988 return 0;
989
990 /* if file_name ended in a '/', Windows returned ENOENT;
991 * try again without trailing slashes
992 */
993 if (errno != ENOENT)
994 return -1;
995
996 namelen = strlen(file_name);
997 if (namelen && file_name[namelen-1] != '/')
998 return -1;
999 while (namelen && file_name[namelen-1] == '/')
1000 --namelen;
1001 if (!namelen || namelen >= PATH_MAX)
1002 return -1;
1003
1004 memcpy(alt_name, file_name, namelen);
1005 alt_name[namelen] = 0;
9b9784ca
PT
1006 return do_lstat(follow, alt_name, buf);
1007}
1008
7bf19838
JS
1009static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
1010{
1011 BY_HANDLE_FILE_INFORMATION fdata;
1012
1013 if (!GetFileInformationByHandle(hnd, &fdata)) {
1014 errno = err_win_to_posix(GetLastError());
1015 return -1;
1016 }
1017
1018 buf->st_ino = 0;
1019 buf->st_gid = 0;
1020 buf->st_uid = 0;
1021 buf->st_nlink = 1;
1022 buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes);
1023 buf->st_size = fdata.nFileSizeLow |
1024 (((off_t)fdata.nFileSizeHigh)<<32);
1025 buf->st_dev = buf->st_rdev = 0; /* not used by Git */
d7e8c874
KB
1026 filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
1027 filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
1028 filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
7bf19838
JS
1029 return 0;
1030}
1031
9b9784ca
PT
1032int mingw_lstat(const char *file_name, struct stat *buf)
1033{
1034 return do_stat_internal(0, file_name, buf);
1035}
1036int mingw_stat(const char *file_name, struct stat *buf)
1037{
1038 return do_stat_internal(1, file_name, buf);
5411bdc4
MSO
1039}
1040
180964f0 1041int mingw_fstat(int fd, struct stat *buf)
5411bdc4
MSO
1042{
1043 HANDLE fh = (HANDLE)_get_osfhandle(fd);
d75e6973 1044 DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
5411bdc4 1045
d75e6973
KB
1046 switch (type) {
1047 case FILE_TYPE_DISK:
1048 return get_file_info_by_handle(fh, buf);
5411bdc4 1049
d75e6973
KB
1050 case FILE_TYPE_CHAR:
1051 case FILE_TYPE_PIPE:
1052 /* initialize stat fields */
1053 memset(buf, 0, sizeof(*buf));
180964f0 1054 buf->st_nlink = 1;
d75e6973
KB
1055
1056 if (type == FILE_TYPE_CHAR) {
1057 buf->st_mode = _S_IFCHR;
1058 } else {
1059 buf->st_mode = _S_IFIFO;
1060 if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
1061 buf->st_size = avail;
1062 }
5411bdc4 1063 return 0;
7bf19838 1064
d75e6973
KB
1065 default:
1066 errno = EBADF;
1067 return -1;
5411bdc4 1068 }
5411bdc4
MSO
1069}
1070
7c0ffa1c
JS
1071static inline void time_t_to_filetime(time_t t, FILETIME *ft)
1072{
1073 long long winTime = t * 10000000LL + 116444736000000000LL;
1074 ft->dwLowDateTime = winTime;
1075 ft->dwHighDateTime = winTime >> 32;
1076}
1077
1078int mingw_utime (const char *file_name, const struct utimbuf *times)
1079{
1080 FILETIME mft, aft;
090a3085 1081 int rc;
85faec9d
KB
1082 DWORD attrs;
1083 wchar_t wfilename[MAX_PATH];
090a3085
TK
1084 HANDLE osfilehandle;
1085
85faec9d
KB
1086 if (xutftowcs_path(wfilename, file_name) < 0)
1087 return -1;
7c0ffa1c
JS
1088
1089 /* must have write permission */
85faec9d 1090 attrs = GetFileAttributesW(wfilename);
852f098c
JS
1091 if (attrs != INVALID_FILE_ATTRIBUTES &&
1092 (attrs & FILE_ATTRIBUTE_READONLY)) {
1093 /* ignore errors here; open() will report them */
85faec9d 1094 SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
852f098c
JS
1095 }
1096
090a3085
TK
1097 osfilehandle = CreateFileW(wfilename,
1098 FILE_WRITE_ATTRIBUTES,
b0b65ec5 1099 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
090a3085
TK
1100 NULL,
1101 OPEN_EXISTING,
1102 (attrs != INVALID_FILE_ATTRIBUTES &&
1103 (attrs & FILE_ATTRIBUTE_DIRECTORY)) ?
1104 FILE_FLAG_BACKUP_SEMANTICS : 0,
1105 NULL);
1106 if (osfilehandle == INVALID_HANDLE_VALUE) {
1107 errno = err_win_to_posix(GetLastError());
852f098c
JS
1108 rc = -1;
1109 goto revert_attrs;
1110 }
7c0ffa1c 1111
ded2d476
SG
1112 if (times) {
1113 time_t_to_filetime(times->modtime, &mft);
1114 time_t_to_filetime(times->actime, &aft);
1115 } else {
1116 GetSystemTimeAsFileTime(&mft);
1117 aft = mft;
1118 }
090a3085
TK
1119
1120 if (!SetFileTime(osfilehandle, NULL, &aft, &mft)) {
7c0ffa1c
JS
1121 errno = EINVAL;
1122 rc = -1;
1123 } else
1124 rc = 0;
090a3085
TK
1125
1126 if (osfilehandle != INVALID_HANDLE_VALUE)
1127 CloseHandle(osfilehandle);
852f098c
JS
1128
1129revert_attrs:
1130 if (attrs != INVALID_FILE_ATTRIBUTES &&
1131 (attrs & FILE_ATTRIBUTE_READONLY)) {
1132 /* ignore errors again */
85faec9d 1133 SetFileAttributesW(wfilename, attrs);
852f098c 1134 }
7c0ffa1c
JS
1135 return rc;
1136}
1137
9ee0540a
JS
1138#undef strftime
1139size_t mingw_strftime(char *s, size_t max,
1140 const char *format, const struct tm *tm)
1141{
a748f3f3
MA
1142 /* a pointer to the original strftime in case we can't find the UCRT version */
1143 static size_t (*fallback)(char *, size_t, const char *, const struct tm *) = strftime;
1144 size_t ret;
4a9b2049 1145 DECLARE_PROC_ADDR(ucrtbase.dll, size_t, __cdecl, strftime, char *, size_t,
a748f3f3
MA
1146 const char *, const struct tm *);
1147
1148 if (INIT_PROC_ADDR(strftime))
1149 ret = strftime(s, max, format, tm);
1150 else
1151 ret = fallback(s, max, format, tm);
9ee0540a
JS
1152
1153 if (!ret && errno == EINVAL)
1154 die("invalid strftime format: '%s'", format);
1155 return ret;
1156}
1157
f4626df5
JS
1158unsigned int sleep (unsigned int seconds)
1159{
1160 Sleep(seconds*1000);
1161 return 0;
1162}
1163
85faec9d
KB
1164char *mingw_mktemp(char *template)
1165{
1166 wchar_t wtemplate[MAX_PATH];
1167 if (xutftowcs_path(wtemplate, template) < 0)
1168 return NULL;
1169 if (!_wmktemp(wtemplate))
1170 return NULL;
1171 if (xwcstoutf(template, wtemplate, strlen(template) + 1) < 0)
1172 return NULL;
1173 return template;
1174}
1175
f4626df5
JS
1176int mkstemp(char *template)
1177{
ae25974d 1178 return git_mkstemp_mode(template, 0600);
f4626df5
JS
1179}
1180
b652382d 1181int gettimeofday(struct timeval *tv, void *tz UNUSED)
f4626df5 1182{
a6d15bc3
JS
1183 FILETIME ft;
1184 long long hnsec;
1185
1186 GetSystemTimeAsFileTime(&ft);
1187 hnsec = filetime_to_hnsec(&ft);
1188 tv->tv_sec = hnsec / 10000000;
1189 tv->tv_usec = (hnsec % 10000000) / 10;
a42a0c2e 1190 return 0;
f4626df5
JS
1191}
1192
897bb8cb
JS
1193int pipe(int filedes[2])
1194{
3e34d665 1195 HANDLE h[2];
897bb8cb 1196
3e34d665
JS
1197 /* this creates non-inheritable handles */
1198 if (!CreatePipe(&h[0], &h[1], NULL, 8192)) {
1199 errno = err_win_to_posix(GetLastError());
897bb8cb
JS
1200 return -1;
1201 }
7c00bc39 1202 filedes[0] = _open_osfhandle(HCAST(int, h[0]), O_NOINHERIT);
3e34d665 1203 if (filedes[0] < 0) {
897bb8cb
JS
1204 CloseHandle(h[0]);
1205 CloseHandle(h[1]);
1206 return -1;
1207 }
7c00bc39 1208 filedes[1] = _open_osfhandle(HCAST(int, h[1]), O_NOINHERIT);
c3cb7b6f 1209 if (filedes[1] < 0) {
897bb8cb 1210 close(filedes[0]);
897bb8cb
JS
1211 CloseHandle(h[1]);
1212 return -1;
1213 }
897bb8cb
JS
1214 return 0;
1215}
1216
9e12400d 1217#ifndef __MINGW64__
f4626df5
JS
1218struct tm *gmtime_r(const time_t *timep, struct tm *result)
1219{
0109d676
ĐTCD
1220 if (gmtime_s(result, timep) == 0)
1221 return result;
1222 return NULL;
f4626df5
JS
1223}
1224
1225struct tm *localtime_r(const time_t *timep, struct tm *result)
1226{
0109d676
ĐTCD
1227 if (localtime_s(result, timep) == 0)
1228 return result;
1229 return NULL;
f4626df5 1230}
9e12400d 1231#endif
f4626df5 1232
25fe217b
JS
1233char *mingw_getcwd(char *pointer, int len)
1234{
937974fc
JS
1235 wchar_t cwd[MAX_PATH], wpointer[MAX_PATH];
1236 DWORD ret = GetCurrentDirectoryW(ARRAY_SIZE(cwd), cwd);
1237
1238 if (!ret || ret >= ARRAY_SIZE(cwd)) {
1239 errno = ret ? ENAMETOOLONG : err_win_to_posix(GetLastError());
1240 return NULL;
1241 }
1242 ret = GetLongPathNameW(cwd, wpointer, ARRAY_SIZE(wpointer));
4745feeb
AS
1243 if (!ret && GetLastError() == ERROR_ACCESS_DENIED) {
1244 HANDLE hnd = CreateFileW(cwd, 0,
1245 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
1246 OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
1247 if (hnd == INVALID_HANDLE_VALUE)
1248 return NULL;
1249 ret = GetFinalPathNameByHandleW(hnd, wpointer, ARRAY_SIZE(wpointer), 0);
1250 CloseHandle(hnd);
1251 if (!ret || ret >= ARRAY_SIZE(wpointer))
1252 return NULL;
1253 if (xwcstoutf(pointer, normalize_ntpath(wpointer), len) < 0)
1254 return NULL;
1255 return pointer;
1256 }
937974fc 1257 if (!ret || ret >= ARRAY_SIZE(wpointer))
85faec9d 1258 return NULL;
e2724c1e
JS
1259 if (GetFileAttributesW(wpointer) == INVALID_FILE_ATTRIBUTES) {
1260 errno = ENOENT;
1261 return NULL;
1262 }
85faec9d
KB
1263 if (xwcstoutf(pointer, wpointer, len) < 0)
1264 return NULL;
8e9b2080 1265 convert_slashes(pointer);
85faec9d 1266 return pointer;
25fe217b
JS
1267}
1268
7e5d7768 1269/*
2ef2ae29
JS
1270 * See "Parsing C++ Command-Line Arguments" at Microsoft's Docs:
1271 * https://docs.microsoft.com/en-us/cpp/cpp/parsing-cpp-command-line-arguments
7e5d7768 1272 */
9e9da23c 1273static const char *quote_arg_msvc(const char *arg)
7e5d7768
JS
1274{
1275 /* count chars to quote */
1276 int len = 0, n = 0;
1277 int force_quotes = 0;
1278 char *q, *d;
1279 const char *p = arg;
1280 if (!*p) force_quotes = 1;
1281 while (*p) {
3aea1a5a 1282 if (isspace(*p) || *p == '*' || *p == '?' || *p == '{' || *p == '\'')
7e5d7768
JS
1283 force_quotes = 1;
1284 else if (*p == '"')
1285 n++;
1286 else if (*p == '\\') {
1287 int count = 0;
1288 while (*p == '\\') {
1289 count++;
1290 p++;
1291 len++;
1292 }
6d868416 1293 if (*p == '"' || !*p)
7e5d7768
JS
1294 n += count*2 + 1;
1295 continue;
1296 }
1297 len++;
1298 p++;
1299 }
1300 if (!force_quotes && n == 0)
1301 return arg;
1302
1303 /* insert \ where necessary */
50a6c8ef 1304 d = q = xmalloc(st_add3(len, n, 3));
7e5d7768
JS
1305 *d++ = '"';
1306 while (*arg) {
1307 if (*arg == '"')
1308 *d++ = '\\';
1309 else if (*arg == '\\') {
1310 int count = 0;
1311 while (*arg == '\\') {
1312 count++;
1313 *d++ = *arg++;
1314 }
6d868416 1315 if (*arg == '"' || !*arg) {
7e5d7768
JS
1316 while (count-- > 0)
1317 *d++ = '\\';
6d868416
JS
1318 /* don't escape the surrounding end quote */
1319 if (!*arg)
1320 break;
7e5d7768
JS
1321 *d++ = '\\';
1322 }
1323 }
1324 *d++ = *arg++;
1325 }
1326 *d++ = '"';
6d868416 1327 *d++ = '\0';
7e5d7768
JS
1328 return q;
1329}
1330
9e9da23c
JS
1331#include "quote.h"
1332
1333static const char *quote_arg_msys2(const char *arg)
1334{
1335 struct strbuf buf = STRBUF_INIT;
1336 const char *p2 = arg, *p;
1337
1338 for (p = arg; *p; p++) {
1339 int ws = isspace(*p);
7d8b6769
JS
1340 if (!ws && *p != '\\' && *p != '"' && *p != '{' && *p != '\'' &&
1341 *p != '?' && *p != '*' && *p != '~')
9e9da23c
JS
1342 continue;
1343 if (!buf.len)
1344 strbuf_addch(&buf, '"');
1345 if (p != p2)
1346 strbuf_add(&buf, p2, p - p2);
7d8b6769 1347 if (*p == '\\' || *p == '"')
9e9da23c
JS
1348 strbuf_addch(&buf, '\\');
1349 p2 = p;
1350 }
1351
1352 if (p == arg)
1353 strbuf_addch(&buf, '"');
1354 else if (!buf.len)
1355 return arg;
1356 else
04522edb 1357 strbuf_add(&buf, p2, p - p2);
9e9da23c
JS
1358
1359 strbuf_addch(&buf, '"');
1360 return strbuf_detach(&buf, 0);
1361}
1362
f1a4dfb8
JS
1363static const char *parse_interpreter(const char *cmd)
1364{
1365 static char buf[100];
1366 char *p, *opt;
386d3720
SK
1367 ssize_t n; /* read() can return negative values */
1368 int fd;
f1a4dfb8
JS
1369
1370 /* don't even try a .exe */
1371 n = strlen(cmd);
1372 if (n >= 4 && !strcasecmp(cmd+n-4, ".exe"))
1373 return NULL;
1374
1375 fd = open(cmd, O_RDONLY);
1376 if (fd < 0)
1377 return NULL;
1378 n = read(fd, buf, sizeof(buf)-1);
1379 close(fd);
1380 if (n < 4) /* at least '#!/x' and not error */
1381 return NULL;
1382
1383 if (buf[0] != '#' || buf[1] != '!')
1384 return NULL;
1385 buf[n] = '\0';
bedc4279
PH
1386 p = buf + strcspn(buf, "\r\n");
1387 if (!*p)
f1a4dfb8
JS
1388 return NULL;
1389
1390 *p = '\0';
1391 if (!(p = strrchr(buf+2, '/')) && !(p = strrchr(buf+2, '\\')))
1392 return NULL;
1393 /* strip options */
1394 if ((opt = strchr(p+1, ' ')))
1395 *opt = '\0';
1396 return p+1;
1397}
1398
f1a4dfb8
JS
1399/*
1400 * exe_only means that we only want to detect .exe files, but not scripts
1401 * (which do not have an extension)
1402 */
e0ca1ca2
RS
1403static char *lookup_prog(const char *dir, int dirlen, const char *cmd,
1404 int isexe, int exe_only)
f1a4dfb8
JS
1405{
1406 char path[MAX_PATH];
4e1a641e 1407 wchar_t wpath[MAX_PATH];
e0ca1ca2 1408 snprintf(path, sizeof(path), "%.*s\\%s.exe", dirlen, dir, cmd);
f1a4dfb8 1409
4e1a641e
AR
1410 if (xutftowcs_path(wpath, path) < 0)
1411 return NULL;
1412
1413 if (!isexe && _waccess(wpath, F_OK) == 0)
f1a4dfb8 1414 return xstrdup(path);
4e1a641e
AR
1415 wpath[wcslen(wpath)-4] = '\0';
1416 if ((!exe_only || isexe) && _waccess(wpath, F_OK) == 0) {
1417 if (!(GetFileAttributesW(wpath) & FILE_ATTRIBUTE_DIRECTORY)) {
1418 path[strlen(path)-4] = '\0';
fe77b695 1419 return xstrdup(path);
4e1a641e
AR
1420 }
1421 }
f1a4dfb8
JS
1422 return NULL;
1423}
1424
1425/*
22e5e58a 1426 * Determines the absolute path of cmd using the split path in path.
f1a4dfb8
JS
1427 * If cmd contains a slash or backslash, no lookup is performed.
1428 */
e0ca1ca2 1429static char *path_lookup(const char *cmd, int exe_only)
f1a4dfb8 1430{
e0ca1ca2 1431 const char *path;
f1a4dfb8 1432 char *prog = NULL;
386d3720 1433 size_t len = strlen(cmd);
f1a4dfb8
JS
1434 int isexe = len >= 4 && !strcasecmp(cmd+len-4, ".exe");
1435
2ce6d075 1436 if (strpbrk(cmd, "/\\"))
e0ca1ca2
RS
1437 return xstrdup(cmd);
1438
1439 path = mingw_getenv("PATH");
1440 if (!path)
1441 return NULL;
f1a4dfb8 1442
e0ca1ca2
RS
1443 while (!prog) {
1444 const char *sep = strchrnul(path, ';');
1445 int dirlen = sep - path;
1446 if (dirlen)
1447 prog = lookup_prog(path, dirlen, cmd, isexe, exe_only);
1448 if (!*sep)
1449 break;
1450 path = sep + 1;
1451 }
f1a4dfb8
JS
1452
1453 return prog;
1454}
1455
2bf46a9f
MA
1456char *mingw_locate_in_PATH(const char *cmd)
1457{
1458 return path_lookup(cmd, 0);
1459}
1460
fe21c6b2
JS
1461static const wchar_t *wcschrnul(const wchar_t *s, wchar_t c)
1462{
1463 while (*s && *s != c)
1464 s++;
1465 return s;
1466}
1467
1468/* Compare only keys */
1469static int wenvcmp(const void *a, const void *b)
1470{
1471 wchar_t *p = *(wchar_t **)a, *q = *(wchar_t **)b;
1472 size_t p_len, q_len;
1473
1474 /* Find the keys */
1475 p_len = wcschrnul(p, L'=') - p;
1476 q_len = wcschrnul(q, L'=') - q;
f279242d 1477
fe21c6b2
JS
1478 /* If the length differs, include the shorter key's NUL */
1479 if (p_len < q_len)
1480 p_len++;
1481 else if (p_len > q_len)
1482 p_len = q_len + 1;
1483
1484 return _wcsnicmp(p, q, p_len);
1485}
f279242d 1486
df0e998c 1487/*
fe21c6b2
JS
1488 * Build an environment block combining the inherited environment
1489 * merged with the given list of settings.
1490 *
1491 * Values of the form "KEY=VALUE" in deltaenv override inherited values.
1492 * Values of the form "KEY" in deltaenv delete inherited values.
1493 *
1494 * Multiple entries in deltaenv for the same key are explicitly allowed.
1495 *
1496 * We return a contiguous block of UNICODE strings with a final trailing
1497 * zero word.
df0e998c 1498 */
77734da2 1499static wchar_t *make_environment_block(char **deltaenv)
7e5d7768 1500{
fe21c6b2
JS
1501 wchar_t *wenv = GetEnvironmentStringsW(), *wdeltaenv, *result, *p;
1502 size_t wlen, s, delta_size, size;
df0e998c 1503
fe21c6b2
JS
1504 wchar_t **array = NULL;
1505 size_t alloc = 0, nr = 0, i;
df0e998c 1506
fe21c6b2
JS
1507 size = 1; /* for extra NUL at the end */
1508
1509 /* If there is no deltaenv to apply, simply return a copy. */
1510 if (!deltaenv || !*deltaenv) {
1511 for (p = wenv; p && *p; ) {
1512 size_t s = wcslen(p) + 1;
1513 size += s;
1514 p += s;
1515 }
77734da2 1516
6e578410 1517 DUP_ARRAY(result, wenv, size);
fe21c6b2
JS
1518 FreeEnvironmentStringsW(wenv);
1519 return result;
1520 }
77734da2 1521
fe21c6b2
JS
1522 /*
1523 * If there is a deltaenv, let's accumulate all keys into `array`,
97fff610
JS
1524 * sort them using the stable git_stable_qsort() and then copy,
1525 * skipping duplicate keys
fe21c6b2
JS
1526 */
1527 for (p = wenv; p && *p; ) {
1528 ALLOC_GROW(array, nr + 1, alloc);
1529 s = wcslen(p) + 1;
1530 array[nr++] = p;
1531 p += s;
1532 size += s;
df0e998c 1533 }
fe21c6b2
JS
1534
1535 /* (over-)assess size needed for wchar version of deltaenv */
1536 for (delta_size = 0, i = 0; deltaenv[i]; i++)
1537 delta_size += strlen(deltaenv[i]) * 2 + 1;
1538 ALLOC_ARRAY(wdeltaenv, delta_size);
1539
1540 /* convert the deltaenv, appending to array */
1541 for (i = 0, p = wdeltaenv; deltaenv[i]; i++) {
1542 ALLOC_GROW(array, nr + 1, alloc);
1543 wlen = xutftowcs(p, deltaenv[i], wdeltaenv + delta_size - p);
1544 array[nr++] = p;
1545 p += wlen + 1;
1546 }
df0e998c 1547
97fff610 1548 git_stable_qsort(array, nr, sizeof(*array), wenvcmp);
fe21c6b2 1549 ALLOC_ARRAY(result, size + delta_size);
df0e998c 1550
fe21c6b2
JS
1551 for (p = result, i = 0; i < nr; i++) {
1552 /* Skip any duplicate keys; last one wins */
1553 while (i + 1 < nr && !wenvcmp(array + i, array + i + 1))
1554 i++;
77734da2 1555
fe21c6b2
JS
1556 /* Skip "to delete" entry */
1557 if (!wcschr(array[i], L'='))
1558 continue;
77734da2 1559
fe21c6b2 1560 size = wcslen(array[i]) + 1;
552fc501 1561 COPY_ARRAY(p, array[i], size);
fe21c6b2 1562 p += size;
df0e998c 1563 }
fe21c6b2
JS
1564 *p = L'\0';
1565
1566 free(array);
1567 free(wdeltaenv);
1568 FreeEnvironmentStringsW(wenv);
1569 return result;
7e5d7768
JS
1570}
1571
0e218f91
JS
1572static void do_unset_environment_variables(void)
1573{
1574 static int done;
1575 char *p = unset_environment_variables;
1576
1577 if (done || !p)
1578 return;
1579 done = 1;
1580
1581 for (;;) {
1582 char *comma = strchr(p, ',');
1583
1584 if (comma)
1585 *comma = '\0';
1586 unsetenv(p);
1587 if (!comma)
1588 break;
1589 p = comma + 1;
1590 }
1591}
1592
52de4db5
EFL
1593struct pinfo_t {
1594 struct pinfo_t *next;
1595 pid_t pid;
1596 HANDLE proc;
657b35f4
RJ
1597};
1598static struct pinfo_t *pinfo = NULL;
52de4db5
EFL
1599CRITICAL_SECTION pinfo_cs;
1600
9e9da23c
JS
1601/* Used to match and chomp off path components */
1602static inline int match_last_path_component(const char *path, size_t *len,
1603 const char *component)
1604{
1605 size_t component_len = strlen(component);
1606 if (*len < component_len + 1 ||
1607 !is_dir_sep(path[*len - component_len - 1]) ||
1608 fspathncmp(path + *len - component_len, component, component_len))
1609 return 0;
1610 *len -= component_len + 1;
1611 /* chomp off repeated dir separators */
1612 while (*len > 0 && is_dir_sep(path[*len - 1]))
1613 (*len)--;
1614 return 1;
1615}
1616
1617static int is_msys2_sh(const char *cmd)
1618{
e2ba3d6f
JS
1619 if (!cmd)
1620 return 0;
1621
1622 if (!strcmp(cmd, "sh")) {
9e9da23c
JS
1623 static int ret = -1;
1624 char *p;
1625
1626 if (ret >= 0)
1627 return ret;
1628
1629 p = path_lookup(cmd, 0);
1630 if (!p)
1631 ret = 0;
1632 else {
1633 size_t len = strlen(p);
1634
1635 ret = match_last_path_component(p, &len, "sh.exe") &&
1636 match_last_path_component(p, &len, "bin") &&
1637 match_last_path_component(p, &len, "usr");
1638 free(p);
1639 }
1640 return ret;
1641 }
e2ba3d6f 1642
f1ed769a 1643 if (ends_with(cmd, "\\sh.exe") || ends_with(cmd, "/sh.exe")) {
e2ba3d6f
JS
1644 static char *sh;
1645
1646 if (!sh)
1647 sh = path_lookup("sh", 0);
1648
1649 return !fspathcmp(cmd, sh);
1650 }
1651
9e9da23c
JS
1652 return 0;
1653}
1654
77734da2 1655static pid_t mingw_spawnve_fd(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1656 const char *dir,
75301f90 1657 int prepend_cmd, int fhin, int fhout, int fherr)
7e5d7768 1658{
ac33519d 1659 static int restrict_handle_inheritance = -1;
9a780a38 1660 STARTUPINFOEXW si;
7e5d7768 1661 PROCESS_INFORMATION pi;
9a780a38
JS
1662 LPPROC_THREAD_ATTRIBUTE_LIST attr_list = NULL;
1663 HANDLE stdhandles[3];
1664 DWORD stdhandles_count = 0;
1665 SIZE_T size;
7eb2619c
KB
1666 struct strbuf args;
1667 wchar_t wcmd[MAX_PATH], wdir[MAX_PATH], *wargs, *wenvblk = NULL;
1668 unsigned flags = CREATE_UNICODE_ENVIRONMENT;
7e5d7768 1669 BOOL ret;
0e218f91 1670 HANDLE cons;
9e9da23c 1671 const char *(*quote_arg)(const char *arg) =
49f7a76d
JS
1672 is_msys2_sh(cmd ? cmd : *argv) ?
1673 quote_arg_msys2 : quote_arg_msvc;
3efc128c 1674 const char *strace_env;
0e218f91 1675
4d0375ca
JS
1676 /* Make sure to override previous errors, if any */
1677 errno = 0;
1678
ac33519d
JS
1679 if (restrict_handle_inheritance < 0)
1680 restrict_handle_inheritance = core_restrict_inherited_handles;
1681 /*
1682 * The following code to restrict which handles are inherited seems
1683 * to work properly only on Windows 7 and later, so let's disable it
1684 * on Windows Vista and 2008.
1685 */
1686 if (restrict_handle_inheritance < 0)
1687 restrict_handle_inheritance = GetVersion() >> 16 >= 7601;
1688
0e218f91 1689 do_unset_environment_variables();
7e5d7768
JS
1690
1691 /* Determine whether or not we are associated to a console */
94238859 1692 cons = CreateFileW(L"CONOUT$", GENERIC_WRITE,
7e5d7768
JS
1693 FILE_SHARE_WRITE, NULL, OPEN_EXISTING,
1694 FILE_ATTRIBUTE_NORMAL, NULL);
1695 if (cons == INVALID_HANDLE_VALUE) {
1696 /* There is no console associated with this process.
1697 * Since the child is a console process, Windows
1698 * would normally create a console window. But
1699 * since we'll be redirecting std streams, we do
1700 * not need the console.
19fb896f
AG
1701 * It is necessary to use DETACHED_PROCESS
1702 * instead of CREATE_NO_WINDOW to make ssh
1703 * recognize that it has no console.
7e5d7768 1704 */
7eb2619c 1705 flags |= DETACHED_PROCESS;
7e5d7768
JS
1706 } else {
1707 /* There is already a console. If we specified
19fb896f 1708 * DETACHED_PROCESS here, too, Windows would
7e5d7768 1709 * disassociate the child from the console.
19fb896f 1710 * The same is true for CREATE_NO_WINDOW.
7e5d7768
JS
1711 * Go figure!
1712 */
7e5d7768
JS
1713 CloseHandle(cons);
1714 }
1715 memset(&si, 0, sizeof(si));
9a780a38
JS
1716 si.StartupInfo.cb = sizeof(si);
1717 si.StartupInfo.hStdInput = winansi_get_osfhandle(fhin);
1718 si.StartupInfo.hStdOutput = winansi_get_osfhandle(fhout);
1719 si.StartupInfo.hStdError = winansi_get_osfhandle(fherr);
1720
1721 /* The list of handles cannot contain duplicates */
1722 if (si.StartupInfo.hStdInput != INVALID_HANDLE_VALUE)
1723 stdhandles[stdhandles_count++] = si.StartupInfo.hStdInput;
1724 if (si.StartupInfo.hStdOutput != INVALID_HANDLE_VALUE &&
1725 si.StartupInfo.hStdOutput != si.StartupInfo.hStdInput)
1726 stdhandles[stdhandles_count++] = si.StartupInfo.hStdOutput;
1727 if (si.StartupInfo.hStdError != INVALID_HANDLE_VALUE &&
1728 si.StartupInfo.hStdError != si.StartupInfo.hStdInput &&
1729 si.StartupInfo.hStdError != si.StartupInfo.hStdOutput)
1730 stdhandles[stdhandles_count++] = si.StartupInfo.hStdError;
1731 if (stdhandles_count)
1732 si.StartupInfo.dwFlags |= STARTF_USESTDHANDLES;
7e5d7768 1733
eb7c7863
JS
1734 if (*argv && !strcmp(cmd, *argv))
1735 wcmd[0] = L'\0';
1736 else if (xutftowcs_path(wcmd, cmd) < 0)
99c3c76d
KB
1737 return -1;
1738 if (dir && xutftowcs_path(wdir, dir) < 0)
1739 return -1;
1740
7e5d7768
JS
1741 /* concatenate argv, quoting args as we go */
1742 strbuf_init(&args, 0);
1743 if (prepend_cmd) {
1744 char *quoted = (char *)quote_arg(cmd);
1745 strbuf_addstr(&args, quoted);
1746 if (quoted != cmd)
1747 free(quoted);
1748 }
1749 for (; *argv; argv++) {
1750 char *quoted = (char *)quote_arg(*argv);
1751 if (*args.buf)
1752 strbuf_addch(&args, ' ');
1753 strbuf_addstr(&args, quoted);
1754 if (quoted != *argv)
1755 free(quoted);
1756 }
1757
3efc128c
JS
1758 strace_env = getenv("GIT_STRACE_COMMANDS");
1759 if (strace_env) {
1760 char *p = path_lookup("strace.exe", 1);
1761 if (!p)
1762 return error("strace not found!");
1763 if (xutftowcs_path(wcmd, p) < 0) {
1764 free(p);
1765 return -1;
1766 }
1767 free(p);
1768 if (!strcmp("1", strace_env) ||
1769 !strcasecmp("yes", strace_env) ||
1770 !strcasecmp("true", strace_env))
1771 strbuf_insert(&args, 0, "strace ", 7);
1772 else {
1773 const char *quoted = quote_arg(strace_env);
1774 struct strbuf buf = STRBUF_INIT;
1775 strbuf_addf(&buf, "strace -o %s ", quoted);
1776 if (quoted != strace_env)
1777 free((char *)quoted);
1778 strbuf_insert(&args, 0, buf.buf, buf.len);
1779 strbuf_release(&buf);
1780 }
1781 }
1782
8d5b3325 1783 ALLOC_ARRAY(wargs, st_add(st_mult(2, args.len), 1));
99c3c76d
KB
1784 xutftowcs(wargs, args.buf, 2 * args.len + 1);
1785 strbuf_release(&args);
1786
77734da2 1787 wenvblk = make_environment_block(deltaenv);
7e5d7768
JS
1788
1789 memset(&pi, 0, sizeof(pi));
9a780a38
JS
1790 if (restrict_handle_inheritance && stdhandles_count &&
1791 (InitializeProcThreadAttributeList(NULL, 1, 0, &size) ||
1792 GetLastError() == ERROR_INSUFFICIENT_BUFFER) &&
1793 (attr_list = (LPPROC_THREAD_ATTRIBUTE_LIST)
1794 (HeapAlloc(GetProcessHeap(), 0, size))) &&
1795 InitializeProcThreadAttributeList(attr_list, 1, 0, &size) &&
1796 UpdateProcThreadAttribute(attr_list, 0,
1797 PROC_THREAD_ATTRIBUTE_HANDLE_LIST,
1798 stdhandles,
1799 stdhandles_count * sizeof(HANDLE),
1800 NULL, NULL)) {
1801 si.lpAttributeList = attr_list;
1802 flags |= EXTENDED_STARTUPINFO_PRESENT;
1803 }
1804
1805 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1806 stdhandles_count ? TRUE : FALSE,
1807 flags, wenvblk, dir ? wdir : NULL,
1808 &si.StartupInfo, &pi);
1809
1810 /*
1811 * On Windows 2008 R2, it seems that specifying certain types of handles
1812 * (such as FILE_TYPE_CHAR or FILE_TYPE_PIPE) will always produce an
1813 * error. Rather than playing finicky and fragile games, let's just try
1814 * to detect this situation and simply try again without restricting any
1815 * handle inheritance. This is still better than failing to create
1816 * processes.
1817 */
1818 if (!ret && restrict_handle_inheritance && stdhandles_count) {
1819 DWORD err = GetLastError();
1820 struct strbuf buf = STRBUF_INIT;
1821
1822 if (err != ERROR_NO_SYSTEM_RESOURCES &&
1823 /*
1824 * On Windows 7 and earlier, handles on pipes and character
1825 * devices are inherited automatically, and cannot be
1826 * specified in the thread handle list. Rather than trying
1827 * to catch each and every corner case (and running the
1828 * chance of *still* forgetting a few), let's just fall
1829 * back to creating the process without trying to limit the
1830 * handle inheritance.
1831 */
1832 !(err == ERROR_INVALID_PARAMETER &&
1833 GetVersion() >> 16 < 9200) &&
1834 !getenv("SUPPRESS_HANDLE_INHERITANCE_WARNING")) {
1835 DWORD fl = 0;
1836 int i;
1837
1838 setenv("SUPPRESS_HANDLE_INHERITANCE_WARNING", "1", 1);
1839
1840 for (i = 0; i < stdhandles_count; i++) {
1841 HANDLE h = stdhandles[i];
1842 strbuf_addf(&buf, "handle #%d: %p (type %lx, "
1843 "handle info (%d) %lx\n", i, h,
1844 GetFileType(h),
1845 GetHandleInformation(h, &fl),
1846 fl);
1847 }
1848 strbuf_addstr(&buf, "\nThis is a bug; please report it "
1849 "at\nhttps://github.com/git-for-windows/"
1850 "git/issues/new\n\n"
1851 "To suppress this warning, please set "
1852 "the environment variable\n\n"
1853 "\tSUPPRESS_HANDLE_INHERITANCE_WARNING=1"
1854 "\n");
1855 }
1856 restrict_handle_inheritance = 0;
1857 flags &= ~EXTENDED_STARTUPINFO_PRESENT;
1858 ret = CreateProcessW(*wcmd ? wcmd : NULL, wargs, NULL, NULL,
1859 TRUE, flags, wenvblk, dir ? wdir : NULL,
1860 &si.StartupInfo, &pi);
4d0375ca 1861 if (!ret)
9a780a38 1862 errno = err_win_to_posix(GetLastError());
4d0375ca 1863 if (ret && buf.len) {
9a780a38
JS
1864 warning("failed to restrict file handles (%ld)\n\n%s",
1865 err, buf.buf);
1866 }
1867 strbuf_release(&buf);
1868 } else if (!ret)
1869 errno = err_win_to_posix(GetLastError());
1870
1871 if (si.lpAttributeList)
1872 DeleteProcThreadAttributeList(si.lpAttributeList);
1873 if (attr_list)
1874 HeapFree(GetProcessHeap(), 0, attr_list);
7e5d7768 1875
7eb2619c 1876 free(wenvblk);
99c3c76d 1877 free(wargs);
7e5d7768 1878
9a780a38 1879 if (!ret)
7e5d7768 1880 return -1;
9a780a38 1881
7e5d7768 1882 CloseHandle(pi.hThread);
52de4db5
EFL
1883
1884 /*
1885 * The process ID is the human-readable identifier of the process
1886 * that we want to present in log and error messages. The handle
1887 * is not useful for this purpose. But we cannot close it, either,
1888 * because it is not possible to turn a process ID into a process
1889 * handle after the process terminated.
1890 * Keep the handle in a list for waitpid.
1891 */
1892 EnterCriticalSection(&pinfo_cs);
1893 {
1894 struct pinfo_t *info = xmalloc(sizeof(struct pinfo_t));
1895 info->pid = pi.dwProcessId;
1896 info->proc = pi.hProcess;
1897 info->next = pinfo;
1898 pinfo = info;
1899 }
1900 LeaveCriticalSection(&pinfo_cs);
1901
1902 return (pid_t)pi.dwProcessId;
7e5d7768
JS
1903}
1904
3e66e47b 1905static pid_t mingw_spawnv(const char *cmd, const char **argv, int prepend_cmd)
75301f90 1906{
77734da2 1907 return mingw_spawnve_fd(cmd, argv, NULL, NULL, prepend_cmd, 0, 1, 2);
75301f90
JS
1908}
1909
77734da2 1910pid_t mingw_spawnvpe(const char *cmd, const char **argv, char **deltaenv,
f9a2743c 1911 const char *dir,
75301f90 1912 int fhin, int fhout, int fherr)
7e5d7768
JS
1913{
1914 pid_t pid;
e0ca1ca2 1915 char *prog = path_lookup(cmd, 0);
7e5d7768
JS
1916
1917 if (!prog) {
1918 errno = ENOENT;
1919 pid = -1;
1920 }
1921 else {
1922 const char *interpr = parse_interpreter(prog);
1923
1924 if (interpr) {
1925 const char *argv0 = argv[0];
e0ca1ca2 1926 char *iprog = path_lookup(interpr, 1);
7e5d7768
JS
1927 argv[0] = prog;
1928 if (!iprog) {
1929 errno = ENOENT;
1930 pid = -1;
1931 }
1932 else {
77734da2 1933 pid = mingw_spawnve_fd(iprog, argv, deltaenv, dir, 1,
75301f90 1934 fhin, fhout, fherr);
7e5d7768
JS
1935 free(iprog);
1936 }
1937 argv[0] = argv0;
1938 }
1939 else
77734da2 1940 pid = mingw_spawnve_fd(prog, argv, deltaenv, dir, 0,
75301f90 1941 fhin, fhout, fherr);
7e5d7768
JS
1942 free(prog);
1943 }
7e5d7768
JS
1944 return pid;
1945}
1946
3e66e47b 1947static int try_shell_exec(const char *cmd, char *const *argv)
f1a4dfb8
JS
1948{
1949 const char *interpr = parse_interpreter(cmd);
f1a4dfb8
JS
1950 char *prog;
1951 int pid = 0;
1952
1953 if (!interpr)
1954 return 0;
e0ca1ca2 1955 prog = path_lookup(interpr, 1);
f1a4dfb8 1956 if (prog) {
ee4512ed 1957 int exec_id;
f1a4dfb8 1958 int argc = 0;
12fb9bd8 1959 char **argv2;
f1a4dfb8 1960 while (argv[argc]) argc++;
b32fa95f 1961 ALLOC_ARRAY(argv2, argc + 1);
7e5d7768 1962 argv2[0] = (char *)cmd; /* full path to the script file */
51bd6be3 1963 COPY_ARRAY(&argv2[1], &argv[1], argc);
09884f35
RS
1964 exec_id = trace2_exec(prog, (const char **)argv2);
1965 pid = mingw_spawnv(prog, (const char **)argv2, 1);
f1a4dfb8
JS
1966 if (pid >= 0) {
1967 int status;
1968 if (waitpid(pid, &status, 0) < 0)
1969 status = 255;
ee4512ed 1970 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1971 exit(status);
1972 }
ee4512ed 1973 trace2_exec_result(exec_id, -1);
f1a4dfb8
JS
1974 pid = 1; /* indicate that we tried but failed */
1975 free(prog);
1976 free(argv2);
1977 }
f1a4dfb8
JS
1978 return pid;
1979}
1980
3e66e47b 1981int mingw_execv(const char *cmd, char *const *argv)
f1a4dfb8
JS
1982{
1983 /* check if git_command is a shell script */
3e66e47b 1984 if (!try_shell_exec(cmd, argv)) {
f1a4dfb8 1985 int pid, status;
ee4512ed 1986 int exec_id;
f1a4dfb8 1987
ee4512ed 1988 exec_id = trace2_exec(cmd, (const char **)argv);
3e66e47b 1989 pid = mingw_spawnv(cmd, (const char **)argv, 0);
ee4512ed
JH
1990 if (pid < 0) {
1991 trace2_exec_result(exec_id, -1);
570f1e6e 1992 return -1;
ee4512ed 1993 }
f1a4dfb8
JS
1994 if (waitpid(pid, &status, 0) < 0)
1995 status = 255;
ee4512ed 1996 trace2_exec_result(exec_id, status);
f1a4dfb8
JS
1997 exit(status);
1998 }
570f1e6e 1999 return -1;
f1a4dfb8
JS
2000}
2001
1696d723 2002int mingw_execvp(const char *cmd, char *const *argv)
f1a4dfb8 2003{
e0ca1ca2 2004 char *prog = path_lookup(cmd, 0);
f1a4dfb8
JS
2005
2006 if (prog) {
3e66e47b 2007 mingw_execv(prog, argv);
f1a4dfb8
JS
2008 free(prog);
2009 } else
2010 errno = ENOENT;
2011
1696d723 2012 return -1;
f1a4dfb8
JS
2013}
2014
82fc07b7
EFL
2015int mingw_kill(pid_t pid, int sig)
2016{
2017 if (pid > 0 && sig == SIGTERM) {
2018 HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
2019
2020 if (TerminateProcess(h, -1)) {
2021 CloseHandle(h);
2022 return 0;
2023 }
2024
2025 errno = err_win_to_posix(GetLastError());
2026 CloseHandle(h);
2027 return -1;
64a99eb4
NTND
2028 } else if (pid > 0 && sig == 0) {
2029 HANDLE h = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
2030 if (h) {
2031 CloseHandle(h);
2032 return 0;
2033 }
82fc07b7
EFL
2034 }
2035
2036 errno = EINVAL;
2037 return -1;
2038}
2039
343ff06d 2040/*
fe21c6b2
JS
2041 * UTF-8 versions of getenv(), putenv() and unsetenv().
2042 * Internally, they use the CRT's stock UNICODE routines
2043 * to avoid data loss.
343ff06d 2044 */
fe21c6b2 2045char *mingw_getenv(const char *name)
343ff06d 2046{
ca1b4116 2047#define GETENV_MAX_RETAIN 64
fe21c6b2
JS
2048 static char *values[GETENV_MAX_RETAIN];
2049 static int value_counter;
386d3720 2050 size_t len_key, len_value;
fe21c6b2
JS
2051 wchar_t *w_key;
2052 char *value;
2053 wchar_t w_value[32768];
343ff06d 2054
fe21c6b2
JS
2055 if (!name || !*name)
2056 return NULL;
ba26f296 2057
fe21c6b2
JS
2058 len_key = strlen(name) + 1;
2059 /* We cannot use xcalloc() here because that uses getenv() itself */
2060 w_key = calloc(len_key, sizeof(wchar_t));
2061 if (!w_key)
386d3720
SK
2062 die("Out of memory, (tried to allocate %"PRIuMAX" wchar_t's)",
2063 (uintmax_t)len_key);
fe21c6b2 2064 xutftowcs(w_key, name, len_key);
61d1d92a
JS
2065 /* GetEnvironmentVariableW() only sets the last error upon failure */
2066 SetLastError(ERROR_SUCCESS);
fe21c6b2
JS
2067 len_value = GetEnvironmentVariableW(w_key, w_value, ARRAY_SIZE(w_value));
2068 if (!len_value && GetLastError() == ERROR_ENVVAR_NOT_FOUND) {
2069 free(w_key);
2070 return NULL;
ba26f296 2071 }
fe21c6b2
JS
2072 free(w_key);
2073
2074 len_value = len_value * 3 + 1;
2075 /* We cannot use xcalloc() here because that uses getenv() itself */
2076 value = calloc(len_value, sizeof(char));
2077 if (!value)
386d3720
SK
2078 die("Out of memory, (tried to allocate %"PRIuMAX" bytes)",
2079 (uintmax_t)len_value);
fe21c6b2
JS
2080 xwcstoutf(value, w_value, len_value);
2081
2082 /*
2083 * We return `value` which is an allocated value and the caller is NOT
2084 * expecting to have to free it, so we keep a round-robin array,
2085 * invalidating the buffer after GETENV_MAX_RETAIN getenv() calls.
2086 */
2087 free(values[value_counter]);
2088 values[value_counter++] = value;
2089 if (value_counter >= ARRAY_SIZE(values))
2090 value_counter = 0;
2091
2092 return value;
ba26f296
JS
2093}
2094
fe21c6b2 2095int mingw_putenv(const char *namevalue)
ba26f296 2096{
386d3720 2097 size_t size;
fe21c6b2
JS
2098 wchar_t *wide, *equal;
2099 BOOL result;
ba26f296 2100
fe21c6b2
JS
2101 if (!namevalue || !*namevalue)
2102 return 0;
ba26f296 2103
fe21c6b2
JS
2104 size = strlen(namevalue) * 2 + 1;
2105 wide = calloc(size, sizeof(wchar_t));
2106 if (!wide)
386d3720
SK
2107 die("Out of memory, (tried to allocate %" PRIuMAX " wchar_t's)",
2108 (uintmax_t)size);
fe21c6b2
JS
2109 xutftowcs(wide, namevalue, size);
2110 equal = wcschr(wide, L'=');
2111 if (!equal)
2112 result = SetEnvironmentVariableW(wide, NULL);
2113 else {
2114 *equal = L'\0';
2115 result = SetEnvironmentVariableW(wide, equal + 1);
ba26f296 2116 }
fe21c6b2 2117 free(wide);
2affea41 2118
fe21c6b2
JS
2119 if (!result)
2120 errno = err_win_to_posix(GetLastError());
df599e96 2121
fe21c6b2 2122 return result ? 0 : -1;
06bc4b79
JS
2123}
2124
b7cc9f82 2125static void ensure_socket_initialization(void)
746fb857
JS
2126{
2127 WSADATA wsa;
b7cc9f82
MS
2128 static int initialized = 0;
2129
2130 if (initialized)
2131 return;
746fb857
JS
2132
2133 if (WSAStartup(MAKEWORD(2,2), &wsa))
2134 die("unable to initialize winsock subsystem, error %d",
2135 WSAGetLastError());
fe3b2b7b 2136
b9f0193b 2137 atexit((void(*)(void)) WSACleanup);
b7cc9f82
MS
2138 initialized = 1;
2139}
2140
13d24b01
PT
2141#undef gethostname
2142int mingw_gethostname(char *name, int namelen)
2143{
2144 ensure_socket_initialization();
2145 return gethostname(name, namelen);
2146}
2147
b7cc9f82
MS
2148#undef gethostbyname
2149struct hostent *mingw_gethostbyname(const char *host)
2150{
2151 ensure_socket_initialization();
746fb857
JS
2152 return gethostbyname(host);
2153}
2154
b9f0193b 2155#undef getaddrinfo
fe3b2b7b
MS
2156int mingw_getaddrinfo(const char *node, const char *service,
2157 const struct addrinfo *hints, struct addrinfo **res)
2158{
2159 ensure_socket_initialization();
b9f0193b 2160 return getaddrinfo(node, service, hints, res);
fe3b2b7b
MS
2161}
2162
746fb857
JS
2163int mingw_socket(int domain, int type, int protocol)
2164{
2165 int sockfd;
772991af
MP
2166 SOCKET s;
2167
2168 ensure_socket_initialization();
2169 s = WSASocket(domain, type, protocol, NULL, 0, 0);
746fb857
JS
2170 if (s == INVALID_SOCKET) {
2171 /*
2172 * WSAGetLastError() values are regular BSD error codes
2173 * biased by WSABASEERR.
2174 * However, strerror() does not know about networking
2175 * specific errors, which are values beginning at 38 or so.
2176 * Therefore, we choose to leave the biased error code
2177 * in errno so that _if_ someone looks up the code somewhere,
2178 * then it is at least the number that are usually listed.
2179 */
2180 errno = WSAGetLastError();
2181 return -1;
2182 }
2183 /* convert into a file descriptor */
2184 if ((sockfd = _open_osfhandle(s, O_RDWR|O_BINARY)) < 0) {
2185 closesocket(s);
2186 return error("unable to make a socket file descriptor: %s",
2187 strerror(errno));
2188 }
2189 return sockfd;
2190}
2191
2192#undef connect
2193int mingw_connect(int sockfd, struct sockaddr *sa, size_t sz)
2194{
2195 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2196 return connect(s, sa, sz);
2197}
2198
772991af
MP
2199#undef bind
2200int mingw_bind(int sockfd, struct sockaddr *sa, size_t sz)
2201{
2202 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2203 return bind(s, sa, sz);
2204}
2205
2206#undef setsockopt
2207int mingw_setsockopt(int sockfd, int lvl, int optname, void *optval, int optlen)
2208{
2209 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2210 return setsockopt(s, lvl, optname, (const char*)optval, optlen);
2211}
2212
a7941795
JS
2213#undef shutdown
2214int mingw_shutdown(int sockfd, int how)
2215{
2216 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2217 return shutdown(s, how);
2218}
2219
772991af
MP
2220#undef listen
2221int mingw_listen(int sockfd, int backlog)
2222{
2223 SOCKET s = (SOCKET)_get_osfhandle(sockfd);
2224 return listen(s, backlog);
2225}
2226
2227#undef accept
2228int mingw_accept(int sockfd1, struct sockaddr *sa, socklen_t *sz)
2229{
2230 int sockfd2;
2231
2232 SOCKET s1 = (SOCKET)_get_osfhandle(sockfd1);
2233 SOCKET s2 = accept(s1, sa, sz);
2234
2235 /* convert into a file descriptor */
2236 if ((sockfd2 = _open_osfhandle(s2, O_RDWR|O_BINARY)) < 0) {
2237 int err = errno;
2238 closesocket(s2);
2239 return error("unable to make a socket file descriptor: %s",
2240 strerror(err));
2241 }
2242 return sockfd2;
2243}
2244
ea9e98c3
JS
2245#undef rename
2246int mingw_rename(const char *pold, const char *pnew)
2247{
391bceae 2248 static int supports_file_rename_info_ex = 1;
6ac6f878
JS
2249 DWORD attrs, gle;
2250 int tries = 0;
85faec9d 2251 wchar_t wpold[MAX_PATH], wpnew[MAX_PATH];
391bceae
PS
2252 int wpnew_len;
2253
2254 if (xutftowcs_path(wpold, pold) < 0)
2255 return -1;
2256 wpnew_len = xutftowcs_path(wpnew, pnew);
2257 if (wpnew_len < 0)
85faec9d 2258 return -1;
632f7017 2259
ea9e98c3
JS
2260 /*
2261 * Try native rename() first to get errno right.
2262 * It is based on MoveFile(), which cannot overwrite existing files.
2263 */
85faec9d 2264 if (!_wrename(wpold, wpnew))
ea9e98c3
JS
2265 return 0;
2266 if (errno != EEXIST)
2267 return -1;
391bceae 2268
6ac6f878 2269repeat:
391bceae
PS
2270 if (supports_file_rename_info_ex) {
2271 /*
2272 * Our minimum required Windows version is still set to Windows
2273 * Vista. We thus have to declare required infrastructure for
2274 * FileRenameInfoEx ourselves until we bump _WIN32_WINNT to
2275 * 0x0A00. Furthermore, we have to handle cases where the
2276 * FileRenameInfoEx call isn't supported yet.
2277 */
2278#define FILE_RENAME_FLAG_REPLACE_IF_EXISTS 0x00000001
2279#define FILE_RENAME_FLAG_POSIX_SEMANTICS 0x00000002
2280 FILE_INFO_BY_HANDLE_CLASS FileRenameInfoEx = 22;
2281 struct {
2282 /*
2283 * This is usually an unnamed union, but that is not
2284 * part of ISO C99. We thus inline the field, as we
2285 * really only care for the Flags field anyway.
2286 */
2287 DWORD Flags;
2288 HANDLE RootDirectory;
2289 DWORD FileNameLength;
2290 /*
2291 * The actual structure is defined with a single-character
2292 * flex array so that the structure has to be allocated on
2293 * the heap. As we declare this structure ourselves though
2294 * we can avoid the allocation and define FileName to have
2295 * MAX_PATH bytes.
2296 */
2297 WCHAR FileName[MAX_PATH];
2298 } rename_info = { 0 };
2299 HANDLE old_handle = INVALID_HANDLE_VALUE;
2300 BOOL success;
2301
2302 old_handle = CreateFileW(wpold, DELETE,
2303 FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
975fc047
EK
2304 NULL, OPEN_EXISTING,
2305 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
2306 NULL);
391bceae
PS
2307 if (old_handle == INVALID_HANDLE_VALUE) {
2308 errno = err_win_to_posix(GetLastError());
2309 return -1;
2310 }
2311
2312 rename_info.Flags = FILE_RENAME_FLAG_REPLACE_IF_EXISTS |
2313 FILE_RENAME_FLAG_POSIX_SEMANTICS;
2314 rename_info.FileNameLength = wpnew_len * sizeof(WCHAR);
2315 memcpy(rename_info.FileName, wpnew, wpnew_len * sizeof(WCHAR));
2316
2317 success = SetFileInformationByHandle(old_handle, FileRenameInfoEx,
2318 &rename_info, sizeof(rename_info));
2319 gle = GetLastError();
2320 CloseHandle(old_handle);
2321 if (success)
2322 return 0;
2323
2324 /*
2325 * When we see ERROR_INVALID_PARAMETER we can assume that the
2326 * current system doesn't support FileRenameInfoEx. Keep us
2327 * from using it in future calls and retry.
2328 */
2329 if (gle == ERROR_INVALID_PARAMETER) {
2330 supports_file_rename_info_ex = 0;
2331 goto repeat;
2332 }
2333
2334 /*
2335 * In theory, we shouldn't get ERROR_ACCESS_DENIED because we
2336 * always open files with FILE_SHARE_DELETE But in practice we
2337 * cannot assume that Git is the only one accessing files, and
2338 * other applications may not set FILE_SHARE_DELETE. So we have
2339 * to retry.
2340 */
2341 } else {
2342 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
2343 return 0;
2344 gle = GetLastError();
2345 }
2346
ea9e98c3 2347 /* TODO: translate more errors */
6ac6f878 2348 if (gle == ERROR_ACCESS_DENIED &&
85faec9d 2349 (attrs = GetFileAttributesW(wpnew)) != INVALID_FILE_ATTRIBUTES) {
632f7017 2350 if (attrs & FILE_ATTRIBUTE_DIRECTORY) {
4426fb51 2351 DWORD attrsold = GetFileAttributesW(wpold);
2352 if (attrsold == INVALID_FILE_ATTRIBUTES ||
2353 !(attrsold & FILE_ATTRIBUTE_DIRECTORY))
2354 errno = EISDIR;
2355 else if (!_wrmdir(wpnew))
2356 goto repeat;
ea9e98c3
JS
2357 return -1;
2358 }
632f7017 2359 if ((attrs & FILE_ATTRIBUTE_READONLY) &&
85faec9d
KB
2360 SetFileAttributesW(wpnew, attrs & ~FILE_ATTRIBUTE_READONLY)) {
2361 if (MoveFileExW(wpold, wpnew, MOVEFILE_REPLACE_EXISTING))
632f7017 2362 return 0;
6ac6f878 2363 gle = GetLastError();
632f7017 2364 /* revert file attributes on failure */
85faec9d 2365 SetFileAttributesW(wpnew, attrs);
632f7017 2366 }
ea9e98c3 2367 }
6ac6f878
JS
2368 if (tries < ARRAY_SIZE(delay) && gle == ERROR_ACCESS_DENIED) {
2369 /*
2370 * We assume that some other process had the source or
2371 * destination file open at the wrong moment and retry.
2372 * In order to give the other process a higher chance to
2373 * complete its operation, we give up our time slice now.
2374 * If we have to retry again, we do sleep a bit.
2375 */
2376 Sleep(delay[tries]);
2377 tries++;
2378 goto repeat;
2379 }
c9b78400
HV
2380 if (gle == ERROR_ACCESS_DENIED &&
2381 ask_yes_no_if_possible("Rename from '%s' to '%s' failed. "
2382 "Should I try again?", pold, pnew))
2383 goto repeat;
2384
ea9e98c3
JS
2385 errno = EACCES;
2386 return -1;
2387}
2388
b1b95204
RJ
2389/*
2390 * Note that this doesn't return the actual pagesize, but
2391 * the allocation granularity. If future Windows specific git code
2392 * needs the real getpagesize function, we need to find another solution.
2393 */
2394int mingw_getpagesize(void)
2395{
2396 SYSTEM_INFO si;
2397 GetSystemInfo(&si);
2398 return si.dwAllocationGranularity;
2399}
2400
564be791
JS
2401/* See https://msdn.microsoft.com/en-us/library/windows/desktop/ms724435.aspx */
2402enum EXTENDED_NAME_FORMAT {
2403 NameDisplay = 3,
2404 NameUserPrincipal = 8
2405};
2406
2407static char *get_extended_user_info(enum EXTENDED_NAME_FORMAT type)
2408{
4a9b2049 2409 DECLARE_PROC_ADDR(secur32.dll, BOOL, SEC_ENTRY, GetUserNameExW,
564be791
JS
2410 enum EXTENDED_NAME_FORMAT, LPCWSTR, PULONG);
2411 static wchar_t wbuffer[1024];
2412 DWORD len;
2413
2414 if (!INIT_PROC_ADDR(GetUserNameExW))
2415 return NULL;
2416
2417 len = ARRAY_SIZE(wbuffer);
2418 if (GetUserNameExW(type, wbuffer, &len)) {
2419 char *converted = xmalloc((len *= 3));
2420 if (xwcstoutf(converted, wbuffer, len) >= 0)
2421 return converted;
2422 free(converted);
2423 }
2424
2425 return NULL;
2426}
2427
501afcb8
JS
2428char *mingw_query_user_email(void)
2429{
2430 return get_extended_user_info(NameUserPrincipal);
2431}
2432
b652382d 2433struct passwd *getpwuid(int uid UNUSED)
f4626df5 2434{
55b6513e 2435 static unsigned initialized;
f7597aca 2436 static char user_name[100];
55b6513e 2437 static struct passwd *p;
39a98e9b 2438 wchar_t buf[100];
55b6513e 2439 DWORD len;
f7597aca 2440
55b6513e
JS
2441 if (initialized)
2442 return p;
f7597aca 2443
697bdd22 2444 len = ARRAY_SIZE(buf);
39a98e9b
JS
2445 if (!GetUserNameW(buf, &len)) {
2446 initialized = 1;
2447 return NULL;
2448 }
2449
2450 if (xwcstoutf(user_name, buf, sizeof(user_name)) < 0) {
55b6513e 2451 initialized = 1;
f7597aca 2452 return NULL;
55b6513e
JS
2453 }
2454
2455 p = xmalloc(sizeof(*p));
2456 p->pw_name = user_name;
564be791
JS
2457 p->pw_gecos = get_extended_user_info(NameDisplay);
2458 if (!p->pw_gecos)
e7b40195
PS
2459 /*
2460 * Data returned by getpwuid(3P) is treated as internal and
2461 * must never be written to or freed.
2462 */
2463 p->pw_gecos = (char *) "unknown";
55b6513e
JS
2464 p->pw_dir = NULL;
2465
2466 initialized = 1;
2467 return p;
f4626df5
JS
2468}
2469
6072fc31
JS
2470static HANDLE timer_event;
2471static HANDLE timer_thread;
2472static int timer_interval;
2473static int one_shot;
176478a8 2474static sig_handler_t timer_fn = SIG_DFL, sigint_fn = SIG_DFL;
6072fc31
JS
2475
2476/* The timer works like this:
2477 * The thread, ticktack(), is a trivial routine that most of the time
2478 * only waits to receive the signal to terminate. The main thread tells
2479 * the thread to terminate by setting the timer_event to the signalled
2480 * state.
2481 * But ticktack() interrupts the wait state after the timer's interval
2482 * length to call the signal handler.
2483 */
2484
b652382d 2485static unsigned __stdcall ticktack(void *dummy UNUSED)
6072fc31
JS
2486{
2487 while (WaitForSingleObject(timer_event, timer_interval) == WAIT_TIMEOUT) {
176478a8 2488 mingw_raise(SIGALRM);
6072fc31
JS
2489 if (one_shot)
2490 break;
2491 }
2492 return 0;
2493}
2494
2495static int start_timer_thread(void)
2496{
2497 timer_event = CreateEvent(NULL, FALSE, FALSE, NULL);
2498 if (timer_event) {
2499 timer_thread = (HANDLE) _beginthreadex(NULL, 0, ticktack, NULL, 0, NULL);
2500 if (!timer_thread )
2501 return errno = ENOMEM,
2502 error("cannot start timer thread");
2503 } else
2504 return errno = ENOMEM,
2505 error("cannot allocate resources for timer");
2506 return 0;
2507}
2508
2509static void stop_timer_thread(void)
2510{
2511 if (timer_event)
2512 SetEvent(timer_event); /* tell thread to terminate */
2513 if (timer_thread) {
72d63b2f 2514 int rc = WaitForSingleObject(timer_thread, 10000);
6072fc31
JS
2515 if (rc == WAIT_TIMEOUT)
2516 error("timer thread did not terminate timely");
2517 else if (rc != WAIT_OBJECT_0)
2518 error("waiting for timer thread failed: %lu",
2519 GetLastError());
2520 CloseHandle(timer_thread);
2521 }
2522 if (timer_event)
2523 CloseHandle(timer_event);
2524 timer_event = NULL;
2525 timer_thread = NULL;
2526}
2527
2528static inline int is_timeval_eq(const struct timeval *i1, const struct timeval *i2)
2529{
2530 return i1->tv_sec == i2->tv_sec && i1->tv_usec == i2->tv_usec;
2531}
2532
b652382d 2533int setitimer(int type UNUSED, struct itimerval *in, struct itimerval *out)
f4626df5 2534{
6072fc31
JS
2535 static const struct timeval zero;
2536 static int atexit_done;
2537
afe8a907 2538 if (out)
6072fc31
JS
2539 return errno = EINVAL,
2540 error("setitimer param 3 != NULL not implemented");
2541 if (!is_timeval_eq(&in->it_interval, &zero) &&
2542 !is_timeval_eq(&in->it_interval, &in->it_value))
2543 return errno = EINVAL,
2544 error("setitimer: it_interval must be zero or eq it_value");
2545
2546 if (timer_thread)
2547 stop_timer_thread();
2548
2549 if (is_timeval_eq(&in->it_value, &zero) &&
2550 is_timeval_eq(&in->it_interval, &zero))
2551 return 0;
2552
2553 timer_interval = in->it_value.tv_sec * 1000 + in->it_value.tv_usec / 1000;
2554 one_shot = is_timeval_eq(&in->it_interval, &zero);
2555 if (!atexit_done) {
2556 atexit(stop_timer_thread);
2557 atexit_done = 1;
2558 }
2559 return start_timer_thread();
f4626df5
JS
2560}
2561
2562int sigaction(int sig, struct sigaction *in, struct sigaction *out)
2563{
6072fc31
JS
2564 if (sig != SIGALRM)
2565 return errno = EINVAL,
2566 error("sigaction only implemented for SIGALRM");
afe8a907 2567 if (out)
6072fc31
JS
2568 return errno = EINVAL,
2569 error("sigaction: param 3 != NULL not implemented");
2570
2571 timer_fn = in->sa_handler;
2572 return 0;
2573}
2574
2575#undef signal
2576sig_handler_t mingw_signal(int sig, sig_handler_t handler)
2577{
a4540658 2578 sig_handler_t old;
176478a8
EFL
2579
2580 switch (sig) {
2581 case SIGALRM:
a4540658 2582 old = timer_fn;
176478a8
EFL
2583 timer_fn = handler;
2584 break;
2585
2586 case SIGINT:
a4540658 2587 old = sigint_fn;
176478a8
EFL
2588 sigint_fn = handler;
2589 break;
2590
2591 default:
6072fc31 2592 return signal(sig, handler);
176478a8
EFL
2593 }
2594
6072fc31 2595 return old;
f4626df5 2596}
4804aabc 2597
176478a8
EFL
2598#undef raise
2599int mingw_raise(int sig)
2600{
2601 switch (sig) {
2602 case SIGALRM:
2603 if (timer_fn == SIG_DFL) {
2604 if (isatty(STDERR_FILENO))
2605 fputs("Alarm clock\n", stderr);
2606 exit(128 + SIGALRM);
2607 } else if (timer_fn != SIG_IGN)
2608 timer_fn(SIGALRM);
2609 return 0;
2610
2611 case SIGINT:
2612 if (sigint_fn == SIG_DFL)
2613 exit(128 + SIGINT);
2614 else if (sigint_fn != SIG_IGN)
2615 sigint_fn(SIGINT);
2616 return 0;
2617
446df603
JH
2618#if defined(_MSC_VER)
2619 case SIGILL:
2620 case SIGFPE:
2621 case SIGSEGV:
2622 case SIGTERM:
2623 case SIGBREAK:
2624 case SIGABRT:
2625 case SIGABRT_COMPAT:
2626 /*
2627 * The <signal.h> header in the MS C Runtime defines 8 signals
2628 * as being supported on the platform. Anything else causes an
2629 * "Invalid signal or error" (which in DEBUG builds causes the
2630 * Abort/Retry/Ignore dialog). We by-pass the CRT for things we
2631 * already know will fail.
2632 */
2633 return raise(sig);
2634 default:
2635 errno = EINVAL;
2636 return -1;
2637
2638#else
2639
176478a8
EFL
2640 default:
2641 return raise(sig);
446df603
JH
2642
2643#endif
2644
176478a8
EFL
2645 }
2646}
2647
7be401e0
PK
2648int link(const char *oldpath, const char *newpath)
2649{
85faec9d
KB
2650 wchar_t woldpath[MAX_PATH], wnewpath[MAX_PATH];
2651 if (xutftowcs_path(woldpath, oldpath) < 0 ||
2652 xutftowcs_path(wnewpath, newpath) < 0)
2653 return -1;
2654
1e1a876b 2655 if (!CreateHardLinkW(wnewpath, woldpath, NULL)) {
7be401e0
PK
2656 errno = err_win_to_posix(GetLastError());
2657 return -1;
2658 }
2659 return 0;
2660}
0dbbbc1e 2661
956d86d1 2662pid_t waitpid(pid_t pid, int *status, int options)
52de4db5
EFL
2663{
2664 HANDLE h = OpenProcess(SYNCHRONIZE | PROCESS_QUERY_INFORMATION,
2665 FALSE, pid);
2666 if (!h) {
2667 errno = ECHILD;
2668 return -1;
2669 }
2670
ef7108ca
EFL
2671 if (pid > 0 && options & WNOHANG) {
2672 if (WAIT_OBJECT_0 != WaitForSingleObject(h, 0)) {
2673 CloseHandle(h);
2674 return 0;
2675 }
2676 options &= ~WNOHANG;
2677 }
2678
52de4db5
EFL
2679 if (options == 0) {
2680 struct pinfo_t **ppinfo;
2681 if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
2682 CloseHandle(h);
2683 return 0;
2684 }
2685
2686 if (status)
2687 GetExitCodeProcess(h, (LPDWORD)status);
2688
2689 EnterCriticalSection(&pinfo_cs);
2690
2691 ppinfo = &pinfo;
2692 while (*ppinfo) {
2693 struct pinfo_t *info = *ppinfo;
2694 if (info->pid == pid) {
2695 CloseHandle(info->proc);
2696 *ppinfo = info->next;
2697 free(info);
2698 break;
2699 }
2700 ppinfo = &info->next;
2701 }
2702
2703 LeaveCriticalSection(&pinfo_cs);
2704
2705 CloseHandle(h);
2706 return pid;
2707 }
2708 CloseHandle(h);
2709
2710 errno = EINVAL;
2711 return -1;
2712}
c2369bdf 2713
1c950a59
KB
2714int xutftowcsn(wchar_t *wcs, const char *utfs, size_t wcslen, int utflen)
2715{
2716 int upos = 0, wpos = 0;
2717 const unsigned char *utf = (const unsigned char*) utfs;
2718 if (!utf || !wcs || wcslen < 1) {
2719 errno = EINVAL;
2720 return -1;
2721 }
2722 /* reserve space for \0 */
2723 wcslen--;
2724 if (utflen < 0)
2725 utflen = INT_MAX;
2726
2727 while (upos < utflen) {
2728 int c = utf[upos++] & 0xff;
2729 if (utflen == INT_MAX && c == 0)
2730 break;
2731
2732 if (wpos >= wcslen) {
2733 wcs[wpos] = 0;
2734 errno = ERANGE;
2735 return -1;
2736 }
2737
2738 if (c < 0x80) {
2739 /* ASCII */
2740 wcs[wpos++] = c;
2741 } else if (c >= 0xc2 && c < 0xe0 && upos < utflen &&
2742 (utf[upos] & 0xc0) == 0x80) {
2743 /* 2-byte utf-8 */
2744 c = ((c & 0x1f) << 6);
2745 c |= (utf[upos++] & 0x3f);
2746 wcs[wpos++] = c;
2747 } else if (c >= 0xe0 && c < 0xf0 && upos + 1 < utflen &&
2748 !(c == 0xe0 && utf[upos] < 0xa0) && /* over-long encoding */
2749 (utf[upos] & 0xc0) == 0x80 &&
2750 (utf[upos + 1] & 0xc0) == 0x80) {
2751 /* 3-byte utf-8 */
2752 c = ((c & 0x0f) << 12);
2753 c |= ((utf[upos++] & 0x3f) << 6);
2754 c |= (utf[upos++] & 0x3f);
2755 wcs[wpos++] = c;
2756 } else if (c >= 0xf0 && c < 0xf5 && upos + 2 < utflen &&
2757 wpos + 1 < wcslen &&
2758 !(c == 0xf0 && utf[upos] < 0x90) && /* over-long encoding */
2759 !(c == 0xf4 && utf[upos] >= 0x90) && /* > \u10ffff */
2760 (utf[upos] & 0xc0) == 0x80 &&
2761 (utf[upos + 1] & 0xc0) == 0x80 &&
2762 (utf[upos + 2] & 0xc0) == 0x80) {
2763 /* 4-byte utf-8: convert to \ud8xx \udcxx surrogate pair */
2764 c = ((c & 0x07) << 18);
2765 c |= ((utf[upos++] & 0x3f) << 12);
2766 c |= ((utf[upos++] & 0x3f) << 6);
2767 c |= (utf[upos++] & 0x3f);
2768 c -= 0x10000;
2769 wcs[wpos++] = 0xd800 | (c >> 10);
2770 wcs[wpos++] = 0xdc00 | (c & 0x3ff);
2771 } else if (c >= 0xa0) {
2772 /* invalid utf-8 byte, printable unicode char: convert 1:1 */
2773 wcs[wpos++] = c;
2774 } else {
2775 /* invalid utf-8 byte, non-printable unicode: convert to hex */
2776 static const char *hex = "0123456789abcdef";
2777 wcs[wpos++] = hex[c >> 4];
2778 if (wpos < wcslen)
2779 wcs[wpos++] = hex[c & 0x0f];
2780 }
2781 }
2782 wcs[wpos] = 0;
2783 return wpos;
2784}
2785
2786int xwcstoutf(char *utf, const wchar_t *wcs, size_t utflen)
2787{
2788 if (!wcs || !utf || utflen < 1) {
2789 errno = EINVAL;
2790 return -1;
2791 }
2792 utflen = WideCharToMultiByte(CP_UTF8, 0, wcs, -1, utf, utflen, NULL, NULL);
2793 if (utflen)
2794 return utflen - 1;
2795 errno = ERANGE;
2796 return -1;
2797}
2798
0767172b 2799static void setup_windows_environment(void)
02e6edc0 2800{
1fc7bf79
JS
2801 char *tmp = getenv("TMPDIR");
2802
02e6edc0 2803 /* on Windows it is TMP and TEMP */
1fc7bf79
JS
2804 if (!tmp) {
2805 if (!(tmp = getenv("TMP")))
02e6edc0 2806 tmp = getenv("TEMP");
1fc7bf79 2807 if (tmp) {
02e6edc0 2808 setenv("TMPDIR", tmp, 1);
1fc7bf79
JS
2809 tmp = getenv("TMPDIR");
2810 }
2811 }
2812
2813 if (tmp) {
2814 /*
2815 * Convert all dir separators to forward slashes,
2816 * to help shell commands called from the Git
2817 * executable (by not mistaking the dir separators
2818 * for escape characters).
2819 */
8e9b2080 2820 convert_slashes(tmp);
02e6edc0
KB
2821 }
2822
2823 /* simulate TERM to enable auto-color (see color.c) */
2824 if (!getenv("TERM"))
2825 setenv("TERM", "cygwin", 1);
e12a9556
KB
2826
2827 /* calculate HOME if not set */
2828 if (!getenv("HOME")) {
2829 /*
2830 * try $HOMEDRIVE$HOMEPATH - the home share may be a network
2831 * location, thus also check if the path exists (i.e. is not
2832 * disconnected)
2833 */
2834 if ((tmp = getenv("HOMEDRIVE"))) {
2835 struct strbuf buf = STRBUF_INIT;
2836 strbuf_addstr(&buf, tmp);
2837 if ((tmp = getenv("HOMEPATH"))) {
2838 strbuf_addstr(&buf, tmp);
2839 if (is_directory(buf.buf))
2840 setenv("HOME", buf.buf, 1);
2841 else
2842 tmp = NULL; /* use $USERPROFILE */
2843 }
2844 strbuf_release(&buf);
2845 }
2846 /* use $USERPROFILE if the home share is not available */
2847 if (!tmp && (tmp = getenv("USERPROFILE")))
2848 setenv("HOME", tmp, 1);
2849 }
02e6edc0
KB
2850}
2851
03a4e46d 2852static void get_current_user_sid(PSID *sid, HANDLE *linked_token)
bdc77d1d
JS
2853{
2854 HANDLE token;
2855 DWORD len = 0;
03a4e46d
JS
2856 TOKEN_ELEVATION_TYPE elevationType;
2857 DWORD size;
2858
2859 *sid = NULL;
2860 *linked_token = NULL;
bdc77d1d
JS
2861
2862 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token))
03a4e46d 2863 return;
bdc77d1d
JS
2864
2865 if (!GetTokenInformation(token, TokenUser, NULL, 0, &len)) {
2866 TOKEN_USER *info = xmalloc((size_t)len);
2867 if (GetTokenInformation(token, TokenUser, info, len, &len)) {
2868 len = GetLengthSid(info->User.Sid);
03a4e46d
JS
2869 *sid = xmalloc(len);
2870 if (!CopySid(len, *sid, info->User.Sid)) {
bdc77d1d
JS
2871 error(_("failed to copy SID (%ld)"),
2872 GetLastError());
03a4e46d 2873 FREE_AND_NULL(*sid);
bdc77d1d
JS
2874 }
2875 }
2876 FREE_AND_NULL(info);
2877 }
bdc77d1d 2878
03a4e46d
JS
2879 if (GetTokenInformation(token, TokenElevationType, &elevationType, sizeof(elevationType), &size) &&
2880 elevationType == TokenElevationTypeLimited) {
2881 /*
2882 * The current process is run by a member of the Administrators
2883 * group, but is not running elevated.
2884 */
2885 if (!GetTokenInformation(token, TokenLinkedToken, linked_token, sizeof(*linked_token), &size))
2886 linked_token = NULL; /* there is no linked token */
2887 }
2888
2889 CloseHandle(token);
bdc77d1d
JS
2890}
2891
f755e092
SK
2892static BOOL user_sid_to_user_name(PSID sid, LPSTR *str)
2893{
2894 SID_NAME_USE pe_use;
2895 DWORD len_user = 0, len_domain = 0;
2896 BOOL translate_sid_to_user;
2897
2898 /*
2899 * returns only FALSE, because the string pointers are NULL
2900 */
2901 LookupAccountSidA(NULL, sid, NULL, &len_user, NULL, &len_domain,
2902 &pe_use);
2903 /*
2904 * Alloc needed space of the strings
2905 */
2906 ALLOC_ARRAY((*str), (size_t)len_domain + (size_t)len_user);
2907 translate_sid_to_user = LookupAccountSidA(NULL, sid,
2908 (*str) + len_domain, &len_user, *str, &len_domain, &pe_use);
2909 if (!translate_sid_to_user)
2910 FREE_AND_NULL(*str);
2911 else
2912 (*str)[len_domain] = '/';
2913 return translate_sid_to_user;
2914}
2915
7c83470e
JS
2916static int acls_supported(const char *path)
2917{
2918 size_t offset = offset_1st_component(path);
2919 WCHAR wroot[MAX_PATH];
2920 DWORD file_system_flags;
2921
2922 if (offset &&
2923 xutftowcsn(wroot, path, MAX_PATH, offset) > 0 &&
2924 GetVolumeInformationW(wroot, NULL, 0, NULL, NULL,
2925 &file_system_flags, NULL, 0))
2926 return !!(file_system_flags & FILE_PERSISTENT_ACLS);
2927
2928 return 0;
2929}
2930
17d3883f 2931int is_path_owned_by_current_sid(const char *path, struct strbuf *report)
bdc77d1d
JS
2932{
2933 WCHAR wpath[MAX_PATH];
2934 PSID sid = NULL;
2935 PSECURITY_DESCRIPTOR descriptor = NULL;
2936 DWORD err;
2937
2938 static wchar_t home[MAX_PATH];
2939
2940 int result = 0;
2941
2942 if (xutftowcs_path(wpath, path) < 0)
2943 return 0;
2944
2945 /*
2946 * On Windows, the home directory is owned by the administrator, but for
2947 * all practical purposes, it belongs to the user. Do pretend that it is
2948 * owned by the user.
2949 */
2950 if (!*home) {
2951 DWORD size = ARRAY_SIZE(home);
2952 DWORD len = GetEnvironmentVariableW(L"HOME", home, size);
2953 if (!len || len > size)
2954 wcscpy(home, L"::N/A::");
2955 }
2956 if (!wcsicmp(wpath, home))
2957 return 1;
2958
2959 /* Get the owner SID */
2960 err = GetNamedSecurityInfoW(wpath, SE_FILE_OBJECT,
2961 OWNER_SECURITY_INFORMATION |
2962 DACL_SECURITY_INFORMATION,
2963 &sid, NULL, NULL, NULL, &descriptor);
2964
2965 if (err != ERROR_SUCCESS)
2966 error(_("failed to get owner for '%s' (%ld)"), path, err);
2967 else if (sid && IsValidSid(sid)) {
2968 /* Now, verify that the SID matches the current user's */
2969 static PSID current_user_sid;
03a4e46d 2970 static HANDLE linked_token;
3f7207e2 2971 BOOL is_member;
bdc77d1d
JS
2972
2973 if (!current_user_sid)
03a4e46d 2974 get_current_user_sid(&current_user_sid, &linked_token);
bdc77d1d
JS
2975
2976 if (current_user_sid &&
2977 IsValidSid(current_user_sid) &&
2978 EqualSid(sid, current_user_sid))
2979 result = 1;
3f7207e2 2980 else if (IsWellKnownSid(sid, WinBuiltinAdministratorsSid) &&
03a4e46d
JS
2981 ((CheckTokenMembership(NULL, sid, &is_member) &&
2982 is_member) ||
2983 (linked_token &&
2984 CheckTokenMembership(linked_token, sid, &is_member) &&
2985 is_member)))
3f7207e2
JS
2986 /*
2987 * If owned by the Administrators group, and the
2988 * current user is an administrator, we consider that
2989 * okay, too.
2990 */
2991 result = 1;
7c83470e
JS
2992 else if (report &&
2993 IsWellKnownSid(sid, WinWorldSid) &&
2994 !acls_supported(path)) {
2995 /*
2996 * On FAT32 volumes, ownership is not actually recorded.
2997 */
4eb1ccec 2998 strbuf_addf(report, "'%s' is on a file system that does "
7c83470e
JS
2999 "not record ownership\n", path);
3000 } else if (report) {
e7b40195
PS
3001 PCSTR str1, str2, str3, str4;
3002 LPSTR to_free1 = NULL, to_free3 = NULL,
3003 to_local_free2 = NULL, to_local_free4 = NULL;
e883e04b 3004
e7b40195
PS
3005 if (user_sid_to_user_name(sid, &to_free1))
3006 str1 = to_free1;
e883e04b
JS
3007 else
3008 str1 = "(inconvertible)";
e7b40195
PS
3009 if (ConvertSidToStringSidA(sid, &to_local_free2))
3010 str2 = to_local_free2;
e883e04b
JS
3011 else
3012 str2 = "(inconvertible)";
f755e092
SK
3013
3014 if (!current_user_sid) {
3015 str3 = "(none)";
3016 str4 = "(none)";
3017 }
3018 else if (!IsValidSid(current_user_sid)) {
3019 str3 = "(invalid)";
3020 str4 = "(invalid)";
3021 } else {
3022 if (user_sid_to_user_name(current_user_sid,
e7b40195
PS
3023 &to_free3))
3024 str3 = to_free3;
f755e092
SK
3025 else
3026 str3 = "(inconvertible)";
3027 if (ConvertSidToStringSidA(current_user_sid,
e7b40195
PS
3028 &to_local_free4))
3029 str4 = to_local_free4;
f755e092
SK
3030 else
3031 str4 = "(inconvertible)";
3032 }
e883e04b
JS
3033 strbuf_addf(report,
3034 "'%s' is owned by:\n"
f755e092
SK
3035 "\t%s (%s)\nbut the current user is:\n"
3036 "\t%s (%s)\n",
3037 path, str1, str2, str3, str4);
3038 free(to_free1);
3039 LocalFree(to_local_free2);
3040 free(to_free3);
3041 LocalFree(to_local_free4);
e883e04b 3042 }
bdc77d1d
JS
3043 }
3044
3045 /*
3046 * We can release the security descriptor struct only now because `sid`
3047 * actually points into this struct.
3048 */
3049 if (descriptor)
3050 LocalFree(descriptor);
3051
3052 return result;
3053}
3054
4dc42c6c 3055int is_valid_win32_path(const char *path, int allow_literal_nul)
d2c84dad 3056{
4dc42c6c 3057 const char *p = path;
d2c84dad
JS
3058 int preceding_space_or_period = 0, i = 0, periods = 0;
3059
3060 if (!protect_ntfs)
3061 return 1;
3062
817ddd64 3063 skip_dos_drive_prefix((char **)&path);
4dc42c6c 3064 goto segment_start;
817ddd64 3065
d2c84dad
JS
3066 for (;;) {
3067 char c = *(path++);
3068 switch (c) {
3069 case '\0':
3070 case '/': case '\\':
3071 /* cannot end in ` ` or `.`, except for `.` and `..` */
3072 if (preceding_space_or_period &&
3073 (i != periods || periods > 2))
3074 return 0;
3075 if (!c)
3076 return 1;
3077
3078 i = periods = preceding_space_or_period = 0;
4dc42c6c
JS
3079
3080segment_start:
3081 switch (*path) {
3082 case 'a': case 'A': /* AUX */
3083 if (((c = path[++i]) != 'u' && c != 'U') ||
3084 ((c = path[++i]) != 'x' && c != 'X')) {
3085not_a_reserved_name:
3086 path += i;
3087 continue;
3088 }
3089 break;
b6852e19
JS
3090 case 'c': case 'C':
3091 /* COM1 ... COM9, CON, CONIN$, CONOUT$ */
4dc42c6c
JS
3092 if ((c = path[++i]) != 'o' && c != 'O')
3093 goto not_a_reserved_name;
3094 c = path[++i];
b6852e19
JS
3095 if (c == 'm' || c == 'M') { /* COM1 ... COM9 */
3096 c = path[++i];
3097 if (c < '1' || c > '9')
4dc42c6c
JS
3098 goto not_a_reserved_name;
3099 } else if (c == 'n' || c == 'N') { /* CON */
3100 c = path[i + 1];
3101 if ((c == 'i' || c == 'I') &&
3102 ((c = path[i + 2]) == 'n' ||
3103 c == 'N') &&
3104 path[i + 3] == '$')
3105 i += 3; /* CONIN$ */
3106 else if ((c == 'o' || c == 'O') &&
3107 ((c = path[i + 2]) == 'u' ||
3108 c == 'U') &&
3109 ((c = path[i + 3]) == 't' ||
3110 c == 'T') &&
3111 path[i + 4] == '$')
3112 i += 4; /* CONOUT$ */
3113 } else
3114 goto not_a_reserved_name;
3115 break;
3116 case 'l': case 'L': /* LPT<N> */
3117 if (((c = path[++i]) != 'p' && c != 'P') ||
3118 ((c = path[++i]) != 't' && c != 'T') ||
3119 !isdigit(path[++i]))
3120 goto not_a_reserved_name;
3121 break;
3122 case 'n': case 'N': /* NUL */
3123 if (((c = path[++i]) != 'u' && c != 'U') ||
3124 ((c = path[++i]) != 'l' && c != 'L') ||
3125 (allow_literal_nul &&
3126 !path[i + 1] && p == path))
3127 goto not_a_reserved_name;
3128 break;
3129 case 'p': case 'P': /* PRN */
3130 if (((c = path[++i]) != 'r' && c != 'R') ||
3131 ((c = path[++i]) != 'n' && c != 'N'))
3132 goto not_a_reserved_name;
3133 break;
3134 default:
3135 continue;
3136 }
3137
3138 /*
3139 * So far, this looks like a reserved name. Let's see
3140 * whether it actually is one: trailing spaces, a file
3141 * extension, or an NTFS Alternate Data Stream do not
3142 * matter, the name is still reserved if any of those
3143 * follow immediately after the actual name.
3144 */
3145 i++;
3146 if (path[i] == ' ') {
3147 preceding_space_or_period = 1;
3148 while (path[++i] == ' ')
3149 ; /* skip all spaces */
3150 }
3151
3152 c = path[i];
9fd512c8 3153 if (c && c != '.' && c != ':' && !is_xplatform_dir_sep(c))
4dc42c6c
JS
3154 goto not_a_reserved_name;
3155
3156 /* contains reserved name */
3157 return 0;
d2c84dad
JS
3158 case '.':
3159 periods++;
3160 /* fallthru */
3161 case ' ':
3162 preceding_space_or_period = 1;
3163 i++;
3164 continue;
817ddd64
JS
3165 case ':': /* DOS drive prefix was already skipped */
3166 case '<': case '>': case '"': case '|': case '?': case '*':
3167 /* illegal character */
3168 return 0;
3169 default:
3170 if (c > '\0' && c < '\x20')
3171 /* illegal character */
3172 return 0;
d2c84dad
JS
3173 }
3174 preceding_space_or_period = 0;
3175 i++;
3176 }
3177}
3178
396ff754 3179#if !defined(_MSC_VER)
5901dc66
KB
3180/*
3181 * Disable MSVCRT command line wildcard expansion (__getmainargs called from
3182 * mingw startup code, see init.c in mingw runtime).
3183 */
3184int _CRT_glob = 0;
396ff754 3185#endif
3f046148 3186
0767172b 3187static NORETURN void die_startup(void)
3f046148
KB
3188{
3189 fputs("fatal: not enough memory for initialization", stderr);
3190 exit(128);
3191}
3192
6f1c189c
KB
3193static void *malloc_startup(size_t size)
3194{
3195 void *result = malloc(size);
3196 if (!result)
3197 die_startup();
3198 return result;
3199}
3200
3201static char *wcstoutfdup_startup(char *buffer, const wchar_t *wcs, size_t len)
3202{
3203 len = xwcstoutf(buffer, wcs, len) + 1;
3204 return memcpy(malloc_startup(len), buffer, len);
3205}
3206
3f944424
JS
3207static void maybe_redirect_std_handle(const wchar_t *key, DWORD std_id, int fd,
3208 DWORD desired_access, DWORD flags)
3209{
3210 DWORD create_flag = fd ? OPEN_ALWAYS : OPEN_EXISTING;
3211 wchar_t buf[MAX_PATH];
3212 DWORD max = ARRAY_SIZE(buf);
3213 HANDLE handle;
3214 DWORD ret = GetEnvironmentVariableW(key, buf, max);
3215
3216 if (!ret || ret >= max)
3217 return;
3218
3219 /* make sure this does not leak into child processes */
3220 SetEnvironmentVariableW(key, NULL);
3221 if (!wcscmp(buf, L"off")) {
3222 close(fd);
3223 handle = GetStdHandle(std_id);
3224 if (handle != INVALID_HANDLE_VALUE)
3225 CloseHandle(handle);
3226 return;
3227 }
1a172e4a
JS
3228 if (std_id == STD_ERROR_HANDLE && !wcscmp(buf, L"2>&1")) {
3229 handle = GetStdHandle(STD_OUTPUT_HANDLE);
3230 if (handle == INVALID_HANDLE_VALUE) {
3231 close(fd);
3232 handle = GetStdHandle(std_id);
3233 if (handle != INVALID_HANDLE_VALUE)
3234 CloseHandle(handle);
3235 } else {
3236 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3237 SetStdHandle(std_id, handle);
3238 dup2(new_fd, fd);
3239 /* do *not* close the new_fd: that would close stdout */
3240 }
3241 return;
3242 }
3f944424
JS
3243 handle = CreateFileW(buf, desired_access, 0, NULL, create_flag,
3244 flags, NULL);
3245 if (handle != INVALID_HANDLE_VALUE) {
3246 int new_fd = _open_osfhandle((intptr_t)handle, O_BINARY);
3247 SetStdHandle(std_id, handle);
3248 dup2(new_fd, fd);
3249 close(new_fd);
3250 }
3251}
3252
3253static void maybe_redirect_std_handles(void)
3254{
3255 maybe_redirect_std_handle(L"GIT_REDIRECT_STDIN", STD_INPUT_HANDLE, 0,
3256 GENERIC_READ, FILE_ATTRIBUTE_NORMAL);
3257 maybe_redirect_std_handle(L"GIT_REDIRECT_STDOUT", STD_OUTPUT_HANDLE, 1,
3258 GENERIC_WRITE, FILE_ATTRIBUTE_NORMAL);
3259 maybe_redirect_std_handle(L"GIT_REDIRECT_STDERR", STD_ERROR_HANDLE, 2,
3260 GENERIC_WRITE, FILE_FLAG_NO_BUFFERING);
3261}
3262
dce7d295
JH
3263#ifdef _MSC_VER
3264#ifdef _DEBUG
3265#include <crtdbg.h>
3266#endif
3267#endif
3268
396ff754
JS
3269/*
3270 * We implement wmain() and compile with -municode, which would
3271 * normally ignore main(), but we call the latter from the former
3272 * so that we can handle non-ASCII command-line parameters
3273 * appropriately.
3274 *
3275 * To be more compatible with the core git code, we convert
3276 * argv into UTF8 and pass them directly to main().
3277 */
3278int wmain(int argc, const wchar_t **wargv)
13f1df43 3279{
386d3720
SK
3280 int i, exit_status;
3281 size_t maxlen;
396ff754
JS
3282 char *buffer, **save;
3283 const char **argv;
3f046148 3284
a0897249
JH
3285 trace2_initialize_clock();
3286
556702f8 3287#ifdef _MSC_VER
f6a63937
JS
3288#ifdef _DEBUG
3289 _CrtSetReportMode(_CRT_ASSERT, _CRTDBG_MODE_DEBUG);
3290#endif
3291
556702f8
JH
3292#ifdef USE_MSVC_CRTDBG
3293 _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
3294#endif
3295#endif
3296
3f944424
JS
3297 maybe_redirect_std_handles();
3298
3f046148 3299 /* determine size of argv and environ conversion buffer */
86e25458 3300 maxlen = wcslen(wargv[0]);
3f046148
KB
3301 for (i = 1; i < argc; i++)
3302 maxlen = max(maxlen, wcslen(wargv[i]));
3303
3304 /* allocate buffer (wchar_t encodes to max 3 UTF-8 bytes) */
3305 maxlen = 3 * maxlen + 1;
6f1c189c 3306 buffer = malloc_startup(maxlen);
3f046148 3307
396ff754
JS
3308 /*
3309 * Create a UTF-8 version of w_argv. Also create a "save" copy
3310 * to remember all the string pointers because parse_options()
3311 * will remove claimed items from the argv that we pass down.
3312 */
3313 ALLOC_ARRAY(argv, argc + 1);
3314 ALLOC_ARRAY(save, argc + 1);
86e25458 3315 for (i = 0; i < argc; i++)
396ff754
JS
3316 argv[i] = save[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
3317 argv[i] = save[i] = NULL;
3f046148 3318 free(buffer);
13f1df43 3319
6dc71543 3320 /* fix Windows specific environment settings */
02e6edc0 3321 setup_windows_environment();
baea068d 3322
0e218f91
JS
3323 unset_environment_variables = xstrdup("PERL5LIB");
3324
13f1df43
KB
3325 /* initialize critical section for waitpid pinfo_t list */
3326 InitializeCriticalSection(&pinfo_cs);
3327
3328 /* set up default file mode and file modes for stdin/out/err */
3329 _fmode = _O_BINARY;
3330 _setmode(_fileno(stdin), _O_BINARY);
3331 _setmode(_fileno(stdout), _O_BINARY);
3332 _setmode(_fileno(stderr), _O_BINARY);
eac14f89
KB
3333
3334 /* initialize Unicode console */
3335 winansi_init();
396ff754
JS
3336
3337 /* invoke the real main() using our utf8 version of argv. */
3338 exit_status = main(argc, argv);
3339
3340 for (i = 0; i < argc; i++)
3341 free(save[i]);
3342 free(save);
3343 free(argv);
3344
3345 return exit_status;
13f1df43 3346}
7b6aff06
NTND
3347
3348int uname(struct utsname *buf)
3349{
d62c89af 3350 unsigned v = (unsigned)GetVersion();
7b6aff06 3351 memset(buf, 0, sizeof(*buf));
5096d490
JK
3352 xsnprintf(buf->sysname, sizeof(buf->sysname), "Windows");
3353 xsnprintf(buf->release, sizeof(buf->release),
3354 "%u.%u", v & 0xff, (v >> 8) & 0xff);
7b6aff06 3355 /* assuming NT variants only.. */
5096d490
JK
3356 xsnprintf(buf->version, sizeof(buf->version),
3357 "%u", (v >> 16) & 0x7fff);
7b6aff06
NTND
3358 return 0;
3359}
2406bf5f 3360
395c130f 3361#ifndef NO_UNIX_SOCKETS
2406bf5f
MA
3362int mingw_have_unix_sockets(void)
3363{
3364 SC_HANDLE scm, srvc;
3365 SERVICE_STATUS_PROCESS status;
3366 DWORD bytes;
3367 int ret = 0;
3368 scm = OpenSCManagerA(NULL, NULL, SC_MANAGER_CONNECT);
3369 if (scm) {
3370 srvc = OpenServiceA(scm, "afunix", SERVICE_QUERY_STATUS);
3371 if (srvc) {
3372 if(QueryServiceStatusEx(srvc, SC_STATUS_PROCESS_INFO, (LPBYTE)&status, sizeof(SERVICE_STATUS_PROCESS), &bytes))
3373 ret = status.dwCurrentState == SERVICE_RUNNING;
3374 CloseServiceHandle(srvc);
3375 }
3376 CloseServiceHandle(scm);
3377 }
3378 return ret;
3379}
395c130f 3380#endif