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