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