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