-
Notifications
You must be signed in to change notification settings - Fork 155
Expand file tree
/
Copy pathposix.c
More file actions
3562 lines (3233 loc) · 111 KB
/
Copy pathposix.c
File metadata and controls
3562 lines (3233 loc) · 111 KB
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
/*
* Copyright (c) 2020, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* The Universal Permissive License (UPL), Version 1.0
*
* Subject to the condition set forth below, permission is hereby granted to any
* person obtaining a copy of this software, associated documentation and/or
* data (collectively the "Software"), free of charge and under any and all
* copyright rights in the Software, and any and all patent rights owned or
* freely licensable by each licensor hereunder covering either (i) the
* unmodified Software as contributed to or provided by such licensor, or (ii)
* the Larger Works (as defined below), to deal in both
*
* (a) the Software, and
*
* (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if
* one is included with the Software each a "Larger Work" to which the Software
* is contributed by such licensors),
*
* without restriction, including without limitation the rights to copy, create
* derivative works of, display, perform, and distribute the Software and make,
* use, sell, offer for sale, import, export, have made, and have sold the
* Software and the Larger Work(s), and to sublicense the foregoing rights on
* either these or other terms.
*
* This license is subject to the following condition:
*
* The above copyright notice and either this complete permission notice or at a
* minimum a reference to the UPL must be included in all copies or substantial
* portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// Helper functions that mostly delegate to POSIX functions
// These functions are called from NativePosixSupport Java class using native-access downcalls
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#include <ws2tcpip.h>
#include <afunix.h>
#include <assert.h>
#include <windows.h>
#include <direct.h>
#include <errno.h>
#include <fcntl.h>
#include <io.h>
#include <process.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "errno_capture.h"
#ifndef SO_UPDATE_ACCEPT_CONTEXT
#define SO_UPDATE_ACCEPT_CONTEXT 0x700B
#endif
#ifndef ENOTSUP
#define ENOTSUP ENOSYS
#endif
#ifndef EWOULDBLOCK
#define EWOULDBLOCK 11
#endif
#ifndef EOVERFLOW
#define EOVERFLOW 75
#endif
#ifndef EALREADY
#define EALREADY 114
#endif
#ifndef EINPROGRESS
#define EINPROGRESS 115
#endif
#ifndef ENOTSOCK
#define ENOTSOCK 88
#endif
#ifndef EDESTADDRREQ
#define EDESTADDRREQ 89
#endif
#ifndef EMSGSIZE
#define EMSGSIZE 90
#endif
#ifndef EPROTOTYPE
#define EPROTOTYPE 91
#endif
#ifndef ENOPROTOOPT
#define ENOPROTOOPT 92
#endif
#ifndef EPROTONOSUPPORT
#define EPROTONOSUPPORT 93
#endif
#ifndef EAFNOSUPPORT
#define EAFNOSUPPORT 97
#endif
#ifndef EADDRINUSE
#define EADDRINUSE 98
#endif
#ifndef EADDRNOTAVAIL
#define EADDRNOTAVAIL 99
#endif
#ifndef ENETDOWN
#define ENETDOWN 100
#endif
#ifndef ENETUNREACH
#define ENETUNREACH 101
#endif
#ifndef ENETRESET
#define ENETRESET 102
#endif
#ifndef ECONNABORTED
#define ECONNABORTED 103
#endif
#ifndef ECONNRESET
#define ECONNRESET 104
#endif
#ifndef ENOBUFS
#define ENOBUFS 105
#endif
#ifndef EISCONN
#define EISCONN 106
#endif
#ifndef ENOTCONN
#define ENOTCONN 107
#endif
#ifndef ETIMEDOUT
#define ETIMEDOUT 110
#endif
#ifndef ECONNREFUSED
#define ECONNREFUSED 111
#endif
#ifndef EHOSTUNREACH
#define EHOSTUNREACH 113
#endif
#define GP_EWOULDBLOCK 11
#define GP_EINPROGRESS 115
#define GP_EALREADY 114
#define GP_ENOTSOCK 88
#define GP_EDESTADDRREQ 89
#define GP_EMSGSIZE 90
#define GP_EPROTOTYPE 91
#define GP_ENOPROTOOPT 92
#define GP_EPROTONOSUPPORT 93
#define GP_EAFNOSUPPORT 97
#define GP_EADDRINUSE 98
#define GP_EADDRNOTAVAIL 99
#define GP_ENETDOWN 100
#define GP_ENETUNREACH 101
#define GP_ENETRESET 102
#define GP_ECONNABORTED 103
#define GP_ECONNRESET 104
#define GP_ENOBUFS 105
#define GP_EISCONN 106
#define GP_ENOTCONN 107
#define GP_ETIMEDOUT 110
#define GP_ECONNREFUSED 111
#define GP_EHOSTUNREACH 113
#define GP_EXPORT __declspec(dllexport)
THREAD_LOCAL int errno_capture = 0;
THREAD_LOCAL int winerror_capture = 0;
THREAD_LOCAL int wsaerror_capture = 0;
THREAD_LOCAL int error_source_capture = ERROR_CAPTURE_ERRNO;
#define WIN_AT_FDCWD (-100)
#define WIN_GRAALPY_DEFAULT_DIR_FD (-1)
#define WIN_DT_UNKNOWN 0
typedef struct {
HANDLE handle;
WIN32_FIND_DATAW data;
int first;
int exhausted;
} win_dir_t;
static void silent_invalid_parameter_handler(const wchar_t *expression, const wchar_t *function, const wchar_t *file, unsigned int line, uintptr_t reserved) {
(void) expression;
(void) function;
(void) file;
(void) line;
(void) reserved;
}
#if defined(_MSC_VER) && _MSC_VER >= 1900
#define BEGIN_SUPPRESS_IPH \
{ _invalid_parameter_handler old_handler = _set_thread_local_invalid_parameter_handler(silent_invalid_parameter_handler);
#define END_SUPPRESS_IPH \
_set_thread_local_invalid_parameter_handler(old_handler); }
#else
#define BEGIN_SUPPRESS_IPH
#define END_SUPPRESS_IPH
#endif
static int is_default_dir_fd(int32_t dirFd) {
return dirFd == 0 || dirFd < 0 || dirFd == WIN_AT_FDCWD || dirFd == WIN_GRAALPY_DEFAULT_DIR_FD;
}
static int unsupported(void) {
errno = ENOSYS;
capture_errno();
return -1;
}
static void set_posix_errno(int error) {
errno = error;
capture_errors();
}
static void set_win_errno(DWORD error) {
capture_errors();
winerror_capture = (int) error;
error_source_capture = ERROR_CAPTURE_WINAPI;
}
/*
* Most Windows filesystem APIs still impose MAX_PATH unless the executable opts in to long path
* support. python-libposix can also be loaded into an embedding executable whose manifest we do not
* control, so make long paths independent of that process-wide setting by using extended paths.
*
* Keep short paths unchanged. Apart from avoiding an allocation in the common case, this preserves
* Win32 handling of special names such as NUL. GetFullPathNameW resolves relative paths and dot
* components before we add the extended path prefix, which requires an absolute normalized path.
*/
#define WIN_LONG_PATH_THRESHOLD (MAX_PATH - 12)
#define WIN_LONG_PATH_LIMIT 32767
typedef struct {
const wchar_t *value;
wchar_t *allocated;
} win_path_t;
static int is_windows_namespace_path(const wchar_t *path) {
return wcsncmp(path, L"\\\\?\\", 4) == 0 ||
wcsncmp(path, L"\\\\.\\", 4) == 0 ||
wcsncmp(path, L"\\??\\", 4) == 0;
}
static int win_path_init(win_path_t *result, const wchar_t *path) {
result->value = path;
result->allocated = NULL;
if (path[0] == L'\0' || is_windows_namespace_path(path)) {
return 0;
}
DWORD full_size = GetFullPathNameW(path, 0, NULL, NULL);
if (full_size == 0) {
// Let the actual filesystem operation report the error for this path.
return 0;
}
wchar_t *full_path = NULL;
DWORD full_len;
for (;;) {
if (full_size > WIN_LONG_PATH_LIMIT || full_size > SIZE_MAX / sizeof(wchar_t)) {
free(full_path);
set_win_errno(ERROR_FILENAME_EXCED_RANGE);
return -1;
}
wchar_t *resized = (wchar_t *) realloc(full_path, (size_t) full_size * sizeof(wchar_t));
if (resized == NULL) {
free(full_path);
set_posix_errno(ENOMEM);
return -1;
}
full_path = resized;
full_len = GetFullPathNameW(path, full_size, full_path, NULL);
if (full_len == 0) {
capture_errors();
free(full_path);
// As above, preserve the error behavior of the actual filesystem operation.
return 0;
}
if (full_len < full_size) {
break;
}
if (full_len >= WIN_LONG_PATH_LIMIT) {
free(full_path);
set_win_errno(ERROR_FILENAME_EXCED_RANGE);
return -1;
}
full_size = full_len + 1;
}
if (full_len < WIN_LONG_PATH_THRESHOLD) {
free(full_path);
return 0;
}
if (is_windows_namespace_path(full_path)) {
result->value = full_path;
result->allocated = full_path;
return 0;
}
const wchar_t *prefix;
size_t prefix_len;
size_t source_offset;
if (full_len >= 2 && full_path[0] == L'\\' && full_path[1] == L'\\') {
prefix = L"\\\\?\\UNC\\";
prefix_len = 8;
source_offset = 2;
} else {
prefix = L"\\\\?\\";
prefix_len = 4;
source_offset = 0;
}
size_t extended_len = prefix_len + full_len - source_offset;
if (extended_len >= WIN_LONG_PATH_LIMIT || extended_len + 1 > SIZE_MAX / sizeof(wchar_t)) {
free(full_path);
set_win_errno(ERROR_FILENAME_EXCED_RANGE);
return -1;
}
wchar_t *extended = (wchar_t *) malloc((extended_len + 1) * sizeof(wchar_t));
if (extended == NULL) {
free(full_path);
set_posix_errno(ENOMEM);
return -1;
}
memcpy(extended, prefix, prefix_len * sizeof(wchar_t));
memcpy(extended + prefix_len, full_path + source_offset, (full_len - source_offset + 1) * sizeof(wchar_t));
for (size_t i = prefix_len; i < extended_len; i++) {
if (extended[i] == L'/') {
extended[i] = L'\\';
}
}
free(full_path);
result->value = extended;
result->allocated = extended;
return 0;
}
static void win_path_clear(win_path_t *path) {
free(path->allocated);
}
static DWORD win_path_remove_extended_prefix(wchar_t *path, DWORD len) {
if (len >= 8 && wcsncmp(path, L"\\\\?\\UNC\\", 8) == 0) {
path[0] = L'\\';
path[1] = L'\\';
memmove(path + 2, path + 8, (len - 8 + 1) * sizeof(wchar_t));
return len - 6;
}
if (len >= 4 && wcsncmp(path, L"\\\\?\\", 4) == 0) {
memmove(path, path + 4, (len - 4 + 1) * sizeof(wchar_t));
return len - 4;
}
return len;
}
static int ensure_winsock(void) {
static int initialized = 0;
if (!initialized) {
WSADATA wsa_data;
int err = WSAStartup(MAKEWORD(2, 2), &wsa_data);
if (err != 0) {
capture_errors();
wsaerror_capture = err;
error_source_capture = ERROR_CAPTURE_WINSOCK;
return -1;
}
initialized = 1;
}
return 0;
}
static int set_wsa_errno_from_error(int error) {
capture_errors();
wsaerror_capture = error;
error_source_capture = ERROR_CAPTURE_WINSOCK;
return -1;
}
static int set_wsa_errno(void) {
return set_wsa_errno_from_error(WSAGetLastError());
}
static int close_noraise(int32_t fd) {
int result;
BEGIN_SUPPRESS_IPH
result = _close(fd);
END_SUPPRESS_IPH
if (result < 0) {
capture_errno();
}
return result;
}
static int64_t read_noraise(int32_t fd, void *buf, unsigned int count) {
int result;
BEGIN_SUPPRESS_IPH
result = _read(fd, buf, count);
END_SUPPRESS_IPH
if (result < 0) {
capture_errno();
}
return result;
}
static int64_t write_noraise(int32_t fd, void *buf, unsigned int count) {
int result;
BEGIN_SUPPRESS_IPH
result = _write(fd, buf, count);
END_SUPPRESS_IPH
if (result < 0) {
capture_errno();
}
return result;
}
static int64_t lseek_noraise(int32_t fd, int64_t offset, int32_t whence) {
int64_t result;
BEGIN_SUPPRESS_IPH
result = _lseeki64(fd, offset, whence);
END_SUPPRESS_IPH
if (result < 0) {
capture_errno();
}
return result;
}
static int chsize_noraise(int32_t fd, int64_t length) {
int result;
BEGIN_SUPPRESS_IPH
result = _chsize_s(fd, length);
END_SUPPRESS_IPH
if (result != 0) {
errno = result;
capture_errno();
}
return result;
}
static int commit_noraise(int32_t fd) {
int result;
BEGIN_SUPPRESS_IPH
result = _commit(fd);
END_SUPPRESS_IPH
if (result < 0) {
capture_errno();
}
return result;
}
static int dup_noraise(int32_t fd) {
int result;
BEGIN_SUPPRESS_IPH
result = _dup(fd);
END_SUPPRESS_IPH
if (result < 0) {
capture_errno();
}
return result;
}
static int dup2_noraise(int32_t oldfd, int32_t newfd) {
int result;
BEGIN_SUPPRESS_IPH
result = _dup2(oldfd, newfd);
END_SUPPRESS_IPH
if (result < 0) {
capture_errno();
}
return result;
}
typedef struct {
int fd;
SOCKET socket;
int blocking;
} win_socket_entry_t;
typedef struct {
void *view;
HANDLE mapping;
} win_mmap_entry_t;
#define WIN_SOCKET_TABLE_SIZE 1024
#define WIN_MMAP_TABLE_SIZE 1024
static win_socket_entry_t win_socket_table[WIN_SOCKET_TABLE_SIZE];
static INIT_ONCE win_socket_table_init_once = INIT_ONCE_STATIC_INIT;
static CRITICAL_SECTION win_socket_table_lock;
static win_mmap_entry_t win_mmap_table[WIN_MMAP_TABLE_SIZE];
static INIT_ONCE win_mmap_table_init_once = INIT_ONCE_STATIC_INIT;
static CRITICAL_SECTION win_mmap_table_lock;
static BOOL CALLBACK win_socket_table_init(PINIT_ONCE init_once, PVOID parameter, PVOID *context) {
(void) init_once;
(void) parameter;
(void) context;
InitializeCriticalSection(&win_socket_table_lock);
for (int i = 0; i < WIN_SOCKET_TABLE_SIZE; i++) {
win_socket_table[i].fd = -1;
win_socket_table[i].socket = INVALID_SOCKET;
win_socket_table[i].blocking = 1;
}
return TRUE;
}
static void ensure_socket_table(void) {
InitOnceExecuteOnce(&win_socket_table_init_once, win_socket_table_init, NULL, NULL);
}
static BOOL CALLBACK win_mmap_table_init(PINIT_ONCE init_once, PVOID parameter, PVOID *context) {
(void) init_once;
(void) parameter;
(void) context;
InitializeCriticalSection(&win_mmap_table_lock);
for (int i = 0; i < WIN_MMAP_TABLE_SIZE; i++) {
win_mmap_table[i].view = NULL;
win_mmap_table[i].mapping = NULL;
}
return TRUE;
}
static void ensure_mmap_table(void) {
InitOnceExecuteOnce(&win_mmap_table_init_once, win_mmap_table_init, NULL, NULL);
}
static int win_add_mmap(void *view, HANDLE mapping) {
ensure_mmap_table();
EnterCriticalSection(&win_mmap_table_lock);
for (int i = 0; i < WIN_MMAP_TABLE_SIZE; i++) {
if (win_mmap_table[i].view == NULL) {
win_mmap_table[i].view = view;
win_mmap_table[i].mapping = mapping;
LeaveCriticalSection(&win_mmap_table_lock);
return 0;
}
}
LeaveCriticalSection(&win_mmap_table_lock);
set_posix_errno(ENOMEM);
return -1;
}
static HANDLE win_remove_mmap(void *view) {
HANDLE mapping = NULL;
ensure_mmap_table();
EnterCriticalSection(&win_mmap_table_lock);
for (int i = 0; i < WIN_MMAP_TABLE_SIZE; i++) {
if (win_mmap_table[i].view == view) {
mapping = win_mmap_table[i].mapping;
win_mmap_table[i].view = NULL;
win_mmap_table[i].mapping = NULL;
break;
}
}
LeaveCriticalSection(&win_mmap_table_lock);
return mapping;
}
static SOCKET win_socket_from_fd(int32_t fd) {
SOCKET result = INVALID_SOCKET;
ensure_socket_table();
EnterCriticalSection(&win_socket_table_lock);
for (int i = 0; i < WIN_SOCKET_TABLE_SIZE; i++) {
if (win_socket_table[i].fd == fd) {
result = win_socket_table[i].socket;
break;
}
}
LeaveCriticalSection(&win_socket_table_lock);
return result;
}
static int win_socket_blocking_from_fd(int32_t fd) {
int result = 1;
ensure_socket_table();
EnterCriticalSection(&win_socket_table_lock);
for (int i = 0; i < WIN_SOCKET_TABLE_SIZE; i++) {
if (win_socket_table[i].fd == fd) {
result = win_socket_table[i].blocking;
break;
}
}
LeaveCriticalSection(&win_socket_table_lock);
return result;
}
static int win_socket_entry_index(int32_t fd) {
int result = -1;
ensure_socket_table();
EnterCriticalSection(&win_socket_table_lock);
for (int i = 0; i < WIN_SOCKET_TABLE_SIZE; i++) {
if (win_socket_table[i].fd == fd) {
result = i;
break;
}
}
LeaveCriticalSection(&win_socket_table_lock);
return result;
}
static int win_alloc_socket_fd(SOCKET s, int blocking) {
int fd = _open("NUL", _O_RDONLY | _O_BINARY | _O_NOINHERIT);
if (fd < 0) {
capture_errno();
closesocket(s);
return -1;
}
ensure_socket_table();
EnterCriticalSection(&win_socket_table_lock);
for (int i = 0; i < WIN_SOCKET_TABLE_SIZE; i++) {
if (win_socket_table[i].fd < 0) {
win_socket_table[i].fd = fd;
win_socket_table[i].socket = s;
win_socket_table[i].blocking = blocking;
LeaveCriticalSection(&win_socket_table_lock);
return fd;
}
}
LeaveCriticalSection(&win_socket_table_lock);
close_noraise(fd);
closesocket(s);
set_posix_errno(EMFILE);
return -1;
}
static SOCKET win_remove_socket_fd(int32_t fd) {
SOCKET result = INVALID_SOCKET;
ensure_socket_table();
EnterCriticalSection(&win_socket_table_lock);
for (int i = 0; i < WIN_SOCKET_TABLE_SIZE; i++) {
if (win_socket_table[i].fd == fd) {
result = win_socket_table[i].socket;
win_socket_table[i].fd = -1;
win_socket_table[i].socket = INVALID_SOCKET;
win_socket_table[i].blocking = 1;
break;
}
}
LeaveCriticalSection(&win_socket_table_lock);
return result;
}
GP_EXPORT int32_t set_inheritable(int32_t fd, int32_t inheritable);
/* The caller must hold win_socket_table_lock. */
static int win_replace_socket_fd_locked(int32_t fd, SOCKET s, int blocking, SOCKET *replaced) {
assert(win_socket_table_lock.OwningThread == (HANDLE) (uintptr_t) GetCurrentThreadId());
int free_index = -1;
for (int i = 0; i < WIN_SOCKET_TABLE_SIZE; i++) {
if (win_socket_table[i].fd == fd) {
*replaced = win_socket_table[i].socket;
win_socket_table[i].socket = s;
win_socket_table[i].blocking = blocking;
return 0;
}
if (free_index < 0 && win_socket_table[i].fd < 0) {
free_index = i;
}
}
if (free_index < 0) {
set_posix_errno(EMFILE);
return -1;
}
win_socket_table[free_index].fd = fd;
win_socket_table[free_index].socket = s;
win_socket_table[free_index].blocking = blocking;
*replaced = INVALID_SOCKET;
return 0;
}
static SOCKET win_duplicate_socket(SOCKET s) {
WSAPROTOCOL_INFOA protocol_info;
if (WSADuplicateSocketA(s, GetCurrentProcessId(), &protocol_info) == SOCKET_ERROR) {
set_wsa_errno();
return INVALID_SOCKET;
}
SOCKET dup = WSASocketA(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, &protocol_info, 0, WSA_FLAG_NO_HANDLE_INHERIT);
if (dup == INVALID_SOCKET) {
set_wsa_errno();
return INVALID_SOCKET;
}
return dup;
}
static int win_socket_dup(int32_t fd) {
SOCKET s = win_socket_from_fd(fd);
int blocking = win_socket_blocking_from_fd(fd);
SOCKET dup = win_duplicate_socket(s);
if (dup == INVALID_SOCKET) {
return -1;
}
return win_alloc_socket_fd(dup, blocking);
}
static int win_socket_dup2(int32_t oldfd, int32_t newfd, int32_t inheritable) {
SOCKET dup = win_duplicate_socket(win_socket_from_fd(oldfd));
if (dup == INVALID_SOCKET) {
return -1;
}
int blocking = win_socket_blocking_from_fd(oldfd);
/*
* Keep the table locked while replacing the dummy CRT fd. This ensures that
* a full table is reported before _dup2 changes newfd and that the table
* entry is updated atomically with respect to other table users.
*/
ensure_socket_table();
EnterCriticalSection(&win_socket_table_lock);
int table_has_slot = 0;
for (int i = 0; i < WIN_SOCKET_TABLE_SIZE; i++) {
if (win_socket_table[i].fd == newfd || win_socket_table[i].fd < 0) {
table_has_slot = 1;
break;
}
}
if (!table_has_slot) {
LeaveCriticalSection(&win_socket_table_lock);
closesocket(dup);
set_posix_errno(EMFILE);
return -1;
}
if (dup2_noraise(oldfd, newfd) != 0) {
LeaveCriticalSection(&win_socket_table_lock);
closesocket(dup);
return -1;
}
SOCKET replaced = INVALID_SOCKET;
int replaced_result = win_replace_socket_fd_locked(newfd, dup, blocking, &replaced);
LeaveCriticalSection(&win_socket_table_lock);
if (replaced_result < 0) {
closesocket(dup);
return -1;
}
if (replaced != INVALID_SOCKET) {
closesocket(replaced);
}
if (!inheritable) {
return set_inheritable(newfd, 0);
}
return 0;
}
static intptr_t get_osfhandle_noraise(int32_t fd) {
intptr_t handle;
BEGIN_SUPPRESS_IPH
handle = _get_osfhandle(fd);
END_SUPPRESS_IPH
if (handle == -1) {
capture_errno();
}
return handle;
}
static int open_osfhandle_noraise(int64_t handle, int32_t flags) {
int fd;
BEGIN_SUPPRESS_IPH
fd = _open_osfhandle((intptr_t) handle, flags);
END_SUPPRESS_IPH
if (fd < 0) {
capture_errno();
}
return fd;
}
static void unix_time_to_filetime(int64_t seconds, int64_t nanoseconds, FILETIME *out) {
int64_t ticks = (seconds + 11644473600LL) * 10000000LL + nanoseconds / 100;
out->dwLowDateTime = (DWORD) ticks;
out->dwHighDateTime = (DWORD) (ticks >> 32);
}
static int64_t filetime_to_unix_time(FILETIME time) {
ULARGE_INTEGER ticks;
ticks.LowPart = time.dwLowDateTime;
ticks.HighPart = time.dwHighDateTime;
return (int64_t) (ticks.QuadPart / 10000000ULL) - 11644473600LL;
}
static int set_file_times(HANDLE handle, int64_t *times, int32_t nanosecond_resolution) {
FILETIME atime;
FILETIME mtime;
if (times == NULL) {
GetSystemTimeAsFileTime(&mtime);
atime = mtime;
} else {
unix_time_to_filetime(times[0], nanosecond_resolution ? times[1] : times[1] * 1000, &atime);
unix_time_to_filetime(times[2], nanosecond_resolution ? times[3] : times[3] * 1000, &mtime);
}
if (!SetFileTime(handle, NULL, &atime, &mtime)) {
set_win_errno(GetLastError());
return -1;
}
return 0;
}
static int set_path_times(const wchar_t *path, int64_t *times, int32_t nanosecond_resolution, int32_t followSymlinks) {
win_path_t prepared;
if (win_path_init(&prepared, path) != 0) {
return -1;
}
DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
if (!followSymlinks) {
flags |= FILE_FLAG_OPEN_REPARSE_POINT;
}
HANDLE handle = CreateFileW(prepared.value, FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING, flags, NULL);
if (handle == INVALID_HANDLE_VALUE) {
set_win_errno(GetLastError());
win_path_clear(&prepared);
return -1;
}
win_path_clear(&prepared);
int result = set_file_times(handle, times, nanosecond_resolution);
CloseHandle(handle);
return result;
}
static int root_path_from_path(const wchar_t *path, wchar_t *root, DWORD root_size) {
wchar_t full_path[32768];
DWORD full_len = GetFullPathNameW(path, (DWORD) (sizeof(full_path) / sizeof(wchar_t)), full_path, NULL);
if (full_len == 0 || full_len >= sizeof(full_path) / sizeof(wchar_t)) {
set_win_errno(GetLastError());
return -1;
}
if (!GetVolumePathNameW(full_path, root, root_size)) {
set_win_errno(GetLastError());
return -1;
}
return 0;
}
static int statvfs_from_root(const wchar_t *root, int64_t *out) {
ULARGE_INTEGER free_bytes_available;
ULARGE_INTEGER total_number_of_bytes;
ULARGE_INTEGER total_number_of_free_bytes;
DWORD sectors_per_cluster = 0;
DWORD bytes_per_sector = 0;
DWORD number_of_free_clusters = 0;
DWORD total_number_of_clusters = 0;
if (!GetDiskFreeSpaceExW(root, &free_bytes_available, &total_number_of_bytes, &total_number_of_free_bytes)) {
set_win_errno(GetLastError());
return -1;
}
if (!GetDiskFreeSpaceW(root, §ors_per_cluster, &bytes_per_sector, &number_of_free_clusters, &total_number_of_clusters)) {
sectors_per_cluster = 1;
bytes_per_sector = 4096;
}
uint64_t block_size = (uint64_t) sectors_per_cluster * bytes_per_sector;
if (block_size == 0) {
block_size = 4096;
}
out[0] = (int64_t) block_size;
out[1] = (int64_t) block_size;
out[2] = (int64_t) (total_number_of_bytes.QuadPart / block_size);
out[3] = (int64_t) (total_number_of_free_bytes.QuadPart / block_size);
out[4] = (int64_t) (free_bytes_available.QuadPart / block_size);
out[5] = 0;
out[6] = 0;
out[7] = 0;
out[8] = 0;
out[9] = 255;
out[10] = 0;
return 0;
}
static int statvfs_from_path(const wchar_t *path, int64_t *out) {
win_path_t prepared;
if (win_path_init(&prepared, path) != 0) {
return -1;
}
DWORD attributes = GetFileAttributesW(prepared.value);
if (attributes == INVALID_FILE_ATTRIBUTES) {
set_win_errno(GetLastError());
win_path_clear(&prepared);
return -1;
}
wchar_t root[MAX_PATH];
if (root_path_from_path(prepared.value, root, MAX_PATH) != 0) {
win_path_clear(&prepared);
return -1;
}
win_path_clear(&prepared);
return statvfs_from_root(root, out);
}
static int copy_string_to_buffer(char *buffer, int32_t bufferSize, size_t *offset, const char *value, uint64_t *out, int32_t outIndex) {
size_t len = strlen(value) + 1;
if (*offset + len > (size_t) bufferSize) {
return ERANGE;
}
out[outIndex] = *offset;
memcpy(buffer + *offset, value, len);
*offset += len;
return 0;
}
static int get_current_username(char *buffer, DWORD size) {
const char *env_name = getenv("USERNAME");
if (env_name != NULL && strlen(env_name) < size) {
strcpy(buffer, env_name);
return 0;
}
if (size > 4) {
strcpy(buffer, "user");
return 0;
}
return ERANGE;
}
static void get_current_home(char *buffer, size_t size) {
const char *profile = getenv("USERPROFILE");
if (profile != NULL && strlen(profile) < size) {
strcpy(buffer, profile);
return;
}
const char *drive = getenv("HOMEDRIVE");
const char *path = getenv("HOMEPATH");
if (drive != NULL && path != NULL && strlen(drive) + strlen(path) < size) {
strcpy(buffer, drive);
strcat(buffer, path);
return;
}
if (size > 0) {
buffer[0] = '\0';
}
}
static int fill_current_pwd(uint64_t uid, char *buffer, int32_t bufferSize, uint64_t *output) {
char name[256];
char dir[1024];
const char *shell = getenv("COMSPEC");
size_t offset = 0;
int result = get_current_username(name, sizeof(name));
if (result != 0) {
return result;
}
get_current_home(dir, sizeof(dir));
if (shell == NULL) {
shell = "";
}
if ((result = copy_string_to_buffer(buffer, bufferSize, &offset, name, output, 0)) != 0) {
return result;
}
output[1] = uid;
output[2] = 0;
if ((result = copy_string_to_buffer(buffer, bufferSize, &offset, dir, output, 3)) != 0) {
return result;
}
return copy_string_to_buffer(buffer, bufferSize, &offset, shell, output, 4);
}
static void stat_struct_to_longs(struct __stat64 *st, int64_t *out) {
out[0] = st->st_mode;
out[1] = st->st_ino;
out[2] = st->st_dev;
out[3] = st->st_nlink;
out[4] = st->st_uid;
out[5] = st->st_gid;
out[6] = st->st_size;
out[7] = st->st_atime;
out[8] = st->st_mtime;
out[9] = st->st_ctime;
out[10] = 0;
out[11] = 0;
out[12] = 0;
}
static void stat_handle_to_longs(HANDLE handle, int64_t *out) {
BY_HANDLE_FILE_INFORMATION info;
if (GetFileInformationByHandle(handle, &info)) {
out[1] = ((int64_t) info.nFileIndexHigh << 32) | info.nFileIndexLow;
out[2] = info.dwVolumeSerialNumber;
out[3] = info.nNumberOfLinks;
out[7] = filetime_to_unix_time(info.ftLastAccessTime);
out[8] = filetime_to_unix_time(info.ftLastWriteTime);
out[9] = filetime_to_unix_time(info.ftCreationTime);
}
}
static void stat_path_handle_to_longs(const wchar_t *path, int32_t followSymlinks, int64_t *out) {
DWORD flags = FILE_FLAG_BACKUP_SEMANTICS;
if (!followSymlinks) {
flags |= FILE_FLAG_OPEN_REPARSE_POINT;
}
HANDLE handle = CreateFileW(path, FILE_READ_ATTRIBUTES, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, flags, NULL);
if (handle != INVALID_HANDLE_VALUE) {
stat_handle_to_longs(handle, out);
CloseHandle(handle);
}
}