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