forked from git/git
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
mingw.c
3546 lines (3102 loc) · 90.9 KB
/
mingw.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "../git-compat-util.h"
#include "win32.h"
#include <conio.h>
#include <wchar.h>
#include <winioctl.h>
#include "../strbuf.h"
#include "../run-command.h"
#include "../cache.h"
#include "win32/lazyload.h"
#include "win32/exit-process.h"
#include "../config.h"
#include "../string-list.h"
#define HCAST(type, handle) ((type)(intptr_t)handle)
int err_win_to_posix(DWORD winerr)
{
int error = ENOSYS;
switch(winerr) {
case ERROR_ACCESS_DENIED: error = EACCES; break;
case ERROR_ACCOUNT_DISABLED: error = EACCES; break;
case ERROR_ACCOUNT_RESTRICTION: error = EACCES; break;
case ERROR_ALREADY_ASSIGNED: error = EBUSY; break;
case ERROR_ALREADY_EXISTS: error = EEXIST; break;
case ERROR_ARITHMETIC_OVERFLOW: error = ERANGE; break;
case ERROR_BAD_COMMAND: error = EIO; break;
case ERROR_BAD_DEVICE: error = ENODEV; break;
case ERROR_BAD_DRIVER_LEVEL: error = ENXIO; break;
case ERROR_BAD_EXE_FORMAT: error = ENOEXEC; break;
case ERROR_BAD_FORMAT: error = ENOEXEC; break;
case ERROR_BAD_LENGTH: error = EINVAL; break;
case ERROR_BAD_PATHNAME: error = ENOENT; break;
case ERROR_BAD_PIPE: error = EPIPE; break;
case ERROR_BAD_UNIT: error = ENODEV; break;
case ERROR_BAD_USERNAME: error = EINVAL; break;
case ERROR_BROKEN_PIPE: error = EPIPE; break;
case ERROR_BUFFER_OVERFLOW: error = ENAMETOOLONG; break;
case ERROR_BUSY: error = EBUSY; break;
case ERROR_BUSY_DRIVE: error = EBUSY; break;
case ERROR_CALL_NOT_IMPLEMENTED: error = ENOSYS; break;
case ERROR_CANNOT_MAKE: error = EACCES; break;
case ERROR_CANTOPEN: error = EIO; break;
case ERROR_CANTREAD: error = EIO; break;
case ERROR_CANTWRITE: error = EIO; break;
case ERROR_CRC: error = EIO; break;
case ERROR_CURRENT_DIRECTORY: error = EACCES; break;
case ERROR_DEVICE_IN_USE: error = EBUSY; break;
case ERROR_DEV_NOT_EXIST: error = ENODEV; break;
case ERROR_DIRECTORY: error = EINVAL; break;
case ERROR_DIR_NOT_EMPTY: error = ENOTEMPTY; break;
case ERROR_DISK_CHANGE: error = EIO; break;
case ERROR_DISK_FULL: error = ENOSPC; break;
case ERROR_DRIVE_LOCKED: error = EBUSY; break;
case ERROR_ENVVAR_NOT_FOUND: error = EINVAL; break;
case ERROR_EXE_MARKED_INVALID: error = ENOEXEC; break;
case ERROR_FILENAME_EXCED_RANGE: error = ENAMETOOLONG; break;
case ERROR_FILE_EXISTS: error = EEXIST; break;
case ERROR_FILE_INVALID: error = ENODEV; break;
case ERROR_FILE_NOT_FOUND: error = ENOENT; break;
case ERROR_GEN_FAILURE: error = EIO; break;
case ERROR_HANDLE_DISK_FULL: error = ENOSPC; break;
case ERROR_INSUFFICIENT_BUFFER: error = ENOMEM; break;
case ERROR_INVALID_ACCESS: error = EACCES; break;
case ERROR_INVALID_ADDRESS: error = EFAULT; break;
case ERROR_INVALID_BLOCK: error = EFAULT; break;
case ERROR_INVALID_DATA: error = EINVAL; break;
case ERROR_INVALID_DRIVE: error = ENODEV; break;
case ERROR_INVALID_EXE_SIGNATURE: error = ENOEXEC; break;
case ERROR_INVALID_FLAGS: error = EINVAL; break;
case ERROR_INVALID_FUNCTION: error = ENOSYS; break;
case ERROR_INVALID_HANDLE: error = EBADF; break;
case ERROR_INVALID_LOGON_HOURS: error = EACCES; break;
case ERROR_INVALID_NAME: error = EINVAL; break;
case ERROR_INVALID_OWNER: error = EINVAL; break;
case ERROR_INVALID_PARAMETER: error = EINVAL; break;
case ERROR_INVALID_PASSWORD: error = EPERM; break;
case ERROR_INVALID_PRIMARY_GROUP: error = EINVAL; break;
case ERROR_INVALID_REPARSE_DATA: error = EINVAL; break;
case ERROR_INVALID_SIGNAL_NUMBER: error = EINVAL; break;
case ERROR_INVALID_TARGET_HANDLE: error = EIO; break;
case ERROR_INVALID_WORKSTATION: error = EACCES; break;
case ERROR_IO_DEVICE: error = EIO; break;
case ERROR_IO_INCOMPLETE: error = EINTR; break;
case ERROR_LOCKED: error = EBUSY; break;
case ERROR_LOCK_VIOLATION: error = EACCES; break;
case ERROR_LOGON_FAILURE: error = EACCES; break;
case ERROR_MAPPED_ALIGNMENT: error = EINVAL; break;
case ERROR_META_EXPANSION_TOO_LONG: error = E2BIG; break;
case ERROR_MORE_DATA: error = EPIPE; break;
case ERROR_NEGATIVE_SEEK: error = ESPIPE; break;
case ERROR_NOACCESS: error = EFAULT; break;
case ERROR_NONE_MAPPED: error = EINVAL; break;
case ERROR_NOT_A_REPARSE_POINT: error = EINVAL; break;
case ERROR_NOT_ENOUGH_MEMORY: error = ENOMEM; break;
case ERROR_NOT_READY: error = EAGAIN; break;
case ERROR_NOT_SAME_DEVICE: error = EXDEV; break;
case ERROR_NO_DATA: error = EPIPE; break;
case ERROR_NO_MORE_SEARCH_HANDLES: error = EIO; break;
case ERROR_NO_PROC_SLOTS: error = EAGAIN; break;
case ERROR_NO_SUCH_PRIVILEGE: error = EACCES; break;
case ERROR_OPEN_FAILED: error = EIO; break;
case ERROR_OPEN_FILES: error = EBUSY; break;
case ERROR_OPERATION_ABORTED: error = EINTR; break;
case ERROR_OUTOFMEMORY: error = ENOMEM; break;
case ERROR_PASSWORD_EXPIRED: error = EACCES; break;
case ERROR_PATH_BUSY: error = EBUSY; break;
case ERROR_PATH_NOT_FOUND: error = ENOENT; break;
case ERROR_PIPE_BUSY: error = EBUSY; break;
case ERROR_PIPE_CONNECTED: error = EPIPE; break;
case ERROR_PIPE_LISTENING: error = EPIPE; break;
case ERROR_PIPE_NOT_CONNECTED: error = EPIPE; break;
case ERROR_PRIVILEGE_NOT_HELD: error = EACCES; break;
case ERROR_READ_FAULT: error = EIO; break;
case ERROR_REPARSE_ATTRIBUTE_CONFLICT: error = EINVAL; break;
case ERROR_REPARSE_TAG_INVALID: error = EINVAL; break;
case ERROR_REPARSE_TAG_MISMATCH: error = EINVAL; break;
case ERROR_SEEK: error = EIO; break;
case ERROR_SEEK_ON_DEVICE: error = ESPIPE; break;
case ERROR_SHARING_BUFFER_EXCEEDED: error = ENFILE; break;
case ERROR_SHARING_VIOLATION: error = EACCES; break;
case ERROR_STACK_OVERFLOW: error = ENOMEM; break;
case ERROR_SWAPERROR: error = ENOENT; break;
case ERROR_TOO_MANY_MODULES: error = EMFILE; break;
case ERROR_TOO_MANY_OPEN_FILES: error = EMFILE; break;
case ERROR_UNRECOGNIZED_MEDIA: error = ENXIO; break;
case ERROR_UNRECOGNIZED_VOLUME: error = ENODEV; break;
case ERROR_WAIT_NO_CHILDREN: error = ECHILD; break;
case ERROR_WRITE_FAULT: error = EIO; break;
case ERROR_WRITE_PROTECT: error = EROFS; break;
}
return error;
}
static inline int is_file_in_use_error(DWORD errcode)
{
switch (errcode) {
case ERROR_SHARING_VIOLATION:
case ERROR_ACCESS_DENIED:
return 1;
}
return 0;
}
static int read_yes_no_answer(void)
{
char answer[1024];
if (fgets(answer, sizeof(answer), stdin)) {
size_t answer_len = strlen(answer);
int got_full_line = 0, c;
/* remove the newline */
if (answer_len >= 2 && answer[answer_len-2] == '\r') {
answer[answer_len-2] = '\0';
got_full_line = 1;
} else if (answer_len >= 1 && answer[answer_len-1] == '\n') {
answer[answer_len-1] = '\0';
got_full_line = 1;
}
/* flush the buffer in case we did not get the full line */
if (!got_full_line)
while ((c = getchar()) != EOF && c != '\n')
;
} else
/* we could not read, return the
* default answer which is no */
return 0;
if (tolower(answer[0]) == 'y' && !answer[1])
return 1;
if (!strncasecmp(answer, "yes", sizeof(answer)))
return 1;
if (tolower(answer[0]) == 'n' && !answer[1])
return 0;
if (!strncasecmp(answer, "no", sizeof(answer)))
return 0;
/* did not find an answer we understand */
return -1;
}
static int ask_yes_no_if_possible(const char *format, va_list args)
{
char question[4096];
const char *retry_hook[] = { NULL, NULL, NULL };
vsnprintf(question, sizeof(question), format, args);
if ((retry_hook[0] = mingw_getenv("GIT_ASK_YESNO"))) {
retry_hook[1] = question;
return !run_command_v_opt(retry_hook, 0);
}
if (!isatty(_fileno(stdin)) || !isatty(_fileno(stderr)))
return 0;
while (1) {
int answer;
fprintf(stderr, "%s (y/n) ", question);
if ((answer = read_yes_no_answer()) >= 0)
return answer;
fprintf(stderr, "Sorry, I did not understand your answer. "
"Please type 'y' or 'n'\n");
}
}
static int retry_ask_yes_no(int *tries, const char *format, ...)
{
static const int delay[] = { 0, 1, 10, 20, 40 };
va_list args;
int result, saved_errno = errno;
if ((*tries) < ARRAY_SIZE(delay)) {
/*
* We assume that some other process had the file open at the wrong
* moment and retry. In order to give the other process a higher
* chance to complete its operation, we give up our time slice now.
* If we have to retry again, we do sleep a bit.
*/
Sleep(delay[*tries]);
(*tries)++;
return 1;
}
va_start(args, format);
result = ask_yes_no_if_possible(format, args);
va_end(args);
errno = saved_errno;
return result;
}
/* Windows only */
enum hide_dotfiles_type {
HIDE_DOTFILES_FALSE = 0,
HIDE_DOTFILES_TRUE,
HIDE_DOTFILES_DOTGITONLY
};
static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
static char *unset_environment_variables;
int core_fscache;
int core_long_paths;
int mingw_core_config(const char *var, const char *value, void *cb)
{
if (!strcmp(var, "core.hidedotfiles")) {
if (value && !strcasecmp(value, "dotgitonly"))
hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
else
hide_dotfiles = git_config_bool(var, value);
return 0;
}
if (!strcmp(var, "core.fscache")) {
core_fscache = git_config_bool(var, value);
return 0;
}
if (!strcmp(var, "core.longpaths")) {
core_long_paths = git_config_bool(var, value);
return 0;
}
if (!strcmp(var, "core.unsetenvvars")) {
free(unset_environment_variables);
unset_environment_variables = xstrdup(value);
return 0;
}
return 0;
}
static DWORD symlink_file_flags = 0, symlink_directory_flags = 1;
enum phantom_symlink_result {
PHANTOM_SYMLINK_RETRY,
PHANTOM_SYMLINK_DONE,
PHANTOM_SYMLINK_DIRECTORY
};
/*
* Changes a file symlink to a directory symlink if the target exists and is a
* directory.
*/
static enum phantom_symlink_result process_phantom_symlink(
const wchar_t *wtarget, const wchar_t *wlink) {
HANDLE hnd;
BY_HANDLE_FILE_INFORMATION fdata;
/* check that wlink is still a file symlink */
if ((GetFileAttributesW(wlink)
& (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY))
!= FILE_ATTRIBUTE_REPARSE_POINT)
return PHANTOM_SYMLINK_DONE;
/* let Windows resolve the link by opening it */
hnd = CreateFileW(wlink, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hnd == INVALID_HANDLE_VALUE) {
errno = err_win_to_posix(GetLastError());
return PHANTOM_SYMLINK_RETRY;
}
if (!GetFileInformationByHandle(hnd, &fdata)) {
errno = err_win_to_posix(GetLastError());
CloseHandle(hnd);
return PHANTOM_SYMLINK_RETRY;
}
CloseHandle(hnd);
/* if target exists and is a file, we're done */
if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
return PHANTOM_SYMLINK_DONE;
/* otherwise recreate the symlink with directory flag */
if (DeleteFileW(wlink) &&
CreateSymbolicLinkW(wlink, wtarget, symlink_directory_flags))
return PHANTOM_SYMLINK_DIRECTORY;
errno = err_win_to_posix(GetLastError());
return PHANTOM_SYMLINK_RETRY;
}
/* keep track of newly created symlinks to non-existing targets */
struct phantom_symlink_info {
struct phantom_symlink_info *next;
wchar_t *wlink;
wchar_t *wtarget;
};
static struct phantom_symlink_info *phantom_symlinks = NULL;
static CRITICAL_SECTION phantom_symlinks_cs;
static void process_phantom_symlinks(void)
{
struct phantom_symlink_info *current, **psi;
EnterCriticalSection(&phantom_symlinks_cs);
/* process phantom symlinks list */
psi = &phantom_symlinks;
while ((current = *psi)) {
enum phantom_symlink_result result = process_phantom_symlink(
current->wtarget, current->wlink);
if (result == PHANTOM_SYMLINK_RETRY) {
psi = ¤t->next;
} else {
/* symlink was processed, remove from list */
*psi = current->next;
free(current);
/* if symlink was a directory, start over */
if (result == PHANTOM_SYMLINK_DIRECTORY)
psi = &phantom_symlinks;
}
}
LeaveCriticalSection(&phantom_symlinks_cs);
}
/* Normalizes NT paths as returned by some low-level APIs. */
static wchar_t *normalize_ntpath(wchar_t *wbuf)
{
int i;
/* fix absolute path prefixes */
if (wbuf[0] == '\\') {
/* strip NT namespace prefixes */
if (!wcsncmp(wbuf, L"\\??\\", 4) ||
!wcsncmp(wbuf, L"\\\\?\\", 4))
wbuf += 4;
else if (!wcsnicmp(wbuf, L"\\DosDevices\\", 12))
wbuf += 12;
/* replace remaining '...UNC\' with '\\' */
if (!wcsnicmp(wbuf, L"UNC\\", 4)) {
wbuf += 2;
*wbuf = '\\';
}
}
/* convert backslashes to slashes */
for (i = 0; wbuf[i]; i++)
if (wbuf[i] == '\\')
wbuf[i] = '/';
return wbuf;
}
int mingw_unlink(const char *pathname)
{
int tries = 0;
wchar_t wpathname[MAX_LONG_PATH];
if (xutftowcs_long_path(wpathname, pathname) < 0)
return -1;
do {
/* read-only files cannot be removed */
_wchmod(wpathname, 0666);
if (!_wunlink(wpathname))
return 0;
if (!is_file_in_use_error(GetLastError()))
break;
/*
* _wunlink() / DeleteFileW() for directory symlinks fails with
* ERROR_ACCESS_DENIED (EACCES), so try _wrmdir() as well. This is the
* same error we get if a file is in use (already checked above).
*/
if (!_wrmdir(wpathname))
return 0;
} while (retry_ask_yes_no(&tries, "Unlink of file '%s' failed. "
"Should I try again?", pathname));
return -1;
}
static int is_dir_empty(const wchar_t *wpath)
{
WIN32_FIND_DATAW findbuf;
HANDLE handle;
wchar_t wbuf[MAX_LONG_PATH + 2];
wcscpy(wbuf, wpath);
wcscat(wbuf, L"\\*");
handle = FindFirstFileW(wbuf, &findbuf);
if (handle == INVALID_HANDLE_VALUE)
return GetLastError() == ERROR_NO_MORE_FILES;
while (!wcscmp(findbuf.cFileName, L".") ||
!wcscmp(findbuf.cFileName, L".."))
if (!FindNextFileW(handle, &findbuf)) {
DWORD err = GetLastError();
FindClose(handle);
return err == ERROR_NO_MORE_FILES;
}
FindClose(handle);
return 0;
}
int mingw_rmdir(const char *pathname)
{
int tries = 0;
wchar_t wpathname[MAX_LONG_PATH];
if (xutftowcs_long_path(wpathname, pathname) < 0)
return -1;
do {
if (!_wrmdir(wpathname))
return 0;
if (!is_file_in_use_error(GetLastError()))
errno = err_win_to_posix(GetLastError());
if (errno != EACCES)
break;
if (!is_dir_empty(wpathname)) {
errno = ENOTEMPTY;
break;
}
} while (retry_ask_yes_no(&tries, "Deletion of directory '%s' failed. "
"Should I try again?", pathname));
return -1;
}
static inline int needs_hiding(const char *path)
{
const char *basename;
if (hide_dotfiles == HIDE_DOTFILES_FALSE)
return 0;
/* We cannot use basename(), as it would remove trailing slashes */
mingw_skip_dos_drive_prefix((char **)&path);
if (!*path)
return 0;
for (basename = path; *path; path++)
if (is_dir_sep(*path)) {
do {
path++;
} while (is_dir_sep(*path));
/* ignore trailing slashes */
if (*path)
basename = path;
}
if (hide_dotfiles == HIDE_DOTFILES_TRUE)
return *basename == '.';
assert(hide_dotfiles == HIDE_DOTFILES_DOTGITONLY);
return !strncasecmp(".git", basename, 4) &&
(!basename[4] || is_dir_sep(basename[4]));
}
static int set_hidden_flag(const wchar_t *path, int set)
{
DWORD original = GetFileAttributesW(path), modified;
if (set)
modified = original | FILE_ATTRIBUTE_HIDDEN;
else
modified = original & ~FILE_ATTRIBUTE_HIDDEN;
if (original == modified || SetFileAttributesW(path, modified))
return 0;
errno = err_win_to_posix(GetLastError());
return -1;
}
int mingw_mkdir(const char *path, int mode)
{
int ret;
wchar_t wpath[MAX_LONG_PATH];
/* CreateDirectoryW path limit is 248 (MAX_PATH - 8.3 file name) */
if (xutftowcs_path_ex(wpath, path, MAX_LONG_PATH, -1, 248,
core_long_paths) < 0)
return -1;
ret = _wmkdir(wpath);
if (!ret)
process_phantom_symlinks();
if (!ret && needs_hiding(path))
return set_hidden_flag(wpath, 1);
return ret;
}
int mingw_open (const char *filename, int oflags, ...)
{
va_list args;
unsigned mode;
int fd;
wchar_t wfilename[MAX_LONG_PATH];
va_start(args, oflags);
mode = va_arg(args, int);
va_end(args);
if (filename && !strcmp(filename, "/dev/null"))
filename = "nul";
if (xutftowcs_long_path(wfilename, filename) < 0)
return -1;
fd = _wopen(wfilename, oflags, mode);
if (fd < 0 && (oflags & O_ACCMODE) != O_RDONLY && errno == EACCES) {
DWORD attrs = GetFileAttributesW(wfilename);
if (attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY))
errno = EISDIR;
}
if ((oflags & O_CREAT) && needs_hiding(filename)) {
/*
* Internally, _wopen() uses the CreateFile() API which errors
* out with an ERROR_ACCESS_DENIED if CREATE_ALWAYS was
* specified and an already existing file's attributes do not
* match *exactly*. As there is no mode or flag we can set that
* would correspond to FILE_ATTRIBUTE_HIDDEN, let's just try
* again *without* the O_CREAT flag (that corresponds to the
* CREATE_ALWAYS flag of CreateFile()).
*/
if (fd < 0 && errno == EACCES)
fd = _wopen(wfilename, oflags & ~O_CREAT, mode);
if (fd >= 0 && set_hidden_flag(wfilename, 1))
warning("could not mark '%s' as hidden.", filename);
}
return fd;
}
static BOOL WINAPI ctrl_ignore(DWORD type)
{
return TRUE;
}
#undef fgetc
int mingw_fgetc(FILE *stream)
{
int ch;
if (!isatty(_fileno(stream)))
return fgetc(stream);
SetConsoleCtrlHandler(ctrl_ignore, TRUE);
while (1) {
ch = fgetc(stream);
if (ch != EOF || GetLastError() != ERROR_OPERATION_ABORTED)
break;
/* Ctrl+C was pressed, simulate SIGINT and retry */
mingw_raise(SIGINT);
}
SetConsoleCtrlHandler(ctrl_ignore, FALSE);
return ch;
}
#undef fopen
FILE *mingw_fopen (const char *filename, const char *otype)
{
int hide = needs_hiding(filename);
FILE *file;
wchar_t wfilename[MAX_LONG_PATH], wotype[4];
if (filename && !strcmp(filename, "/dev/null"))
filename = "nul";
if (xutftowcs_long_path(wfilename, filename) < 0 ||
xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
return NULL;
if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
error("could not unhide %s", filename);
return NULL;
}
file = _wfopen(wfilename, wotype);
if (!file && GetLastError() == ERROR_INVALID_NAME)
errno = ENOENT;
if (file && hide && set_hidden_flag(wfilename, 1))
warning("could not mark '%s' as hidden.", filename);
return file;
}
FILE *mingw_freopen (const char *filename, const char *otype, FILE *stream)
{
int hide = needs_hiding(filename);
FILE *file;
wchar_t wfilename[MAX_LONG_PATH], wotype[4];
if (filename && !strcmp(filename, "/dev/null"))
filename = "nul";
if (xutftowcs_long_path(wfilename, filename) < 0 ||
xutftowcs(wotype, otype, ARRAY_SIZE(wotype)) < 0)
return NULL;
if (hide && !access(filename, F_OK) && set_hidden_flag(wfilename, 0)) {
error("could not unhide %s", filename);
return NULL;
}
file = _wfreopen(wfilename, wotype, stream);
if (file && hide && set_hidden_flag(wfilename, 1))
warning("could not mark '%s' as hidden.", filename);
return file;
}
#undef fflush
int mingw_fflush(FILE *stream)
{
int ret = fflush(stream);
/*
* write() is used behind the scenes of stdio output functions.
* Since git code does not check for errors after each stdio write
* operation, it can happen that write() is called by a later
* stdio function even if an earlier write() call failed. In the
* case of a pipe whose readable end was closed, only the first
* call to write() reports EPIPE on Windows. Subsequent write()
* calls report EINVAL. It is impossible to notice whether this
* fflush invocation triggered such a case, therefore, we have to
* catch all EINVAL errors whole-sale.
*/
if (ret && errno == EINVAL)
errno = EPIPE;
return ret;
}
#undef write
ssize_t mingw_write(int fd, const void *buf, size_t len)
{
ssize_t result = write(fd, buf, len);
if (result < 0 && errno == EINVAL && buf) {
/* check if fd is a pipe */
HANDLE h = (HANDLE) _get_osfhandle(fd);
if (GetFileType(h) == FILE_TYPE_PIPE)
errno = EPIPE;
else
errno = EINVAL;
}
return result;
}
int mingw_access(const char *filename, int mode)
{
wchar_t wfilename[MAX_LONG_PATH];
if (xutftowcs_long_path(wfilename, filename) < 0)
return -1;
/* X_OK is not supported by the MSVCRT version */
return _waccess(wfilename, mode & ~X_OK);
}
/* cached length of current directory for handle_long_path */
static int current_directory_len = 0;
int mingw_chdir(const char *dirname)
{
int result;
DECLARE_PROC_ADDR(kernel32.dll, DWORD, GetFinalPathNameByHandleW,
HANDLE, LPWSTR, DWORD, DWORD);
wchar_t wdirname[MAX_LONG_PATH];
if (xutftowcs_long_path(wdirname, dirname) < 0)
return -1;
if (has_symlinks && INIT_PROC_ADDR(GetFinalPathNameByHandleW)) {
HANDLE hnd = CreateFileW(wdirname, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hnd == INVALID_HANDLE_VALUE) {
errno = err_win_to_posix(GetLastError());
return -1;
}
if (!GetFinalPathNameByHandleW(hnd, wdirname, ARRAY_SIZE(wdirname), 0)) {
errno = err_win_to_posix(GetLastError());
CloseHandle(hnd);
return -1;
}
CloseHandle(hnd);
}
result = _wchdir(normalize_ntpath(wdirname));
current_directory_len = GetCurrentDirectoryW(0, NULL);
return result;
}
int mingw_chmod(const char *filename, int mode)
{
wchar_t wfilename[MAX_LONG_PATH];
if (xutftowcs_long_path(wfilename, filename) < 0)
return -1;
return _wchmod(wfilename, mode);
}
/**
* Verifies that safe_create_leading_directories() would succeed.
*/
static int has_valid_directory_prefix(wchar_t *wfilename)
{
int n = wcslen(wfilename);
while (n > 0) {
wchar_t c = wfilename[--n];
DWORD attributes;
if (!is_dir_sep(c))
continue;
wfilename[n] = L'\0';
attributes = GetFileAttributesW(wfilename);
wfilename[n] = c;
if (attributes == FILE_ATTRIBUTE_DIRECTORY ||
attributes == FILE_ATTRIBUTE_DEVICE)
return 1;
if (attributes == INVALID_FILE_ATTRIBUTES)
switch (GetLastError()) {
case ERROR_PATH_NOT_FOUND:
continue;
case ERROR_FILE_NOT_FOUND:
/* This implies parent directory exists. */
return 1;
}
return 0;
}
return 1;
}
int mingw_lstat(const char *file_name, struct stat *buf)
{
WIN32_FILE_ATTRIBUTE_DATA fdata;
WIN32_FIND_DATAW findbuf;
wchar_t wfilename[MAX_LONG_PATH];
int wlen = xutftowcs_long_path(wfilename, file_name);
if (wlen < 0)
return -1;
/* strip trailing '/', or GetFileAttributes will fail */
while (wlen && is_dir_sep(wfilename[wlen - 1]))
wfilename[--wlen] = 0;
if (!wlen) {
errno = ENOENT;
return -1;
}
if (GetFileAttributesExW(wfilename, GetFileExInfoStandard, &fdata)) {
/* for reparse points, use FindFirstFile to get the reparse tag */
if (fdata.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) {
HANDLE handle = FindFirstFileW(wfilename, &findbuf);
if (handle == INVALID_HANDLE_VALUE)
goto error;
FindClose(handle);
}
buf->st_ino = 0;
buf->st_gid = 0;
buf->st_uid = 0;
buf->st_nlink = 1;
buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes,
findbuf.dwReserved0);
buf->st_size = S_ISLNK(buf->st_mode) ? MAX_LONG_PATH :
fdata.nFileSizeLow | (((off_t) fdata.nFileSizeHigh) << 32);
buf->st_dev = buf->st_rdev = 0; /* not used by Git */
filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
return 0;
}
error:
switch (GetLastError()) {
case ERROR_ACCESS_DENIED:
case ERROR_SHARING_VIOLATION:
case ERROR_LOCK_VIOLATION:
case ERROR_SHARING_BUFFER_EXCEEDED:
errno = EACCES;
break;
case ERROR_BUFFER_OVERFLOW:
errno = ENAMETOOLONG;
break;
case ERROR_NOT_ENOUGH_MEMORY:
errno = ENOMEM;
break;
case ERROR_PATH_NOT_FOUND:
if (!has_valid_directory_prefix(wfilename)) {
errno = ENOTDIR;
break;
}
/* fallthru */
default:
errno = ENOENT;
break;
}
return -1;
}
int (*lstat)(const char *file_name, struct stat *buf) = mingw_lstat;
static int get_file_info_by_handle(HANDLE hnd, struct stat *buf)
{
BY_HANDLE_FILE_INFORMATION fdata;
if (!GetFileInformationByHandle(hnd, &fdata)) {
errno = err_win_to_posix(GetLastError());
return -1;
}
buf->st_ino = 0;
buf->st_dev = buf->st_rdev = 0; /* not used by Git */
buf->st_gid = buf->st_uid = 0;
buf->st_nlink = 1;
buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes, 0);
buf->st_size = fdata.nFileSizeLow | (((off_t) fdata.nFileSizeHigh) << 32);
filetime_to_timespec(&(fdata.ftLastAccessTime), &(buf->st_atim));
filetime_to_timespec(&(fdata.ftLastWriteTime), &(buf->st_mtim));
filetime_to_timespec(&(fdata.ftCreationTime), &(buf->st_ctim));
return 0;
}
int mingw_stat(const char *file_name, struct stat *buf)
{
wchar_t wfile_name[MAX_LONG_PATH];
HANDLE hnd;
int result;
/* open the file and let Windows resolve the links */
if (xutftowcs_long_path(wfile_name, file_name) < 0)
return -1;
hnd = CreateFileW(wfile_name, 0,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if (hnd == INVALID_HANDLE_VALUE) {
errno = err_win_to_posix(GetLastError());
return -1;
}
result = get_file_info_by_handle(hnd, buf);
CloseHandle(hnd);
return result;
}
int mingw_fstat(int fd, struct stat *buf)
{
HANDLE fh = (HANDLE)_get_osfhandle(fd);
DWORD avail, type = GetFileType(fh) & ~FILE_TYPE_REMOTE;
switch (type) {
case FILE_TYPE_DISK:
return get_file_info_by_handle(fh, buf);
case FILE_TYPE_CHAR:
case FILE_TYPE_PIPE:
/* initialize stat fields */
memset(buf, 0, sizeof(*buf));
buf->st_nlink = 1;
if (type == FILE_TYPE_CHAR) {
buf->st_mode = _S_IFCHR;
} else {
buf->st_mode = _S_IFIFO;
if (PeekNamedPipe(fh, NULL, 0, NULL, &avail, NULL))
buf->st_size = avail;
}
return 0;
default:
errno = EBADF;
return -1;
}
}
static inline void time_t_to_filetime(time_t t, FILETIME *ft)
{
long long winTime = t * 10000000LL + 116444736000000000LL;
ft->dwLowDateTime = winTime;
ft->dwHighDateTime = winTime >> 32;
}
int mingw_utime (const char *file_name, const struct utimbuf *times)
{
FILETIME mft, aft;
int fh, rc;
DWORD attrs;
wchar_t wfilename[MAX_LONG_PATH];
if (xutftowcs_long_path(wfilename, file_name) < 0)
return -1;
/* must have write permission */
attrs = GetFileAttributesW(wfilename);
if (attrs != INVALID_FILE_ATTRIBUTES &&
(attrs & FILE_ATTRIBUTE_READONLY)) {
/* ignore errors here; open() will report them */
SetFileAttributesW(wfilename, attrs & ~FILE_ATTRIBUTE_READONLY);
}
if ((fh = _wopen(wfilename, O_RDWR | O_BINARY)) < 0) {
rc = -1;
goto revert_attrs;
}
if (times) {
time_t_to_filetime(times->modtime, &mft);
time_t_to_filetime(times->actime, &aft);
} else {
GetSystemTimeAsFileTime(&mft);
aft = mft;
}
if (!SetFileTime((HANDLE)_get_osfhandle(fh), NULL, &aft, &mft)) {
errno = EINVAL;
rc = -1;
} else
rc = 0;
close(fh);
revert_attrs:
if (attrs != INVALID_FILE_ATTRIBUTES &&
(attrs & FILE_ATTRIBUTE_READONLY)) {
/* ignore errors again */
SetFileAttributesW(wfilename, attrs);
}
return rc;
}
#undef strftime
size_t mingw_strftime(char *s, size_t max,
const char *format, const struct tm *tm)
{
size_t ret = strftime(s, max, format, tm);
if (!ret && errno == EINVAL)
die("invalid strftime format: '%s'", format);
return ret;
}
unsigned int sleep (unsigned int seconds)
{
Sleep(seconds*1000);
return 0;
}
char *mingw_mktemp(char *template)
{
wchar_t wtemplate[MAX_PATH];
int offset = 0;
/* we need to return the path, thus no long paths here! */
if (xutftowcs_path(wtemplate, template) < 0)
return NULL;
if (is_dir_sep(template[0]) && !is_dir_sep(template[1]) &&
iswalpha(wtemplate[0]) && wtemplate[1] == L':') {
/* We have an absolute path missing the drive prefix */
offset = 2;
}
if (!_wmktemp(wtemplate))
return NULL;
if (xwcstoutf(template, wtemplate + offset, strlen(template) + 1) < 0)
return NULL;
return template;
}
int mkstemp(char *template)
{
char *filename = mktemp(template);
if (filename == NULL)
return -1;
return open(filename, O_RDWR | O_CREAT, 0600);
}
int gettimeofday(struct timeval *tv, void *tz)
{
FILETIME ft;
long long hnsec;
GetSystemTimeAsFileTime(&ft);
hnsec = filetime_to_hnsec(&ft);
tv->tv_sec = hnsec / 10000000;
tv->tv_usec = (hnsec % 10000000) / 10;
return 0;
}
int pipe(int filedes[2])
{
HANDLE h[2];
/* this creates non-inheritable handles */