forked from git/git
-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
mingw.c
4249 lines (3739 loc) · 110 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
#define USE_THE_REPOSITORY_VARIABLE
#include "../git-compat-util.h"
#include "win32.h"
#include <aclapi.h>
#include <sddl.h>
#include <conio.h>
#include <wchar.h>
#include <winioctl.h>
#include "../strbuf.h"
#include "../run-command.h"
#include "../abspath.h"
#include "../alloc.h"
#include "win32/exit-process.h"
#include "win32/lazyload.h"
#include "../config.h"
#include "../environment.h"
#include "../trace2.h"
#include "../symlinks.h"
#include "../wrapper.h"
#include "dir.h"
#include "gettext.h"
#define SECURITY_WIN32
#include <sspi.h>
#include "../write-or-die.h"
#include "../repository.h"
#include "win32/fscache.h"
#include "../attr.h"
#include "../string-list.h"
#include "win32/wsl.h"
#define HCAST(type, handle) ((type)(intptr_t)handle)
void open_in_gdb(void)
{
static struct child_process cp = CHILD_PROCESS_INIT;
strvec_pushl(&cp.args, "mintty", "gdb", NULL);
strvec_pushf(&cp.args, "--pid=%d", getpid());
cp.clean_on_exit = 1;
if (start_command(&cp) < 0)
die_errno("Could not start gdb");
sleep(1);
}
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_SUCCESS: BUG("err_win_to_posix() called without an error!");
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;
vsnprintf(question, sizeof(question), format, args);
retry_hook = mingw_getenv("GIT_ASK_YESNO");
if (retry_hook) {
struct child_process cmd = CHILD_PROCESS_INIT;
strvec_pushl(&cmd.args, retry_hook, question, NULL);
return !run_command(&cmd);
}
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 int core_restrict_inherited_handles = -1;
static enum hide_dotfiles_type hide_dotfiles = HIDE_DOTFILES_DOTGITONLY;
static char *unset_environment_variables;
int core_fscache;
int are_long_paths_enabled(void)
{
/* default to `false` during initialization */
static const int fallback = 0;
static int enabled = -1;
if (enabled < 0) {
/* avoid infinite recursion */
if (!the_repository)
return fallback;
if (the_repository->config &&
the_repository->config->hash_initialized &&
git_config_get_bool("core.longpaths", &enabled) < 0)
enabled = 0;
}
return enabled < 0 ? fallback : enabled;
}
int mingw_core_config(const char *var, const char *value,
const struct config_context *ctx UNUSED,
void *cb UNUSED)
{
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.unsetenvvars")) {
if (!value)
return config_error_nonbool(var);
free(unset_environment_variables);
unset_environment_variables = xstrdup(value);
return 0;
}
if (!strcmp(var, "core.restrictinheritedhandles")) {
if (value && !strcasecmp(value, "auto"))
core_restrict_inherited_handles = -1;
else
core_restrict_inherited_handles =
git_config_bool(var, value);
return 0;
}
return 0;
}
static inline int is_wdir_sep(wchar_t wchar)
{
return wchar == L'/' || wchar == L'\\';
}
static const wchar_t *make_relative_to(const wchar_t *path,
const wchar_t *relative_to, wchar_t *out,
size_t size)
{
size_t i = wcslen(relative_to), len;
/* Is `path` already absolute? */
if (is_wdir_sep(path[0]) ||
(iswalpha(path[0]) && path[1] == L':' && is_wdir_sep(path[2])))
return path;
while (i > 0 && !is_wdir_sep(relative_to[i - 1]))
i--;
/* Is `relative_to` in the current directory? */
if (!i)
return path;
len = wcslen(path);
if (i + len + 1 > size) {
error("Could not make '%ls' relative to '%ls' (too large)",
path, relative_to);
return NULL;
}
memcpy(out, relative_to, i * sizeof(wchar_t));
wcscpy(out + i, path);
return out;
}
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;
wchar_t relative[MAX_LONG_PATH];
const wchar_t *rel;
/* 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;
/* make it relative, if necessary */
rel = make_relative_to(wtarget, wlink, relative, ARRAY_SIZE(relative));
if (!rel)
return PHANTOM_SYMLINK_DONE;
/* let Windows resolve the link by opening it */
hnd = CreateFileW(rel, 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);
}
static int create_phantom_symlink(wchar_t *wtarget, wchar_t *wlink)
{
int len;
/* create file symlink */
if (!CreateSymbolicLinkW(wlink, wtarget, symlink_file_flags)) {
errno = err_win_to_posix(GetLastError());
return -1;
}
/* convert to directory symlink if target exists */
switch (process_phantom_symlink(wtarget, wlink)) {
case PHANTOM_SYMLINK_RETRY: {
/* if target doesn't exist, add to phantom symlinks list */
wchar_t wfullpath[MAX_LONG_PATH];
struct phantom_symlink_info *psi;
/* convert to absolute path to be independent of cwd */
len = GetFullPathNameW(wlink, MAX_LONG_PATH, wfullpath, NULL);
if (!len || len >= MAX_LONG_PATH) {
errno = err_win_to_posix(GetLastError());
return -1;
}
/* over-allocate and fill phantom_symlink_info structure */
psi = xmalloc(sizeof(struct phantom_symlink_info) +
sizeof(wchar_t) * (len + wcslen(wtarget) + 2));
psi->wlink = (wchar_t *)(psi + 1);
wcscpy(psi->wlink, wfullpath);
psi->wtarget = psi->wlink + len + 1;
wcscpy(psi->wtarget, wtarget);
EnterCriticalSection(&phantom_symlinks_cs);
psi->next = phantom_symlinks;
phantom_symlinks = psi;
LeaveCriticalSection(&phantom_symlinks_cs);
break;
}
case PHANTOM_SYMLINK_DIRECTORY:
/* if we created a dir symlink, process other phantom symlinks */
process_phantom_symlinks();
break;
default:
break;
}
return 0;
}
/* 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;
if (DeleteFileW(wpathname))
return 0;
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];
struct stat st;
/*
* Contrary to Linux' `rmdir()`, Windows' _wrmdir() and _rmdir()
* (and `RemoveDirectoryW()`) will attempt to remove the target of a
* symbolic link (if it points to a directory).
*
* This behavior breaks the assumption of e.g. `remove_path()` which
* upon successful deletion of a file will attempt to remove its parent
* directories recursively until failure (which usually happens when
* the directory is not empty).
*
* Therefore, before calling `_wrmdir()`, we first check if the path is
* a symbolic link. If it is, we exit and return the same error as
* Linux' `rmdir()` would, i.e. `ENOTDIR`.
*/
if (!mingw_lstat(pathname, &st) && S_ISLNK(st.st_mode)) {
errno = ENOTDIR;
return -1;
}
if (xutftowcs_long_path(wpathname, pathname) < 0)
return -1;
do {
if (!_wrmdir(wpathname)) {
invalidate_lstat_cache();
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 */
win32_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;
else
break;
}
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 UNUSED)
{
int ret;
wchar_t wpath[MAX_LONG_PATH];
if (!is_valid_win32_path(path, 0)) {
errno = EINVAL;
return -1;
}
/* CreateDirectoryW path limit is 248 (MAX_PATH - 8.3 file name) */
if (xutftowcs_path_ex(wpath, path, MAX_LONG_PATH, -1, 248,
are_long_paths_enabled()) < 0)
return -1;
ret = _wmkdir(wpath);
if (!ret)
process_phantom_symlinks();
if (!ret && needs_hiding(path))
return set_hidden_flag(wpath, 1);
return ret;
}
/*
* Calling CreateFile() using FILE_APPEND_DATA and without FILE_WRITE_DATA
* is documented in [1] as opening a writable file handle in append mode.
* (It is believed that) this is atomic since it is maintained by the
* kernel unlike the O_APPEND flag which is racily maintained by the CRT.
*
* [1] https://docs.microsoft.com/en-us/windows/desktop/fileio/file-access-rights-constants
*
* This trick does not appear to work for named pipes. Instead it creates
* a named pipe client handle that cannot be written to. Callers should
* just use the regular _wopen() for them. (And since client handle gets
* bound to a unique server handle, it isn't really an issue.)
*/
static int mingw_open_append(wchar_t const *wfilename, int oflags, ...)
{
HANDLE handle;
int fd;
DWORD create = (oflags & O_CREAT) ? OPEN_ALWAYS : OPEN_EXISTING;
/* only these flags are supported */
if ((oflags & ~O_CREAT) != (O_WRONLY | O_APPEND))
return errno = ENOSYS, -1;
/*
* FILE_SHARE_WRITE is required to permit child processes
* to append to the file.
*/
handle = CreateFileW(wfilename, FILE_APPEND_DATA,
FILE_SHARE_WRITE | FILE_SHARE_READ,
NULL, create, FILE_ATTRIBUTE_NORMAL, NULL);
if (handle == INVALID_HANDLE_VALUE) {
DWORD err = GetLastError();
/*
* Some network storage solutions (e.g. Isilon) might return
* ERROR_INVALID_PARAMETER instead of expected error
* ERROR_PATH_NOT_FOUND, which results in an unknown error. If
* so, let's turn the error to ERROR_PATH_NOT_FOUND instead.
*/
if (err == ERROR_INVALID_PARAMETER)
err = ERROR_PATH_NOT_FOUND;
errno = err_win_to_posix(err);
return -1;
}
/*
* No O_APPEND here, because the CRT uses it only to reset the
* file pointer to EOF before each write(); but that is not
* necessary (and may lead to races) for a file created with
* FILE_APPEND_DATA.
*/
fd = _open_osfhandle((intptr_t)handle, O_BINARY);
if (fd < 0)
CloseHandle(handle);
return fd;
}
/*
* Does the pathname map to the local named pipe filesystem?
* That is, does it have a "//./pipe/" prefix?
*/
static int is_local_named_pipe_path(const char *filename)
{
return (is_dir_sep(filename[0]) &&
is_dir_sep(filename[1]) &&
filename[2] == '.' &&
is_dir_sep(filename[3]) &&
!strncasecmp(filename+4, "pipe", 4) &&
is_dir_sep(filename[8]) &&
filename[9]);
}
int mingw_open (const char *filename, int oflags, ...)
{
static int append_atomically = -1;
typedef int (*open_fn_t)(wchar_t const *wfilename, int oflags, ...);
va_list args;
unsigned mode;
int fd, create = (oflags & (O_CREAT | O_EXCL)) == (O_CREAT | O_EXCL);
wchar_t wfilename[MAX_LONG_PATH];
open_fn_t open_fn;
va_start(args, oflags);
mode = va_arg(args, int);
va_end(args);
if (!is_valid_win32_path(filename, !create)) {
errno = create ? EINVAL : ENOENT;
return -1;
}
/*
* Only set append_atomically to default value(1) when repo is initialized
* and fail to get config value
*/
if (append_atomically < 0 && the_repository && the_repository->commondir &&
git_config_get_bool("windows.appendatomically", &append_atomically))
append_atomically = 1;
if (append_atomically && (oflags & O_APPEND) &&
!is_local_named_pipe_path(filename))
open_fn = mingw_open_append;
else
open_fn = _wopen;
if (filename && !strcmp(filename, "/dev/null"))
wcscpy(wfilename, L"nul");
else if (xutftowcs_long_path(wfilename, filename) < 0)
return -1;
fd = open_fn(wfilename, oflags, mode);
if ((oflags & O_CREAT) && fd >= 0 && are_wsl_compatible_mode_bits_enabled()) {
_mode_t wsl_mode = S_IFREG | (mode&0777);
set_wsl_mode_bits_by_handle((HANDLE)_get_osfhandle(fd), wsl_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 = open_fn(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 UNUSED)
{
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"))
wcscpy(wfilename, L"nul");
else if (!is_valid_win32_path(filename, 1)) {
int create = otype && strchr(otype, 'w');
errno = create ? EINVAL : ENOENT;
return NULL;
} else if (xutftowcs_long_path(wfilename, filename) < 0)
return NULL;
if (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"))
wcscpy(wfilename, L"nul");
else if (!is_valid_win32_path(filename, 1)) {
int create = otype && strchr(otype, 'w');
errno = create ? EINVAL : ENOENT;
return NULL;
} else if (xutftowcs_long_path(wfilename, filename) < 0)
return NULL;
if (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 || errno == EBADF || errno == ENOSPC) && buf) {
int orig = errno;
/* check if fd is a pipe */
HANDLE h = (HANDLE) _get_osfhandle(fd);
if (GetFileType(h) != FILE_TYPE_PIPE) {
if (orig == EINVAL) {
wchar_t path[MAX_LONG_PATH];
DWORD ret = GetFinalPathNameByHandleW(h, path,
ARRAY_SIZE(path), 0);
UINT drive_type = ret > 0 && ret < ARRAY_SIZE(path) ?
GetDriveTypeW(path) : DRIVE_UNKNOWN;
/*
* The default atomic append causes such an error on
* network file systems, in such a case, it should be
* turned off via config.
*
* `drive_type` of UNC path: DRIVE_NO_ROOT_DIR
*/
if (DRIVE_NO_ROOT_DIR == drive_type || DRIVE_REMOTE == drive_type)
warning("invalid write operation detected; you may try:\n"
"\n\tgit config windows.appendAtomically false");
}
errno = orig;
} else if (orig == EINVAL || errno == EBADF)
errno = EPIPE;
else {
DWORD buf_size;
if (!GetNamedPipeInfo(h, NULL, NULL, &buf_size, NULL))
buf_size = 4096;
if (len > buf_size)
return write(fd, buf, buf_size);
errno = orig;
}
}
return result;
}
int mingw_access(const char *filename, int mode)
{
wchar_t wfilename[MAX_LONG_PATH];
if (!strcmp("nul", filename) || !strcmp("/dev/null", filename))