-
-
Notifications
You must be signed in to change notification settings - Fork 31.2k
/
Copy pathfileutils.c
1585 lines (1389 loc) · 42.1 KB
/
fileutils.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 "Python.h"
#include "osdefs.h"
#include <locale.h>
#ifdef MS_WINDOWS
# include <malloc.h>
# include <windows.h>
extern int winerror_to_errno(int);
#endif
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif /* HAVE_FCNTL_H */
#if defined(__APPLE__) || defined(__ANDROID__)
extern wchar_t* _Py_DecodeUTF8_surrogateescape(const char *s, Py_ssize_t size);
#endif
#ifdef O_CLOEXEC
/* Does open() support the O_CLOEXEC flag? Possible values:
-1: unknown
0: open() ignores O_CLOEXEC flag, ex: Linux kernel older than 2.6.23
1: open() supports O_CLOEXEC flag, close-on-exec is set
The flag is used by _Py_open(), _Py_open_noraise(), io.FileIO
and os.open(). */
int _Py_open_cloexec_works = -1;
#endif
PyObject *
_Py_device_encoding(int fd)
{
#if defined(MS_WINDOWS)
UINT cp;
#endif
int valid;
_Py_BEGIN_SUPPRESS_IPH
valid = isatty(fd);
_Py_END_SUPPRESS_IPH
if (!valid)
Py_RETURN_NONE;
#if defined(MS_WINDOWS)
if (fd == 0)
cp = GetConsoleCP();
else if (fd == 1 || fd == 2)
cp = GetConsoleOutputCP();
else
cp = 0;
/* GetConsoleCP() and GetConsoleOutputCP() return 0 if the application
has no console */
if (cp != 0)
return PyUnicode_FromFormat("cp%u", (unsigned int)cp);
#elif defined(CODESET)
{
char *codeset = nl_langinfo(CODESET);
if (codeset != NULL && codeset[0] != 0)
return PyUnicode_FromString(codeset);
}
#endif
Py_RETURN_NONE;
}
#if !defined(__APPLE__) && !defined(MS_WINDOWS)
extern int _Py_normalize_encoding(const char *, char *, size_t);
/* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale.
On these operating systems, nl_langinfo(CODESET) announces an alias of the
ASCII encoding, whereas mbstowcs() and wcstombs() functions use the
ISO-8859-1 encoding. The problem is that os.fsencode() and os.fsdecode() use
locale.getpreferredencoding() codec. For example, if command line arguments
are decoded by mbstowcs() and encoded back by os.fsencode(), we get a
UnicodeEncodeError instead of retrieving the original byte string.
The workaround is enabled if setlocale(LC_CTYPE, NULL) returns "C",
nl_langinfo(CODESET) announces "ascii" (or an alias to ASCII), and at least
one byte in range 0x80-0xff can be decoded from the locale encoding. The
workaround is also enabled on error, for example if getting the locale
failed.
Values of force_ascii:
1: the workaround is used: Py_EncodeLocale() uses
encode_ascii_surrogateescape() and Py_DecodeLocale() uses
decode_ascii_surrogateescape()
0: the workaround is not used: Py_EncodeLocale() uses wcstombs() and
Py_DecodeLocale() uses mbstowcs()
-1: unknown, need to call check_force_ascii() to get the value
*/
static int force_ascii = -1;
static int
check_force_ascii(void)
{
char *loc;
#if defined(HAVE_LANGINFO_H) && defined(CODESET)
char *codeset, **alias;
char encoding[20]; /* longest name: "iso_646.irv_1991\0" */
int is_ascii;
unsigned int i;
char* ascii_aliases[] = {
"ascii",
/* Aliases from Lib/encodings/aliases.py */
"646",
"ansi_x3.4_1968",
"ansi_x3.4_1986",
"ansi_x3_4_1968",
"cp367",
"csascii",
"ibm367",
"iso646_us",
"iso_646.irv_1991",
"iso_ir_6",
"us",
"us_ascii",
NULL
};
#endif
loc = setlocale(LC_CTYPE, NULL);
if (loc == NULL)
goto error;
if (strcmp(loc, "C") != 0) {
/* the LC_CTYPE locale is different than C */
return 0;
}
#if defined(HAVE_LANGINFO_H) && defined(CODESET)
codeset = nl_langinfo(CODESET);
if (!codeset || codeset[0] == '\0') {
/* CODESET is not set or empty */
goto error;
}
if (!_Py_normalize_encoding(codeset, encoding, sizeof(encoding)))
goto error;
is_ascii = 0;
for (alias=ascii_aliases; *alias != NULL; alias++) {
if (strcmp(encoding, *alias) == 0) {
is_ascii = 1;
break;
}
}
if (!is_ascii) {
/* nl_langinfo(CODESET) is not "ascii" or an alias of ASCII */
return 0;
}
for (i=0x80; i<0xff; i++) {
unsigned char ch;
wchar_t wch;
size_t res;
ch = (unsigned char)i;
res = mbstowcs(&wch, (char*)&ch, 1);
if (res != (size_t)-1) {
/* decoding a non-ASCII character from the locale encoding succeed:
the locale encoding is not ASCII, force ASCII */
return 1;
}
}
/* None of the bytes in the range 0x80-0xff can be decoded from the locale
encoding: the locale encoding is really ASCII */
return 0;
#else
/* nl_langinfo(CODESET) is not available: always force ASCII */
return 1;
#endif
error:
/* if an error occurred, force the ASCII encoding */
return 1;
}
static char*
encode_ascii_surrogateescape(const wchar_t *text, size_t *error_pos)
{
char *result = NULL, *out;
size_t len, i;
wchar_t ch;
if (error_pos != NULL)
*error_pos = (size_t)-1;
len = wcslen(text);
result = PyMem_Malloc(len + 1); /* +1 for NUL byte */
if (result == NULL)
return NULL;
out = result;
for (i=0; i<len; i++) {
ch = text[i];
if (ch <= 0x7f) {
/* ASCII character */
*out++ = (char)ch;
}
else if (0xdc80 <= ch && ch <= 0xdcff) {
/* UTF-8b surrogate */
*out++ = (char)(ch - 0xdc00);
}
else {
if (error_pos != NULL)
*error_pos = i;
PyMem_Free(result);
return NULL;
}
}
*out = '\0';
return result;
}
#endif /* !defined(__APPLE__) && !defined(MS_WINDOWS) */
#if !defined(__APPLE__) && (!defined(MS_WINDOWS) || !defined(HAVE_MBRTOWC))
static wchar_t*
decode_ascii_surrogateescape(const char *arg, size_t *size)
{
wchar_t *res;
unsigned char *in;
wchar_t *out;
size_t argsize = strlen(arg) + 1;
if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
return NULL;
res = PyMem_RawMalloc(argsize*sizeof(wchar_t));
if (!res)
return NULL;
in = (unsigned char*)arg;
out = res;
while(*in)
if(*in < 128)
*out++ = *in++;
else
*out++ = 0xdc00 + *in++;
*out = 0;
if (size != NULL)
*size = out - res;
return res;
}
#endif
/* Decode a byte string from the locale encoding with the
surrogateescape error handler: undecodable bytes are decoded as characters
in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate
character, escape the bytes using the surrogateescape error handler instead
of decoding them.
Return a pointer to a newly allocated wide character string, use
PyMem_RawFree() to free the memory. If size is not NULL, write the number of
wide characters excluding the null character into *size
Return NULL on decoding error or memory allocation error. If *size* is not
NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on
decoding error.
Decoding errors should never happen, unless there is a bug in the C
library.
Use the Py_EncodeLocale() function to encode the character string back to a
byte string. */
wchar_t*
Py_DecodeLocale(const char* arg, size_t *size)
{
#if defined(__APPLE__) || defined(__ANDROID__)
wchar_t *wstr;
wstr = _Py_DecodeUTF8_surrogateescape(arg, strlen(arg));
if (size != NULL) {
if (wstr != NULL)
*size = wcslen(wstr);
else
*size = (size_t)-1;
}
return wstr;
#else
wchar_t *res;
size_t argsize;
size_t count;
#ifdef HAVE_MBRTOWC
unsigned char *in;
wchar_t *out;
mbstate_t mbs;
#endif
#ifndef MS_WINDOWS
if (force_ascii == -1)
force_ascii = check_force_ascii();
if (force_ascii) {
/* force ASCII encoding to workaround mbstowcs() issue */
res = decode_ascii_surrogateescape(arg, size);
if (res == NULL)
goto oom;
return res;
}
#endif
#ifdef HAVE_BROKEN_MBSTOWCS
/* Some platforms have a broken implementation of
* mbstowcs which does not count the characters that
* would result from conversion. Use an upper bound.
*/
argsize = strlen(arg);
#else
argsize = mbstowcs(NULL, arg, 0);
#endif
if (argsize != (size_t)-1) {
if (argsize == PY_SSIZE_T_MAX)
goto oom;
argsize += 1;
if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
goto oom;
res = (wchar_t *)PyMem_RawMalloc(argsize*sizeof(wchar_t));
if (!res)
goto oom;
count = mbstowcs(res, arg, argsize);
if (count != (size_t)-1) {
wchar_t *tmp;
/* Only use the result if it contains no
surrogate characters. */
for (tmp = res; *tmp != 0 &&
!Py_UNICODE_IS_SURROGATE(*tmp); tmp++)
;
if (*tmp == 0) {
if (size != NULL)
*size = count;
return res;
}
}
PyMem_RawFree(res);
}
/* Conversion failed. Fall back to escaping with surrogateescape. */
#ifdef HAVE_MBRTOWC
/* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
/* Overallocate; as multi-byte characters are in the argument, the
actual output could use less memory. */
argsize = strlen(arg) + 1;
if (argsize > PY_SSIZE_T_MAX/sizeof(wchar_t))
goto oom;
res = (wchar_t*)PyMem_RawMalloc(argsize*sizeof(wchar_t));
if (!res)
goto oom;
in = (unsigned char*)arg;
out = res;
memset(&mbs, 0, sizeof mbs);
while (argsize) {
size_t converted = mbrtowc(out, (char*)in, argsize, &mbs);
if (converted == 0)
/* Reached end of string; null char stored. */
break;
if (converted == (size_t)-2) {
/* Incomplete character. This should never happen,
since we provide everything that we have -
unless there is a bug in the C library, or I
misunderstood how mbrtowc works. */
PyMem_RawFree(res);
if (size != NULL)
*size = (size_t)-2;
return NULL;
}
if (converted == (size_t)-1) {
/* Conversion error. Escape as UTF-8b, and start over
in the initial shift state. */
*out++ = 0xdc00 + *in++;
argsize--;
memset(&mbs, 0, sizeof mbs);
continue;
}
if (Py_UNICODE_IS_SURROGATE(*out)) {
/* Surrogate character. Escape the original
byte sequence with surrogateescape. */
argsize -= converted;
while (converted--)
*out++ = 0xdc00 + *in++;
continue;
}
/* successfully converted some bytes */
in += converted;
argsize -= converted;
out++;
}
if (size != NULL)
*size = out - res;
#else /* HAVE_MBRTOWC */
/* Cannot use C locale for escaping; manually escape as if charset
is ASCII (i.e. escape all bytes > 128. This will still roundtrip
correctly in the locale's charset, which must be an ASCII superset. */
res = decode_ascii_surrogateescape(arg, size);
if (res == NULL)
goto oom;
#endif /* HAVE_MBRTOWC */
return res;
oom:
if (size != NULL)
*size = (size_t)-1;
return NULL;
#endif /* __APPLE__ or __ANDROID__ */
}
/* Encode a wide character string to the locale encoding with the
surrogateescape error handler: surrogate characters in the range
U+DC80..U+DCFF are converted to bytes 0x80..0xFF.
Return a pointer to a newly allocated byte string, use PyMem_Free() to free
the memory. Return NULL on encoding or memory allocation error.
If error_pos is not NULL, *error_pos is set to the index of the invalid
character on encoding error, or set to (size_t)-1 otherwise.
Use the Py_DecodeLocale() function to decode the bytes string back to a wide
character string. */
char*
Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
{
#if defined(__APPLE__) || defined(__ANDROID__)
Py_ssize_t len;
PyObject *unicode, *bytes = NULL;
char *cpath;
unicode = PyUnicode_FromWideChar(text, wcslen(text));
if (unicode == NULL)
return NULL;
bytes = _PyUnicode_AsUTF8String(unicode, "surrogateescape");
Py_DECREF(unicode);
if (bytes == NULL) {
PyErr_Clear();
if (error_pos != NULL)
*error_pos = (size_t)-1;
return NULL;
}
len = PyBytes_GET_SIZE(bytes);
cpath = PyMem_Malloc(len+1);
if (cpath == NULL) {
PyErr_Clear();
Py_DECREF(bytes);
if (error_pos != NULL)
*error_pos = (size_t)-1;
return NULL;
}
memcpy(cpath, PyBytes_AsString(bytes), len + 1);
Py_DECREF(bytes);
return cpath;
#else /* __APPLE__ */
const size_t len = wcslen(text);
char *result = NULL, *bytes = NULL;
size_t i, size, converted;
wchar_t c, buf[2];
#ifndef MS_WINDOWS
if (force_ascii == -1)
force_ascii = check_force_ascii();
if (force_ascii)
return encode_ascii_surrogateescape(text, error_pos);
#endif
/* The function works in two steps:
1. compute the length of the output buffer in bytes (size)
2. outputs the bytes */
size = 0;
buf[1] = 0;
while (1) {
for (i=0; i < len; i++) {
c = text[i];
if (c >= 0xdc80 && c <= 0xdcff) {
/* UTF-8b surrogate */
if (bytes != NULL) {
*bytes++ = c - 0xdc00;
size--;
}
else
size++;
continue;
}
else {
buf[0] = c;
if (bytes != NULL)
converted = wcstombs(bytes, buf, size);
else
converted = wcstombs(NULL, buf, 0);
if (converted == (size_t)-1) {
if (result != NULL)
PyMem_Free(result);
if (error_pos != NULL)
*error_pos = i;
return NULL;
}
if (bytes != NULL) {
bytes += converted;
size -= converted;
}
else
size += converted;
}
}
if (result != NULL) {
*bytes = '\0';
break;
}
size += 1; /* nul byte at the end */
result = PyMem_Malloc(size);
if (result == NULL) {
if (error_pos != NULL)
*error_pos = (size_t)-1;
return NULL;
}
bytes = result;
}
return result;
#endif /* __APPLE__ or __ANDROID__ */
}
#ifdef MS_WINDOWS
static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
static void
FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
{
/* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
/* Cannot simply cast and dereference in_ptr,
since it might not be aligned properly */
__int64 in;
memcpy(&in, in_ptr, sizeof(in));
*nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
*time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
}
void
_Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
{
/* XXX endianness */
__int64 out;
out = time_in + secs_between_epochs;
out = out * 10000000 + nsec_in / 100;
memcpy(out_ptr, &out, sizeof(out));
}
/* Below, we *know* that ugo+r is 0444 */
#if _S_IREAD != 0400
#error Unsupported C library
#endif
static int
attributes_to_mode(DWORD attr)
{
int m = 0;
if (attr & FILE_ATTRIBUTE_DIRECTORY)
m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
else
m |= _S_IFREG;
if (attr & FILE_ATTRIBUTE_READONLY)
m |= 0444;
else
m |= 0666;
return m;
}
void
_Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
struct _Py_stat_struct *result)
{
memset(result, 0, sizeof(*result));
result->st_mode = attributes_to_mode(info->dwFileAttributes);
result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
result->st_dev = info->dwVolumeSerialNumber;
result->st_rdev = result->st_dev;
FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_ctime, &result->st_ctime_nsec);
FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
result->st_nlink = info->nNumberOfLinks;
result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow;
if (reparse_tag == IO_REPARSE_TAG_SYMLINK) {
/* first clear the S_IFMT bits */
result->st_mode ^= (result->st_mode & S_IFMT);
/* now set the bits that make this a symlink */
result->st_mode |= S_IFLNK;
}
result->st_file_attributes = info->dwFileAttributes;
}
#endif
/* Return information about a file.
On POSIX, use fstat().
On Windows, use GetFileType() and GetFileInformationByHandle() which support
files larger than 2 GB. fstat() may fail with EOVERFLOW on files larger
than 2 GB because the file size type is a signed 32-bit integer: see issue
#23152.
On Windows, set the last Windows error and return nonzero on error. On
POSIX, set errno and return nonzero on error. Fill status and return 0 on
success. */
int
_Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
{
#ifdef MS_WINDOWS
BY_HANDLE_FILE_INFORMATION info;
HANDLE h;
int type;
_Py_BEGIN_SUPPRESS_IPH
h = (HANDLE)_get_osfhandle(fd);
_Py_END_SUPPRESS_IPH
if (h == INVALID_HANDLE_VALUE) {
/* errno is already set by _get_osfhandle, but we also set
the Win32 error for callers who expect that */
SetLastError(ERROR_INVALID_HANDLE);
return -1;
}
memset(status, 0, sizeof(*status));
type = GetFileType(h);
if (type == FILE_TYPE_UNKNOWN) {
DWORD error = GetLastError();
if (error != 0) {
errno = winerror_to_errno(error);
return -1;
}
/* else: valid but unknown file */
}
if (type != FILE_TYPE_DISK) {
if (type == FILE_TYPE_CHAR)
status->st_mode = _S_IFCHR;
else if (type == FILE_TYPE_PIPE)
status->st_mode = _S_IFIFO;
return 0;
}
if (!GetFileInformationByHandle(h, &info)) {
/* The Win32 error is already set, but we also set errno for
callers who expect it */
errno = winerror_to_errno(GetLastError());
return -1;
}
_Py_attribute_data_to_stat(&info, 0, status);
/* specific to fstat() */
status->st_ino = (((uint64_t)info.nFileIndexHigh) << 32) + info.nFileIndexLow;
return 0;
#else
return fstat(fd, status);
#endif
}
/* Return information about a file.
On POSIX, use fstat().
On Windows, use GetFileType() and GetFileInformationByHandle() which support
files larger than 2 GB. fstat() may fail with EOVERFLOW on files larger
than 2 GB because the file size type is a signed 32-bit integer: see issue
#23152.
Raise an exception and return -1 on error. On Windows, set the last Windows
error on error. On POSIX, set errno on error. Fill status and return 0 on
success.
Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
to call fstat(). The caller must hold the GIL. */
int
_Py_fstat(int fd, struct _Py_stat_struct *status)
{
int res;
assert(PyGILState_Check());
Py_BEGIN_ALLOW_THREADS
res = _Py_fstat_noraise(fd, status);
Py_END_ALLOW_THREADS
if (res != 0) {
#ifdef MS_WINDOWS
PyErr_SetFromWindowsErr(0);
#else
PyErr_SetFromErrno(PyExc_OSError);
#endif
return -1;
}
return 0;
}
/* Call _wstat() on Windows, or encode the path to the filesystem encoding and
call stat() otherwise. Only fill st_mode attribute on Windows.
Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
raised. */
int
_Py_stat(PyObject *path, struct stat *statbuf)
{
#ifdef MS_WINDOWS
int err;
struct _stat wstatbuf;
const wchar_t *wpath;
wpath = _PyUnicode_AsUnicode(path);
if (wpath == NULL)
return -2;
err = _wstat(wpath, &wstatbuf);
if (!err)
statbuf->st_mode = wstatbuf.st_mode;
return err;
#else
int ret;
PyObject *bytes;
char *cpath;
bytes = PyUnicode_EncodeFSDefault(path);
if (bytes == NULL)
return -2;
/* check for embedded null bytes */
if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
Py_DECREF(bytes);
return -2;
}
ret = stat(cpath, statbuf);
Py_DECREF(bytes);
return ret;
#endif
}
static int
get_inheritable(int fd, int raise)
{
#ifdef MS_WINDOWS
HANDLE handle;
DWORD flags;
_Py_BEGIN_SUPPRESS_IPH
handle = (HANDLE)_get_osfhandle(fd);
_Py_END_SUPPRESS_IPH
if (handle == INVALID_HANDLE_VALUE) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (!GetHandleInformation(handle, &flags)) {
if (raise)
PyErr_SetFromWindowsErr(0);
return -1;
}
return (flags & HANDLE_FLAG_INHERIT);
#else
int flags;
flags = fcntl(fd, F_GETFD, 0);
if (flags == -1) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
return !(flags & FD_CLOEXEC);
#endif
}
/* Get the inheritable flag of the specified file descriptor.
Return 1 if the file descriptor can be inherited, 0 if it cannot,
raise an exception and return -1 on error. */
int
_Py_get_inheritable(int fd)
{
return get_inheritable(fd, 1);
}
static int
set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
{
#ifdef MS_WINDOWS
HANDLE handle;
DWORD flags;
#else
#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
static int ioctl_works = -1;
int request;
int err;
#endif
int flags, new_flags;
int res;
#endif
/* atomic_flag_works can only be used to make the file descriptor
non-inheritable */
assert(!(atomic_flag_works != NULL && inheritable));
if (atomic_flag_works != NULL && !inheritable) {
if (*atomic_flag_works == -1) {
int isInheritable = get_inheritable(fd, raise);
if (isInheritable == -1)
return -1;
*atomic_flag_works = !isInheritable;
}
if (*atomic_flag_works)
return 0;
}
#ifdef MS_WINDOWS
_Py_BEGIN_SUPPRESS_IPH
handle = (HANDLE)_get_osfhandle(fd);
_Py_END_SUPPRESS_IPH
if (handle == INVALID_HANDLE_VALUE) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (inheritable)
flags = HANDLE_FLAG_INHERIT;
else
flags = 0;
if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
if (raise)
PyErr_SetFromWindowsErr(0);
return -1;
}
return 0;
#else
#if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
if (ioctl_works != 0) {
/* fast-path: ioctl() only requires one syscall */
if (inheritable)
request = FIONCLEX;
else
request = FIOCLEX;
err = ioctl(fd, request, NULL);
if (!err) {
ioctl_works = 1;
return 0;
}
if (errno != ENOTTY && errno != EACCES) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
else {
/* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
device". The ioctl is declared but not supported by the kernel.
Remember that ioctl() doesn't work. It is the case on
Illumos-based OS for example.
Issue #27057: When SELinux policy disallows ioctl it will fail
with EACCES. While FIOCLEX is safe operation it may be
unavailable because ioctl was denied altogether.
This can be the case on Android. */
ioctl_works = 0;
}
/* fallback to fcntl() if ioctl() does not work */
}
#endif
/* slow-path: fcntl() requires two syscalls */
flags = fcntl(fd, F_GETFD);
if (flags < 0) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
if (inheritable) {
new_flags = flags & ~FD_CLOEXEC;
}
else {
new_flags = flags | FD_CLOEXEC;
}
if (new_flags == flags) {
/* FD_CLOEXEC flag already set/cleared: nothing to do */
return 0;
}
res = fcntl(fd, F_SETFD, new_flags);
if (res < 0) {
if (raise)
PyErr_SetFromErrno(PyExc_OSError);
return -1;
}
return 0;
#endif
}
/* Make the file descriptor non-inheritable.
Return 0 on success, set errno and return -1 on error. */
static int
make_non_inheritable(int fd)
{
return set_inheritable(fd, 0, 0, NULL);
}
/* Set the inheritable flag of the specified file descriptor.
On success: return 0, on error: raise an exception if raise is nonzero
and return -1.
If atomic_flag_works is not NULL:
* if *atomic_flag_works==-1, check if the inheritable is set on the file
descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
set the inheritable flag
* if *atomic_flag_works==1: do nothing
* if *atomic_flag_works==0: set inheritable flag to False
Set atomic_flag_works to NULL if no atomic flag was used to create the
file descriptor.
atomic_flag_works can only be used to make a file descriptor
non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
int
_Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
{
return set_inheritable(fd, inheritable, 1, atomic_flag_works);
}
static int
_Py_open_impl(const char *pathname, int flags, int gil_held)
{
int fd;
int async_err = 0;
#ifndef MS_WINDOWS
int *atomic_flag_works;
#endif
#ifdef MS_WINDOWS
flags |= O_NOINHERIT;
#elif defined(O_CLOEXEC)
atomic_flag_works = &_Py_open_cloexec_works;
flags |= O_CLOEXEC;
#else
atomic_flag_works = NULL;
#endif
if (gil_held) {
do {
Py_BEGIN_ALLOW_THREADS
fd = open(pathname, flags);
Py_END_ALLOW_THREADS
} while (fd < 0
&& errno == EINTR && !(async_err = PyErr_CheckSignals()));
if (async_err)
return -1;
if (fd < 0) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, pathname);
return -1;
}
}
else {
fd = open(pathname, flags);
if (fd < 0)
return -1;
}
#ifndef MS_WINDOWS
if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
close(fd);
return -1;
}
#endif
return fd;
}
/* Open a file with the specified flags (wrapper to open() function).
Return a file descriptor on success. Raise an exception and return -1 on
error.
The file descriptor is created non-inheritable.
When interrupted by a signal (open() fails with EINTR), retry the syscall,
except if the Python signal handler raises an exception.
Release the GIL to call open(). The caller must hold the GIL. */
int
_Py_open(const char *pathname, int flags)
{
/* _Py_open() must be called with the GIL held. */