fileutils.c 81 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942
  1. #include "Python.h"
  2. #include "pycore_fileutils.h" // fileutils definitions
  3. #include "pycore_runtime.h" // _PyRuntime
  4. #include "osdefs.h" // SEP
  5. #include <locale.h>
  6. #include <stdlib.h> // mbstowcs()
  7. #ifdef MS_WINDOWS
  8. # include <malloc.h>
  9. # include <windows.h>
  10. # include <winioctl.h> // FILE_DEVICE_* constants
  11. # include "pycore_fileutils_windows.h" // FILE_STAT_BASIC_INFORMATION
  12. # if defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP)
  13. # define PATHCCH_ALLOW_LONG_PATHS 0x01
  14. # else
  15. # include <pathcch.h> // PathCchCombineEx
  16. # endif
  17. extern int winerror_to_errno(int);
  18. #endif
  19. #ifdef HAVE_LANGINFO_H
  20. #include <langinfo.h>
  21. #endif
  22. #ifdef HAVE_SYS_IOCTL_H
  23. #include <sys/ioctl.h>
  24. #endif
  25. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  26. #error #include <iconv.h>
  27. #endif
  28. #ifdef HAVE_FCNTL_H
  29. #include <fcntl.h>
  30. #endif /* HAVE_FCNTL_H */
  31. #ifdef O_CLOEXEC
  32. /* Does open() support the O_CLOEXEC flag? Possible values:
  33. -1: unknown
  34. 0: open() ignores O_CLOEXEC flag, ex: Linux kernel older than 2.6.23
  35. 1: open() supports O_CLOEXEC flag, close-on-exec is set
  36. The flag is used by _Py_open(), _Py_open_noraise(), io.FileIO
  37. and os.open(). */
  38. int _Py_open_cloexec_works = -1;
  39. #endif
  40. // The value must be the same in unicodeobject.c.
  41. #define MAX_UNICODE 0x10ffff
  42. // mbstowcs() and mbrtowc() errors
  43. static const size_t DECODE_ERROR = ((size_t)-1);
  44. static const size_t INCOMPLETE_CHARACTER = (size_t)-2;
  45. static int
  46. get_surrogateescape(_Py_error_handler errors, int *surrogateescape)
  47. {
  48. switch (errors)
  49. {
  50. case _Py_ERROR_STRICT:
  51. *surrogateescape = 0;
  52. return 0;
  53. case _Py_ERROR_SURROGATEESCAPE:
  54. *surrogateescape = 1;
  55. return 0;
  56. default:
  57. return -1;
  58. }
  59. }
  60. PyObject *
  61. _Py_device_encoding(int fd)
  62. {
  63. int valid;
  64. Py_BEGIN_ALLOW_THREADS
  65. _Py_BEGIN_SUPPRESS_IPH
  66. valid = isatty(fd);
  67. _Py_END_SUPPRESS_IPH
  68. Py_END_ALLOW_THREADS
  69. if (!valid)
  70. Py_RETURN_NONE;
  71. #ifdef MS_WINDOWS
  72. #ifdef HAVE_WINDOWS_CONSOLE_IO
  73. UINT cp;
  74. if (fd == 0)
  75. cp = GetConsoleCP();
  76. else if (fd == 1 || fd == 2)
  77. cp = GetConsoleOutputCP();
  78. else
  79. cp = 0;
  80. /* GetConsoleCP() and GetConsoleOutputCP() return 0 if the application
  81. has no console */
  82. if (cp == 0) {
  83. Py_RETURN_NONE;
  84. }
  85. return PyUnicode_FromFormat("cp%u", (unsigned int)cp);
  86. #else
  87. Py_RETURN_NONE;
  88. #endif /* HAVE_WINDOWS_CONSOLE_IO */
  89. #else
  90. if (_PyRuntime.preconfig.utf8_mode) {
  91. _Py_DECLARE_STR(utf_8, "utf-8");
  92. return Py_NewRef(&_Py_STR(utf_8));
  93. }
  94. return _Py_GetLocaleEncodingObject();
  95. #endif
  96. }
  97. static size_t
  98. is_valid_wide_char(wchar_t ch)
  99. {
  100. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  101. /* Oracle Solaris doesn't use Unicode code points as wchar_t encoding
  102. for non-Unicode locales, which makes values higher than MAX_UNICODE
  103. possibly valid. */
  104. return 1;
  105. #endif
  106. if (Py_UNICODE_IS_SURROGATE(ch)) {
  107. // Reject lone surrogate characters
  108. return 0;
  109. }
  110. if (ch > MAX_UNICODE) {
  111. // bpo-35883: Reject characters outside [U+0000; U+10ffff] range.
  112. // The glibc mbstowcs() UTF-8 decoder does not respect the RFC 3629,
  113. // it creates characters outside the [U+0000; U+10ffff] range:
  114. // https://sourceware.org/bugzilla/show_bug.cgi?id=2373
  115. return 0;
  116. }
  117. return 1;
  118. }
  119. static size_t
  120. _Py_mbstowcs(wchar_t *dest, const char *src, size_t n)
  121. {
  122. size_t count = mbstowcs(dest, src, n);
  123. if (dest != NULL && count != DECODE_ERROR) {
  124. for (size_t i=0; i < count; i++) {
  125. wchar_t ch = dest[i];
  126. if (!is_valid_wide_char(ch)) {
  127. return DECODE_ERROR;
  128. }
  129. }
  130. }
  131. return count;
  132. }
  133. #ifdef HAVE_MBRTOWC
  134. static size_t
  135. _Py_mbrtowc(wchar_t *pwc, const char *str, size_t len, mbstate_t *pmbs)
  136. {
  137. assert(pwc != NULL);
  138. size_t count = mbrtowc(pwc, str, len, pmbs);
  139. if (count != 0 && count != DECODE_ERROR && count != INCOMPLETE_CHARACTER) {
  140. if (!is_valid_wide_char(*pwc)) {
  141. return DECODE_ERROR;
  142. }
  143. }
  144. return count;
  145. }
  146. #endif
  147. #if !defined(_Py_FORCE_UTF8_FS_ENCODING) && !defined(MS_WINDOWS)
  148. #define USE_FORCE_ASCII
  149. extern int _Py_normalize_encoding(const char *, char *, size_t);
  150. /* Workaround FreeBSD and OpenIndiana locale encoding issue with the C locale
  151. and POSIX locale. nl_langinfo(CODESET) announces an alias of the
  152. ASCII encoding, whereas mbstowcs() and wcstombs() functions use the
  153. ISO-8859-1 encoding. The problem is that os.fsencode() and os.fsdecode() use
  154. locale.getpreferredencoding() codec. For example, if command line arguments
  155. are decoded by mbstowcs() and encoded back by os.fsencode(), we get a
  156. UnicodeEncodeError instead of retrieving the original byte string.
  157. The workaround is enabled if setlocale(LC_CTYPE, NULL) returns "C",
  158. nl_langinfo(CODESET) announces "ascii" (or an alias to ASCII), and at least
  159. one byte in range 0x80-0xff can be decoded from the locale encoding. The
  160. workaround is also enabled on error, for example if getting the locale
  161. failed.
  162. On HP-UX with the C locale or the POSIX locale, nl_langinfo(CODESET)
  163. announces "roman8" but mbstowcs() uses Latin1 in practice. Force also the
  164. ASCII encoding in this case.
  165. Values of force_ascii:
  166. 1: the workaround is used: Py_EncodeLocale() uses
  167. encode_ascii_surrogateescape() and Py_DecodeLocale() uses
  168. decode_ascii()
  169. 0: the workaround is not used: Py_EncodeLocale() uses wcstombs() and
  170. Py_DecodeLocale() uses mbstowcs()
  171. -1: unknown, need to call check_force_ascii() to get the value
  172. */
  173. #define force_ascii (_PyRuntime.fileutils.force_ascii)
  174. static int
  175. check_force_ascii(void)
  176. {
  177. char *loc = setlocale(LC_CTYPE, NULL);
  178. if (loc == NULL) {
  179. goto error;
  180. }
  181. if (strcmp(loc, "C") != 0 && strcmp(loc, "POSIX") != 0) {
  182. /* the LC_CTYPE locale is different than C and POSIX */
  183. return 0;
  184. }
  185. #if defined(HAVE_LANGINFO_H) && defined(CODESET)
  186. const char *codeset = nl_langinfo(CODESET);
  187. if (!codeset || codeset[0] == '\0') {
  188. /* CODESET is not set or empty */
  189. goto error;
  190. }
  191. char encoding[20]; /* longest name: "iso_646.irv_1991\0" */
  192. if (!_Py_normalize_encoding(codeset, encoding, sizeof(encoding))) {
  193. goto error;
  194. }
  195. #ifdef __hpux
  196. if (strcmp(encoding, "roman8") == 0) {
  197. unsigned char ch;
  198. wchar_t wch;
  199. size_t res;
  200. ch = (unsigned char)0xA7;
  201. res = _Py_mbstowcs(&wch, (char*)&ch, 1);
  202. if (res != DECODE_ERROR && wch == L'\xA7') {
  203. /* On HP-UX with C locale or the POSIX locale,
  204. nl_langinfo(CODESET) announces "roman8", whereas mbstowcs() uses
  205. Latin1 encoding in practice. Force ASCII in this case.
  206. Roman8 decodes 0xA7 to U+00CF. Latin1 decodes 0xA7 to U+00A7. */
  207. return 1;
  208. }
  209. }
  210. #else
  211. const char* ascii_aliases[] = {
  212. "ascii",
  213. /* Aliases from Lib/encodings/aliases.py */
  214. "646",
  215. "ansi_x3.4_1968",
  216. "ansi_x3.4_1986",
  217. "ansi_x3_4_1968",
  218. "cp367",
  219. "csascii",
  220. "ibm367",
  221. "iso646_us",
  222. "iso_646.irv_1991",
  223. "iso_ir_6",
  224. "us",
  225. "us_ascii",
  226. NULL
  227. };
  228. int is_ascii = 0;
  229. for (const char **alias=ascii_aliases; *alias != NULL; alias++) {
  230. if (strcmp(encoding, *alias) == 0) {
  231. is_ascii = 1;
  232. break;
  233. }
  234. }
  235. if (!is_ascii) {
  236. /* nl_langinfo(CODESET) is not "ascii" or an alias of ASCII */
  237. return 0;
  238. }
  239. for (unsigned int i=0x80; i<=0xff; i++) {
  240. char ch[1];
  241. wchar_t wch[1];
  242. size_t res;
  243. unsigned uch = (unsigned char)i;
  244. ch[0] = (char)uch;
  245. res = _Py_mbstowcs(wch, ch, 1);
  246. if (res != DECODE_ERROR) {
  247. /* decoding a non-ASCII character from the locale encoding succeed:
  248. the locale encoding is not ASCII, force ASCII */
  249. return 1;
  250. }
  251. }
  252. /* None of the bytes in the range 0x80-0xff can be decoded from the locale
  253. encoding: the locale encoding is really ASCII */
  254. #endif /* !defined(__hpux) */
  255. return 0;
  256. #else
  257. /* nl_langinfo(CODESET) is not available: always force ASCII */
  258. return 1;
  259. #endif /* defined(HAVE_LANGINFO_H) && defined(CODESET) */
  260. error:
  261. /* if an error occurred, force the ASCII encoding */
  262. return 1;
  263. }
  264. int
  265. _Py_GetForceASCII(void)
  266. {
  267. if (force_ascii == -1) {
  268. force_ascii = check_force_ascii();
  269. }
  270. return force_ascii;
  271. }
  272. void
  273. _Py_ResetForceASCII(void)
  274. {
  275. force_ascii = -1;
  276. }
  277. static int
  278. encode_ascii(const wchar_t *text, char **str,
  279. size_t *error_pos, const char **reason,
  280. int raw_malloc, _Py_error_handler errors)
  281. {
  282. char *result = NULL, *out;
  283. size_t len, i;
  284. wchar_t ch;
  285. int surrogateescape;
  286. if (get_surrogateescape(errors, &surrogateescape) < 0) {
  287. return -3;
  288. }
  289. len = wcslen(text);
  290. /* +1 for NULL byte */
  291. if (raw_malloc) {
  292. result = PyMem_RawMalloc(len + 1);
  293. }
  294. else {
  295. result = PyMem_Malloc(len + 1);
  296. }
  297. if (result == NULL) {
  298. return -1;
  299. }
  300. out = result;
  301. for (i=0; i<len; i++) {
  302. ch = text[i];
  303. if (ch <= 0x7f) {
  304. /* ASCII character */
  305. *out++ = (char)ch;
  306. }
  307. else if (surrogateescape && 0xdc80 <= ch && ch <= 0xdcff) {
  308. /* UTF-8b surrogate */
  309. *out++ = (char)(ch - 0xdc00);
  310. }
  311. else {
  312. if (raw_malloc) {
  313. PyMem_RawFree(result);
  314. }
  315. else {
  316. PyMem_Free(result);
  317. }
  318. if (error_pos != NULL) {
  319. *error_pos = i;
  320. }
  321. if (reason) {
  322. *reason = "encoding error";
  323. }
  324. return -2;
  325. }
  326. }
  327. *out = '\0';
  328. *str = result;
  329. return 0;
  330. }
  331. #else
  332. int
  333. _Py_GetForceASCII(void)
  334. {
  335. return 0;
  336. }
  337. void
  338. _Py_ResetForceASCII(void)
  339. {
  340. /* nothing to do */
  341. }
  342. #endif /* !defined(_Py_FORCE_UTF8_FS_ENCODING) && !defined(MS_WINDOWS) */
  343. #if !defined(HAVE_MBRTOWC) || defined(USE_FORCE_ASCII)
  344. static int
  345. decode_ascii(const char *arg, wchar_t **wstr, size_t *wlen,
  346. const char **reason, _Py_error_handler errors)
  347. {
  348. wchar_t *res;
  349. unsigned char *in;
  350. wchar_t *out;
  351. size_t argsize = strlen(arg) + 1;
  352. int surrogateescape;
  353. if (get_surrogateescape(errors, &surrogateescape) < 0) {
  354. return -3;
  355. }
  356. if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  357. return -1;
  358. }
  359. res = PyMem_RawMalloc(argsize * sizeof(wchar_t));
  360. if (!res) {
  361. return -1;
  362. }
  363. out = res;
  364. for (in = (unsigned char*)arg; *in; in++) {
  365. unsigned char ch = *in;
  366. if (ch < 128) {
  367. *out++ = ch;
  368. }
  369. else {
  370. if (!surrogateescape) {
  371. PyMem_RawFree(res);
  372. if (wlen) {
  373. *wlen = in - (unsigned char*)arg;
  374. }
  375. if (reason) {
  376. *reason = "decoding error";
  377. }
  378. return -2;
  379. }
  380. *out++ = 0xdc00 + ch;
  381. }
  382. }
  383. *out = 0;
  384. if (wlen != NULL) {
  385. *wlen = out - res;
  386. }
  387. *wstr = res;
  388. return 0;
  389. }
  390. #endif /* !HAVE_MBRTOWC */
  391. static int
  392. decode_current_locale(const char* arg, wchar_t **wstr, size_t *wlen,
  393. const char **reason, _Py_error_handler errors)
  394. {
  395. wchar_t *res;
  396. size_t argsize;
  397. size_t count;
  398. #ifdef HAVE_MBRTOWC
  399. unsigned char *in;
  400. wchar_t *out;
  401. mbstate_t mbs;
  402. #endif
  403. int surrogateescape;
  404. if (get_surrogateescape(errors, &surrogateescape) < 0) {
  405. return -3;
  406. }
  407. #ifdef HAVE_BROKEN_MBSTOWCS
  408. /* Some platforms have a broken implementation of
  409. * mbstowcs which does not count the characters that
  410. * would result from conversion. Use an upper bound.
  411. */
  412. argsize = strlen(arg);
  413. #else
  414. argsize = _Py_mbstowcs(NULL, arg, 0);
  415. #endif
  416. if (argsize != DECODE_ERROR) {
  417. if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t) - 1) {
  418. return -1;
  419. }
  420. res = (wchar_t *)PyMem_RawMalloc((argsize + 1) * sizeof(wchar_t));
  421. if (!res) {
  422. return -1;
  423. }
  424. count = _Py_mbstowcs(res, arg, argsize + 1);
  425. if (count != DECODE_ERROR) {
  426. *wstr = res;
  427. if (wlen != NULL) {
  428. *wlen = count;
  429. }
  430. return 0;
  431. }
  432. PyMem_RawFree(res);
  433. }
  434. /* Conversion failed. Fall back to escaping with surrogateescape. */
  435. #ifdef HAVE_MBRTOWC
  436. /* Try conversion with mbrtwoc (C99), and escape non-decodable bytes. */
  437. /* Overallocate; as multi-byte characters are in the argument, the
  438. actual output could use less memory. */
  439. argsize = strlen(arg) + 1;
  440. if (argsize > PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  441. return -1;
  442. }
  443. res = (wchar_t*)PyMem_RawMalloc(argsize * sizeof(wchar_t));
  444. if (!res) {
  445. return -1;
  446. }
  447. in = (unsigned char*)arg;
  448. out = res;
  449. memset(&mbs, 0, sizeof mbs);
  450. while (argsize) {
  451. size_t converted = _Py_mbrtowc(out, (char*)in, argsize, &mbs);
  452. if (converted == 0) {
  453. /* Reached end of string; null char stored. */
  454. break;
  455. }
  456. if (converted == INCOMPLETE_CHARACTER) {
  457. /* Incomplete character. This should never happen,
  458. since we provide everything that we have -
  459. unless there is a bug in the C library, or I
  460. misunderstood how mbrtowc works. */
  461. goto decode_error;
  462. }
  463. if (converted == DECODE_ERROR) {
  464. if (!surrogateescape) {
  465. goto decode_error;
  466. }
  467. /* Decoding error. Escape as UTF-8b, and start over in the initial
  468. shift state. */
  469. *out++ = 0xdc00 + *in++;
  470. argsize--;
  471. memset(&mbs, 0, sizeof mbs);
  472. continue;
  473. }
  474. // _Py_mbrtowc() reject lone surrogate characters
  475. assert(!Py_UNICODE_IS_SURROGATE(*out));
  476. /* successfully converted some bytes */
  477. in += converted;
  478. argsize -= converted;
  479. out++;
  480. }
  481. if (wlen != NULL) {
  482. *wlen = out - res;
  483. }
  484. *wstr = res;
  485. return 0;
  486. decode_error:
  487. PyMem_RawFree(res);
  488. if (wlen) {
  489. *wlen = in - (unsigned char*)arg;
  490. }
  491. if (reason) {
  492. *reason = "decoding error";
  493. }
  494. return -2;
  495. #else /* HAVE_MBRTOWC */
  496. /* Cannot use C locale for escaping; manually escape as if charset
  497. is ASCII (i.e. escape all bytes > 128. This will still roundtrip
  498. correctly in the locale's charset, which must be an ASCII superset. */
  499. return decode_ascii(arg, wstr, wlen, reason, errors);
  500. #endif /* HAVE_MBRTOWC */
  501. }
  502. /* Decode a byte string from the locale encoding.
  503. Use the strict error handler if 'surrogateescape' is zero. Use the
  504. surrogateescape error handler if 'surrogateescape' is non-zero: undecodable
  505. bytes are decoded as characters in range U+DC80..U+DCFF. If a byte sequence
  506. can be decoded as a surrogate character, escape the bytes using the
  507. surrogateescape error handler instead of decoding them.
  508. On success, return 0 and write the newly allocated wide character string into
  509. *wstr (use PyMem_RawFree() to free the memory). If wlen is not NULL, write
  510. the number of wide characters excluding the null character into *wlen.
  511. On memory allocation failure, return -1.
  512. On decoding error, return -2. If wlen is not NULL, write the start of
  513. invalid byte sequence in the input string into *wlen. If reason is not NULL,
  514. write the decoding error message into *reason.
  515. Return -3 if the error handler 'errors' is not supported.
  516. Use the Py_EncodeLocaleEx() function to encode the character string back to
  517. a byte string. */
  518. int
  519. _Py_DecodeLocaleEx(const char* arg, wchar_t **wstr, size_t *wlen,
  520. const char **reason,
  521. int current_locale, _Py_error_handler errors)
  522. {
  523. if (current_locale) {
  524. #ifdef _Py_FORCE_UTF8_LOCALE
  525. return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
  526. errors);
  527. #else
  528. return decode_current_locale(arg, wstr, wlen, reason, errors);
  529. #endif
  530. }
  531. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  532. return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
  533. errors);
  534. #else
  535. int use_utf8 = (_PyRuntime.preconfig.utf8_mode >= 1);
  536. #ifdef MS_WINDOWS
  537. use_utf8 |= (_PyRuntime.preconfig.legacy_windows_fs_encoding == 0);
  538. #endif
  539. if (use_utf8) {
  540. return _Py_DecodeUTF8Ex(arg, strlen(arg), wstr, wlen, reason,
  541. errors);
  542. }
  543. #ifdef USE_FORCE_ASCII
  544. if (force_ascii == -1) {
  545. force_ascii = check_force_ascii();
  546. }
  547. if (force_ascii) {
  548. /* force ASCII encoding to workaround mbstowcs() issue */
  549. return decode_ascii(arg, wstr, wlen, reason, errors);
  550. }
  551. #endif
  552. return decode_current_locale(arg, wstr, wlen, reason, errors);
  553. #endif /* !_Py_FORCE_UTF8_FS_ENCODING */
  554. }
  555. /* Decode a byte string from the locale encoding with the
  556. surrogateescape error handler: undecodable bytes are decoded as characters
  557. in range U+DC80..U+DCFF. If a byte sequence can be decoded as a surrogate
  558. character, escape the bytes using the surrogateescape error handler instead
  559. of decoding them.
  560. Return a pointer to a newly allocated wide character string, use
  561. PyMem_RawFree() to free the memory. If size is not NULL, write the number of
  562. wide characters excluding the null character into *size
  563. Return NULL on decoding error or memory allocation error. If *size* is not
  564. NULL, *size is set to (size_t)-1 on memory error or set to (size_t)-2 on
  565. decoding error.
  566. Decoding errors should never happen, unless there is a bug in the C
  567. library.
  568. Use the Py_EncodeLocale() function to encode the character string back to a
  569. byte string. */
  570. wchar_t*
  571. Py_DecodeLocale(const char* arg, size_t *wlen)
  572. {
  573. wchar_t *wstr;
  574. int res = _Py_DecodeLocaleEx(arg, &wstr, wlen,
  575. NULL, 0,
  576. _Py_ERROR_SURROGATEESCAPE);
  577. if (res != 0) {
  578. assert(res != -3);
  579. if (wlen != NULL) {
  580. *wlen = (size_t)res;
  581. }
  582. return NULL;
  583. }
  584. return wstr;
  585. }
  586. static int
  587. encode_current_locale(const wchar_t *text, char **str,
  588. size_t *error_pos, const char **reason,
  589. int raw_malloc, _Py_error_handler errors)
  590. {
  591. const size_t len = wcslen(text);
  592. char *result = NULL, *bytes = NULL;
  593. size_t i, size, converted;
  594. wchar_t c, buf[2];
  595. int surrogateescape;
  596. if (get_surrogateescape(errors, &surrogateescape) < 0) {
  597. return -3;
  598. }
  599. /* The function works in two steps:
  600. 1. compute the length of the output buffer in bytes (size)
  601. 2. outputs the bytes */
  602. size = 0;
  603. buf[1] = 0;
  604. while (1) {
  605. for (i=0; i < len; i++) {
  606. c = text[i];
  607. if (c >= 0xdc80 && c <= 0xdcff) {
  608. if (!surrogateescape) {
  609. goto encode_error;
  610. }
  611. /* UTF-8b surrogate */
  612. if (bytes != NULL) {
  613. *bytes++ = c - 0xdc00;
  614. size--;
  615. }
  616. else {
  617. size++;
  618. }
  619. continue;
  620. }
  621. else {
  622. buf[0] = c;
  623. if (bytes != NULL) {
  624. converted = wcstombs(bytes, buf, size);
  625. }
  626. else {
  627. converted = wcstombs(NULL, buf, 0);
  628. }
  629. if (converted == DECODE_ERROR) {
  630. goto encode_error;
  631. }
  632. if (bytes != NULL) {
  633. bytes += converted;
  634. size -= converted;
  635. }
  636. else {
  637. size += converted;
  638. }
  639. }
  640. }
  641. if (result != NULL) {
  642. *bytes = '\0';
  643. break;
  644. }
  645. size += 1; /* nul byte at the end */
  646. if (raw_malloc) {
  647. result = PyMem_RawMalloc(size);
  648. }
  649. else {
  650. result = PyMem_Malloc(size);
  651. }
  652. if (result == NULL) {
  653. return -1;
  654. }
  655. bytes = result;
  656. }
  657. *str = result;
  658. return 0;
  659. encode_error:
  660. if (raw_malloc) {
  661. PyMem_RawFree(result);
  662. }
  663. else {
  664. PyMem_Free(result);
  665. }
  666. if (error_pos != NULL) {
  667. *error_pos = i;
  668. }
  669. if (reason) {
  670. *reason = "encoding error";
  671. }
  672. return -2;
  673. }
  674. /* Encode a string to the locale encoding.
  675. Parameters:
  676. * raw_malloc: if non-zero, allocate memory using PyMem_RawMalloc() instead
  677. of PyMem_Malloc().
  678. * current_locale: if non-zero, use the current LC_CTYPE, otherwise use
  679. Python filesystem encoding.
  680. * errors: error handler like "strict" or "surrogateescape".
  681. Return value:
  682. 0: success, *str is set to a newly allocated decoded string.
  683. -1: memory allocation failure
  684. -2: encoding error, set *error_pos and *reason (if set).
  685. -3: the error handler 'errors' is not supported.
  686. */
  687. static int
  688. encode_locale_ex(const wchar_t *text, char **str, size_t *error_pos,
  689. const char **reason,
  690. int raw_malloc, int current_locale, _Py_error_handler errors)
  691. {
  692. if (current_locale) {
  693. #ifdef _Py_FORCE_UTF8_LOCALE
  694. return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
  695. raw_malloc, errors);
  696. #else
  697. return encode_current_locale(text, str, error_pos, reason,
  698. raw_malloc, errors);
  699. #endif
  700. }
  701. #ifdef _Py_FORCE_UTF8_FS_ENCODING
  702. return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
  703. raw_malloc, errors);
  704. #else
  705. int use_utf8 = (_PyRuntime.preconfig.utf8_mode >= 1);
  706. #ifdef MS_WINDOWS
  707. use_utf8 |= (_PyRuntime.preconfig.legacy_windows_fs_encoding == 0);
  708. #endif
  709. if (use_utf8) {
  710. return _Py_EncodeUTF8Ex(text, str, error_pos, reason,
  711. raw_malloc, errors);
  712. }
  713. #ifdef USE_FORCE_ASCII
  714. if (force_ascii == -1) {
  715. force_ascii = check_force_ascii();
  716. }
  717. if (force_ascii) {
  718. return encode_ascii(text, str, error_pos, reason,
  719. raw_malloc, errors);
  720. }
  721. #endif
  722. return encode_current_locale(text, str, error_pos, reason,
  723. raw_malloc, errors);
  724. #endif /* _Py_FORCE_UTF8_FS_ENCODING */
  725. }
  726. static char*
  727. encode_locale(const wchar_t *text, size_t *error_pos,
  728. int raw_malloc, int current_locale)
  729. {
  730. char *str;
  731. int res = encode_locale_ex(text, &str, error_pos, NULL,
  732. raw_malloc, current_locale,
  733. _Py_ERROR_SURROGATEESCAPE);
  734. if (res != -2 && error_pos) {
  735. *error_pos = (size_t)-1;
  736. }
  737. if (res != 0) {
  738. return NULL;
  739. }
  740. return str;
  741. }
  742. /* Encode a wide character string to the locale encoding with the
  743. surrogateescape error handler: surrogate characters in the range
  744. U+DC80..U+DCFF are converted to bytes 0x80..0xFF.
  745. Return a pointer to a newly allocated byte string, use PyMem_Free() to free
  746. the memory. Return NULL on encoding or memory allocation error.
  747. If error_pos is not NULL, *error_pos is set to (size_t)-1 on success, or set
  748. to the index of the invalid character on encoding error.
  749. Use the Py_DecodeLocale() function to decode the bytes string back to a wide
  750. character string. */
  751. char*
  752. Py_EncodeLocale(const wchar_t *text, size_t *error_pos)
  753. {
  754. return encode_locale(text, error_pos, 0, 0);
  755. }
  756. /* Similar to Py_EncodeLocale(), but result must be freed by PyMem_RawFree()
  757. instead of PyMem_Free(). */
  758. char*
  759. _Py_EncodeLocaleRaw(const wchar_t *text, size_t *error_pos)
  760. {
  761. return encode_locale(text, error_pos, 1, 0);
  762. }
  763. int
  764. _Py_EncodeLocaleEx(const wchar_t *text, char **str,
  765. size_t *error_pos, const char **reason,
  766. int current_locale, _Py_error_handler errors)
  767. {
  768. return encode_locale_ex(text, str, error_pos, reason, 1,
  769. current_locale, errors);
  770. }
  771. // Get the current locale encoding name:
  772. //
  773. // - Return "utf-8" if _Py_FORCE_UTF8_LOCALE macro is defined (ex: on Android)
  774. // - Return "utf-8" if the UTF-8 Mode is enabled
  775. // - On Windows, return the ANSI code page (ex: "cp1250")
  776. // - Return "utf-8" if nl_langinfo(CODESET) returns an empty string.
  777. // - Otherwise, return nl_langinfo(CODESET).
  778. //
  779. // Return NULL on memory allocation failure.
  780. //
  781. // See also config_get_locale_encoding()
  782. wchar_t*
  783. _Py_GetLocaleEncoding(void)
  784. {
  785. #ifdef _Py_FORCE_UTF8_LOCALE
  786. // On Android langinfo.h and CODESET are missing,
  787. // and UTF-8 is always used in mbstowcs() and wcstombs().
  788. return _PyMem_RawWcsdup(L"utf-8");
  789. #else
  790. #ifdef MS_WINDOWS
  791. wchar_t encoding[23];
  792. unsigned int ansi_codepage = GetACP();
  793. swprintf(encoding, Py_ARRAY_LENGTH(encoding), L"cp%u", ansi_codepage);
  794. encoding[Py_ARRAY_LENGTH(encoding) - 1] = 0;
  795. return _PyMem_RawWcsdup(encoding);
  796. #else
  797. const char *encoding = nl_langinfo(CODESET);
  798. if (!encoding || encoding[0] == '\0') {
  799. // Use UTF-8 if nl_langinfo() returns an empty string. It can happen on
  800. // macOS if the LC_CTYPE locale is not supported.
  801. return _PyMem_RawWcsdup(L"utf-8");
  802. }
  803. wchar_t *wstr;
  804. int res = decode_current_locale(encoding, &wstr, NULL,
  805. NULL, _Py_ERROR_SURROGATEESCAPE);
  806. if (res < 0) {
  807. return NULL;
  808. }
  809. return wstr;
  810. #endif // !MS_WINDOWS
  811. #endif // !_Py_FORCE_UTF8_LOCALE
  812. }
  813. PyObject *
  814. _Py_GetLocaleEncodingObject(void)
  815. {
  816. wchar_t *encoding = _Py_GetLocaleEncoding();
  817. if (encoding == NULL) {
  818. PyErr_NoMemory();
  819. return NULL;
  820. }
  821. PyObject *str = PyUnicode_FromWideChar(encoding, -1);
  822. PyMem_RawFree(encoding);
  823. return str;
  824. }
  825. #ifdef HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION
  826. /* Check whether current locale uses Unicode as internal wchar_t form. */
  827. int
  828. _Py_LocaleUsesNonUnicodeWchar(void)
  829. {
  830. /* Oracle Solaris uses non-Unicode internal wchar_t form for
  831. non-Unicode locales and hence needs conversion to UTF first. */
  832. char* codeset = nl_langinfo(CODESET);
  833. if (!codeset) {
  834. return 0;
  835. }
  836. /* 646 refers to ISO/IEC 646 standard that corresponds to ASCII encoding */
  837. return (strcmp(codeset, "UTF-8") != 0 && strcmp(codeset, "646") != 0);
  838. }
  839. static wchar_t *
  840. _Py_ConvertWCharForm(const wchar_t *source, Py_ssize_t size,
  841. const char *tocode, const char *fromcode)
  842. {
  843. static_assert(sizeof(wchar_t) == 4, "wchar_t must be 32-bit");
  844. /* Ensure we won't overflow the size. */
  845. if (size > (PY_SSIZE_T_MAX / (Py_ssize_t)sizeof(wchar_t))) {
  846. PyErr_NoMemory();
  847. return NULL;
  848. }
  849. /* the string doesn't have to be NULL terminated */
  850. wchar_t* target = PyMem_Malloc(size * sizeof(wchar_t));
  851. if (target == NULL) {
  852. PyErr_NoMemory();
  853. return NULL;
  854. }
  855. iconv_t cd = iconv_open(tocode, fromcode);
  856. if (cd == (iconv_t)-1) {
  857. PyErr_Format(PyExc_ValueError, "iconv_open() failed");
  858. PyMem_Free(target);
  859. return NULL;
  860. }
  861. char *inbuf = (char *) source;
  862. char *outbuf = (char *) target;
  863. size_t inbytesleft = sizeof(wchar_t) * size;
  864. size_t outbytesleft = inbytesleft;
  865. size_t ret = iconv(cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
  866. if (ret == DECODE_ERROR) {
  867. PyErr_Format(PyExc_ValueError, "iconv() failed");
  868. PyMem_Free(target);
  869. iconv_close(cd);
  870. return NULL;
  871. }
  872. iconv_close(cd);
  873. return target;
  874. }
  875. /* Convert a wide character string to the UCS-4 encoded string. This
  876. is necessary on systems where internal form of wchar_t are not Unicode
  877. code points (e.g. Oracle Solaris).
  878. Return a pointer to a newly allocated string, use PyMem_Free() to free
  879. the memory. Return NULL and raise exception on conversion or memory
  880. allocation error. */
  881. wchar_t *
  882. _Py_DecodeNonUnicodeWchar(const wchar_t *native, Py_ssize_t size)
  883. {
  884. return _Py_ConvertWCharForm(native, size, "UCS-4-INTERNAL", "wchar_t");
  885. }
  886. /* Convert a UCS-4 encoded string to native wide character string. This
  887. is necessary on systems where internal form of wchar_t are not Unicode
  888. code points (e.g. Oracle Solaris).
  889. The conversion is done in place. This can be done because both wchar_t
  890. and UCS-4 use 4-byte encoding, and one wchar_t symbol always correspond
  891. to a single UCS-4 symbol and vice versa. (This is true for Oracle Solaris,
  892. which is currently the only system using these functions; it doesn't have
  893. to be for other systems).
  894. Return 0 on success. Return -1 and raise exception on conversion
  895. or memory allocation error. */
  896. int
  897. _Py_EncodeNonUnicodeWchar_InPlace(wchar_t *unicode, Py_ssize_t size)
  898. {
  899. wchar_t* result = _Py_ConvertWCharForm(unicode, size, "wchar_t", "UCS-4-INTERNAL");
  900. if (!result) {
  901. return -1;
  902. }
  903. memcpy(unicode, result, size * sizeof(wchar_t));
  904. PyMem_Free(result);
  905. return 0;
  906. }
  907. #endif /* HAVE_NON_UNICODE_WCHAR_T_REPRESENTATION */
  908. #ifdef MS_WINDOWS
  909. static __int64 secs_between_epochs = 11644473600; /* Seconds between 1.1.1601 and 1.1.1970 */
  910. static void
  911. FILE_TIME_to_time_t_nsec(FILETIME *in_ptr, time_t *time_out, int* nsec_out)
  912. {
  913. /* XXX endianness. Shouldn't matter, as all Windows implementations are little-endian */
  914. /* Cannot simply cast and dereference in_ptr,
  915. since it might not be aligned properly */
  916. __int64 in;
  917. memcpy(&in, in_ptr, sizeof(in));
  918. *nsec_out = (int)(in % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
  919. *time_out = Py_SAFE_DOWNCAST((in / 10000000) - secs_between_epochs, __int64, time_t);
  920. }
  921. static void
  922. LARGE_INTEGER_to_time_t_nsec(LARGE_INTEGER *in_ptr, time_t *time_out, int* nsec_out)
  923. {
  924. *nsec_out = (int)(in_ptr->QuadPart % 10000000) * 100; /* FILETIME is in units of 100 nsec. */
  925. *time_out = Py_SAFE_DOWNCAST((in_ptr->QuadPart / 10000000) - secs_between_epochs, __int64, time_t);
  926. }
  927. void
  928. _Py_time_t_to_FILE_TIME(time_t time_in, int nsec_in, FILETIME *out_ptr)
  929. {
  930. /* XXX endianness */
  931. __int64 out;
  932. out = time_in + secs_between_epochs;
  933. out = out * 10000000 + nsec_in / 100;
  934. memcpy(out_ptr, &out, sizeof(out));
  935. }
  936. /* Below, we *know* that ugo+r is 0444 */
  937. #if _S_IREAD != 0400
  938. #error Unsupported C library
  939. #endif
  940. static int
  941. attributes_to_mode(DWORD attr)
  942. {
  943. int m = 0;
  944. if (attr & FILE_ATTRIBUTE_DIRECTORY)
  945. m |= _S_IFDIR | 0111; /* IFEXEC for user,group,other */
  946. else
  947. m |= _S_IFREG;
  948. if (attr & FILE_ATTRIBUTE_READONLY)
  949. m |= 0444;
  950. else
  951. m |= 0666;
  952. return m;
  953. }
  954. typedef union {
  955. FILE_ID_128 id;
  956. struct {
  957. uint64_t st_ino;
  958. uint64_t st_ino_high;
  959. };
  960. } id_128_to_ino;
  961. void
  962. _Py_attribute_data_to_stat(BY_HANDLE_FILE_INFORMATION *info, ULONG reparse_tag,
  963. FILE_BASIC_INFO *basic_info, FILE_ID_INFO *id_info,
  964. struct _Py_stat_struct *result)
  965. {
  966. memset(result, 0, sizeof(*result));
  967. result->st_mode = attributes_to_mode(info->dwFileAttributes);
  968. result->st_size = (((__int64)info->nFileSizeHigh)<<32) + info->nFileSizeLow;
  969. result->st_dev = id_info ? id_info->VolumeSerialNumber : info->dwVolumeSerialNumber;
  970. result->st_rdev = 0;
  971. /* st_ctime is deprecated, but we preserve the legacy value in our caller, not here */
  972. if (basic_info) {
  973. LARGE_INTEGER_to_time_t_nsec(&basic_info->CreationTime, &result->st_birthtime, &result->st_birthtime_nsec);
  974. LARGE_INTEGER_to_time_t_nsec(&basic_info->ChangeTime, &result->st_ctime, &result->st_ctime_nsec);
  975. LARGE_INTEGER_to_time_t_nsec(&basic_info->LastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  976. LARGE_INTEGER_to_time_t_nsec(&basic_info->LastAccessTime, &result->st_atime, &result->st_atime_nsec);
  977. } else {
  978. FILE_TIME_to_time_t_nsec(&info->ftCreationTime, &result->st_birthtime, &result->st_birthtime_nsec);
  979. FILE_TIME_to_time_t_nsec(&info->ftLastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  980. FILE_TIME_to_time_t_nsec(&info->ftLastAccessTime, &result->st_atime, &result->st_atime_nsec);
  981. }
  982. result->st_nlink = info->nNumberOfLinks;
  983. if (id_info) {
  984. id_128_to_ino file_id;
  985. file_id.id = id_info->FileId;
  986. result->st_ino = file_id.st_ino;
  987. result->st_ino_high = file_id.st_ino_high;
  988. }
  989. if (!result->st_ino && !result->st_ino_high) {
  990. /* should only occur for DirEntry_from_find_data, in which case the
  991. index is likely to be zero anyway. */
  992. result->st_ino = (((uint64_t)info->nFileIndexHigh) << 32) + info->nFileIndexLow;
  993. }
  994. /* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will
  995. open other name surrogate reparse points without traversing them. To
  996. detect/handle these, check st_file_attributes and st_reparse_tag. */
  997. result->st_reparse_tag = reparse_tag;
  998. if (info->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
  999. reparse_tag == IO_REPARSE_TAG_SYMLINK) {
  1000. /* set the bits that make this a symlink */
  1001. result->st_mode = (result->st_mode & ~S_IFMT) | S_IFLNK;
  1002. }
  1003. result->st_file_attributes = info->dwFileAttributes;
  1004. }
  1005. void
  1006. _Py_stat_basic_info_to_stat(FILE_STAT_BASIC_INFORMATION *info,
  1007. struct _Py_stat_struct *result)
  1008. {
  1009. memset(result, 0, sizeof(*result));
  1010. result->st_mode = attributes_to_mode(info->FileAttributes);
  1011. result->st_size = info->EndOfFile.QuadPart;
  1012. LARGE_INTEGER_to_time_t_nsec(&info->CreationTime, &result->st_birthtime, &result->st_birthtime_nsec);
  1013. LARGE_INTEGER_to_time_t_nsec(&info->ChangeTime, &result->st_ctime, &result->st_ctime_nsec);
  1014. LARGE_INTEGER_to_time_t_nsec(&info->LastWriteTime, &result->st_mtime, &result->st_mtime_nsec);
  1015. LARGE_INTEGER_to_time_t_nsec(&info->LastAccessTime, &result->st_atime, &result->st_atime_nsec);
  1016. result->st_nlink = info->NumberOfLinks;
  1017. result->st_dev = info->VolumeSerialNumber.QuadPart;
  1018. /* File systems with less than 128-bits zero pad into this field */
  1019. id_128_to_ino file_id;
  1020. file_id.id = info->FileId128;
  1021. result->st_ino = file_id.st_ino;
  1022. result->st_ino_high = file_id.st_ino_high;
  1023. /* bpo-37834: Only actual symlinks set the S_IFLNK flag. But lstat() will
  1024. open other name surrogate reparse points without traversing them. To
  1025. detect/handle these, check st_file_attributes and st_reparse_tag. */
  1026. result->st_reparse_tag = info->ReparseTag;
  1027. if (info->FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT &&
  1028. info->ReparseTag == IO_REPARSE_TAG_SYMLINK) {
  1029. /* set the bits that make this a symlink */
  1030. result->st_mode = (result->st_mode & ~S_IFMT) | S_IFLNK;
  1031. }
  1032. result->st_file_attributes = info->FileAttributes;
  1033. switch (info->DeviceType) {
  1034. case FILE_DEVICE_DISK:
  1035. case FILE_DEVICE_VIRTUAL_DISK:
  1036. case FILE_DEVICE_DFS:
  1037. case FILE_DEVICE_CD_ROM:
  1038. case FILE_DEVICE_CONTROLLER:
  1039. case FILE_DEVICE_DATALINK:
  1040. break;
  1041. case FILE_DEVICE_DISK_FILE_SYSTEM:
  1042. case FILE_DEVICE_CD_ROM_FILE_SYSTEM:
  1043. case FILE_DEVICE_NETWORK_FILE_SYSTEM:
  1044. result->st_mode = (result->st_mode & ~S_IFMT) | 0x6000; /* _S_IFBLK */
  1045. break;
  1046. case FILE_DEVICE_CONSOLE:
  1047. case FILE_DEVICE_NULL:
  1048. case FILE_DEVICE_KEYBOARD:
  1049. case FILE_DEVICE_MODEM:
  1050. case FILE_DEVICE_MOUSE:
  1051. case FILE_DEVICE_PARALLEL_PORT:
  1052. case FILE_DEVICE_PRINTER:
  1053. case FILE_DEVICE_SCREEN:
  1054. case FILE_DEVICE_SERIAL_PORT:
  1055. case FILE_DEVICE_SOUND:
  1056. result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFCHR;
  1057. break;
  1058. case FILE_DEVICE_NAMED_PIPE:
  1059. result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFIFO;
  1060. break;
  1061. default:
  1062. if (info->FileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
  1063. result->st_mode = (result->st_mode & ~S_IFMT) | _S_IFDIR;
  1064. }
  1065. break;
  1066. }
  1067. }
  1068. #endif
  1069. /* Return information about a file.
  1070. On POSIX, use fstat().
  1071. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  1072. files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
  1073. than 2 GiB because the file size type is a signed 32-bit integer: see issue
  1074. #23152.
  1075. On Windows, set the last Windows error and return nonzero on error. On
  1076. POSIX, set errno and return nonzero on error. Fill status and return 0 on
  1077. success. */
  1078. int
  1079. _Py_fstat_noraise(int fd, struct _Py_stat_struct *status)
  1080. {
  1081. #ifdef MS_WINDOWS
  1082. BY_HANDLE_FILE_INFORMATION info;
  1083. FILE_BASIC_INFO basicInfo;
  1084. FILE_ID_INFO idInfo;
  1085. FILE_ID_INFO *pIdInfo = &idInfo;
  1086. HANDLE h;
  1087. int type;
  1088. h = _Py_get_osfhandle_noraise(fd);
  1089. if (h == INVALID_HANDLE_VALUE) {
  1090. /* errno is already set by _get_osfhandle, but we also set
  1091. the Win32 error for callers who expect that */
  1092. SetLastError(ERROR_INVALID_HANDLE);
  1093. return -1;
  1094. }
  1095. memset(status, 0, sizeof(*status));
  1096. type = GetFileType(h);
  1097. if (type == FILE_TYPE_UNKNOWN) {
  1098. DWORD error = GetLastError();
  1099. if (error != 0) {
  1100. errno = winerror_to_errno(error);
  1101. return -1;
  1102. }
  1103. /* else: valid but unknown file */
  1104. }
  1105. if (type != FILE_TYPE_DISK) {
  1106. if (type == FILE_TYPE_CHAR)
  1107. status->st_mode = _S_IFCHR;
  1108. else if (type == FILE_TYPE_PIPE)
  1109. status->st_mode = _S_IFIFO;
  1110. return 0;
  1111. }
  1112. if (!GetFileInformationByHandle(h, &info) ||
  1113. !GetFileInformationByHandleEx(h, FileBasicInfo, &basicInfo, sizeof(basicInfo))) {
  1114. /* The Win32 error is already set, but we also set errno for
  1115. callers who expect it */
  1116. errno = winerror_to_errno(GetLastError());
  1117. return -1;
  1118. }
  1119. if (!GetFileInformationByHandleEx(h, FileIdInfo, &idInfo, sizeof(idInfo))) {
  1120. /* Failed to get FileIdInfo, so do not pass it along */
  1121. pIdInfo = NULL;
  1122. }
  1123. _Py_attribute_data_to_stat(&info, 0, &basicInfo, pIdInfo, status);
  1124. return 0;
  1125. #else
  1126. return fstat(fd, status);
  1127. #endif
  1128. }
  1129. /* Return information about a file.
  1130. On POSIX, use fstat().
  1131. On Windows, use GetFileType() and GetFileInformationByHandle() which support
  1132. files larger than 2 GiB. fstat() may fail with EOVERFLOW on files larger
  1133. than 2 GiB because the file size type is a signed 32-bit integer: see issue
  1134. #23152.
  1135. Raise an exception and return -1 on error. On Windows, set the last Windows
  1136. error on error. On POSIX, set errno on error. Fill status and return 0 on
  1137. success.
  1138. Release the GIL to call GetFileType() and GetFileInformationByHandle(), or
  1139. to call fstat(). The caller must hold the GIL. */
  1140. int
  1141. _Py_fstat(int fd, struct _Py_stat_struct *status)
  1142. {
  1143. int res;
  1144. assert(PyGILState_Check());
  1145. Py_BEGIN_ALLOW_THREADS
  1146. res = _Py_fstat_noraise(fd, status);
  1147. Py_END_ALLOW_THREADS
  1148. if (res != 0) {
  1149. #ifdef MS_WINDOWS
  1150. PyErr_SetFromWindowsErr(0);
  1151. #else
  1152. PyErr_SetFromErrno(PyExc_OSError);
  1153. #endif
  1154. return -1;
  1155. }
  1156. return 0;
  1157. }
  1158. /* Like _Py_stat() but with a raw filename. */
  1159. int
  1160. _Py_wstat(const wchar_t* path, struct stat *buf)
  1161. {
  1162. int err;
  1163. #ifdef MS_WINDOWS
  1164. struct _stat wstatbuf;
  1165. err = _wstat(path, &wstatbuf);
  1166. if (!err) {
  1167. buf->st_mode = wstatbuf.st_mode;
  1168. }
  1169. #else
  1170. char *fname;
  1171. fname = _Py_EncodeLocaleRaw(path, NULL);
  1172. if (fname == NULL) {
  1173. errno = EINVAL;
  1174. return -1;
  1175. }
  1176. err = stat(fname, buf);
  1177. PyMem_RawFree(fname);
  1178. #endif
  1179. return err;
  1180. }
  1181. /* Call _wstat() on Windows, or encode the path to the filesystem encoding and
  1182. call stat() otherwise. Only fill st_mode attribute on Windows.
  1183. Return 0 on success, -1 on _wstat() / stat() error, -2 if an exception was
  1184. raised. */
  1185. int
  1186. _Py_stat(PyObject *path, struct stat *statbuf)
  1187. {
  1188. #ifdef MS_WINDOWS
  1189. int err;
  1190. wchar_t *wpath = PyUnicode_AsWideCharString(path, NULL);
  1191. if (wpath == NULL)
  1192. return -2;
  1193. err = _Py_wstat(wpath, statbuf);
  1194. PyMem_Free(wpath);
  1195. return err;
  1196. #else
  1197. int ret;
  1198. PyObject *bytes;
  1199. char *cpath;
  1200. bytes = PyUnicode_EncodeFSDefault(path);
  1201. if (bytes == NULL)
  1202. return -2;
  1203. /* check for embedded null bytes */
  1204. if (PyBytes_AsStringAndSize(bytes, &cpath, NULL) == -1) {
  1205. Py_DECREF(bytes);
  1206. return -2;
  1207. }
  1208. ret = stat(cpath, statbuf);
  1209. Py_DECREF(bytes);
  1210. return ret;
  1211. #endif
  1212. }
  1213. #ifdef MS_WINDOWS
  1214. // For some Windows API partitions, SetHandleInformation() is declared
  1215. // but none of the handle flags are defined.
  1216. #ifndef HANDLE_FLAG_INHERIT
  1217. #define HANDLE_FLAG_INHERIT 0x00000001
  1218. #endif
  1219. #endif
  1220. /* This function MUST be kept async-signal-safe on POSIX when raise=0. */
  1221. static int
  1222. get_inheritable(int fd, int raise)
  1223. {
  1224. #ifdef MS_WINDOWS
  1225. HANDLE handle;
  1226. DWORD flags;
  1227. handle = _Py_get_osfhandle_noraise(fd);
  1228. if (handle == INVALID_HANDLE_VALUE) {
  1229. if (raise)
  1230. PyErr_SetFromErrno(PyExc_OSError);
  1231. return -1;
  1232. }
  1233. if (!GetHandleInformation(handle, &flags)) {
  1234. if (raise)
  1235. PyErr_SetFromWindowsErr(0);
  1236. return -1;
  1237. }
  1238. return (flags & HANDLE_FLAG_INHERIT);
  1239. #else
  1240. int flags;
  1241. flags = fcntl(fd, F_GETFD, 0);
  1242. if (flags == -1) {
  1243. if (raise)
  1244. PyErr_SetFromErrno(PyExc_OSError);
  1245. return -1;
  1246. }
  1247. return !(flags & FD_CLOEXEC);
  1248. #endif
  1249. }
  1250. /* Get the inheritable flag of the specified file descriptor.
  1251. Return 1 if the file descriptor can be inherited, 0 if it cannot,
  1252. raise an exception and return -1 on error. */
  1253. int
  1254. _Py_get_inheritable(int fd)
  1255. {
  1256. return get_inheritable(fd, 1);
  1257. }
  1258. /* This function MUST be kept async-signal-safe on POSIX when raise=0. */
  1259. static int
  1260. set_inheritable(int fd, int inheritable, int raise, int *atomic_flag_works)
  1261. {
  1262. #ifdef MS_WINDOWS
  1263. HANDLE handle;
  1264. DWORD flags;
  1265. #else
  1266. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  1267. static int ioctl_works = -1;
  1268. int request;
  1269. int err;
  1270. #endif
  1271. int flags, new_flags;
  1272. int res;
  1273. #endif
  1274. /* atomic_flag_works can only be used to make the file descriptor
  1275. non-inheritable */
  1276. assert(!(atomic_flag_works != NULL && inheritable));
  1277. if (atomic_flag_works != NULL && !inheritable) {
  1278. if (*atomic_flag_works == -1) {
  1279. int isInheritable = get_inheritable(fd, raise);
  1280. if (isInheritable == -1)
  1281. return -1;
  1282. *atomic_flag_works = !isInheritable;
  1283. }
  1284. if (*atomic_flag_works)
  1285. return 0;
  1286. }
  1287. #ifdef MS_WINDOWS
  1288. handle = _Py_get_osfhandle_noraise(fd);
  1289. if (handle == INVALID_HANDLE_VALUE) {
  1290. if (raise)
  1291. PyErr_SetFromErrno(PyExc_OSError);
  1292. return -1;
  1293. }
  1294. if (inheritable)
  1295. flags = HANDLE_FLAG_INHERIT;
  1296. else
  1297. flags = 0;
  1298. if (!SetHandleInformation(handle, HANDLE_FLAG_INHERIT, flags)) {
  1299. if (raise)
  1300. PyErr_SetFromWindowsErr(0);
  1301. return -1;
  1302. }
  1303. return 0;
  1304. #else
  1305. #if defined(HAVE_SYS_IOCTL_H) && defined(FIOCLEX) && defined(FIONCLEX)
  1306. if (ioctl_works != 0 && raise != 0) {
  1307. /* fast-path: ioctl() only requires one syscall */
  1308. /* caveat: raise=0 is an indicator that we must be async-signal-safe
  1309. * thus avoid using ioctl() so we skip the fast-path. */
  1310. if (inheritable)
  1311. request = FIONCLEX;
  1312. else
  1313. request = FIOCLEX;
  1314. err = ioctl(fd, request, NULL);
  1315. if (!err) {
  1316. ioctl_works = 1;
  1317. return 0;
  1318. }
  1319. #ifdef O_PATH
  1320. if (errno == EBADF) {
  1321. // bpo-44849: On Linux and FreeBSD, ioctl(FIOCLEX) fails with EBADF
  1322. // on O_PATH file descriptors. Fall through to the fcntl()
  1323. // implementation.
  1324. }
  1325. else
  1326. #endif
  1327. if (errno != ENOTTY && errno != EACCES) {
  1328. if (raise)
  1329. PyErr_SetFromErrno(PyExc_OSError);
  1330. return -1;
  1331. }
  1332. else {
  1333. /* Issue #22258: Here, ENOTTY means "Inappropriate ioctl for
  1334. device". The ioctl is declared but not supported by the kernel.
  1335. Remember that ioctl() doesn't work. It is the case on
  1336. Illumos-based OS for example.
  1337. Issue #27057: When SELinux policy disallows ioctl it will fail
  1338. with EACCES. While FIOCLEX is safe operation it may be
  1339. unavailable because ioctl was denied altogether.
  1340. This can be the case on Android. */
  1341. ioctl_works = 0;
  1342. }
  1343. /* fallback to fcntl() if ioctl() does not work */
  1344. }
  1345. #endif
  1346. /* slow-path: fcntl() requires two syscalls */
  1347. flags = fcntl(fd, F_GETFD);
  1348. if (flags < 0) {
  1349. if (raise)
  1350. PyErr_SetFromErrno(PyExc_OSError);
  1351. return -1;
  1352. }
  1353. if (inheritable) {
  1354. new_flags = flags & ~FD_CLOEXEC;
  1355. }
  1356. else {
  1357. new_flags = flags | FD_CLOEXEC;
  1358. }
  1359. if (new_flags == flags) {
  1360. /* FD_CLOEXEC flag already set/cleared: nothing to do */
  1361. return 0;
  1362. }
  1363. res = fcntl(fd, F_SETFD, new_flags);
  1364. if (res < 0) {
  1365. if (raise)
  1366. PyErr_SetFromErrno(PyExc_OSError);
  1367. return -1;
  1368. }
  1369. return 0;
  1370. #endif
  1371. }
  1372. /* Make the file descriptor non-inheritable.
  1373. Return 0 on success, set errno and return -1 on error. */
  1374. static int
  1375. make_non_inheritable(int fd)
  1376. {
  1377. return set_inheritable(fd, 0, 0, NULL);
  1378. }
  1379. /* Set the inheritable flag of the specified file descriptor.
  1380. On success: return 0, on error: raise an exception and return -1.
  1381. If atomic_flag_works is not NULL:
  1382. * if *atomic_flag_works==-1, check if the inheritable is set on the file
  1383. descriptor: if yes, set *atomic_flag_works to 1, otherwise set to 0 and
  1384. set the inheritable flag
  1385. * if *atomic_flag_works==1: do nothing
  1386. * if *atomic_flag_works==0: set inheritable flag to False
  1387. Set atomic_flag_works to NULL if no atomic flag was used to create the
  1388. file descriptor.
  1389. atomic_flag_works can only be used to make a file descriptor
  1390. non-inheritable: atomic_flag_works must be NULL if inheritable=1. */
  1391. int
  1392. _Py_set_inheritable(int fd, int inheritable, int *atomic_flag_works)
  1393. {
  1394. return set_inheritable(fd, inheritable, 1, atomic_flag_works);
  1395. }
  1396. /* Same as _Py_set_inheritable() but on error, set errno and
  1397. don't raise an exception.
  1398. This function is async-signal-safe. */
  1399. int
  1400. _Py_set_inheritable_async_safe(int fd, int inheritable, int *atomic_flag_works)
  1401. {
  1402. return set_inheritable(fd, inheritable, 0, atomic_flag_works);
  1403. }
  1404. static int
  1405. _Py_open_impl(const char *pathname, int flags, int gil_held)
  1406. {
  1407. int fd;
  1408. int async_err = 0;
  1409. #ifndef MS_WINDOWS
  1410. int *atomic_flag_works;
  1411. #endif
  1412. #ifdef MS_WINDOWS
  1413. flags |= O_NOINHERIT;
  1414. #elif defined(O_CLOEXEC)
  1415. atomic_flag_works = &_Py_open_cloexec_works;
  1416. flags |= O_CLOEXEC;
  1417. #else
  1418. atomic_flag_works = NULL;
  1419. #endif
  1420. if (gil_held) {
  1421. PyObject *pathname_obj = PyUnicode_DecodeFSDefault(pathname);
  1422. if (pathname_obj == NULL) {
  1423. return -1;
  1424. }
  1425. if (PySys_Audit("open", "OOi", pathname_obj, Py_None, flags) < 0) {
  1426. Py_DECREF(pathname_obj);
  1427. return -1;
  1428. }
  1429. do {
  1430. Py_BEGIN_ALLOW_THREADS
  1431. fd = open(pathname, flags);
  1432. Py_END_ALLOW_THREADS
  1433. } while (fd < 0
  1434. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1435. if (async_err) {
  1436. Py_DECREF(pathname_obj);
  1437. return -1;
  1438. }
  1439. if (fd < 0) {
  1440. PyErr_SetFromErrnoWithFilenameObjects(PyExc_OSError, pathname_obj, NULL);
  1441. Py_DECREF(pathname_obj);
  1442. return -1;
  1443. }
  1444. Py_DECREF(pathname_obj);
  1445. }
  1446. else {
  1447. fd = open(pathname, flags);
  1448. if (fd < 0)
  1449. return -1;
  1450. }
  1451. #ifndef MS_WINDOWS
  1452. if (set_inheritable(fd, 0, gil_held, atomic_flag_works) < 0) {
  1453. close(fd);
  1454. return -1;
  1455. }
  1456. #endif
  1457. return fd;
  1458. }
  1459. /* Open a file with the specified flags (wrapper to open() function).
  1460. Return a file descriptor on success. Raise an exception and return -1 on
  1461. error.
  1462. The file descriptor is created non-inheritable.
  1463. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  1464. except if the Python signal handler raises an exception.
  1465. Release the GIL to call open(). The caller must hold the GIL. */
  1466. int
  1467. _Py_open(const char *pathname, int flags)
  1468. {
  1469. /* _Py_open() must be called with the GIL held. */
  1470. assert(PyGILState_Check());
  1471. return _Py_open_impl(pathname, flags, 1);
  1472. }
  1473. /* Open a file with the specified flags (wrapper to open() function).
  1474. Return a file descriptor on success. Set errno and return -1 on error.
  1475. The file descriptor is created non-inheritable.
  1476. If interrupted by a signal, fail with EINTR. */
  1477. int
  1478. _Py_open_noraise(const char *pathname, int flags)
  1479. {
  1480. return _Py_open_impl(pathname, flags, 0);
  1481. }
  1482. /* Open a file. Use _wfopen() on Windows, encode the path to the locale
  1483. encoding and use fopen() otherwise.
  1484. The file descriptor is created non-inheritable.
  1485. If interrupted by a signal, fail with EINTR. */
  1486. FILE *
  1487. _Py_wfopen(const wchar_t *path, const wchar_t *mode)
  1488. {
  1489. FILE *f;
  1490. if (PySys_Audit("open", "uui", path, mode, 0) < 0) {
  1491. return NULL;
  1492. }
  1493. #ifndef MS_WINDOWS
  1494. char *cpath;
  1495. char cmode[10];
  1496. size_t r;
  1497. r = wcstombs(cmode, mode, 10);
  1498. if (r == DECODE_ERROR || r >= 10) {
  1499. errno = EINVAL;
  1500. return NULL;
  1501. }
  1502. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1503. if (cpath == NULL) {
  1504. return NULL;
  1505. }
  1506. f = fopen(cpath, cmode);
  1507. PyMem_RawFree(cpath);
  1508. #else
  1509. f = _wfopen(path, mode);
  1510. #endif
  1511. if (f == NULL)
  1512. return NULL;
  1513. if (make_non_inheritable(fileno(f)) < 0) {
  1514. fclose(f);
  1515. return NULL;
  1516. }
  1517. return f;
  1518. }
  1519. /* Open a file. Call _wfopen() on Windows, or encode the path to the filesystem
  1520. encoding and call fopen() otherwise.
  1521. Return the new file object on success. Raise an exception and return NULL
  1522. on error.
  1523. The file descriptor is created non-inheritable.
  1524. When interrupted by a signal (open() fails with EINTR), retry the syscall,
  1525. except if the Python signal handler raises an exception.
  1526. Release the GIL to call _wfopen() or fopen(). The caller must hold
  1527. the GIL. */
  1528. FILE*
  1529. _Py_fopen_obj(PyObject *path, const char *mode)
  1530. {
  1531. FILE *f;
  1532. int async_err = 0;
  1533. #ifdef MS_WINDOWS
  1534. wchar_t wmode[10];
  1535. int usize;
  1536. assert(PyGILState_Check());
  1537. if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
  1538. return NULL;
  1539. }
  1540. if (!PyUnicode_Check(path)) {
  1541. PyErr_Format(PyExc_TypeError,
  1542. "str file path expected under Windows, got %R",
  1543. Py_TYPE(path));
  1544. return NULL;
  1545. }
  1546. wchar_t *wpath = PyUnicode_AsWideCharString(path, NULL);
  1547. if (wpath == NULL)
  1548. return NULL;
  1549. usize = MultiByteToWideChar(CP_ACP, 0, mode, -1,
  1550. wmode, Py_ARRAY_LENGTH(wmode));
  1551. if (usize == 0) {
  1552. PyErr_SetFromWindowsErr(0);
  1553. PyMem_Free(wpath);
  1554. return NULL;
  1555. }
  1556. do {
  1557. Py_BEGIN_ALLOW_THREADS
  1558. f = _wfopen(wpath, wmode);
  1559. Py_END_ALLOW_THREADS
  1560. } while (f == NULL
  1561. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1562. int saved_errno = errno;
  1563. PyMem_Free(wpath);
  1564. #else
  1565. PyObject *bytes;
  1566. const char *path_bytes;
  1567. assert(PyGILState_Check());
  1568. if (!PyUnicode_FSConverter(path, &bytes))
  1569. return NULL;
  1570. path_bytes = PyBytes_AS_STRING(bytes);
  1571. if (PySys_Audit("open", "Osi", path, mode, 0) < 0) {
  1572. Py_DECREF(bytes);
  1573. return NULL;
  1574. }
  1575. do {
  1576. Py_BEGIN_ALLOW_THREADS
  1577. f = fopen(path_bytes, mode);
  1578. Py_END_ALLOW_THREADS
  1579. } while (f == NULL
  1580. && errno == EINTR && !(async_err = PyErr_CheckSignals()));
  1581. int saved_errno = errno;
  1582. Py_DECREF(bytes);
  1583. #endif
  1584. if (async_err)
  1585. return NULL;
  1586. if (f == NULL) {
  1587. errno = saved_errno;
  1588. PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);
  1589. return NULL;
  1590. }
  1591. if (set_inheritable(fileno(f), 0, 1, NULL) < 0) {
  1592. fclose(f);
  1593. return NULL;
  1594. }
  1595. return f;
  1596. }
  1597. /* Read count bytes from fd into buf.
  1598. On success, return the number of read bytes, it can be lower than count.
  1599. If the current file offset is at or past the end of file, no bytes are read,
  1600. and read() returns zero.
  1601. On error, raise an exception, set errno and return -1.
  1602. When interrupted by a signal (read() fails with EINTR), retry the syscall.
  1603. If the Python signal handler raises an exception, the function returns -1
  1604. (the syscall is not retried).
  1605. Release the GIL to call read(). The caller must hold the GIL. */
  1606. Py_ssize_t
  1607. _Py_read(int fd, void *buf, size_t count)
  1608. {
  1609. Py_ssize_t n;
  1610. int err;
  1611. int async_err = 0;
  1612. assert(PyGILState_Check());
  1613. /* _Py_read() must not be called with an exception set, otherwise the
  1614. * caller may think that read() was interrupted by a signal and the signal
  1615. * handler raised an exception. */
  1616. assert(!PyErr_Occurred());
  1617. if (count > _PY_READ_MAX) {
  1618. count = _PY_READ_MAX;
  1619. }
  1620. _Py_BEGIN_SUPPRESS_IPH
  1621. do {
  1622. Py_BEGIN_ALLOW_THREADS
  1623. errno = 0;
  1624. #ifdef MS_WINDOWS
  1625. _doserrno = 0;
  1626. n = read(fd, buf, (int)count);
  1627. // read() on a non-blocking empty pipe fails with EINVAL, which is
  1628. // mapped from the Windows error code ERROR_NO_DATA.
  1629. if (n < 0 && errno == EINVAL) {
  1630. if (_doserrno == ERROR_NO_DATA) {
  1631. errno = EAGAIN;
  1632. }
  1633. }
  1634. #else
  1635. n = read(fd, buf, count);
  1636. #endif
  1637. /* save/restore errno because PyErr_CheckSignals()
  1638. * and PyErr_SetFromErrno() can modify it */
  1639. err = errno;
  1640. Py_END_ALLOW_THREADS
  1641. } while (n < 0 && err == EINTR &&
  1642. !(async_err = PyErr_CheckSignals()));
  1643. _Py_END_SUPPRESS_IPH
  1644. if (async_err) {
  1645. /* read() was interrupted by a signal (failed with EINTR)
  1646. * and the Python signal handler raised an exception */
  1647. errno = err;
  1648. assert(errno == EINTR && PyErr_Occurred());
  1649. return -1;
  1650. }
  1651. if (n < 0) {
  1652. PyErr_SetFromErrno(PyExc_OSError);
  1653. errno = err;
  1654. return -1;
  1655. }
  1656. return n;
  1657. }
  1658. static Py_ssize_t
  1659. _Py_write_impl(int fd, const void *buf, size_t count, int gil_held)
  1660. {
  1661. Py_ssize_t n;
  1662. int err;
  1663. int async_err = 0;
  1664. _Py_BEGIN_SUPPRESS_IPH
  1665. #ifdef MS_WINDOWS
  1666. if (count > 32767) {
  1667. /* Issue #11395: the Windows console returns an error (12: not
  1668. enough space error) on writing into stdout if stdout mode is
  1669. binary and the length is greater than 66,000 bytes (or less,
  1670. depending on heap usage). */
  1671. if (gil_held) {
  1672. Py_BEGIN_ALLOW_THREADS
  1673. if (isatty(fd)) {
  1674. count = 32767;
  1675. }
  1676. Py_END_ALLOW_THREADS
  1677. } else {
  1678. if (isatty(fd)) {
  1679. count = 32767;
  1680. }
  1681. }
  1682. }
  1683. #endif
  1684. if (count > _PY_WRITE_MAX) {
  1685. count = _PY_WRITE_MAX;
  1686. }
  1687. if (gil_held) {
  1688. do {
  1689. Py_BEGIN_ALLOW_THREADS
  1690. errno = 0;
  1691. #ifdef MS_WINDOWS
  1692. // write() on a non-blocking pipe fails with ENOSPC on Windows if
  1693. // the pipe lacks available space for the entire buffer.
  1694. int c = (int)count;
  1695. do {
  1696. _doserrno = 0;
  1697. n = write(fd, buf, c);
  1698. if (n >= 0 || errno != ENOSPC || _doserrno != 0) {
  1699. break;
  1700. }
  1701. errno = EAGAIN;
  1702. c /= 2;
  1703. } while (c > 0);
  1704. #else
  1705. n = write(fd, buf, count);
  1706. #endif
  1707. /* save/restore errno because PyErr_CheckSignals()
  1708. * and PyErr_SetFromErrno() can modify it */
  1709. err = errno;
  1710. Py_END_ALLOW_THREADS
  1711. } while (n < 0 && err == EINTR &&
  1712. !(async_err = PyErr_CheckSignals()));
  1713. }
  1714. else {
  1715. do {
  1716. errno = 0;
  1717. #ifdef MS_WINDOWS
  1718. // write() on a non-blocking pipe fails with ENOSPC on Windows if
  1719. // the pipe lacks available space for the entire buffer.
  1720. int c = (int)count;
  1721. do {
  1722. _doserrno = 0;
  1723. n = write(fd, buf, c);
  1724. if (n >= 0 || errno != ENOSPC || _doserrno != 0) {
  1725. break;
  1726. }
  1727. errno = EAGAIN;
  1728. c /= 2;
  1729. } while (c > 0);
  1730. #else
  1731. n = write(fd, buf, count);
  1732. #endif
  1733. err = errno;
  1734. } while (n < 0 && err == EINTR);
  1735. }
  1736. _Py_END_SUPPRESS_IPH
  1737. if (async_err) {
  1738. /* write() was interrupted by a signal (failed with EINTR)
  1739. and the Python signal handler raised an exception (if gil_held is
  1740. nonzero). */
  1741. errno = err;
  1742. assert(errno == EINTR && (!gil_held || PyErr_Occurred()));
  1743. return -1;
  1744. }
  1745. if (n < 0) {
  1746. if (gil_held)
  1747. PyErr_SetFromErrno(PyExc_OSError);
  1748. errno = err;
  1749. return -1;
  1750. }
  1751. return n;
  1752. }
  1753. /* Write count bytes of buf into fd.
  1754. On success, return the number of written bytes, it can be lower than count
  1755. including 0. On error, raise an exception, set errno and return -1.
  1756. When interrupted by a signal (write() fails with EINTR), retry the syscall.
  1757. If the Python signal handler raises an exception, the function returns -1
  1758. (the syscall is not retried).
  1759. Release the GIL to call write(). The caller must hold the GIL. */
  1760. Py_ssize_t
  1761. _Py_write(int fd, const void *buf, size_t count)
  1762. {
  1763. assert(PyGILState_Check());
  1764. /* _Py_write() must not be called with an exception set, otherwise the
  1765. * caller may think that write() was interrupted by a signal and the signal
  1766. * handler raised an exception. */
  1767. assert(!PyErr_Occurred());
  1768. return _Py_write_impl(fd, buf, count, 1);
  1769. }
  1770. /* Write count bytes of buf into fd.
  1771. *
  1772. * On success, return the number of written bytes, it can be lower than count
  1773. * including 0. On error, set errno and return -1.
  1774. *
  1775. * When interrupted by a signal (write() fails with EINTR), retry the syscall
  1776. * without calling the Python signal handler. */
  1777. Py_ssize_t
  1778. _Py_write_noraise(int fd, const void *buf, size_t count)
  1779. {
  1780. return _Py_write_impl(fd, buf, count, 0);
  1781. }
  1782. #ifdef HAVE_READLINK
  1783. /* Read value of symbolic link. Encode the path to the locale encoding, decode
  1784. the result from the locale encoding.
  1785. Return -1 on encoding error, on readlink() error, if the internal buffer is
  1786. too short, on decoding error, or if 'buf' is too short. */
  1787. int
  1788. _Py_wreadlink(const wchar_t *path, wchar_t *buf, size_t buflen)
  1789. {
  1790. char *cpath;
  1791. char cbuf[MAXPATHLEN];
  1792. size_t cbuf_len = Py_ARRAY_LENGTH(cbuf);
  1793. wchar_t *wbuf;
  1794. Py_ssize_t res;
  1795. size_t r1;
  1796. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1797. if (cpath == NULL) {
  1798. errno = EINVAL;
  1799. return -1;
  1800. }
  1801. res = readlink(cpath, cbuf, cbuf_len);
  1802. PyMem_RawFree(cpath);
  1803. if (res == -1) {
  1804. return -1;
  1805. }
  1806. if ((size_t)res == cbuf_len) {
  1807. errno = EINVAL;
  1808. return -1;
  1809. }
  1810. cbuf[res] = '\0'; /* buf will be null terminated */
  1811. wbuf = Py_DecodeLocale(cbuf, &r1);
  1812. if (wbuf == NULL) {
  1813. errno = EINVAL;
  1814. return -1;
  1815. }
  1816. /* wbuf must have space to store the trailing NUL character */
  1817. if (buflen <= r1) {
  1818. PyMem_RawFree(wbuf);
  1819. errno = EINVAL;
  1820. return -1;
  1821. }
  1822. wcsncpy(buf, wbuf, buflen);
  1823. PyMem_RawFree(wbuf);
  1824. return (int)r1;
  1825. }
  1826. #endif
  1827. #ifdef HAVE_REALPATH
  1828. /* Return the canonicalized absolute pathname. Encode path to the locale
  1829. encoding, decode the result from the locale encoding.
  1830. Return NULL on encoding error, realpath() error, decoding error
  1831. or if 'resolved_path' is too short. */
  1832. wchar_t*
  1833. _Py_wrealpath(const wchar_t *path,
  1834. wchar_t *resolved_path, size_t resolved_path_len)
  1835. {
  1836. char *cpath;
  1837. char cresolved_path[MAXPATHLEN];
  1838. wchar_t *wresolved_path;
  1839. char *res;
  1840. size_t r;
  1841. cpath = _Py_EncodeLocaleRaw(path, NULL);
  1842. if (cpath == NULL) {
  1843. errno = EINVAL;
  1844. return NULL;
  1845. }
  1846. res = realpath(cpath, cresolved_path);
  1847. PyMem_RawFree(cpath);
  1848. if (res == NULL)
  1849. return NULL;
  1850. wresolved_path = Py_DecodeLocale(cresolved_path, &r);
  1851. if (wresolved_path == NULL) {
  1852. errno = EINVAL;
  1853. return NULL;
  1854. }
  1855. /* wresolved_path must have space to store the trailing NUL character */
  1856. if (resolved_path_len <= r) {
  1857. PyMem_RawFree(wresolved_path);
  1858. errno = EINVAL;
  1859. return NULL;
  1860. }
  1861. wcsncpy(resolved_path, wresolved_path, resolved_path_len);
  1862. PyMem_RawFree(wresolved_path);
  1863. return resolved_path;
  1864. }
  1865. #endif
  1866. int
  1867. _Py_isabs(const wchar_t *path)
  1868. {
  1869. #ifdef MS_WINDOWS
  1870. const wchar_t *tail;
  1871. HRESULT hr = PathCchSkipRoot(path, &tail);
  1872. if (FAILED(hr) || path == tail) {
  1873. return 0;
  1874. }
  1875. if (tail == &path[1] && (path[0] == SEP || path[0] == ALTSEP)) {
  1876. // Exclude paths with leading SEP
  1877. return 0;
  1878. }
  1879. if (tail == &path[2] && path[1] == L':') {
  1880. // Exclude drive-relative paths (e.g. C:filename.ext)
  1881. return 0;
  1882. }
  1883. return 1;
  1884. #else
  1885. return (path[0] == SEP);
  1886. #endif
  1887. }
  1888. /* Get an absolute path.
  1889. On error (ex: fail to get the current directory), return -1.
  1890. On memory allocation failure, set *abspath_p to NULL and return 0.
  1891. On success, return a newly allocated to *abspath_p to and return 0.
  1892. The string must be freed by PyMem_RawFree(). */
  1893. int
  1894. _Py_abspath(const wchar_t *path, wchar_t **abspath_p)
  1895. {
  1896. if (path[0] == '\0' || !wcscmp(path, L".")) {
  1897. wchar_t cwd[MAXPATHLEN + 1];
  1898. cwd[Py_ARRAY_LENGTH(cwd) - 1] = 0;
  1899. if (!_Py_wgetcwd(cwd, Py_ARRAY_LENGTH(cwd) - 1)) {
  1900. /* unable to get the current directory */
  1901. return -1;
  1902. }
  1903. *abspath_p = _PyMem_RawWcsdup(cwd);
  1904. return 0;
  1905. }
  1906. if (_Py_isabs(path)) {
  1907. *abspath_p = _PyMem_RawWcsdup(path);
  1908. return 0;
  1909. }
  1910. #ifdef MS_WINDOWS
  1911. return _PyOS_getfullpathname(path, abspath_p);
  1912. #else
  1913. wchar_t cwd[MAXPATHLEN + 1];
  1914. cwd[Py_ARRAY_LENGTH(cwd) - 1] = 0;
  1915. if (!_Py_wgetcwd(cwd, Py_ARRAY_LENGTH(cwd) - 1)) {
  1916. /* unable to get the current directory */
  1917. return -1;
  1918. }
  1919. size_t cwd_len = wcslen(cwd);
  1920. size_t path_len = wcslen(path);
  1921. size_t len = cwd_len + 1 + path_len + 1;
  1922. if (len <= (size_t)PY_SSIZE_T_MAX / sizeof(wchar_t)) {
  1923. *abspath_p = PyMem_RawMalloc(len * sizeof(wchar_t));
  1924. }
  1925. else {
  1926. *abspath_p = NULL;
  1927. }
  1928. if (*abspath_p == NULL) {
  1929. return 0;
  1930. }
  1931. wchar_t *abspath = *abspath_p;
  1932. memcpy(abspath, cwd, cwd_len * sizeof(wchar_t));
  1933. abspath += cwd_len;
  1934. *abspath = (wchar_t)SEP;
  1935. abspath++;
  1936. memcpy(abspath, path, path_len * sizeof(wchar_t));
  1937. abspath += path_len;
  1938. *abspath = 0;
  1939. return 0;
  1940. #endif
  1941. }
  1942. // The Windows Games API family implements the PathCch* APIs in the Xbox OS,
  1943. // but does not expose them yet. Load them dynamically until
  1944. // 1) they are officially exposed
  1945. // 2) we stop supporting older versions of the GDK which do not expose them
  1946. #if defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP)
  1947. HRESULT
  1948. PathCchSkipRoot(const wchar_t *path, const wchar_t **rootEnd)
  1949. {
  1950. static int initialized = 0;
  1951. typedef HRESULT(__stdcall *PPathCchSkipRoot) (PCWSTR pszPath,
  1952. PCWSTR *ppszRootEnd);
  1953. static PPathCchSkipRoot _PathCchSkipRoot;
  1954. if (initialized == 0) {
  1955. HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL,
  1956. LOAD_LIBRARY_SEARCH_SYSTEM32);
  1957. if (pathapi) {
  1958. _PathCchSkipRoot = (PPathCchSkipRoot)GetProcAddress(
  1959. pathapi, "PathCchSkipRoot");
  1960. }
  1961. else {
  1962. _PathCchSkipRoot = NULL;
  1963. }
  1964. initialized = 1;
  1965. }
  1966. if (!_PathCchSkipRoot) {
  1967. return E_NOINTERFACE;
  1968. }
  1969. return _PathCchSkipRoot(path, rootEnd);
  1970. }
  1971. static HRESULT
  1972. PathCchCombineEx(wchar_t *buffer, size_t bufsize, const wchar_t *dirname,
  1973. const wchar_t *relfile, unsigned long flags)
  1974. {
  1975. static int initialized = 0;
  1976. typedef HRESULT(__stdcall *PPathCchCombineEx) (PWSTR pszPathOut,
  1977. size_t cchPathOut,
  1978. PCWSTR pszPathIn,
  1979. PCWSTR pszMore,
  1980. unsigned long dwFlags);
  1981. static PPathCchCombineEx _PathCchCombineEx;
  1982. if (initialized == 0) {
  1983. HMODULE pathapi = LoadLibraryExW(L"api-ms-win-core-path-l1-1-0.dll", NULL,
  1984. LOAD_LIBRARY_SEARCH_SYSTEM32);
  1985. if (pathapi) {
  1986. _PathCchCombineEx = (PPathCchCombineEx)GetProcAddress(
  1987. pathapi, "PathCchCombineEx");
  1988. }
  1989. else {
  1990. _PathCchCombineEx = NULL;
  1991. }
  1992. initialized = 1;
  1993. }
  1994. if (!_PathCchCombineEx) {
  1995. return E_NOINTERFACE;
  1996. }
  1997. return _PathCchCombineEx(buffer, bufsize, dirname, relfile, flags);
  1998. }
  1999. #endif /* defined(MS_WINDOWS_GAMES) && !defined(MS_WINDOWS_DESKTOP) */
  2000. // The caller must ensure "buffer" is big enough.
  2001. static int
  2002. join_relfile(wchar_t *buffer, size_t bufsize,
  2003. const wchar_t *dirname, const wchar_t *relfile)
  2004. {
  2005. #ifdef MS_WINDOWS
  2006. if (FAILED(PathCchCombineEx(buffer, bufsize, dirname, relfile,
  2007. PATHCCH_ALLOW_LONG_PATHS))) {
  2008. return -1;
  2009. }
  2010. #else
  2011. assert(!_Py_isabs(relfile));
  2012. size_t dirlen = wcslen(dirname);
  2013. size_t rellen = wcslen(relfile);
  2014. size_t maxlen = bufsize - 1;
  2015. if (maxlen > MAXPATHLEN || dirlen >= maxlen || rellen >= maxlen - dirlen) {
  2016. return -1;
  2017. }
  2018. if (dirlen == 0) {
  2019. // We do not add a leading separator.
  2020. wcscpy(buffer, relfile);
  2021. }
  2022. else {
  2023. if (dirname != buffer) {
  2024. wcscpy(buffer, dirname);
  2025. }
  2026. size_t relstart = dirlen;
  2027. if (dirlen > 1 && dirname[dirlen - 1] != SEP) {
  2028. buffer[dirlen] = SEP;
  2029. relstart += 1;
  2030. }
  2031. wcscpy(&buffer[relstart], relfile);
  2032. }
  2033. #endif
  2034. return 0;
  2035. }
  2036. /* Join the two paths together, like os.path.join(). Return NULL
  2037. if memory could not be allocated. The caller is responsible
  2038. for calling PyMem_RawFree() on the result. */
  2039. wchar_t *
  2040. _Py_join_relfile(const wchar_t *dirname, const wchar_t *relfile)
  2041. {
  2042. assert(dirname != NULL && relfile != NULL);
  2043. #ifndef MS_WINDOWS
  2044. assert(!_Py_isabs(relfile));
  2045. #endif
  2046. size_t maxlen = wcslen(dirname) + 1 + wcslen(relfile);
  2047. size_t bufsize = maxlen + 1;
  2048. wchar_t *filename = PyMem_RawMalloc(bufsize * sizeof(wchar_t));
  2049. if (filename == NULL) {
  2050. return NULL;
  2051. }
  2052. assert(wcslen(dirname) < MAXPATHLEN);
  2053. assert(wcslen(relfile) < MAXPATHLEN - wcslen(dirname));
  2054. if (join_relfile(filename, bufsize, dirname, relfile) < 0) {
  2055. PyMem_RawFree(filename);
  2056. return NULL;
  2057. }
  2058. return filename;
  2059. }
  2060. /* Join the two paths together, like os.path.join().
  2061. dirname: the target buffer with the dirname already in place,
  2062. including trailing NUL
  2063. relfile: this must be a relative path
  2064. bufsize: total allocated size of the buffer
  2065. Return -1 if anything is wrong with the path lengths. */
  2066. int
  2067. _Py_add_relfile(wchar_t *dirname, const wchar_t *relfile, size_t bufsize)
  2068. {
  2069. assert(dirname != NULL && relfile != NULL);
  2070. assert(bufsize > 0);
  2071. return join_relfile(dirname, bufsize, dirname, relfile);
  2072. }
  2073. size_t
  2074. _Py_find_basename(const wchar_t *filename)
  2075. {
  2076. for (size_t i = wcslen(filename); i > 0; --i) {
  2077. if (filename[i] == SEP) {
  2078. return i + 1;
  2079. }
  2080. }
  2081. return 0;
  2082. }
  2083. /* In-place path normalisation. Returns the start of the normalized
  2084. path, which will be within the original buffer. Guaranteed to not
  2085. make the path longer, and will not fail. 'size' is the length of
  2086. the path, if known. If -1, the first null character will be assumed
  2087. to be the end of the path. 'normsize' will be set to contain the
  2088. length of the resulting normalized path. */
  2089. wchar_t *
  2090. _Py_normpath_and_size(wchar_t *path, Py_ssize_t size, Py_ssize_t *normsize)
  2091. {
  2092. assert(path != NULL);
  2093. if ((size < 0 && !path[0]) || size == 0) {
  2094. *normsize = 0;
  2095. return path;
  2096. }
  2097. wchar_t *pEnd = size >= 0 ? &path[size] : NULL;
  2098. wchar_t *p1 = path; // sequentially scanned address in the path
  2099. wchar_t *p2 = path; // destination of a scanned character to be ljusted
  2100. wchar_t *minP2 = path; // the beginning of the destination range
  2101. wchar_t lastC = L'\0'; // the last ljusted character, p2[-1] in most cases
  2102. #define IS_END(x) (pEnd ? (x) == pEnd : !*(x))
  2103. #ifdef ALTSEP
  2104. #define IS_SEP(x) (*(x) == SEP || *(x) == ALTSEP)
  2105. #else
  2106. #define IS_SEP(x) (*(x) == SEP)
  2107. #endif
  2108. #define SEP_OR_END(x) (IS_SEP(x) || IS_END(x))
  2109. // Skip leading '.\'
  2110. if (p1[0] == L'.' && IS_SEP(&p1[1])) {
  2111. path = &path[2];
  2112. while (IS_SEP(path) && !IS_END(path)) {
  2113. path++;
  2114. }
  2115. p1 = p2 = minP2 = path;
  2116. lastC = SEP;
  2117. }
  2118. #ifdef MS_WINDOWS
  2119. // Skip past drive segment and update minP2
  2120. else if (p1[0] && p1[1] == L':') {
  2121. *p2++ = *p1++;
  2122. *p2++ = *p1++;
  2123. minP2 = p2;
  2124. lastC = L':';
  2125. }
  2126. // Skip past all \\-prefixed paths, including \\?\, \\.\,
  2127. // and network paths, including the first segment.
  2128. else if (IS_SEP(&p1[0]) && IS_SEP(&p1[1])) {
  2129. int sepCount = 2;
  2130. *p2++ = SEP;
  2131. *p2++ = SEP;
  2132. p1 += 2;
  2133. for (; !IS_END(p1) && sepCount; ++p1) {
  2134. if (IS_SEP(p1)) {
  2135. --sepCount;
  2136. *p2++ = lastC = SEP;
  2137. } else {
  2138. *p2++ = lastC = *p1;
  2139. }
  2140. }
  2141. minP2 = p2 - 1;
  2142. }
  2143. #else
  2144. // Skip past two leading SEPs
  2145. else if (IS_SEP(&p1[0]) && IS_SEP(&p1[1]) && !IS_SEP(&p1[2])) {
  2146. *p2++ = *p1++;
  2147. *p2++ = *p1++;
  2148. minP2 = p2 - 1; // Absolute path has SEP at minP2
  2149. lastC = SEP;
  2150. }
  2151. #endif /* MS_WINDOWS */
  2152. /* if pEnd is specified, check that. Else, check for null terminator */
  2153. for (; !IS_END(p1); ++p1) {
  2154. wchar_t c = *p1;
  2155. #ifdef ALTSEP
  2156. if (c == ALTSEP) {
  2157. c = SEP;
  2158. }
  2159. #endif
  2160. if (lastC == SEP) {
  2161. if (c == L'.') {
  2162. int sep_at_1 = SEP_OR_END(&p1[1]);
  2163. int sep_at_2 = !sep_at_1 && SEP_OR_END(&p1[2]);
  2164. if (sep_at_2 && p1[1] == L'.') {
  2165. wchar_t *p3 = p2;
  2166. while (p3 != minP2 && *--p3 == SEP) { }
  2167. while (p3 != minP2 && *(p3 - 1) != SEP) { --p3; }
  2168. if (p2 == minP2
  2169. || (p3[0] == L'.' && p3[1] == L'.' && IS_SEP(&p3[2])))
  2170. {
  2171. // Previous segment is also ../, so append instead.
  2172. // Relative path does not absorb ../ at minP2 as well.
  2173. *p2++ = L'.';
  2174. *p2++ = L'.';
  2175. lastC = L'.';
  2176. } else if (p3[0] == SEP) {
  2177. // Absolute path, so absorb segment
  2178. p2 = p3 + 1;
  2179. } else {
  2180. p2 = p3;
  2181. }
  2182. p1 += 1;
  2183. } else if (sep_at_1) {
  2184. } else {
  2185. *p2++ = lastC = c;
  2186. }
  2187. } else if (c == SEP) {
  2188. } else {
  2189. *p2++ = lastC = c;
  2190. }
  2191. } else {
  2192. *p2++ = lastC = c;
  2193. }
  2194. }
  2195. *p2 = L'\0';
  2196. if (p2 != minP2) {
  2197. while (--p2 != minP2 && *p2 == SEP) {
  2198. *p2 = L'\0';
  2199. }
  2200. } else {
  2201. --p2;
  2202. }
  2203. *normsize = p2 - path + 1;
  2204. #undef SEP_OR_END
  2205. #undef IS_SEP
  2206. #undef IS_END
  2207. return path;
  2208. }
  2209. /* In-place path normalisation. Returns the start of the normalized
  2210. path, which will be within the original buffer. Guaranteed to not
  2211. make the path longer, and will not fail. 'size' is the length of
  2212. the path, if known. If -1, the first null character will be assumed
  2213. to be the end of the path. */
  2214. wchar_t *
  2215. _Py_normpath(wchar_t *path, Py_ssize_t size)
  2216. {
  2217. Py_ssize_t norm_length;
  2218. return _Py_normpath_and_size(path, size, &norm_length);
  2219. }
  2220. /* Get the current directory. buflen is the buffer size in wide characters
  2221. including the null character. Decode the path from the locale encoding.
  2222. Return NULL on getcwd() error, on decoding error, or if 'buf' is
  2223. too short. */
  2224. wchar_t*
  2225. _Py_wgetcwd(wchar_t *buf, size_t buflen)
  2226. {
  2227. #ifdef MS_WINDOWS
  2228. int ibuflen = (int)Py_MIN(buflen, INT_MAX);
  2229. return _wgetcwd(buf, ibuflen);
  2230. #else
  2231. char fname[MAXPATHLEN];
  2232. wchar_t *wname;
  2233. size_t len;
  2234. if (getcwd(fname, Py_ARRAY_LENGTH(fname)) == NULL)
  2235. return NULL;
  2236. wname = Py_DecodeLocale(fname, &len);
  2237. if (wname == NULL)
  2238. return NULL;
  2239. /* wname must have space to store the trailing NUL character */
  2240. if (buflen <= len) {
  2241. PyMem_RawFree(wname);
  2242. return NULL;
  2243. }
  2244. wcsncpy(buf, wname, buflen);
  2245. PyMem_RawFree(wname);
  2246. return buf;
  2247. #endif
  2248. }
  2249. /* Duplicate a file descriptor. The new file descriptor is created as
  2250. non-inheritable. Return a new file descriptor on success, raise an OSError
  2251. exception and return -1 on error.
  2252. The GIL is released to call dup(). The caller must hold the GIL. */
  2253. int
  2254. _Py_dup(int fd)
  2255. {
  2256. #ifdef MS_WINDOWS
  2257. HANDLE handle;
  2258. #endif
  2259. assert(PyGILState_Check());
  2260. #ifdef MS_WINDOWS
  2261. handle = _Py_get_osfhandle(fd);
  2262. if (handle == INVALID_HANDLE_VALUE)
  2263. return -1;
  2264. Py_BEGIN_ALLOW_THREADS
  2265. _Py_BEGIN_SUPPRESS_IPH
  2266. fd = dup(fd);
  2267. _Py_END_SUPPRESS_IPH
  2268. Py_END_ALLOW_THREADS
  2269. if (fd < 0) {
  2270. PyErr_SetFromErrno(PyExc_OSError);
  2271. return -1;
  2272. }
  2273. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  2274. _Py_BEGIN_SUPPRESS_IPH
  2275. close(fd);
  2276. _Py_END_SUPPRESS_IPH
  2277. return -1;
  2278. }
  2279. #elif defined(HAVE_FCNTL_H) && defined(F_DUPFD_CLOEXEC)
  2280. Py_BEGIN_ALLOW_THREADS
  2281. _Py_BEGIN_SUPPRESS_IPH
  2282. fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
  2283. _Py_END_SUPPRESS_IPH
  2284. Py_END_ALLOW_THREADS
  2285. if (fd < 0) {
  2286. PyErr_SetFromErrno(PyExc_OSError);
  2287. return -1;
  2288. }
  2289. #elif HAVE_DUP
  2290. Py_BEGIN_ALLOW_THREADS
  2291. _Py_BEGIN_SUPPRESS_IPH
  2292. fd = dup(fd);
  2293. _Py_END_SUPPRESS_IPH
  2294. Py_END_ALLOW_THREADS
  2295. if (fd < 0) {
  2296. PyErr_SetFromErrno(PyExc_OSError);
  2297. return -1;
  2298. }
  2299. if (_Py_set_inheritable(fd, 0, NULL) < 0) {
  2300. _Py_BEGIN_SUPPRESS_IPH
  2301. close(fd);
  2302. _Py_END_SUPPRESS_IPH
  2303. return -1;
  2304. }
  2305. #else
  2306. errno = ENOTSUP;
  2307. PyErr_SetFromErrno(PyExc_OSError);
  2308. return -1;
  2309. #endif
  2310. return fd;
  2311. }
  2312. #ifndef MS_WINDOWS
  2313. /* Get the blocking mode of the file descriptor.
  2314. Return 0 if the O_NONBLOCK flag is set, 1 if the flag is cleared,
  2315. raise an exception and return -1 on error. */
  2316. int
  2317. _Py_get_blocking(int fd)
  2318. {
  2319. int flags;
  2320. _Py_BEGIN_SUPPRESS_IPH
  2321. flags = fcntl(fd, F_GETFL, 0);
  2322. _Py_END_SUPPRESS_IPH
  2323. if (flags < 0) {
  2324. PyErr_SetFromErrno(PyExc_OSError);
  2325. return -1;
  2326. }
  2327. return !(flags & O_NONBLOCK);
  2328. }
  2329. /* Set the blocking mode of the specified file descriptor.
  2330. Set the O_NONBLOCK flag if blocking is False, clear the O_NONBLOCK flag
  2331. otherwise.
  2332. Return 0 on success, raise an exception and return -1 on error. */
  2333. int
  2334. _Py_set_blocking(int fd, int blocking)
  2335. {
  2336. /* bpo-41462: On VxWorks, ioctl(FIONBIO) only works on sockets.
  2337. Use fcntl() instead. */
  2338. #if defined(HAVE_SYS_IOCTL_H) && defined(FIONBIO) && !defined(__VXWORKS__)
  2339. int arg = !blocking;
  2340. if (ioctl(fd, FIONBIO, &arg) < 0)
  2341. goto error;
  2342. #else
  2343. int flags, res;
  2344. _Py_BEGIN_SUPPRESS_IPH
  2345. flags = fcntl(fd, F_GETFL, 0);
  2346. if (flags >= 0) {
  2347. if (blocking)
  2348. flags = flags & (~O_NONBLOCK);
  2349. else
  2350. flags = flags | O_NONBLOCK;
  2351. res = fcntl(fd, F_SETFL, flags);
  2352. } else {
  2353. res = -1;
  2354. }
  2355. _Py_END_SUPPRESS_IPH
  2356. if (res < 0)
  2357. goto error;
  2358. #endif
  2359. return 0;
  2360. error:
  2361. PyErr_SetFromErrno(PyExc_OSError);
  2362. return -1;
  2363. }
  2364. #else /* MS_WINDOWS */
  2365. int
  2366. _Py_get_blocking(int fd)
  2367. {
  2368. HANDLE handle;
  2369. DWORD mode;
  2370. BOOL success;
  2371. handle = _Py_get_osfhandle(fd);
  2372. if (handle == INVALID_HANDLE_VALUE) {
  2373. return -1;
  2374. }
  2375. Py_BEGIN_ALLOW_THREADS
  2376. success = GetNamedPipeHandleStateW(handle, &mode,
  2377. NULL, NULL, NULL, NULL, 0);
  2378. Py_END_ALLOW_THREADS
  2379. if (!success) {
  2380. PyErr_SetFromWindowsErr(0);
  2381. return -1;
  2382. }
  2383. return !(mode & PIPE_NOWAIT);
  2384. }
  2385. int
  2386. _Py_set_blocking(int fd, int blocking)
  2387. {
  2388. HANDLE handle;
  2389. DWORD mode;
  2390. BOOL success;
  2391. handle = _Py_get_osfhandle(fd);
  2392. if (handle == INVALID_HANDLE_VALUE) {
  2393. return -1;
  2394. }
  2395. Py_BEGIN_ALLOW_THREADS
  2396. success = GetNamedPipeHandleStateW(handle, &mode,
  2397. NULL, NULL, NULL, NULL, 0);
  2398. if (success) {
  2399. if (blocking) {
  2400. mode &= ~PIPE_NOWAIT;
  2401. }
  2402. else {
  2403. mode |= PIPE_NOWAIT;
  2404. }
  2405. success = SetNamedPipeHandleState(handle, &mode, NULL, NULL);
  2406. }
  2407. Py_END_ALLOW_THREADS
  2408. if (!success) {
  2409. PyErr_SetFromWindowsErr(0);
  2410. return -1;
  2411. }
  2412. return 0;
  2413. }
  2414. void*
  2415. _Py_get_osfhandle_noraise(int fd)
  2416. {
  2417. void *handle;
  2418. _Py_BEGIN_SUPPRESS_IPH
  2419. handle = (void*)_get_osfhandle(fd);
  2420. _Py_END_SUPPRESS_IPH
  2421. return handle;
  2422. }
  2423. void*
  2424. _Py_get_osfhandle(int fd)
  2425. {
  2426. void *handle = _Py_get_osfhandle_noraise(fd);
  2427. if (handle == INVALID_HANDLE_VALUE)
  2428. PyErr_SetFromErrno(PyExc_OSError);
  2429. return handle;
  2430. }
  2431. int
  2432. _Py_open_osfhandle_noraise(void *handle, int flags)
  2433. {
  2434. int fd;
  2435. _Py_BEGIN_SUPPRESS_IPH
  2436. fd = _open_osfhandle((intptr_t)handle, flags);
  2437. _Py_END_SUPPRESS_IPH
  2438. return fd;
  2439. }
  2440. int
  2441. _Py_open_osfhandle(void *handle, int flags)
  2442. {
  2443. int fd = _Py_open_osfhandle_noraise(handle, flags);
  2444. if (fd == -1)
  2445. PyErr_SetFromErrno(PyExc_OSError);
  2446. return fd;
  2447. }
  2448. #endif /* MS_WINDOWS */
  2449. int
  2450. _Py_GetLocaleconvNumeric(struct lconv *lc,
  2451. PyObject **decimal_point, PyObject **thousands_sep)
  2452. {
  2453. assert(decimal_point != NULL);
  2454. assert(thousands_sep != NULL);
  2455. #ifndef MS_WINDOWS
  2456. int change_locale = 0;
  2457. if ((strlen(lc->decimal_point) > 1 || ((unsigned char)lc->decimal_point[0]) > 127)) {
  2458. change_locale = 1;
  2459. }
  2460. if ((strlen(lc->thousands_sep) > 1 || ((unsigned char)lc->thousands_sep[0]) > 127)) {
  2461. change_locale = 1;
  2462. }
  2463. /* Keep a copy of the LC_CTYPE locale */
  2464. char *oldloc = NULL, *loc = NULL;
  2465. if (change_locale) {
  2466. oldloc = setlocale(LC_CTYPE, NULL);
  2467. if (!oldloc) {
  2468. PyErr_SetString(PyExc_RuntimeWarning,
  2469. "failed to get LC_CTYPE locale");
  2470. return -1;
  2471. }
  2472. oldloc = _PyMem_Strdup(oldloc);
  2473. if (!oldloc) {
  2474. PyErr_NoMemory();
  2475. return -1;
  2476. }
  2477. loc = setlocale(LC_NUMERIC, NULL);
  2478. if (loc != NULL && strcmp(loc, oldloc) == 0) {
  2479. loc = NULL;
  2480. }
  2481. if (loc != NULL) {
  2482. /* Only set the locale temporarily the LC_CTYPE locale
  2483. if LC_NUMERIC locale is different than LC_CTYPE locale and
  2484. decimal_point and/or thousands_sep are non-ASCII or longer than
  2485. 1 byte */
  2486. setlocale(LC_CTYPE, loc);
  2487. }
  2488. }
  2489. #define GET_LOCALE_STRING(ATTR) PyUnicode_DecodeLocale(lc->ATTR, NULL)
  2490. #else /* MS_WINDOWS */
  2491. /* Use _W_* fields of Windows strcut lconv */
  2492. #define GET_LOCALE_STRING(ATTR) PyUnicode_FromWideChar(lc->_W_ ## ATTR, -1)
  2493. #endif /* MS_WINDOWS */
  2494. int res = -1;
  2495. *decimal_point = GET_LOCALE_STRING(decimal_point);
  2496. if (*decimal_point == NULL) {
  2497. goto done;
  2498. }
  2499. *thousands_sep = GET_LOCALE_STRING(thousands_sep);
  2500. if (*thousands_sep == NULL) {
  2501. goto done;
  2502. }
  2503. res = 0;
  2504. done:
  2505. #ifndef MS_WINDOWS
  2506. if (loc != NULL) {
  2507. setlocale(LC_CTYPE, oldloc);
  2508. }
  2509. PyMem_Free(oldloc);
  2510. #endif
  2511. return res;
  2512. #undef GET_LOCALE_STRING
  2513. }
  2514. /* Our selection logic for which function to use is as follows:
  2515. * 1. If close_range(2) is available, always prefer that; it's better for
  2516. * contiguous ranges like this than fdwalk(3) which entails iterating over
  2517. * the entire fd space and simply doing nothing for those outside the range.
  2518. * 2. If closefrom(2) is available, we'll attempt to use that next if we're
  2519. * closing up to sysconf(_SC_OPEN_MAX).
  2520. * 2a. Fallback to fdwalk(3) if we're not closing up to sysconf(_SC_OPEN_MAX),
  2521. * as that will be more performant if the range happens to have any chunk of
  2522. * non-opened fd in the middle.
  2523. * 2b. If fdwalk(3) isn't available, just do a plain close(2) loop.
  2524. */
  2525. #ifdef __FreeBSD__
  2526. # define USE_CLOSEFROM
  2527. #endif /* __FreeBSD__ */
  2528. #ifdef HAVE_FDWALK
  2529. # define USE_FDWALK
  2530. #endif /* HAVE_FDWALK */
  2531. #ifdef USE_FDWALK
  2532. static int
  2533. _fdwalk_close_func(void *lohi, int fd)
  2534. {
  2535. int lo = ((int *)lohi)[0];
  2536. int hi = ((int *)lohi)[1];
  2537. if (fd >= hi) {
  2538. return 1;
  2539. }
  2540. else if (fd >= lo) {
  2541. /* Ignore errors */
  2542. (void)close(fd);
  2543. }
  2544. return 0;
  2545. }
  2546. #endif /* USE_FDWALK */
  2547. /* Closes all file descriptors in [first, last], ignoring errors. */
  2548. void
  2549. _Py_closerange(int first, int last)
  2550. {
  2551. first = Py_MAX(first, 0);
  2552. _Py_BEGIN_SUPPRESS_IPH
  2553. #ifdef HAVE_CLOSE_RANGE
  2554. if (close_range(first, last, 0) == 0) {
  2555. /* close_range() ignores errors when it closes file descriptors.
  2556. * Possible reasons of an error return are lack of kernel support
  2557. * or denial of the underlying syscall by a seccomp sandbox on Linux.
  2558. * Fallback to other methods in case of any error. */
  2559. }
  2560. else
  2561. #endif /* HAVE_CLOSE_RANGE */
  2562. #ifdef USE_CLOSEFROM
  2563. if (last >= sysconf(_SC_OPEN_MAX)) {
  2564. /* Any errors encountered while closing file descriptors are ignored */
  2565. closefrom(first);
  2566. }
  2567. else
  2568. #endif /* USE_CLOSEFROM */
  2569. #ifdef USE_FDWALK
  2570. {
  2571. int lohi[2];
  2572. lohi[0] = first;
  2573. lohi[1] = last + 1;
  2574. fdwalk(_fdwalk_close_func, lohi);
  2575. }
  2576. #else
  2577. {
  2578. for (int i = first; i <= last; i++) {
  2579. /* Ignore errors */
  2580. (void)close(i);
  2581. }
  2582. }
  2583. #endif /* USE_FDWALK */
  2584. _Py_END_SUPPRESS_IPH
  2585. }