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